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,282
Enable Fast Tail Call Optimization for ARM32
- Not use fast tail call when callee use split struct argument - Not use fast tail call when callee use non-standard calling convention - Not use fast tail call when it overwrites stack which will be passed to callee.
clamp03
2022-03-07T05:47:20Z
2022-03-13T11:50:20Z
227ff3d53784f655fa04dad059a98b3e8d291d61
51b90cc60b8528c77829ef18481b0f58db812776
Enable Fast Tail Call Optimization for ARM32. - Not use fast tail call when callee use split struct argument - Not use fast tail call when callee use non-standard calling convention - Not use fast tail call when it overwrites stack which will be passed to callee.
./src/tests/baseservices/exceptions/stackoverflow/stackoverflow3.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 TestStackOverflow3 { class Program { private const int MAX_RECURSIVE_CALLS = 1000000; static int ctr = 0; public static void Main() { Program ex = new Program(); ex.Execute(); } private unsafe void Execute(string arg1 = "") { long* bar = stackalloc long [1000]; ctr++; if (ctr % 50 == 0) Console.WriteLine("Call number {0} to the Execute method", ctr); if (ctr <= MAX_RECURSIVE_CALLS) Execute(string.Format("{0}", (IntPtr)bar)); ctr--; } } }
// 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 TestStackOverflow3 { class Program { private const int MAX_RECURSIVE_CALLS = 1000000; static int ctr = 0; public static void Main() { Program ex = new Program(); ex.Execute(); } private unsafe void Execute(string arg1 = "") { long* bar = stackalloc long [1000]; ctr++; if (ctr % 50 == 0) Console.WriteLine("Call number {0} to the Execute method", ctr); if (ctr <= MAX_RECURSIVE_CALLS) Execute(string.Format("{0}", (IntPtr)bar)); ctr--; } } }
-1
dotnet/runtime
66,282
Enable Fast Tail Call Optimization for ARM32
- Not use fast tail call when callee use split struct argument - Not use fast tail call when callee use non-standard calling convention - Not use fast tail call when it overwrites stack which will be passed to callee.
clamp03
2022-03-07T05:47:20Z
2022-03-13T11:50:20Z
227ff3d53784f655fa04dad059a98b3e8d291d61
51b90cc60b8528c77829ef18481b0f58db812776
Enable Fast Tail Call Optimization for ARM32. - Not use fast tail call when callee use split struct argument - Not use fast tail call when callee use non-standard calling convention - Not use fast tail call when it overwrites stack which will be passed to callee.
./src/libraries/Common/src/System/Collections/Generic/LargeArrayBuilder.SpeedOpt.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.Runtime.CompilerServices; namespace System.Collections.Generic { /// <summary> /// Helper type for building dynamically-sized arrays while minimizing allocations and copying. /// </summary> /// <typeparam name="T">The element type.</typeparam> internal struct LargeArrayBuilder<T> { private const int StartingCapacity = 4; private const int ResizeLimit = 8; private readonly int _maxCapacity; // The maximum capacity this builder can have. private T[] _first; // The first buffer we store items in. Resized until ResizeLimit. private ArrayBuilder<T[]> _buffers; // After ResizeLimit * 2, we store previous buffers we've filled out here. private T[] _current; // Current buffer we're reading into. If _count <= ResizeLimit, this is _first. private int _index; // Index into the current buffer. private int _count; // Count of all of the items in this builder. /// <summary> /// Constructs a new builder. /// </summary> /// <param name="initialize">Pass <c>true</c>.</param> public LargeArrayBuilder(bool initialize) : this(maxCapacity: int.MaxValue) { // This is a workaround for C# not having parameterless struct constructors yet. // Once it gets them, replace this with a parameterless constructor. Debug.Assert(initialize); } /// <summary> /// Constructs a new builder with the specified maximum capacity. /// </summary> /// <param name="maxCapacity">The maximum capacity this builder can have.</param> /// <remarks> /// Do not add more than <paramref name="maxCapacity"/> items to this builder. /// </remarks> public LargeArrayBuilder(int maxCapacity) : this() { Debug.Assert(maxCapacity >= 0); _first = _current = Array.Empty<T>(); _maxCapacity = maxCapacity; } /// <summary> /// Gets the number of items added to the builder. /// </summary> public int Count => _count; /// <summary> /// Adds an item to this builder. /// </summary> /// <param name="item">The item to add.</param> /// <remarks> /// Use <see cref="Add"/> if adding to the builder is a bottleneck for your use case. /// Otherwise, use <see cref="SlowAdd"/>. /// </remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Add(T item) { Debug.Assert(_maxCapacity > _count); int index = _index; T[] current = _current; // Must be >= and not == to enable range check elimination if ((uint)index >= (uint)current.Length) { AddWithBufferAllocation(item); } else { current[index] = item; _index = index + 1; } _count++; } // Non-inline to improve code quality as uncommon path [MethodImpl(MethodImplOptions.NoInlining)] private void AddWithBufferAllocation(T item) { AllocateBuffer(); _current[_index++] = item; } /// <summary> /// Adds a range of items to this builder. /// </summary> /// <param name="items">The sequence to add.</param> /// <remarks> /// It is the caller's responsibility to ensure that adding <paramref name="items"/> /// does not cause the builder to exceed its maximum capacity. /// </remarks> public void AddRange(IEnumerable<T> items) { Debug.Assert(items != null); using (IEnumerator<T> enumerator = items.GetEnumerator()) { T[] destination = _current; int index = _index; // Continuously read in items from the enumerator, updating _count // and _index when we run out of space. while (enumerator.MoveNext()) { T item = enumerator.Current; if ((uint)index >= (uint)destination.Length) { AddWithBufferAllocation(item, ref destination, ref index); } else { destination[index] = item; } index++; } // Final update to _count and _index. _count += index - _index; _index = index; } } // Non-inline to improve code quality as uncommon path [MethodImpl(MethodImplOptions.NoInlining)] private void AddWithBufferAllocation(T item, ref T[] destination, ref int index) { _count += index - _index; _index = index; AllocateBuffer(); destination = _current; index = _index; _current[index] = item; } /// <summary> /// Copies the contents of this builder to the specified array. /// </summary> /// <param name="array">The destination array.</param> /// <param name="arrayIndex">The index in <paramref name="array"/> to start copying to.</param> /// <param name="count">The number of items to copy.</param> public void CopyTo(T[] array, int arrayIndex, int count) { Debug.Assert(arrayIndex >= 0); Debug.Assert(count >= 0 && count <= Count); Debug.Assert(array.Length - arrayIndex >= count); for (int i = 0; count > 0; i++) { // Find the buffer we're copying from. T[] buffer = GetBuffer(index: i); // Copy until we satisfy count, or we reach the end of the buffer. int toCopy = Math.Min(count, buffer.Length); Array.Copy(buffer, 0, array, arrayIndex, toCopy); // Increment variables to that position. count -= toCopy; arrayIndex += toCopy; } } /// <summary> /// Copies the contents of this builder to the specified array. /// </summary> /// <param name="position">The position in this builder to start copying from.</param> /// <param name="array">The destination array.</param> /// <param name="arrayIndex">The index in <paramref name="array"/> to start copying to.</param> /// <param name="count">The number of items to copy.</param> /// <returns>The position in this builder that was copied up to.</returns> public CopyPosition CopyTo(CopyPosition position, T[] array, int arrayIndex, int count) { Debug.Assert(array != null); Debug.Assert(arrayIndex >= 0); Debug.Assert(count > 0 && count <= Count); Debug.Assert(array.Length - arrayIndex >= count); // Go through each buffer, which contains one 'row' of items. // The index in each buffer is referred to as the 'column'. /* * Visual representation: * * C0 C1 C2 .. C31 .. C63 * R0: [0] [1] [2] .. [31] * R1: [32] [33] [34] .. [63] * R2: [64] [65] [66] .. [95] .. [127] */ int row = position.Row; int column = position.Column; T[] buffer = GetBuffer(row); int copied = CopyToCore(buffer, column); if (count == 0) { return new CopyPosition(row, column + copied).Normalize(buffer.Length); } do { buffer = GetBuffer(++row); copied = CopyToCore(buffer, 0); } while (count > 0); return new CopyPosition(row, copied).Normalize(buffer.Length); int CopyToCore(T[] sourceBuffer, int sourceIndex) { Debug.Assert(sourceBuffer.Length > sourceIndex); // Copy until we satisfy `count` or reach the end of the current buffer. int copyCount = Math.Min(sourceBuffer.Length - sourceIndex, count); Array.Copy(sourceBuffer, sourceIndex, array, arrayIndex, copyCount); arrayIndex += copyCount; count -= copyCount; return copyCount; } } /// <summary> /// Retrieves the buffer at the specified index. /// </summary> /// <param name="index">The index of the buffer.</param> public T[] GetBuffer(int index) { Debug.Assert(index >= 0 && index < _buffers.Count + 2); return index == 0 ? _first : index <= _buffers.Count ? _buffers[index - 1] : _current; } /// <summary> /// Adds an item to this builder. /// </summary> /// <param name="item">The item to add.</param> /// <remarks> /// Use <see cref="Add"/> if adding to the builder is a bottleneck for your use case. /// Otherwise, use <see cref="SlowAdd"/>. /// </remarks> [MethodImpl(MethodImplOptions.NoInlining)] public void SlowAdd(T item) => Add(item); /// <summary> /// Creates an array from the contents of this builder. /// </summary> public T[] ToArray() { if (TryMove(out T[] array)) { // No resizing to do. return array; } array = new T[_count]; CopyTo(array, 0, _count); return array; } /// <summary> /// Attempts to transfer this builder into an array without copying. /// </summary> /// <param name="array">The transferred array, if the operation succeeded.</param> /// <returns><c>true</c> if the operation succeeded; otherwise, <c>false</c>.</returns> public bool TryMove(out T[] array) { array = _first; return _count == _first.Length; } private void AllocateBuffer() { // - On the first few adds, simply resize _first. // - When we pass ResizeLimit, allocate ResizeLimit elements for _current // and start reading into _current. Set _index to 0. // - When _current runs out of space, add it to _buffers and repeat the // above step, except with _current.Length * 2. // - Make sure we never pass _maxCapacity in all of the above steps. Debug.Assert((uint)_maxCapacity > (uint)_count); Debug.Assert(_index == _current.Length, $"{nameof(AllocateBuffer)} was called, but there's more space."); // If _count is int.MinValue, we want to go down the other path which will raise an exception. if ((uint)_count < (uint)ResizeLimit) { // We haven't passed ResizeLimit. Resize _first, copying over the previous items. Debug.Assert(_current == _first && _count == _first.Length); int nextCapacity = Math.Min(_count == 0 ? StartingCapacity : _count * 2, _maxCapacity); _current = new T[nextCapacity]; Array.Copy(_first, _current, _count); _first = _current; } else { Debug.Assert(_maxCapacity > ResizeLimit); Debug.Assert(_count == ResizeLimit ^ _current != _first); int nextCapacity; if (_count == ResizeLimit) { nextCapacity = ResizeLimit; } else { // Example scenario: Let's say _count == 64. // Then our buffers look like this: | 8 | 8 | 16 | 32 | // As you can see, our count will be just double the last buffer. // Now, say _maxCapacity is 100. We will find the right amount to allocate by // doing min(64, 100 - 64). The lhs represents double the last buffer, // the rhs the limit minus the amount we've already allocated. Debug.Assert(_count >= ResizeLimit * 2); Debug.Assert(_count == _current.Length * 2); _buffers.Add(_current); nextCapacity = Math.Min(_count, _maxCapacity - _count); } _current = new T[nextCapacity]; _index = 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.Diagnostics; using System.Runtime.CompilerServices; namespace System.Collections.Generic { /// <summary> /// Helper type for building dynamically-sized arrays while minimizing allocations and copying. /// </summary> /// <typeparam name="T">The element type.</typeparam> internal struct LargeArrayBuilder<T> { private const int StartingCapacity = 4; private const int ResizeLimit = 8; private readonly int _maxCapacity; // The maximum capacity this builder can have. private T[] _first; // The first buffer we store items in. Resized until ResizeLimit. private ArrayBuilder<T[]> _buffers; // After ResizeLimit * 2, we store previous buffers we've filled out here. private T[] _current; // Current buffer we're reading into. If _count <= ResizeLimit, this is _first. private int _index; // Index into the current buffer. private int _count; // Count of all of the items in this builder. /// <summary> /// Constructs a new builder. /// </summary> /// <param name="initialize">Pass <c>true</c>.</param> public LargeArrayBuilder(bool initialize) : this(maxCapacity: int.MaxValue) { // This is a workaround for C# not having parameterless struct constructors yet. // Once it gets them, replace this with a parameterless constructor. Debug.Assert(initialize); } /// <summary> /// Constructs a new builder with the specified maximum capacity. /// </summary> /// <param name="maxCapacity">The maximum capacity this builder can have.</param> /// <remarks> /// Do not add more than <paramref name="maxCapacity"/> items to this builder. /// </remarks> public LargeArrayBuilder(int maxCapacity) : this() { Debug.Assert(maxCapacity >= 0); _first = _current = Array.Empty<T>(); _maxCapacity = maxCapacity; } /// <summary> /// Gets the number of items added to the builder. /// </summary> public int Count => _count; /// <summary> /// Adds an item to this builder. /// </summary> /// <param name="item">The item to add.</param> /// <remarks> /// Use <see cref="Add"/> if adding to the builder is a bottleneck for your use case. /// Otherwise, use <see cref="SlowAdd"/>. /// </remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Add(T item) { Debug.Assert(_maxCapacity > _count); int index = _index; T[] current = _current; // Must be >= and not == to enable range check elimination if ((uint)index >= (uint)current.Length) { AddWithBufferAllocation(item); } else { current[index] = item; _index = index + 1; } _count++; } // Non-inline to improve code quality as uncommon path [MethodImpl(MethodImplOptions.NoInlining)] private void AddWithBufferAllocation(T item) { AllocateBuffer(); _current[_index++] = item; } /// <summary> /// Adds a range of items to this builder. /// </summary> /// <param name="items">The sequence to add.</param> /// <remarks> /// It is the caller's responsibility to ensure that adding <paramref name="items"/> /// does not cause the builder to exceed its maximum capacity. /// </remarks> public void AddRange(IEnumerable<T> items) { Debug.Assert(items != null); using (IEnumerator<T> enumerator = items.GetEnumerator()) { T[] destination = _current; int index = _index; // Continuously read in items from the enumerator, updating _count // and _index when we run out of space. while (enumerator.MoveNext()) { T item = enumerator.Current; if ((uint)index >= (uint)destination.Length) { AddWithBufferAllocation(item, ref destination, ref index); } else { destination[index] = item; } index++; } // Final update to _count and _index. _count += index - _index; _index = index; } } // Non-inline to improve code quality as uncommon path [MethodImpl(MethodImplOptions.NoInlining)] private void AddWithBufferAllocation(T item, ref T[] destination, ref int index) { _count += index - _index; _index = index; AllocateBuffer(); destination = _current; index = _index; _current[index] = item; } /// <summary> /// Copies the contents of this builder to the specified array. /// </summary> /// <param name="array">The destination array.</param> /// <param name="arrayIndex">The index in <paramref name="array"/> to start copying to.</param> /// <param name="count">The number of items to copy.</param> public void CopyTo(T[] array, int arrayIndex, int count) { Debug.Assert(arrayIndex >= 0); Debug.Assert(count >= 0 && count <= Count); Debug.Assert(array.Length - arrayIndex >= count); for (int i = 0; count > 0; i++) { // Find the buffer we're copying from. T[] buffer = GetBuffer(index: i); // Copy until we satisfy count, or we reach the end of the buffer. int toCopy = Math.Min(count, buffer.Length); Array.Copy(buffer, 0, array, arrayIndex, toCopy); // Increment variables to that position. count -= toCopy; arrayIndex += toCopy; } } /// <summary> /// Copies the contents of this builder to the specified array. /// </summary> /// <param name="position">The position in this builder to start copying from.</param> /// <param name="array">The destination array.</param> /// <param name="arrayIndex">The index in <paramref name="array"/> to start copying to.</param> /// <param name="count">The number of items to copy.</param> /// <returns>The position in this builder that was copied up to.</returns> public CopyPosition CopyTo(CopyPosition position, T[] array, int arrayIndex, int count) { Debug.Assert(array != null); Debug.Assert(arrayIndex >= 0); Debug.Assert(count > 0 && count <= Count); Debug.Assert(array.Length - arrayIndex >= count); // Go through each buffer, which contains one 'row' of items. // The index in each buffer is referred to as the 'column'. /* * Visual representation: * * C0 C1 C2 .. C31 .. C63 * R0: [0] [1] [2] .. [31] * R1: [32] [33] [34] .. [63] * R2: [64] [65] [66] .. [95] .. [127] */ int row = position.Row; int column = position.Column; T[] buffer = GetBuffer(row); int copied = CopyToCore(buffer, column); if (count == 0) { return new CopyPosition(row, column + copied).Normalize(buffer.Length); } do { buffer = GetBuffer(++row); copied = CopyToCore(buffer, 0); } while (count > 0); return new CopyPosition(row, copied).Normalize(buffer.Length); int CopyToCore(T[] sourceBuffer, int sourceIndex) { Debug.Assert(sourceBuffer.Length > sourceIndex); // Copy until we satisfy `count` or reach the end of the current buffer. int copyCount = Math.Min(sourceBuffer.Length - sourceIndex, count); Array.Copy(sourceBuffer, sourceIndex, array, arrayIndex, copyCount); arrayIndex += copyCount; count -= copyCount; return copyCount; } } /// <summary> /// Retrieves the buffer at the specified index. /// </summary> /// <param name="index">The index of the buffer.</param> public T[] GetBuffer(int index) { Debug.Assert(index >= 0 && index < _buffers.Count + 2); return index == 0 ? _first : index <= _buffers.Count ? _buffers[index - 1] : _current; } /// <summary> /// Adds an item to this builder. /// </summary> /// <param name="item">The item to add.</param> /// <remarks> /// Use <see cref="Add"/> if adding to the builder is a bottleneck for your use case. /// Otherwise, use <see cref="SlowAdd"/>. /// </remarks> [MethodImpl(MethodImplOptions.NoInlining)] public void SlowAdd(T item) => Add(item); /// <summary> /// Creates an array from the contents of this builder. /// </summary> public T[] ToArray() { if (TryMove(out T[] array)) { // No resizing to do. return array; } array = new T[_count]; CopyTo(array, 0, _count); return array; } /// <summary> /// Attempts to transfer this builder into an array without copying. /// </summary> /// <param name="array">The transferred array, if the operation succeeded.</param> /// <returns><c>true</c> if the operation succeeded; otherwise, <c>false</c>.</returns> public bool TryMove(out T[] array) { array = _first; return _count == _first.Length; } private void AllocateBuffer() { // - On the first few adds, simply resize _first. // - When we pass ResizeLimit, allocate ResizeLimit elements for _current // and start reading into _current. Set _index to 0. // - When _current runs out of space, add it to _buffers and repeat the // above step, except with _current.Length * 2. // - Make sure we never pass _maxCapacity in all of the above steps. Debug.Assert((uint)_maxCapacity > (uint)_count); Debug.Assert(_index == _current.Length, $"{nameof(AllocateBuffer)} was called, but there's more space."); // If _count is int.MinValue, we want to go down the other path which will raise an exception. if ((uint)_count < (uint)ResizeLimit) { // We haven't passed ResizeLimit. Resize _first, copying over the previous items. Debug.Assert(_current == _first && _count == _first.Length); int nextCapacity = Math.Min(_count == 0 ? StartingCapacity : _count * 2, _maxCapacity); _current = new T[nextCapacity]; Array.Copy(_first, _current, _count); _first = _current; } else { Debug.Assert(_maxCapacity > ResizeLimit); Debug.Assert(_count == ResizeLimit ^ _current != _first); int nextCapacity; if (_count == ResizeLimit) { nextCapacity = ResizeLimit; } else { // Example scenario: Let's say _count == 64. // Then our buffers look like this: | 8 | 8 | 16 | 32 | // As you can see, our count will be just double the last buffer. // Now, say _maxCapacity is 100. We will find the right amount to allocate by // doing min(64, 100 - 64). The lhs represents double the last buffer, // the rhs the limit minus the amount we've already allocated. Debug.Assert(_count >= ResizeLimit * 2); Debug.Assert(_count == _current.Length * 2); _buffers.Add(_current); nextCapacity = Math.Min(_count, _maxCapacity - _count); } _current = new T[nextCapacity]; _index = 0; } } } }
-1
dotnet/runtime
66,282
Enable Fast Tail Call Optimization for ARM32
- Not use fast tail call when callee use split struct argument - Not use fast tail call when callee use non-standard calling convention - Not use fast tail call when it overwrites stack which will be passed to callee.
clamp03
2022-03-07T05:47:20Z
2022-03-13T11:50:20Z
227ff3d53784f655fa04dad059a98b3e8d291d61
51b90cc60b8528c77829ef18481b0f58db812776
Enable Fast Tail Call Optimization for ARM32. - Not use fast tail call when callee use split struct argument - Not use fast tail call when callee use non-standard calling convention - Not use fast tail call when it overwrites stack which will be passed to callee.
./src/tests/JIT/jit64/hfa/main/testA/hfa_sd2A_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="hfa_testA.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\dll\common.csproj" /> <ProjectReference Include="..\dll\hfa_simple_f64_common.csproj" /> <ProjectReference Include="..\dll\hfa_simple_f64_interop_cpp.csproj" /> <CMakeProjectReference Include="..\dll\CMakelists.txt" /> </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="hfa_testA.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\dll\common.csproj" /> <ProjectReference Include="..\dll\hfa_simple_f64_common.csproj" /> <ProjectReference Include="..\dll\hfa_simple_f64_interop_cpp.csproj" /> <CMakeProjectReference Include="..\dll\CMakelists.txt" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,282
Enable Fast Tail Call Optimization for ARM32
- Not use fast tail call when callee use split struct argument - Not use fast tail call when callee use non-standard calling convention - Not use fast tail call when it overwrites stack which will be passed to callee.
clamp03
2022-03-07T05:47:20Z
2022-03-13T11:50:20Z
227ff3d53784f655fa04dad059a98b3e8d291d61
51b90cc60b8528c77829ef18481b0f58db812776
Enable Fast Tail Call Optimization for ARM32. - Not use fast tail call when callee use split struct argument - Not use fast tail call when callee use non-standard calling convention - Not use fast tail call when it overwrites stack which will be passed to callee.
./src/tests/JIT/Regression/JitBlue/DevDiv_794631/DevDiv_794631_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="DevDiv_794631.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="DevDiv_794631.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,282
Enable Fast Tail Call Optimization for ARM32
- Not use fast tail call when callee use split struct argument - Not use fast tail call when callee use non-standard calling convention - Not use fast tail call when it overwrites stack which will be passed to callee.
clamp03
2022-03-07T05:47:20Z
2022-03-13T11:50:20Z
227ff3d53784f655fa04dad059a98b3e8d291d61
51b90cc60b8528c77829ef18481b0f58db812776
Enable Fast Tail Call Optimization for ARM32. - Not use fast tail call when callee use split struct argument - Not use fast tail call when callee use non-standard calling convention - Not use fast tail call when it overwrites stack which will be passed to callee.
./src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/SafeCustomLineCapHandle.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.Globalization; using System.Runtime.InteropServices; using System.Security; using Gdip = System.Drawing.SafeNativeMethods.Gdip; namespace System.Drawing.Drawing2D { internal sealed class SafeCustomLineCapHandle : SafeHandle { public SafeCustomLineCapHandle() : base(IntPtr.Zero, true) { } // Create a SafeHandle, informing the base class // that this SafeHandle instance "owns" the handle, // and therefore SafeHandle should call // our ReleaseHandle method when the SafeHandle // is no longer in use. internal SafeCustomLineCapHandle(IntPtr h) : base(IntPtr.Zero, true) { SetHandle(h); } protected override bool ReleaseHandle() { int status = Gdip.Ok; if (!IsInvalid) { try { status = !Gdip.Initialized ? Gdip.Ok : Gdip.GdipDeleteCustomLineCap(new HandleRef(this, handle)); } catch (Exception ex) { if (ClientUtils.IsSecurityOrCriticalException(ex)) { throw; } Debug.Fail("Exception thrown during ReleaseHandle: " + ex.ToString()); } finally { handle = IntPtr.Zero; } Debug.Assert(status == Gdip.Ok, $"GDI+ returned an error status: {status.ToString(CultureInfo.InvariantCulture)}"); } return status == Gdip.Ok; } public override bool IsInvalid => handle == IntPtr.Zero; public static implicit operator IntPtr(SafeCustomLineCapHandle handle) => handle?.handle ?? IntPtr.Zero; public static explicit operator SafeCustomLineCapHandle(IntPtr handle) => new SafeCustomLineCapHandle(handle); } }
// 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.Globalization; using System.Runtime.InteropServices; using System.Security; using Gdip = System.Drawing.SafeNativeMethods.Gdip; namespace System.Drawing.Drawing2D { internal sealed class SafeCustomLineCapHandle : SafeHandle { public SafeCustomLineCapHandle() : base(IntPtr.Zero, true) { } // Create a SafeHandle, informing the base class // that this SafeHandle instance "owns" the handle, // and therefore SafeHandle should call // our ReleaseHandle method when the SafeHandle // is no longer in use. internal SafeCustomLineCapHandle(IntPtr h) : base(IntPtr.Zero, true) { SetHandle(h); } protected override bool ReleaseHandle() { int status = Gdip.Ok; if (!IsInvalid) { try { status = !Gdip.Initialized ? Gdip.Ok : Gdip.GdipDeleteCustomLineCap(new HandleRef(this, handle)); } catch (Exception ex) { if (ClientUtils.IsSecurityOrCriticalException(ex)) { throw; } Debug.Fail("Exception thrown during ReleaseHandle: " + ex.ToString()); } finally { handle = IntPtr.Zero; } Debug.Assert(status == Gdip.Ok, $"GDI+ returned an error status: {status.ToString(CultureInfo.InvariantCulture)}"); } return status == Gdip.Ok; } public override bool IsInvalid => handle == IntPtr.Zero; public static implicit operator IntPtr(SafeCustomLineCapHandle handle) => handle?.handle ?? IntPtr.Zero; public static explicit operator SafeCustomLineCapHandle(IntPtr handle) => new SafeCustomLineCapHandle(handle); } }
-1
dotnet/runtime
66,282
Enable Fast Tail Call Optimization for ARM32
- Not use fast tail call when callee use split struct argument - Not use fast tail call when callee use non-standard calling convention - Not use fast tail call when it overwrites stack which will be passed to callee.
clamp03
2022-03-07T05:47:20Z
2022-03-13T11:50:20Z
227ff3d53784f655fa04dad059a98b3e8d291d61
51b90cc60b8528c77829ef18481b0f58db812776
Enable Fast Tail Call Optimization for ARM32. - Not use fast tail call when callee use split struct argument - Not use fast tail call when callee use non-standard calling convention - Not use fast tail call when it overwrites stack which will be passed to callee.
./src/coreclr/gc/env/gcenv.interlocked.inl
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // __forceinline implementation of the Interlocked class methods // #ifndef __GCENV_INTERLOCKED_INL__ #define __GCENV_INTERLOCKED_INL__ #ifdef _MSC_VER #include <intrin.h> #endif // _MSC_VER #ifndef _MSC_VER __forceinline void Interlocked::ArmInterlockedOperationBarrier() { #ifdef HOST_ARM64 // See PAL_ArmInterlockedOperationBarrier() in the PAL __sync_synchronize(); #endif // HOST_ARM64 #ifdef HOST_LOONGARCH64 __sync_synchronize(); #endif //HOST_LOONGARCH64 } #endif // !_MSC_VER // Increment the value of the specified 32-bit variable as an atomic operation. // Parameters: // addend - variable to be incremented // Return: // The resulting incremented value template <typename T> __forceinline T Interlocked::Increment(T volatile *addend) { #ifdef _MSC_VER static_assert(sizeof(long) == sizeof(T), "Size of long must be the same as size of T"); return _InterlockedIncrement((long*)addend); #else T result = __sync_add_and_fetch(addend, 1); ArmInterlockedOperationBarrier(); return result; #endif } // Decrement the value of the specified 32-bit variable as an atomic operation. // Parameters: // addend - variable to be decremented // Return: // The resulting decremented value template <typename T> __forceinline T Interlocked::Decrement(T volatile *addend) { #ifdef _MSC_VER static_assert(sizeof(long) == sizeof(T), "Size of long must be the same as size of T"); return _InterlockedDecrement((long*)addend); #else T result = __sync_sub_and_fetch(addend, 1); ArmInterlockedOperationBarrier(); return result; #endif } // Set a 32-bit variable to the specified value as an atomic operation. // Parameters: // destination - value to be exchanged // value - value to set the destination to // Return: // The previous value of the destination template <typename T> __forceinline T Interlocked::Exchange(T volatile *destination, T value) { #ifdef _MSC_VER static_assert(sizeof(long) == sizeof(T), "Size of long must be the same as size of T"); return _InterlockedExchange((long*)destination, value); #else T result = __atomic_exchange_n(destination, value, __ATOMIC_ACQ_REL); ArmInterlockedOperationBarrier(); return result; #endif } // Performs an atomic compare-and-exchange operation on the specified values. // Parameters: // destination - value to be exchanged // exchange - value to set the destinaton to // comparand - value to compare the destination to before setting it to the exchange. // The destination is set only if the destination is equal to the comparand. // Return: // The original value of the destination template <typename T> __forceinline T Interlocked::CompareExchange(T volatile *destination, T exchange, T comparand) { #ifdef _MSC_VER static_assert(sizeof(long) == sizeof(T), "Size of long must be the same as size of T"); return _InterlockedCompareExchange((long*)destination, exchange, comparand); #else T result = __sync_val_compare_and_swap(destination, comparand, exchange); ArmInterlockedOperationBarrier(); return result; #endif } // Perform an atomic addition of two 32-bit values and return the original value of the addend. // Parameters: // addend - variable to be added to // value - value to add // Return: // The previous value of the addend template <typename T> __forceinline T Interlocked::ExchangeAdd(T volatile *addend, T value) { #ifdef _MSC_VER static_assert(sizeof(long) == sizeof(T), "Size of long must be the same as size of T"); return _InterlockedExchangeAdd((long*)addend, value); #else T result = __sync_fetch_and_add(addend, value); ArmInterlockedOperationBarrier(); return result; #endif } template <typename T> __forceinline T Interlocked::ExchangeAdd64(T volatile* addend, T value) { #ifdef _MSC_VER static_assert(sizeof(int64_t) == sizeof(T), "Size of LONGLONG must be the same as size of T"); return _InterlockedExchangeAdd64((int64_t*)addend, value); #else T result = __sync_fetch_and_add(addend, value); ArmInterlockedOperationBarrier(); return result; #endif } template <typename T> __forceinline T Interlocked::ExchangeAddPtr(T volatile* addend, T value) { #ifdef _MSC_VER #ifdef HOST_64BIT static_assert(sizeof(int64_t) == sizeof(T), "Size of LONGLONG must be the same as size of T"); return _InterlockedExchangeAdd64((int64_t*)addend, value); #else static_assert(sizeof(long) == sizeof(T), "Size of long must be the same as size of T"); return _InterlockedExchangeAdd((long*)addend, value); #endif #else T result = __sync_fetch_and_add(addend, value); ArmInterlockedOperationBarrier(); return result; #endif } // Perform an atomic AND operation on the specified values values // Parameters: // destination - the first operand and the destination // value - second operand template <typename T> __forceinline void Interlocked::And(T volatile *destination, T value) { #ifdef _MSC_VER static_assert(sizeof(long) == sizeof(T), "Size of long must be the same as size of T"); _InterlockedAnd((long*)destination, value); #else __sync_and_and_fetch(destination, value); ArmInterlockedOperationBarrier(); #endif } // Perform an atomic OR operation on the specified values values // Parameters: // destination - the first operand and the destination // value - second operand template <typename T> __forceinline void Interlocked::Or(T volatile *destination, T value) { #ifdef _MSC_VER static_assert(sizeof(long) == sizeof(T), "Size of long must be the same as size of T"); _InterlockedOr((long*)destination, value); #else __sync_or_and_fetch(destination, value); ArmInterlockedOperationBarrier(); #endif } // Set a pointer variable to the specified value as an atomic operation. // Parameters: // destination - value to be exchanged // value - value to set the destination to // Return: // The previous value of the destination template <typename T> __forceinline T Interlocked::ExchangePointer(T volatile * destination, T value) { #ifdef _MSC_VER #ifdef HOST_64BIT return (T)(TADDR)_InterlockedExchangePointer((void* volatile *)destination, value); #else return (T)(TADDR)_InterlockedExchange((long volatile *)(void* volatile *)destination, (long)(void*)value); #endif #else T result = (T)(TADDR)__atomic_exchange_n((void* volatile *)destination, value, __ATOMIC_ACQ_REL); ArmInterlockedOperationBarrier(); return result; #endif } template <typename T> __forceinline T Interlocked::ExchangePointer(T volatile * destination, std::nullptr_t value) { #ifdef _MSC_VER #ifdef HOST_64BIT return (T)(TADDR)_InterlockedExchangePointer((void* volatile *)destination, value); #else return (T)(TADDR)_InterlockedExchange((long volatile *)(void* volatile *)destination, (long)(void*)value); #endif #else T result = (T)(TADDR)__atomic_exchange_n((void* volatile *)destination, value, __ATOMIC_ACQ_REL); ArmInterlockedOperationBarrier(); return result; #endif } // Performs an atomic compare-and-exchange operation on the specified pointers. // Parameters: // destination - value to be exchanged // exchange - value to set the destinaton to // comparand - value to compare the destination to before setting it to the exchange. // The destination is set only if the destination is equal to the comparand. // Return: // The original value of the destination template <typename T> __forceinline T Interlocked::CompareExchangePointer(T volatile *destination, T exchange, T comparand) { #ifdef _MSC_VER #ifdef HOST_64BIT return (T)(TADDR)_InterlockedCompareExchangePointer((void* volatile *)destination, exchange, comparand); #else return (T)(TADDR)_InterlockedCompareExchange((long volatile *)(void* volatile *)destination, (long)(void*)exchange, (long)(void*)comparand); #endif #else T result = (T)(TADDR)__sync_val_compare_and_swap((void* volatile *)destination, comparand, exchange); ArmInterlockedOperationBarrier(); return result; #endif } template <typename T> __forceinline T Interlocked::CompareExchangePointer(T volatile *destination, T exchange, std::nullptr_t comparand) { #ifdef _MSC_VER #ifdef HOST_64BIT return (T)(TADDR)_InterlockedCompareExchangePointer((void* volatile *)destination, (void*)exchange, (void*)comparand); #else return (T)(TADDR)_InterlockedCompareExchange((long volatile *)(void* volatile *)destination, (long)(void*)exchange, (long)(void*)comparand); #endif #else T result = (T)(TADDR)__sync_val_compare_and_swap((void* volatile *)destination, (void*)comparand, (void*)exchange); ArmInterlockedOperationBarrier(); return result; #endif } #endif // __GCENV_INTERLOCKED_INL__
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // __forceinline implementation of the Interlocked class methods // #ifndef __GCENV_INTERLOCKED_INL__ #define __GCENV_INTERLOCKED_INL__ #ifdef _MSC_VER #include <intrin.h> #endif // _MSC_VER #ifndef _MSC_VER __forceinline void Interlocked::ArmInterlockedOperationBarrier() { #ifdef HOST_ARM64 // See PAL_ArmInterlockedOperationBarrier() in the PAL __sync_synchronize(); #endif // HOST_ARM64 #ifdef HOST_LOONGARCH64 __sync_synchronize(); #endif //HOST_LOONGARCH64 } #endif // !_MSC_VER // Increment the value of the specified 32-bit variable as an atomic operation. // Parameters: // addend - variable to be incremented // Return: // The resulting incremented value template <typename T> __forceinline T Interlocked::Increment(T volatile *addend) { #ifdef _MSC_VER static_assert(sizeof(long) == sizeof(T), "Size of long must be the same as size of T"); return _InterlockedIncrement((long*)addend); #else T result = __sync_add_and_fetch(addend, 1); ArmInterlockedOperationBarrier(); return result; #endif } // Decrement the value of the specified 32-bit variable as an atomic operation. // Parameters: // addend - variable to be decremented // Return: // The resulting decremented value template <typename T> __forceinline T Interlocked::Decrement(T volatile *addend) { #ifdef _MSC_VER static_assert(sizeof(long) == sizeof(T), "Size of long must be the same as size of T"); return _InterlockedDecrement((long*)addend); #else T result = __sync_sub_and_fetch(addend, 1); ArmInterlockedOperationBarrier(); return result; #endif } // Set a 32-bit variable to the specified value as an atomic operation. // Parameters: // destination - value to be exchanged // value - value to set the destination to // Return: // The previous value of the destination template <typename T> __forceinline T Interlocked::Exchange(T volatile *destination, T value) { #ifdef _MSC_VER static_assert(sizeof(long) == sizeof(T), "Size of long must be the same as size of T"); return _InterlockedExchange((long*)destination, value); #else T result = __atomic_exchange_n(destination, value, __ATOMIC_ACQ_REL); ArmInterlockedOperationBarrier(); return result; #endif } // Performs an atomic compare-and-exchange operation on the specified values. // Parameters: // destination - value to be exchanged // exchange - value to set the destinaton to // comparand - value to compare the destination to before setting it to the exchange. // The destination is set only if the destination is equal to the comparand. // Return: // The original value of the destination template <typename T> __forceinline T Interlocked::CompareExchange(T volatile *destination, T exchange, T comparand) { #ifdef _MSC_VER static_assert(sizeof(long) == sizeof(T), "Size of long must be the same as size of T"); return _InterlockedCompareExchange((long*)destination, exchange, comparand); #else T result = __sync_val_compare_and_swap(destination, comparand, exchange); ArmInterlockedOperationBarrier(); return result; #endif } // Perform an atomic addition of two 32-bit values and return the original value of the addend. // Parameters: // addend - variable to be added to // value - value to add // Return: // The previous value of the addend template <typename T> __forceinline T Interlocked::ExchangeAdd(T volatile *addend, T value) { #ifdef _MSC_VER static_assert(sizeof(long) == sizeof(T), "Size of long must be the same as size of T"); return _InterlockedExchangeAdd((long*)addend, value); #else T result = __sync_fetch_and_add(addend, value); ArmInterlockedOperationBarrier(); return result; #endif } template <typename T> __forceinline T Interlocked::ExchangeAdd64(T volatile* addend, T value) { #ifdef _MSC_VER static_assert(sizeof(int64_t) == sizeof(T), "Size of LONGLONG must be the same as size of T"); return _InterlockedExchangeAdd64((int64_t*)addend, value); #else T result = __sync_fetch_and_add(addend, value); ArmInterlockedOperationBarrier(); return result; #endif } template <typename T> __forceinline T Interlocked::ExchangeAddPtr(T volatile* addend, T value) { #ifdef _MSC_VER #ifdef HOST_64BIT static_assert(sizeof(int64_t) == sizeof(T), "Size of LONGLONG must be the same as size of T"); return _InterlockedExchangeAdd64((int64_t*)addend, value); #else static_assert(sizeof(long) == sizeof(T), "Size of long must be the same as size of T"); return _InterlockedExchangeAdd((long*)addend, value); #endif #else T result = __sync_fetch_and_add(addend, value); ArmInterlockedOperationBarrier(); return result; #endif } // Perform an atomic AND operation on the specified values values // Parameters: // destination - the first operand and the destination // value - second operand template <typename T> __forceinline void Interlocked::And(T volatile *destination, T value) { #ifdef _MSC_VER static_assert(sizeof(long) == sizeof(T), "Size of long must be the same as size of T"); _InterlockedAnd((long*)destination, value); #else __sync_and_and_fetch(destination, value); ArmInterlockedOperationBarrier(); #endif } // Perform an atomic OR operation on the specified values values // Parameters: // destination - the first operand and the destination // value - second operand template <typename T> __forceinline void Interlocked::Or(T volatile *destination, T value) { #ifdef _MSC_VER static_assert(sizeof(long) == sizeof(T), "Size of long must be the same as size of T"); _InterlockedOr((long*)destination, value); #else __sync_or_and_fetch(destination, value); ArmInterlockedOperationBarrier(); #endif } // Set a pointer variable to the specified value as an atomic operation. // Parameters: // destination - value to be exchanged // value - value to set the destination to // Return: // The previous value of the destination template <typename T> __forceinline T Interlocked::ExchangePointer(T volatile * destination, T value) { #ifdef _MSC_VER #ifdef HOST_64BIT return (T)(TADDR)_InterlockedExchangePointer((void* volatile *)destination, value); #else return (T)(TADDR)_InterlockedExchange((long volatile *)(void* volatile *)destination, (long)(void*)value); #endif #else T result = (T)(TADDR)__atomic_exchange_n((void* volatile *)destination, value, __ATOMIC_ACQ_REL); ArmInterlockedOperationBarrier(); return result; #endif } template <typename T> __forceinline T Interlocked::ExchangePointer(T volatile * destination, std::nullptr_t value) { #ifdef _MSC_VER #ifdef HOST_64BIT return (T)(TADDR)_InterlockedExchangePointer((void* volatile *)destination, value); #else return (T)(TADDR)_InterlockedExchange((long volatile *)(void* volatile *)destination, (long)(void*)value); #endif #else T result = (T)(TADDR)__atomic_exchange_n((void* volatile *)destination, value, __ATOMIC_ACQ_REL); ArmInterlockedOperationBarrier(); return result; #endif } // Performs an atomic compare-and-exchange operation on the specified pointers. // Parameters: // destination - value to be exchanged // exchange - value to set the destinaton to // comparand - value to compare the destination to before setting it to the exchange. // The destination is set only if the destination is equal to the comparand. // Return: // The original value of the destination template <typename T> __forceinline T Interlocked::CompareExchangePointer(T volatile *destination, T exchange, T comparand) { #ifdef _MSC_VER #ifdef HOST_64BIT return (T)(TADDR)_InterlockedCompareExchangePointer((void* volatile *)destination, exchange, comparand); #else return (T)(TADDR)_InterlockedCompareExchange((long volatile *)(void* volatile *)destination, (long)(void*)exchange, (long)(void*)comparand); #endif #else T result = (T)(TADDR)__sync_val_compare_and_swap((void* volatile *)destination, comparand, exchange); ArmInterlockedOperationBarrier(); return result; #endif } template <typename T> __forceinline T Interlocked::CompareExchangePointer(T volatile *destination, T exchange, std::nullptr_t comparand) { #ifdef _MSC_VER #ifdef HOST_64BIT return (T)(TADDR)_InterlockedCompareExchangePointer((void* volatile *)destination, (void*)exchange, (void*)comparand); #else return (T)(TADDR)_InterlockedCompareExchange((long volatile *)(void* volatile *)destination, (long)(void*)exchange, (long)(void*)comparand); #endif #else T result = (T)(TADDR)__sync_val_compare_and_swap((void* volatile *)destination, (void*)comparand, (void*)exchange); ArmInterlockedOperationBarrier(); return result; #endif } #endif // __GCENV_INTERLOCKED_INL__
-1
dotnet/runtime
66,282
Enable Fast Tail Call Optimization for ARM32
- Not use fast tail call when callee use split struct argument - Not use fast tail call when callee use non-standard calling convention - Not use fast tail call when it overwrites stack which will be passed to callee.
clamp03
2022-03-07T05:47:20Z
2022-03-13T11:50:20Z
227ff3d53784f655fa04dad059a98b3e8d291d61
51b90cc60b8528c77829ef18481b0f58db812776
Enable Fast Tail Call Optimization for ARM32. - Not use fast tail call when callee use split struct argument - Not use fast tail call when callee use non-standard calling convention - Not use fast tail call when it overwrites stack which will be passed to callee.
./src/mono/mono/eglib/test/utf8.c
#include <stdlib.h> #include "test.h" /* * g_utf16_to_utf8 */ static glong compare_strings_utf8_pos (const gchar *expected, const gchar *actual, glong size) { int i; for (i = 0; i < size; i++) if (expected [i] != actual [i]) return i; return -1; } static RESULT compare_strings_utf8_RESULT (const gchar *expected, const gchar *actual, glong size) { glong ret; ret = compare_strings_utf8_pos (expected, actual, size); if (ret < 0) return OK; return FAILED ("Incorrect output: expected '%s' but was '%s', differ at %d\n", expected, actual, ret); } static void gchar_to_gunichar2 (gunichar2 ret[], const gchar *src) { int i; for (i = 0; src [i]; i++) ret [i] = src [i]; ret [i] = 0; } static RESULT compare_utf16_to_utf8_explicit (const gchar *expected, const gunichar2 *utf16, glong len_in, glong len_out, glong size_spec) { GError *gerror; gchar* ret; RESULT result; glong in_read, out_read; result = NULL; gerror = NULL; ret = g_utf16_to_utf8 (utf16, size_spec, &in_read, &out_read, &gerror); if (gerror) { result = FAILED ("The error is %d %s\n", gerror->code, gerror->message); g_error_free (gerror); if (ret) g_free (ret); return result; } if (in_read != len_in) result = FAILED ("Read size is incorrect: expected %d but was %d\n", len_in, in_read); else if (out_read != len_out) result = FAILED ("Converted size is incorrect: expected %d but was %d\n", len_out, out_read); else result = compare_strings_utf8_RESULT (expected, ret, len_out); g_free (ret); if (result) return result; return OK; } static RESULT compare_utf16_to_utf8 (const gchar *expected, const gunichar2 *utf16, glong len_in, glong len_out) { RESULT result; result = compare_utf16_to_utf8_explicit (expected, utf16, len_in, len_out, -1); if (result != OK) return result; return compare_utf16_to_utf8_explicit (expected, utf16, len_in, len_out, len_in); } static RESULT test_utf16_to_utf8 (void) { const gchar *src0 = "", *src1 = "ABCDE", *src2 = "\xE5\xB9\xB4\x27", *src3 = "\xEF\xBC\xA1", *src4 = "\xEF\xBD\x81", *src5 = "\xF0\x90\x90\x80"; gunichar2 str0 [] = {0}, str1 [6], str2 [] = {0x5E74, 39, 0}, str3 [] = {0xFF21, 0}, str4 [] = {0xFF41, 0}, str5 [] = {0xD801, 0xDC00, 0}; RESULT result; gchar_to_gunichar2 (str1, src1); /* empty string */ result = compare_utf16_to_utf8 (src0, str0, 0, 0); if (result != OK) return result; result = compare_utf16_to_utf8 (src1, str1, 5, 5); if (result != OK) return result; result = compare_utf16_to_utf8 (src2, str2, 2, 4); if (result != OK) return result; result = compare_utf16_to_utf8 (src3, str3, 1, 3); if (result != OK) return result; result = compare_utf16_to_utf8 (src4, str4, 1, 3); if (result != OK) return result; result = compare_utf16_to_utf8 (src5, str5, 2, 4); if (result != OK) return result; return OK; } /* * g_utf8_to_utf16 */ static glong compare_strings_utf16_pos (const gunichar2 *expected, const gunichar2 *actual, glong size) { int i; for (i = 0; i < size; i++) if (expected [i] != actual [i]) return i; return -1; } static RESULT compare_strings_utf16_RESULT (const gunichar2 *expected, const gunichar2 *actual, glong size) { glong ret; ret = compare_strings_utf16_pos (expected, actual, size); if (ret < 0) return OK; return FAILED ("Incorrect output: expected '%s' but was '%s', differ at %d ('%c' x '%c')\n", expected, actual, ret, expected [ret], actual [ret]); } #if !defined(EGLIB_TESTS) #define eg_utf8_to_utf16_with_nuls g_utf8_to_utf16 #endif static RESULT compare_utf8_to_utf16_explicit (const gunichar2 *expected, const gchar *utf8, glong len_in, glong len_out, glong size_spec, gboolean include_nuls) { GError *gerror; gunichar2* ret; RESULT result; glong in_read, out_read; result = NULL; gerror = NULL; if (include_nuls) ret = eg_utf8_to_utf16_with_nuls (utf8, size_spec, &in_read, &out_read, &gerror); else ret = g_utf8_to_utf16 (utf8, size_spec, &in_read, &out_read, &gerror); if (gerror) { result = FAILED ("The error is %d %s\n", gerror->code, gerror->message); g_error_free (gerror); if (ret) g_free (ret); return result; } if (in_read != len_in) result = FAILED ("Read size is incorrect: expected %d but was %d\n", len_in, in_read); else if (out_read != len_out) result = FAILED ("Converted size is incorrect: expected %d but was %d\n", len_out, out_read); else result = compare_strings_utf16_RESULT (expected, ret, len_out); g_free (ret); if (result) return result; return OK; } static RESULT compare_utf8_to_utf16_general (const gunichar2 *expected, const gchar *utf8, glong len_in, glong len_out, gboolean include_nuls) { RESULT result; result = compare_utf8_to_utf16_explicit (expected, utf8, len_in, len_out, -1, include_nuls); if (result != OK) return result; return compare_utf8_to_utf16_explicit (expected, utf8, len_in, len_out, len_in, include_nuls); } static RESULT compare_utf8_to_utf16 (const gunichar2 *expected, const gchar *utf8, glong len_in, glong len_out) { return compare_utf8_to_utf16_general (expected, utf8, len_in, len_out, FALSE); } static RESULT compare_utf8_to_utf16_with_nuls (const gunichar2 *expected, const gchar *utf8, glong len_in, glong len_out) { return compare_utf8_to_utf16_explicit (expected, utf8, len_in, len_out, len_in, TRUE); } static RESULT test_utf8_seq (void) { const gchar *src = "\xE5\xB9\xB4\x27"; glong in_read, out_read; //gunichar2 expected [6]; GError *gerror = NULL; gunichar2 *dst; //printf ("got: %s\n", src); dst = g_utf8_to_utf16 (src, (glong)strlen (src), &in_read, &out_read, &gerror); if (gerror != NULL){ return gerror->message; } if (in_read != 4) { return FAILED ("in_read is expected to be 4 but was %d\n", in_read); } if (out_read != 2) { return FAILED ("out_read is expected to be 2 but was %d\n", out_read); } g_free (dst); return OK; } static RESULT test_utf8_to_utf16 (void) { const gchar *src0 = "", *src1 = "ABCDE", *src2 = "\xE5\xB9\xB4\x27", *src3 = "\xEF\xBC\xA1", *src4 = "\xEF\xBD\x81"; gunichar2 str0 [] = {0}, str1 [6], str2 [] = {0x5E74, 39, 0}, str3 [] = {0xFF21, 0}, str4 [] = {0xFF41, 0}; RESULT result; gchar_to_gunichar2 (str1, src1); /* empty string */ result = compare_utf8_to_utf16 (str0, src0, 0, 0); if (result != OK) return result; result = compare_utf8_to_utf16 (str1, src1, 5, 5); if (result != OK) return result; result = compare_utf8_to_utf16 (str2, src2, 4, 2); if (result != OK) return result; result = compare_utf8_to_utf16 (str3, src3, 3, 1); if (result != OK) return result; result = compare_utf8_to_utf16 (str4, src4, 3, 1); if (result != OK) return result; return OK; } static RESULT test_utf8_to_utf16_with_nuls (void) { const gchar *src0 = "", *src1 = "AB\0DE", *src2 = "\xE5\xB9\xB4\x27", *src3 = "\xEF\xBC\xA1", *src4 = "\xEF\xBD\x81"; gunichar2 str0 [] = {0}, str1 [] = {'A', 'B', 0, 'D', 'E', 0}, str2 [] = {0x5E74, 39, 0}, str3 [] = {0xFF21, 0}, str4 [] = {0xFF41, 0}; RESULT result; #if !defined(EGLIB_TESTS) return OK; #endif /* implicit length is forbidden */ if (eg_utf8_to_utf16_with_nuls (src1, -1, NULL, NULL, NULL) != NULL) return FAILED ("explicit nulls must fail with -1 length\n"); /* empty string */ result = compare_utf8_to_utf16_with_nuls (str0, src0, 0, 0); if (result != OK) return result; result = compare_utf8_to_utf16_with_nuls (str1, src1, 5, 5); if (result != OK) return result; result = compare_utf8_to_utf16_with_nuls (str2, src2, 4, 2); if (result != OK) return result; result = compare_utf8_to_utf16_with_nuls (str3, src3, 3, 1); if (result != OK) return result; result = compare_utf8_to_utf16_with_nuls (str4, src4, 3, 1); if (result != OK) return result; return OK; } static RESULT ucs4_to_utf16_check_result (const gunichar2 *result_str, const gunichar2 *expected_str, glong result_items_read, glong expected_items_read, glong result_items_written, glong expected_items_written, GError* result_error, gboolean expect_error) { glong i; if (result_items_read != expected_items_read) return FAILED("Incorrect number of items read; expected %d, got %d", expected_items_read, result_items_read); if (result_items_written != expected_items_written) return FAILED("Incorrect number of items written; expected %d, got %d", expected_items_written, result_items_written); if (result_error && !expect_error) return FAILED("There should not be an error code."); if (!result_error && expect_error) return FAILED("Unexpected error object."); if (expect_error && result_str) return FAILED("NULL should be returned when an error occurs."); if (!expect_error && !result_str) return FAILED("When no error occurs NULL should not be returned."); for (i=0; i<expected_items_written;i++) { if (result_str [i] != expected_str [i]) return FAILED("Incorrect value %d at index %d", result_str [i], i); } if (result_str && result_str[expected_items_written] != '\0') return FAILED("Null termination not found at the end of the string."); return OK; } static RESULT test_ucs4_to_utf16 (void) { static gunichar str1[12] = {'H','e','l','l','o',' ','W','o','r','l','d','\0'}; static gunichar2 exp1[12] = {'H','e','l','l','o',' ','W','o','r','l','d','\0'}; static gunichar str2[3] = {'h',0x80000000,'\0'}; static gunichar2 exp2[2] = {'h','\0'}; static gunichar str3[3] = {'h',0xDA00,'\0'}; static gunichar str4[3] = {'h',0x10FFFF,'\0'}; static gunichar2 exp4[4] = {'h',0xdbff,0xdfff,'\0'}; static gunichar str5[7] = {0xD7FF,0xD800,0xDFFF,0xE000,0x110000,0x10FFFF,'\0'}; static gunichar2 exp5[5] = {0xD7FF,0xE000,0xdbff,0xdfff,'\0'}; static gunichar str6[2] = {0x10400, '\0'}; static gunichar2 exp6[3] = {0xD801, 0xDC00, '\0'}; static glong read_write[12] = {1,1,0,0,0,0,1,1,0,0,1,2}; gunichar2* res; glong items_read, items_written, current_write_index; GError* err=0; RESULT check_result; glong i; res = g_ucs4_to_utf16 (str1, 12, &items_read, &items_written, &err); check_result = ucs4_to_utf16_check_result (res, exp1, items_read, 11, items_written, 11, err, FALSE); if (check_result) return check_result; g_free (res); items_read = items_written = 0; res = g_ucs4_to_utf16 (str2, 0, &items_read, &items_written, &err); check_result = ucs4_to_utf16_check_result (res, exp2, items_read, 0, items_written, 0, err, FALSE); if (check_result) return check_result; g_free (res); items_read = items_written = 0; res = g_ucs4_to_utf16 (str2, 1, &items_read, &items_written, &err); check_result = ucs4_to_utf16_check_result (res, exp2, items_read, 1, items_written, 1, err, FALSE); if (check_result) return check_result; g_free (res); items_read = items_written = 0; res = g_ucs4_to_utf16 (str2, 2, &items_read, &items_written, &err); check_result = ucs4_to_utf16_check_result (res, 0, items_read, 1, items_written, 0, err, TRUE); g_free (res); if (check_result) return check_result; items_read = items_written = 0; err = 0; res = g_ucs4_to_utf16 (str3, 2, &items_read, &items_written, &err); check_result = ucs4_to_utf16_check_result (res, 0, items_read, 1, items_written, 0, err, TRUE); if (check_result) return check_result; g_free (res); items_read = items_written = 0; err = 0; res = g_ucs4_to_utf16 (str4, 5, &items_read, &items_written, &err); check_result = ucs4_to_utf16_check_result (res, exp4, items_read, 2, items_written, 3, err, FALSE); if (check_result) return check_result; g_free (res); // This loop tests the bounds of the conversion algorithm current_write_index = 0; for (i=0;i<6;i++) { items_read = items_written = 0; err = 0; res = g_ucs4_to_utf16 (&str5[i], 1, &items_read, &items_written, &err); check_result = ucs4_to_utf16_check_result (res, &exp5[current_write_index], items_read, read_write[i*2], items_written, read_write[(i*2)+1], err, !read_write[(i*2)+1]); if (check_result) return check_result; g_free (res); current_write_index += items_written; } items_read = items_written = 0; err = 0; res = g_ucs4_to_utf16 (str6, 1, &items_read, &items_written, &err); check_result = ucs4_to_utf16_check_result (res, exp6, items_read, 1, items_written, 2, err, FALSE); if (check_result) return check_result; g_free (res); return OK; } static RESULT utf16_to_ucs4_check_result (const gunichar *result_str, const gunichar *expected_str, glong result_items_read, glong expected_items_read, glong result_items_written, glong expected_items_written, GError* result_error, gboolean expect_error) { glong i; if (result_items_read != expected_items_read) return FAILED("Incorrect number of items read; expected %d, got %d", expected_items_read, result_items_read); if (result_items_written != expected_items_written) return FAILED("Incorrect number of items written; expected %d, got %d", expected_items_written, result_items_written); if (result_error && !expect_error) return FAILED("There should not be an error code."); if (!result_error && expect_error) return FAILED("Unexpected error object."); if (expect_error && result_str) return FAILED("NULL should be returned when an error occurs."); if (!expect_error && !result_str) return FAILED("When no error occurs NULL should not be returned."); for (i=0; i<expected_items_written;i++) { if (result_str [i] != expected_str [i]) return FAILED("Incorrect value %d at index %d", result_str [i], i); } if (result_str && result_str[expected_items_written] != '\0') return FAILED("Null termination not found at the end of the string."); return OK; } static RESULT test_utf16_to_ucs4 (void) { static gunichar2 str1[12] = {'H','e','l','l','o',' ','W','o','r','l','d','\0'}; static gunichar exp1[12] = {'H','e','l','l','o',' ','W','o','r','l','d','\0'}; static gunichar2 str2[7] = {'H', 0xD800, 0xDC01,0xD800,0xDBFF,'l','\0'}; static gunichar exp2[3] = {'H',0x00010001,'\0'}; static gunichar2 str3[4] = {'H', 0xDC00 ,'l','\0'}; static gunichar exp3[2] = {'H','\0'}; static gunichar2 str4[20] = {0xDC00,0xDFFF,0xDFF,0xD800,0xDBFF,0xD800,0xDC00,0xD800,0xDFFF, 0xD800,0xE000,0xDBFF,0xDBFF,0xDBFF,0xDC00,0xDBFF,0xDFFF,0xDBFF,0xE000,'\0'}; static gunichar exp4[6] = {0xDFF,0x10000,0x103ff,0x10fc00,0x10FFFF,'\0'}; static gunichar2 str5[3] = {0xD801, 0xDC00, 0}; static gunichar exp5[2] = {0x10400, 0}; static glong read_write[33] = {1,0,0,1,0,0,1,1,1,2,1,0,2,2,1,2,2,1,2,1,0,2,1,0,2,2,1,2,2,1,2,1,0}; gunichar* res; glong items_read, items_written, current_read_index,current_write_index; GError* err=0; RESULT check_result; glong i; res = g_utf16_to_ucs4 (str1, 12, &items_read, &items_written, &err); check_result = utf16_to_ucs4_check_result (res, exp1, items_read, 11, items_written, 11, err, FALSE); if (check_result) return check_result; g_free (res); items_read = items_written = 0; res = g_utf16_to_ucs4 (str2, 0, &items_read, &items_written, &err); check_result = utf16_to_ucs4_check_result (res, exp2, items_read, 0, items_written, 0, err, FALSE); if (check_result) return check_result; g_free (res); items_read = items_written = 0; res = g_utf16_to_ucs4 (str2, 1, &items_read, &items_written, &err); check_result = utf16_to_ucs4_check_result (res, exp2, items_read, 1, items_written, 1, err, FALSE); if (check_result) return check_result; g_free (res); items_read = items_written = 0; res = g_utf16_to_ucs4 (str2, 2, &items_read, &items_written, &err); check_result = utf16_to_ucs4_check_result (res, exp2, items_read, 1, items_written, 1, err, FALSE); if (check_result) return check_result; g_free (res); items_read = items_written = 0; res = g_utf16_to_ucs4 (str2, 3, &items_read, &items_written, &err); check_result = utf16_to_ucs4_check_result (res, exp2, items_read, 3, items_written, 2, err, FALSE); if (check_result) return check_result; g_free (res); items_read = items_written = 0; res = g_utf16_to_ucs4 (str2, 4, &items_read, &items_written, &err); check_result = utf16_to_ucs4_check_result (res, exp2, items_read, 3, items_written, 2, err, FALSE); if (check_result) return check_result; g_free (res); items_read = items_written = 0; res = g_utf16_to_ucs4 (str2, 5, &items_read, &items_written, &err); check_result = utf16_to_ucs4_check_result (res, exp2, items_read, 4, items_written, 0, err, TRUE); if (check_result) return check_result; g_free (res); items_read = items_written = 0; err = 0; res = g_utf16_to_ucs4 (str3, 5, &items_read, &items_written, &err); check_result = utf16_to_ucs4_check_result (res, exp3, items_read, 1, items_written, 0, err, TRUE); if (check_result) return check_result; g_free (res); // This loop tests the bounds of the conversion algorithm current_read_index = current_write_index = 0; for (i=0;i<11;i++) { items_read = items_written = 0; err = 0; res = g_utf16_to_ucs4 (&str4[current_read_index], read_write[i*3], &items_read, &items_written, &err); check_result = utf16_to_ucs4_check_result (res, &exp4[current_write_index], items_read, read_write[(i*3)+1], items_written, read_write[(i*3)+2], err, !read_write[(i*3)+2]); if (check_result) return check_result; g_free (res); current_read_index += read_write[i*3]; current_write_index += items_written; } items_read = items_written = 0; err = 0; res = g_utf16_to_ucs4 (str5, 2, &items_read, &items_written, &err); check_result = utf16_to_ucs4_check_result (res, exp5, items_read, 2, items_written, 1, err, FALSE); if (check_result) return check_result; g_free (res); return OK; } static RESULT test_utf8_strlen (void) { gchar word1 [] = {0xC2, 0x82,0x45,0xE1, 0x81, 0x83,0x58,0xF1, 0x82, 0x82, 0x82,'\0'};//Valid, len = 5 gchar word2 [] = {0xF1, 0x82, 0x82, 0x82,0xC2, 0x82,0x45,0xE1, 0x81, 0x83,0x58,'\0'};//Valid, len = 5 gchar word3 [] = {'h','e',0xC2, 0x82,0x45,'\0'}; //Valid, len = 4 gchar word4 [] = {0x62,0xC2, 0x82,0x45,0xE1, 0x81, 0x83,0x58,'\0'}; //Valid, len = 5 glong len = 0; //Test word1 len = g_utf8_strlen (word1,-1); if (len != 5) return FAILED ("Word1 expected length of 5, but was %i", len); //Do tests with different values for max parameter. len = g_utf8_strlen (word1,1); if (len != 0) return FAILED ("Word1, max = 1, expected length of 0, but was %i", len); len = g_utf8_strlen (word1,2); if (len != 1) return FAILED ("Word1, max = 1, expected length of 1, but was %i", len); len = g_utf8_strlen (word1,3); if (len != 2) return FAILED ("Word1, max = 2, expected length of 2, but was %i", len); //Test word2 len = g_utf8_strlen (word2,-1); if (len != 5) return FAILED ("Word2 expected length of 5, but was %i", len); //Test word3 len = g_utf8_strlen (word3,-1); if (len != 4) return FAILED ("Word3 expected length of 4, but was %i", len); //Test word4 len = g_utf8_strlen (word4,-1); if (len != 5) return FAILED ("Word4 expected length of 5, but was %i", len); //Test null case len = g_utf8_strlen(NULL,0); if (len != 0) return FAILED ("Expected passing null to result in a length of 0"); return OK; } static RESULT test_utf8_get_char (void) { gchar word1 [] = {0xC2, 0x82,0x45,0xE1, 0x81, 0x83,0x58,0xF1, 0x82, 0x82, 0x82,'\0'}; //Valid, len = 5 gunichar value = g_utf8_get_char (&word1 [0]); if (value != 0x82UL) return FAILED ("Expected value of 0x82, but was %x", value); value = g_utf8_get_char (&word1 [2]); if (value != 0x45UL) return FAILED ("Expected value of 0x45, but was %x", value); value = g_utf8_get_char (&word1 [3]); if (value != 0x1043UL) return FAILED ("Expected value of 0x1043, but was %x", value); value = g_utf8_get_char (&word1 [6]); if (value != 0x58UL) return FAILED ("Expected value of 0x58, but was %x", value); value = g_utf8_get_char (&word1 [7]); if (value != 0x42082UL) return FAILED ("Expected value of 0x42082, but was %x", value); return OK; } static RESULT test_utf8_next_char (void) { gchar word1 [] = {0xC2, 0x82,0x45,0xE1, 0x81, 0x83,0x58,0xF1, 0x82, 0x82, 0x82,'\0'}; //Valid, len = 5 gchar word2 [] = {0xF1, 0x82, 0x82, 0x82,0xC2, 0x82,0x45,0xE1, 0x81, 0x83,0x58,'\0'}; //Valid, len = 5 gchar word1ExpectedValues [] = {0xC2, 0x45,0xE1, 0x58, 0xF1}; gchar word2ExpectedValues [] = {0xF1, 0xC2, 0x45, 0xE1, 0x58}; gchar* ptr = word1; gint count = 0; //Test word1 while (*ptr != 0) { if (count > 4) return FAILED ("Word1 has gone past its expected length"); if (*ptr != word1ExpectedValues[count]) return FAILED ("Word1 has an incorrect next_char at index %i", count); ptr = g_utf8_next_char (ptr); count++; } //Test word2 count = 0; ptr = word2; while (*ptr != 0) { if (count > 4) return FAILED ("Word2 has gone past its expected length"); if (*ptr != word2ExpectedValues[count]) return FAILED ("Word2 has an incorrect next_char at index %i", count); ptr = g_utf8_next_char (ptr); count++; } return OK; } static RESULT test_utf8_validate (void) { gchar invalidWord1 [] = {0xC3, 0x82, 0xC1,0x90,'\0'}; //Invalid, 1nd oct Can't be 0xC0 or 0xC1 gchar invalidWord2 [] = {0xC1, 0x89, 0x60, '\0'}; //Invalid, 1st oct can not be 0xC1 gchar invalidWord3 [] = {0xC2, 0x45,0xE1, 0x81, 0x83,0x58,'\0'}; //Invalid, oct after 0xC2 must be > 0x80 gchar validWord1 [] = {0xC2, 0x82, 0xC3,0xA0,'\0'}; //Valid gchar validWord2 [] = {0xC2, 0x82,0x45,0xE1, 0x81, 0x83,0x58,0xF1, 0x82, 0x82, 0x82,'\0'}; //Valid const gchar* end; gboolean retVal = g_utf8_validate (invalidWord1, -1, &end); if (retVal != FALSE) return FAILED ("Expected invalidWord1 to be invalid"); if (end != &invalidWord1 [2]) return FAILED ("Expected end parameter to be pointing to invalidWord1[2]"); end = NULL; retVal = g_utf8_validate (invalidWord2, -1, &end); if (retVal != FALSE) return FAILED ("Expected invalidWord2 to be invalid"); if (end != &invalidWord2 [0]) return FAILED ("Expected end parameter to be pointing to invalidWord2[0]"); end = NULL; retVal = g_utf8_validate (invalidWord3, -1, &end); if (retVal != FALSE) return FAILED ("Expected invalidWord3 to be invalid"); if (end != &invalidWord3 [0]) return FAILED ("Expected end parameter to be pointing to invalidWord3[1]"); end = NULL; retVal = g_utf8_validate (validWord1, -1, &end); if (retVal != TRUE) return FAILED ("Expected validWord1 to be valid"); if (end != &validWord1 [4]) return FAILED ("Expected end parameter to be pointing to validWord1[4]"); end = NULL; retVal = g_utf8_validate (validWord2, -1, &end); if (retVal != TRUE) return FAILED ("Expected validWord2 to be valid"); if (end != &validWord2 [11]) return FAILED ("Expected end parameter to be pointing to validWord2[11]"); return OK; } static glong utf8_byteslen (const gchar *src) { int i = 0; do { if (src [i] == '\0') return i; i++; } while (TRUE); } /* * test initialization */ static Test utf8_tests [] = { {"g_utf16_to_utf8", test_utf16_to_utf8}, {"g_utf8_to_utf16", test_utf8_to_utf16}, {"g_utf8_to_utf16_with_nuls", test_utf8_to_utf16_with_nuls}, {"g_utf8_seq", test_utf8_seq}, {"g_ucs4_to_utf16", test_ucs4_to_utf16 }, {"g_utf16_to_ucs4", test_utf16_to_ucs4 }, {"g_utf8_strlen", test_utf8_strlen }, {"g_utf8_get_char", test_utf8_get_char }, {"g_utf8_next_char", test_utf8_next_char }, {"g_utf8_validate", test_utf8_validate }, {NULL, NULL} }; DEFINE_TEST_GROUP_INIT(utf8_tests_init, utf8_tests)
#include <stdlib.h> #include "test.h" /* * g_utf16_to_utf8 */ static glong compare_strings_utf8_pos (const gchar *expected, const gchar *actual, glong size) { int i; for (i = 0; i < size; i++) if (expected [i] != actual [i]) return i; return -1; } static RESULT compare_strings_utf8_RESULT (const gchar *expected, const gchar *actual, glong size) { glong ret; ret = compare_strings_utf8_pos (expected, actual, size); if (ret < 0) return OK; return FAILED ("Incorrect output: expected '%s' but was '%s', differ at %d\n", expected, actual, ret); } static void gchar_to_gunichar2 (gunichar2 ret[], const gchar *src) { int i; for (i = 0; src [i]; i++) ret [i] = src [i]; ret [i] = 0; } static RESULT compare_utf16_to_utf8_explicit (const gchar *expected, const gunichar2 *utf16, glong len_in, glong len_out, glong size_spec) { GError *gerror; gchar* ret; RESULT result; glong in_read, out_read; result = NULL; gerror = NULL; ret = g_utf16_to_utf8 (utf16, size_spec, &in_read, &out_read, &gerror); if (gerror) { result = FAILED ("The error is %d %s\n", gerror->code, gerror->message); g_error_free (gerror); if (ret) g_free (ret); return result; } if (in_read != len_in) result = FAILED ("Read size is incorrect: expected %d but was %d\n", len_in, in_read); else if (out_read != len_out) result = FAILED ("Converted size is incorrect: expected %d but was %d\n", len_out, out_read); else result = compare_strings_utf8_RESULT (expected, ret, len_out); g_free (ret); if (result) return result; return OK; } static RESULT compare_utf16_to_utf8 (const gchar *expected, const gunichar2 *utf16, glong len_in, glong len_out) { RESULT result; result = compare_utf16_to_utf8_explicit (expected, utf16, len_in, len_out, -1); if (result != OK) return result; return compare_utf16_to_utf8_explicit (expected, utf16, len_in, len_out, len_in); } static RESULT test_utf16_to_utf8 (void) { const gchar *src0 = "", *src1 = "ABCDE", *src2 = "\xE5\xB9\xB4\x27", *src3 = "\xEF\xBC\xA1", *src4 = "\xEF\xBD\x81", *src5 = "\xF0\x90\x90\x80"; gunichar2 str0 [] = {0}, str1 [6], str2 [] = {0x5E74, 39, 0}, str3 [] = {0xFF21, 0}, str4 [] = {0xFF41, 0}, str5 [] = {0xD801, 0xDC00, 0}; RESULT result; gchar_to_gunichar2 (str1, src1); /* empty string */ result = compare_utf16_to_utf8 (src0, str0, 0, 0); if (result != OK) return result; result = compare_utf16_to_utf8 (src1, str1, 5, 5); if (result != OK) return result; result = compare_utf16_to_utf8 (src2, str2, 2, 4); if (result != OK) return result; result = compare_utf16_to_utf8 (src3, str3, 1, 3); if (result != OK) return result; result = compare_utf16_to_utf8 (src4, str4, 1, 3); if (result != OK) return result; result = compare_utf16_to_utf8 (src5, str5, 2, 4); if (result != OK) return result; return OK; } /* * g_utf8_to_utf16 */ static glong compare_strings_utf16_pos (const gunichar2 *expected, const gunichar2 *actual, glong size) { int i; for (i = 0; i < size; i++) if (expected [i] != actual [i]) return i; return -1; } static RESULT compare_strings_utf16_RESULT (const gunichar2 *expected, const gunichar2 *actual, glong size) { glong ret; ret = compare_strings_utf16_pos (expected, actual, size); if (ret < 0) return OK; return FAILED ("Incorrect output: expected '%s' but was '%s', differ at %d ('%c' x '%c')\n", expected, actual, ret, expected [ret], actual [ret]); } #if !defined(EGLIB_TESTS) #define eg_utf8_to_utf16_with_nuls g_utf8_to_utf16 #endif static RESULT compare_utf8_to_utf16_explicit (const gunichar2 *expected, const gchar *utf8, glong len_in, glong len_out, glong size_spec, gboolean include_nuls) { GError *gerror; gunichar2* ret; RESULT result; glong in_read, out_read; result = NULL; gerror = NULL; if (include_nuls) ret = eg_utf8_to_utf16_with_nuls (utf8, size_spec, &in_read, &out_read, &gerror); else ret = g_utf8_to_utf16 (utf8, size_spec, &in_read, &out_read, &gerror); if (gerror) { result = FAILED ("The error is %d %s\n", gerror->code, gerror->message); g_error_free (gerror); if (ret) g_free (ret); return result; } if (in_read != len_in) result = FAILED ("Read size is incorrect: expected %d but was %d\n", len_in, in_read); else if (out_read != len_out) result = FAILED ("Converted size is incorrect: expected %d but was %d\n", len_out, out_read); else result = compare_strings_utf16_RESULT (expected, ret, len_out); g_free (ret); if (result) return result; return OK; } static RESULT compare_utf8_to_utf16_general (const gunichar2 *expected, const gchar *utf8, glong len_in, glong len_out, gboolean include_nuls) { RESULT result; result = compare_utf8_to_utf16_explicit (expected, utf8, len_in, len_out, -1, include_nuls); if (result != OK) return result; return compare_utf8_to_utf16_explicit (expected, utf8, len_in, len_out, len_in, include_nuls); } static RESULT compare_utf8_to_utf16 (const gunichar2 *expected, const gchar *utf8, glong len_in, glong len_out) { return compare_utf8_to_utf16_general (expected, utf8, len_in, len_out, FALSE); } static RESULT compare_utf8_to_utf16_with_nuls (const gunichar2 *expected, const gchar *utf8, glong len_in, glong len_out) { return compare_utf8_to_utf16_explicit (expected, utf8, len_in, len_out, len_in, TRUE); } static RESULT test_utf8_seq (void) { const gchar *src = "\xE5\xB9\xB4\x27"; glong in_read, out_read; //gunichar2 expected [6]; GError *gerror = NULL; gunichar2 *dst; //printf ("got: %s\n", src); dst = g_utf8_to_utf16 (src, (glong)strlen (src), &in_read, &out_read, &gerror); if (gerror != NULL){ return gerror->message; } if (in_read != 4) { return FAILED ("in_read is expected to be 4 but was %d\n", in_read); } if (out_read != 2) { return FAILED ("out_read is expected to be 2 but was %d\n", out_read); } g_free (dst); return OK; } static RESULT test_utf8_to_utf16 (void) { const gchar *src0 = "", *src1 = "ABCDE", *src2 = "\xE5\xB9\xB4\x27", *src3 = "\xEF\xBC\xA1", *src4 = "\xEF\xBD\x81"; gunichar2 str0 [] = {0}, str1 [6], str2 [] = {0x5E74, 39, 0}, str3 [] = {0xFF21, 0}, str4 [] = {0xFF41, 0}; RESULT result; gchar_to_gunichar2 (str1, src1); /* empty string */ result = compare_utf8_to_utf16 (str0, src0, 0, 0); if (result != OK) return result; result = compare_utf8_to_utf16 (str1, src1, 5, 5); if (result != OK) return result; result = compare_utf8_to_utf16 (str2, src2, 4, 2); if (result != OK) return result; result = compare_utf8_to_utf16 (str3, src3, 3, 1); if (result != OK) return result; result = compare_utf8_to_utf16 (str4, src4, 3, 1); if (result != OK) return result; return OK; } static RESULT test_utf8_to_utf16_with_nuls (void) { const gchar *src0 = "", *src1 = "AB\0DE", *src2 = "\xE5\xB9\xB4\x27", *src3 = "\xEF\xBC\xA1", *src4 = "\xEF\xBD\x81"; gunichar2 str0 [] = {0}, str1 [] = {'A', 'B', 0, 'D', 'E', 0}, str2 [] = {0x5E74, 39, 0}, str3 [] = {0xFF21, 0}, str4 [] = {0xFF41, 0}; RESULT result; #if !defined(EGLIB_TESTS) return OK; #endif /* implicit length is forbidden */ if (eg_utf8_to_utf16_with_nuls (src1, -1, NULL, NULL, NULL) != NULL) return FAILED ("explicit nulls must fail with -1 length\n"); /* empty string */ result = compare_utf8_to_utf16_with_nuls (str0, src0, 0, 0); if (result != OK) return result; result = compare_utf8_to_utf16_with_nuls (str1, src1, 5, 5); if (result != OK) return result; result = compare_utf8_to_utf16_with_nuls (str2, src2, 4, 2); if (result != OK) return result; result = compare_utf8_to_utf16_with_nuls (str3, src3, 3, 1); if (result != OK) return result; result = compare_utf8_to_utf16_with_nuls (str4, src4, 3, 1); if (result != OK) return result; return OK; } static RESULT ucs4_to_utf16_check_result (const gunichar2 *result_str, const gunichar2 *expected_str, glong result_items_read, glong expected_items_read, glong result_items_written, glong expected_items_written, GError* result_error, gboolean expect_error) { glong i; if (result_items_read != expected_items_read) return FAILED("Incorrect number of items read; expected %d, got %d", expected_items_read, result_items_read); if (result_items_written != expected_items_written) return FAILED("Incorrect number of items written; expected %d, got %d", expected_items_written, result_items_written); if (result_error && !expect_error) return FAILED("There should not be an error code."); if (!result_error && expect_error) return FAILED("Unexpected error object."); if (expect_error && result_str) return FAILED("NULL should be returned when an error occurs."); if (!expect_error && !result_str) return FAILED("When no error occurs NULL should not be returned."); for (i=0; i<expected_items_written;i++) { if (result_str [i] != expected_str [i]) return FAILED("Incorrect value %d at index %d", result_str [i], i); } if (result_str && result_str[expected_items_written] != '\0') return FAILED("Null termination not found at the end of the string."); return OK; } static RESULT test_ucs4_to_utf16 (void) { static gunichar str1[12] = {'H','e','l','l','o',' ','W','o','r','l','d','\0'}; static gunichar2 exp1[12] = {'H','e','l','l','o',' ','W','o','r','l','d','\0'}; static gunichar str2[3] = {'h',0x80000000,'\0'}; static gunichar2 exp2[2] = {'h','\0'}; static gunichar str3[3] = {'h',0xDA00,'\0'}; static gunichar str4[3] = {'h',0x10FFFF,'\0'}; static gunichar2 exp4[4] = {'h',0xdbff,0xdfff,'\0'}; static gunichar str5[7] = {0xD7FF,0xD800,0xDFFF,0xE000,0x110000,0x10FFFF,'\0'}; static gunichar2 exp5[5] = {0xD7FF,0xE000,0xdbff,0xdfff,'\0'}; static gunichar str6[2] = {0x10400, '\0'}; static gunichar2 exp6[3] = {0xD801, 0xDC00, '\0'}; static glong read_write[12] = {1,1,0,0,0,0,1,1,0,0,1,2}; gunichar2* res; glong items_read, items_written, current_write_index; GError* err=0; RESULT check_result; glong i; res = g_ucs4_to_utf16 (str1, 12, &items_read, &items_written, &err); check_result = ucs4_to_utf16_check_result (res, exp1, items_read, 11, items_written, 11, err, FALSE); if (check_result) return check_result; g_free (res); items_read = items_written = 0; res = g_ucs4_to_utf16 (str2, 0, &items_read, &items_written, &err); check_result = ucs4_to_utf16_check_result (res, exp2, items_read, 0, items_written, 0, err, FALSE); if (check_result) return check_result; g_free (res); items_read = items_written = 0; res = g_ucs4_to_utf16 (str2, 1, &items_read, &items_written, &err); check_result = ucs4_to_utf16_check_result (res, exp2, items_read, 1, items_written, 1, err, FALSE); if (check_result) return check_result; g_free (res); items_read = items_written = 0; res = g_ucs4_to_utf16 (str2, 2, &items_read, &items_written, &err); check_result = ucs4_to_utf16_check_result (res, 0, items_read, 1, items_written, 0, err, TRUE); g_free (res); if (check_result) return check_result; items_read = items_written = 0; err = 0; res = g_ucs4_to_utf16 (str3, 2, &items_read, &items_written, &err); check_result = ucs4_to_utf16_check_result (res, 0, items_read, 1, items_written, 0, err, TRUE); if (check_result) return check_result; g_free (res); items_read = items_written = 0; err = 0; res = g_ucs4_to_utf16 (str4, 5, &items_read, &items_written, &err); check_result = ucs4_to_utf16_check_result (res, exp4, items_read, 2, items_written, 3, err, FALSE); if (check_result) return check_result; g_free (res); // This loop tests the bounds of the conversion algorithm current_write_index = 0; for (i=0;i<6;i++) { items_read = items_written = 0; err = 0; res = g_ucs4_to_utf16 (&str5[i], 1, &items_read, &items_written, &err); check_result = ucs4_to_utf16_check_result (res, &exp5[current_write_index], items_read, read_write[i*2], items_written, read_write[(i*2)+1], err, !read_write[(i*2)+1]); if (check_result) return check_result; g_free (res); current_write_index += items_written; } items_read = items_written = 0; err = 0; res = g_ucs4_to_utf16 (str6, 1, &items_read, &items_written, &err); check_result = ucs4_to_utf16_check_result (res, exp6, items_read, 1, items_written, 2, err, FALSE); if (check_result) return check_result; g_free (res); return OK; } static RESULT utf16_to_ucs4_check_result (const gunichar *result_str, const gunichar *expected_str, glong result_items_read, glong expected_items_read, glong result_items_written, glong expected_items_written, GError* result_error, gboolean expect_error) { glong i; if (result_items_read != expected_items_read) return FAILED("Incorrect number of items read; expected %d, got %d", expected_items_read, result_items_read); if (result_items_written != expected_items_written) return FAILED("Incorrect number of items written; expected %d, got %d", expected_items_written, result_items_written); if (result_error && !expect_error) return FAILED("There should not be an error code."); if (!result_error && expect_error) return FAILED("Unexpected error object."); if (expect_error && result_str) return FAILED("NULL should be returned when an error occurs."); if (!expect_error && !result_str) return FAILED("When no error occurs NULL should not be returned."); for (i=0; i<expected_items_written;i++) { if (result_str [i] != expected_str [i]) return FAILED("Incorrect value %d at index %d", result_str [i], i); } if (result_str && result_str[expected_items_written] != '\0') return FAILED("Null termination not found at the end of the string."); return OK; } static RESULT test_utf16_to_ucs4 (void) { static gunichar2 str1[12] = {'H','e','l','l','o',' ','W','o','r','l','d','\0'}; static gunichar exp1[12] = {'H','e','l','l','o',' ','W','o','r','l','d','\0'}; static gunichar2 str2[7] = {'H', 0xD800, 0xDC01,0xD800,0xDBFF,'l','\0'}; static gunichar exp2[3] = {'H',0x00010001,'\0'}; static gunichar2 str3[4] = {'H', 0xDC00 ,'l','\0'}; static gunichar exp3[2] = {'H','\0'}; static gunichar2 str4[20] = {0xDC00,0xDFFF,0xDFF,0xD800,0xDBFF,0xD800,0xDC00,0xD800,0xDFFF, 0xD800,0xE000,0xDBFF,0xDBFF,0xDBFF,0xDC00,0xDBFF,0xDFFF,0xDBFF,0xE000,'\0'}; static gunichar exp4[6] = {0xDFF,0x10000,0x103ff,0x10fc00,0x10FFFF,'\0'}; static gunichar2 str5[3] = {0xD801, 0xDC00, 0}; static gunichar exp5[2] = {0x10400, 0}; static glong read_write[33] = {1,0,0,1,0,0,1,1,1,2,1,0,2,2,1,2,2,1,2,1,0,2,1,0,2,2,1,2,2,1,2,1,0}; gunichar* res; glong items_read, items_written, current_read_index,current_write_index; GError* err=0; RESULT check_result; glong i; res = g_utf16_to_ucs4 (str1, 12, &items_read, &items_written, &err); check_result = utf16_to_ucs4_check_result (res, exp1, items_read, 11, items_written, 11, err, FALSE); if (check_result) return check_result; g_free (res); items_read = items_written = 0; res = g_utf16_to_ucs4 (str2, 0, &items_read, &items_written, &err); check_result = utf16_to_ucs4_check_result (res, exp2, items_read, 0, items_written, 0, err, FALSE); if (check_result) return check_result; g_free (res); items_read = items_written = 0; res = g_utf16_to_ucs4 (str2, 1, &items_read, &items_written, &err); check_result = utf16_to_ucs4_check_result (res, exp2, items_read, 1, items_written, 1, err, FALSE); if (check_result) return check_result; g_free (res); items_read = items_written = 0; res = g_utf16_to_ucs4 (str2, 2, &items_read, &items_written, &err); check_result = utf16_to_ucs4_check_result (res, exp2, items_read, 1, items_written, 1, err, FALSE); if (check_result) return check_result; g_free (res); items_read = items_written = 0; res = g_utf16_to_ucs4 (str2, 3, &items_read, &items_written, &err); check_result = utf16_to_ucs4_check_result (res, exp2, items_read, 3, items_written, 2, err, FALSE); if (check_result) return check_result; g_free (res); items_read = items_written = 0; res = g_utf16_to_ucs4 (str2, 4, &items_read, &items_written, &err); check_result = utf16_to_ucs4_check_result (res, exp2, items_read, 3, items_written, 2, err, FALSE); if (check_result) return check_result; g_free (res); items_read = items_written = 0; res = g_utf16_to_ucs4 (str2, 5, &items_read, &items_written, &err); check_result = utf16_to_ucs4_check_result (res, exp2, items_read, 4, items_written, 0, err, TRUE); if (check_result) return check_result; g_free (res); items_read = items_written = 0; err = 0; res = g_utf16_to_ucs4 (str3, 5, &items_read, &items_written, &err); check_result = utf16_to_ucs4_check_result (res, exp3, items_read, 1, items_written, 0, err, TRUE); if (check_result) return check_result; g_free (res); // This loop tests the bounds of the conversion algorithm current_read_index = current_write_index = 0; for (i=0;i<11;i++) { items_read = items_written = 0; err = 0; res = g_utf16_to_ucs4 (&str4[current_read_index], read_write[i*3], &items_read, &items_written, &err); check_result = utf16_to_ucs4_check_result (res, &exp4[current_write_index], items_read, read_write[(i*3)+1], items_written, read_write[(i*3)+2], err, !read_write[(i*3)+2]); if (check_result) return check_result; g_free (res); current_read_index += read_write[i*3]; current_write_index += items_written; } items_read = items_written = 0; err = 0; res = g_utf16_to_ucs4 (str5, 2, &items_read, &items_written, &err); check_result = utf16_to_ucs4_check_result (res, exp5, items_read, 2, items_written, 1, err, FALSE); if (check_result) return check_result; g_free (res); return OK; } static RESULT test_utf8_strlen (void) { gchar word1 [] = {0xC2, 0x82,0x45,0xE1, 0x81, 0x83,0x58,0xF1, 0x82, 0x82, 0x82,'\0'};//Valid, len = 5 gchar word2 [] = {0xF1, 0x82, 0x82, 0x82,0xC2, 0x82,0x45,0xE1, 0x81, 0x83,0x58,'\0'};//Valid, len = 5 gchar word3 [] = {'h','e',0xC2, 0x82,0x45,'\0'}; //Valid, len = 4 gchar word4 [] = {0x62,0xC2, 0x82,0x45,0xE1, 0x81, 0x83,0x58,'\0'}; //Valid, len = 5 glong len = 0; //Test word1 len = g_utf8_strlen (word1,-1); if (len != 5) return FAILED ("Word1 expected length of 5, but was %i", len); //Do tests with different values for max parameter. len = g_utf8_strlen (word1,1); if (len != 0) return FAILED ("Word1, max = 1, expected length of 0, but was %i", len); len = g_utf8_strlen (word1,2); if (len != 1) return FAILED ("Word1, max = 1, expected length of 1, but was %i", len); len = g_utf8_strlen (word1,3); if (len != 2) return FAILED ("Word1, max = 2, expected length of 2, but was %i", len); //Test word2 len = g_utf8_strlen (word2,-1); if (len != 5) return FAILED ("Word2 expected length of 5, but was %i", len); //Test word3 len = g_utf8_strlen (word3,-1); if (len != 4) return FAILED ("Word3 expected length of 4, but was %i", len); //Test word4 len = g_utf8_strlen (word4,-1); if (len != 5) return FAILED ("Word4 expected length of 5, but was %i", len); //Test null case len = g_utf8_strlen(NULL,0); if (len != 0) return FAILED ("Expected passing null to result in a length of 0"); return OK; } static RESULT test_utf8_get_char (void) { gchar word1 [] = {0xC2, 0x82,0x45,0xE1, 0x81, 0x83,0x58,0xF1, 0x82, 0x82, 0x82,'\0'}; //Valid, len = 5 gunichar value = g_utf8_get_char (&word1 [0]); if (value != 0x82UL) return FAILED ("Expected value of 0x82, but was %x", value); value = g_utf8_get_char (&word1 [2]); if (value != 0x45UL) return FAILED ("Expected value of 0x45, but was %x", value); value = g_utf8_get_char (&word1 [3]); if (value != 0x1043UL) return FAILED ("Expected value of 0x1043, but was %x", value); value = g_utf8_get_char (&word1 [6]); if (value != 0x58UL) return FAILED ("Expected value of 0x58, but was %x", value); value = g_utf8_get_char (&word1 [7]); if (value != 0x42082UL) return FAILED ("Expected value of 0x42082, but was %x", value); return OK; } static RESULT test_utf8_next_char (void) { gchar word1 [] = {0xC2, 0x82,0x45,0xE1, 0x81, 0x83,0x58,0xF1, 0x82, 0x82, 0x82,'\0'}; //Valid, len = 5 gchar word2 [] = {0xF1, 0x82, 0x82, 0x82,0xC2, 0x82,0x45,0xE1, 0x81, 0x83,0x58,'\0'}; //Valid, len = 5 gchar word1ExpectedValues [] = {0xC2, 0x45,0xE1, 0x58, 0xF1}; gchar word2ExpectedValues [] = {0xF1, 0xC2, 0x45, 0xE1, 0x58}; gchar* ptr = word1; gint count = 0; //Test word1 while (*ptr != 0) { if (count > 4) return FAILED ("Word1 has gone past its expected length"); if (*ptr != word1ExpectedValues[count]) return FAILED ("Word1 has an incorrect next_char at index %i", count); ptr = g_utf8_next_char (ptr); count++; } //Test word2 count = 0; ptr = word2; while (*ptr != 0) { if (count > 4) return FAILED ("Word2 has gone past its expected length"); if (*ptr != word2ExpectedValues[count]) return FAILED ("Word2 has an incorrect next_char at index %i", count); ptr = g_utf8_next_char (ptr); count++; } return OK; } static RESULT test_utf8_validate (void) { gchar invalidWord1 [] = {0xC3, 0x82, 0xC1,0x90,'\0'}; //Invalid, 1nd oct Can't be 0xC0 or 0xC1 gchar invalidWord2 [] = {0xC1, 0x89, 0x60, '\0'}; //Invalid, 1st oct can not be 0xC1 gchar invalidWord3 [] = {0xC2, 0x45,0xE1, 0x81, 0x83,0x58,'\0'}; //Invalid, oct after 0xC2 must be > 0x80 gchar validWord1 [] = {0xC2, 0x82, 0xC3,0xA0,'\0'}; //Valid gchar validWord2 [] = {0xC2, 0x82,0x45,0xE1, 0x81, 0x83,0x58,0xF1, 0x82, 0x82, 0x82,'\0'}; //Valid const gchar* end; gboolean retVal = g_utf8_validate (invalidWord1, -1, &end); if (retVal != FALSE) return FAILED ("Expected invalidWord1 to be invalid"); if (end != &invalidWord1 [2]) return FAILED ("Expected end parameter to be pointing to invalidWord1[2]"); end = NULL; retVal = g_utf8_validate (invalidWord2, -1, &end); if (retVal != FALSE) return FAILED ("Expected invalidWord2 to be invalid"); if (end != &invalidWord2 [0]) return FAILED ("Expected end parameter to be pointing to invalidWord2[0]"); end = NULL; retVal = g_utf8_validate (invalidWord3, -1, &end); if (retVal != FALSE) return FAILED ("Expected invalidWord3 to be invalid"); if (end != &invalidWord3 [0]) return FAILED ("Expected end parameter to be pointing to invalidWord3[1]"); end = NULL; retVal = g_utf8_validate (validWord1, -1, &end); if (retVal != TRUE) return FAILED ("Expected validWord1 to be valid"); if (end != &validWord1 [4]) return FAILED ("Expected end parameter to be pointing to validWord1[4]"); end = NULL; retVal = g_utf8_validate (validWord2, -1, &end); if (retVal != TRUE) return FAILED ("Expected validWord2 to be valid"); if (end != &validWord2 [11]) return FAILED ("Expected end parameter to be pointing to validWord2[11]"); return OK; } static glong utf8_byteslen (const gchar *src) { int i = 0; do { if (src [i] == '\0') return i; i++; } while (TRUE); } /* * test initialization */ static Test utf8_tests [] = { {"g_utf16_to_utf8", test_utf16_to_utf8}, {"g_utf8_to_utf16", test_utf8_to_utf16}, {"g_utf8_to_utf16_with_nuls", test_utf8_to_utf16_with_nuls}, {"g_utf8_seq", test_utf8_seq}, {"g_ucs4_to_utf16", test_ucs4_to_utf16 }, {"g_utf16_to_ucs4", test_utf16_to_ucs4 }, {"g_utf8_strlen", test_utf8_strlen }, {"g_utf8_get_char", test_utf8_get_char }, {"g_utf8_next_char", test_utf8_next_char }, {"g_utf8_validate", test_utf8_validate }, {NULL, NULL} }; DEFINE_TEST_GROUP_INIT(utf8_tests_init, utf8_tests)
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./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>Gets whether a given regular expression method is supported by the code generator.</summary> private static bool SupportsCodeGeneration(RegexMethod rm, out string? reason) { RegexNode root = rm.Tree.Root; if (!root.SupportsCompilation(out reason)) { return false; } if (ExceedsMaxDepthForSimpleCodeGeneration(root, allowedDepth: 40)) { // Deep RegexNode trees can result in emitting C# code that exceeds C# compiler // limitations, leading to "CS8078: An expression is too long or complex to compile". // Place an artificial limit on max tree depth in order to mitigate such issues. // The allowed depth can be tweaked as needed;its exceedingly rare to find // expressions with such deep trees. reason = "the regex will result in code that may exceed C# compiler limits"; return false; } return true; static bool ExceedsMaxDepthForSimpleCodeGeneration(RegexNode node, int allowedDepth) { if (allowedDepth <= 0) { return true; } int childCount = node.ChildCount(); for (int i = 0; i < childCount; i++) { if (ExceedsMaxDepthForSimpleCodeGeneration(node.Child(i), allowedDepth - 1)) { return true; } } return false; } } /// <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 (!SupportsCodeGeneration(rm, 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) { 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 == text.Length)")) { writer.WriteLine("return;"); } writer.WriteLine(); writer.WriteLine("base.runtextpos++;"); } } /// <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; // 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 switch { 0 => "if (pos <= inputSpan.Length)", 1 => "if (pos < inputSpan.Length)", _ => $"if (pos < inputSpan.Length - {minRequiredLength - 1})" }; 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(regexTree.FindOptimizations.LeadingCaseSensitivePrefix); break; case FindNextStartingPositionMode.FixedSets_LeftToRight_CaseSensitive: case FindNextStartingPositionMode.FixedSets_LeftToRight_CaseInsensitive: case FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseSensitive: case FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseInsensitive: Debug.Assert(regexTree.FindOptimizations.FixedDistanceSets is { Count: > 0 }); EmitFixedSet(); 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 = inputSpan.Length;"); 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)")) { Goto(NoStartingPositionFound); } writer.WriteLine("return true;"); return true; case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_Start: writer.WriteLine("// Start \\G anchor"); using (EmitBlock(writer, "if (pos > base.runtextstart)")) { 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)")) { 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)")) { writer.WriteLine("base.runtextpos = inputSpan.Length;"); } 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(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 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() { 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 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.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() { if (sliceStaticPos > 0) { EmitAdd(writer, "pos", sliceStaticPos); writer.WriteLine($"{sliceSpan} = {sliceSpan}.Slice({sliceStaticPos});"); sliceStaticPos = 0; } } // 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 = 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});"); if (!IsCaseInsensitive(node)) { // 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); } } // 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 lookahead. 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 lookahead; however, a positive lookahead 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 lookahead. 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 lookahead. 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 lookahead assertion. void EmitPositiveLookaheadAssertion(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.PositiveLookaround, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); // Save off pos. We'll need to reset this upon successful completion of the lookahead. string startingPos = ReserveName("positivelookahead_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 lookahead. writer.WriteLine(); writer.WriteLine($"pos = {startingPos};"); SliceInputSpan(writer); sliceStaticPos = startingSliceStaticPos; } // Emits the code to handle a negative lookahead assertion. void EmitNegativeLookaheadAssertion(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.NegativeLookaround, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); string originalDoneLabel = doneLabel; // Save off pos. We'll need to reset this upon successful completion of the lookahead. string startingPos = ReserveName("negativelookahead_starting_pos"); writer.WriteLine($"int {startingPos} = pos;"); int startingSliceStaticPos = sliceStaticPos; string negativeLookaheadDoneLabel = ReserveName("NegativeLookaheadMatch"); 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 lookahead, which actually // means failure for a _negative_ lookahead, so we need to jump to the original done. writer.WriteLine(); Goto(originalDoneLabel); writer.WriteLine(); // Failures (success for a negative lookahead) jump here. MarkLabel(negativeLookaheadDoneLabel, emitSemicolon: false); // After the child completes in failure (success for negative lookahead), 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; } // 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: EmitPositiveLookaheadAssertion(node); break; case RegexNodeKind.NegativeLookaround: EmitNegativeLookaheadAssertion(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 (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}"); // This only emits a single check, but it's called from the looping constructs in a loop // to generate the code for a single check, so we map those looping constructs to the // appropriate single check. string expr = $"{sliceSpan}[{Sum(sliceStaticPos, offset)}]"; 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 { using (EmitBlock(writer, emitLengthCheck ? $"if ({SpanLengthCheck(1, offset)} || {expr})" : $"if ({expr})")) { Goto(doneLabel); } } sliceStaticPos++; } // 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(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: if (sliceStaticPos > 0) { using (EmitBlock(writer, $"if ({sliceSpan}[{sliceStaticPos - 1}] != '\\n')")) { Goto(doneLabel); } } else { // We can't use our slice in this case, because we'd need to access slice[-1], so we access the inputSpan field directly: using (EmitBlock(writer, $"if (pos > 0 && inputSpan[pos - 1] != '\\n')")) { Goto(doneLabel); } } break; case RegexNodeKind.End: using (EmitBlock(writer, $"if ({IsSliceLengthGreaterThanSliceStaticPos()})")) { Goto(doneLabel); } break; case RegexNodeKind.EndZ: writer.WriteLine($"if ({sliceSpan}.Length > {sliceStaticPos + 1} || ({IsSliceLengthGreaterThanSliceStaticPos()} && {sliceSpan}[{sliceStaticPos}] != '\\n'))"); using (EmitBlock(writer, null)) { Goto(doneLabel); } break; case RegexNodeKind.Eol: using (EmitBlock(writer, $"if ({IsSliceLengthGreaterThanSliceStaticPos()} && {sliceSpan}[{sliceStaticPos}] != '\\n')")) { Goto(doneLabel); } break; string IsSliceLengthGreaterThanSliceStaticPos() => sliceStaticPos == 0 ? $"!{sliceSpan}.IsEmpty" : $"{sliceSpan}.Length > {sliceStaticPos}"; } } // 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); } void EmitMultiCharString(string str, bool caseInsensitive, bool emitLengthCheck) { Debug.Assert(str.Length >= 2); 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;"); // 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, 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 (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} >= {endingPos})")) { Goto(doneLabel); } writer.WriteLine($"pos = --{endingPos};"); } 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 (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; 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); return; } 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; Span<char> setChars = stackalloc char[5]; // 5 is max optimized by IndexOfAny today int numSetChars = 0; string iterationLocal = ReserveName("iteration"); 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. writer.WriteLine($"{sliceSpan} = {sliceSpan}.Slice({iterationLocal});"); 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); string expr = $"{sliceSpan}[{sliceStaticPos}]"; 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 = sliceStaticPos != 0 ? $"(uint){sliceSpan}.Length > (uint){sliceStaticPos}" : $"!{sliceSpan}.IsEmpty"; using (EmitBlock(writer, $"if ({spaceAvailable} && {expr})")) { writer.WriteLine($"{sliceSpan} = {sliceSpan}.Slice(1);"); 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) => 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!)}.", 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)}.", 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)}.", RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Onelazy => $"Match {Literal(node.Ch)} {DescribeLoop(node, analysis)}.", RegexNodeKind.NegativeLookaround => $"Zero-width negative lookahead assertion.", RegexNodeKind.Backreference => $"Match the same text as matched by the {DescribeCapture(node.M, analysis)}.", RegexNodeKind.PositiveLookaround => $"Zero-width positive lookahead assertion.", RegexNodeKind.Set => $"Match {DescribeSet(node.Str!)}.", 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); 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 } } }
1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/libraries/System.Text.RegularExpressions/gen/RegexGenerator.Parser.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 Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.DotnetRuntime.Extensions; using System; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Threading; namespace System.Text.RegularExpressions.Generator { public partial class RegexGenerator { private const string RegexName = "System.Text.RegularExpressions.Regex"; private const string RegexGeneratorAttributeName = "System.Text.RegularExpressions.RegexGeneratorAttribute"; private static bool IsSyntaxTargetForGeneration(SyntaxNode node, CancellationToken cancellationToken) => // We don't have a semantic model here, so the best we can do is say whether there are any attributes. node is MethodDeclarationSyntax { AttributeLists: { Count: > 0 } }; private static bool IsSemanticTargetForGeneration(SemanticModel semanticModel, MethodDeclarationSyntax methodDeclarationSyntax, CancellationToken cancellationToken) { foreach (AttributeListSyntax attributeListSyntax in methodDeclarationSyntax.AttributeLists) { foreach (AttributeSyntax attributeSyntax in attributeListSyntax.Attributes) { if (semanticModel.GetSymbolInfo(attributeSyntax, cancellationToken).Symbol is IMethodSymbol attributeSymbol && attributeSymbol.ContainingType.ToDisplayString() == RegexGeneratorAttributeName) { return true; } } } return false; } // Returns null if nothing to do, Diagnostic if there's an error to report, or RegexType if the type was analyzed successfully. private static object? GetSemanticTargetForGeneration(GeneratorSyntaxContext context, CancellationToken cancellationToken) { var methodSyntax = (MethodDeclarationSyntax)context.Node; SemanticModel sm = context.SemanticModel; if (!IsSemanticTargetForGeneration(sm, methodSyntax, cancellationToken)) { return null; } Compilation compilation = sm.Compilation; INamedTypeSymbol? regexSymbol = compilation.GetBestTypeByMetadataName(RegexName); INamedTypeSymbol? regexGeneratorAttributeSymbol = compilation.GetBestTypeByMetadataName(RegexGeneratorAttributeName); if (regexSymbol is null || regexGeneratorAttributeSymbol is null) { // Required types aren't available return null; } TypeDeclarationSyntax? typeDec = methodSyntax.Parent as TypeDeclarationSyntax; if (typeDec is null) { return null; } IMethodSymbol? regexMethodSymbol = sm.GetDeclaredSymbol(methodSyntax, cancellationToken) as IMethodSymbol; if (regexMethodSymbol is null) { return null; } ImmutableArray<AttributeData>? boundAttributes = regexMethodSymbol.GetAttributes(); if (boundAttributes is null || boundAttributes.Value.Length == 0) { return null; } bool attributeFound = false; string? pattern = null; int? options = null; int? matchTimeout = null; foreach (AttributeData attributeData in boundAttributes) { if (attributeData.AttributeClass?.Equals(regexGeneratorAttributeSymbol) != true) { continue; } if (attributeData.ConstructorArguments.Any(ca => ca.Kind == TypedConstantKind.Error)) { return Diagnostic.Create(DiagnosticDescriptors.InvalidRegexGeneratorAttribute, methodSyntax.GetLocation()); } if (pattern is not null) { return Diagnostic.Create(DiagnosticDescriptors.MultipleRegexGeneratorAttributes, methodSyntax.GetLocation()); } ImmutableArray<TypedConstant> items = attributeData.ConstructorArguments; if (items.Length == 0 || items.Length > 3) { return Diagnostic.Create(DiagnosticDescriptors.InvalidRegexGeneratorAttribute, methodSyntax.GetLocation()); } attributeFound = true; pattern = items[0].Value as string; if (items.Length >= 2) { options = items[1].Value as int?; if (items.Length == 3) { matchTimeout = items[2].Value as int?; } } } if (!attributeFound) { return null; } if (pattern is null) { return Diagnostic.Create(DiagnosticDescriptors.InvalidRegexArguments, methodSyntax.GetLocation(), "(null)"); } if (!regexMethodSymbol.IsPartialDefinition || regexMethodSymbol.Parameters.Length != 0 || regexMethodSymbol.Arity != 0 || !regexMethodSymbol.ReturnType.Equals(regexSymbol)) { return Diagnostic.Create(DiagnosticDescriptors.RegexMethodMustHaveValidSignature, methodSyntax.GetLocation()); } if (typeDec.SyntaxTree.Options is CSharpParseOptions { LanguageVersion: <= LanguageVersion.CSharp10 }) { return Diagnostic.Create(DiagnosticDescriptors.InvalidLangVersion, methodSyntax.GetLocation()); } RegexOptions regexOptions = RegexOptions.Compiled | (options is not null ? (RegexOptions)options : RegexOptions.None); // TODO: This is going to include the culture that's current at the time of compilation. // What should we do about that? We could: // - say not specifying CultureInvariant is invalid if anything about options or the expression will look at culture // - fall back to not generating source if it's not specified // - just use whatever culture is present at build time // - devise a new way of not using the culture present at build time // - ... CultureInfo culture = (regexOptions & RegexOptions.CultureInvariant) != 0 ? CultureInfo.InvariantCulture : CultureInfo.CurrentCulture; // Validate the options const RegexOptions SupportedOptions = RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.ECMAScript | RegexOptions.ExplicitCapture | RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline | RegexOptions.NonBacktracking | RegexOptions.RightToLeft | RegexOptions.Singleline; if ((regexOptions & ~SupportedOptions) != 0) { return Diagnostic.Create(DiagnosticDescriptors.InvalidRegexArguments, methodSyntax.GetLocation(), "options"); } // Validate the timeout if (matchTimeout is 0 or < -1) { return Diagnostic.Create(DiagnosticDescriptors.InvalidRegexArguments, methodSyntax.GetLocation(), "matchTimeout"); } // Parse the input pattern RegexTree tree; try { tree = RegexParser.Parse(pattern, regexOptions, culture); } catch (Exception e) { return Diagnostic.Create(DiagnosticDescriptors.InvalidRegexArguments, methodSyntax.GetLocation(), e.Message); } // Determine the namespace the class is declared in, if any string? ns = regexMethodSymbol.ContainingType?.ContainingNamespace?.ToDisplayString( SymbolDisplayFormat.FullyQualifiedFormat.WithGlobalNamespaceStyle(SymbolDisplayGlobalNamespaceStyle.Omitted)); var regexMethod = new RegexMethod( methodSyntax, regexMethodSymbol.Name, methodSyntax.Modifiers.ToString(), pattern, regexOptions, matchTimeout ?? Timeout.Infinite, tree); var regexType = new RegexType( regexMethod, typeDec is RecordDeclarationSyntax rds ? $"{typeDec.Keyword.ValueText} {rds.ClassOrStructKeyword}" : typeDec.Keyword.ValueText, ns ?? string.Empty, $"{typeDec.Identifier}{typeDec.TypeParameterList}"); RegexType current = regexType; var parent = typeDec.Parent as TypeDeclarationSyntax; while (parent is not null && IsAllowedKind(parent.Kind())) { current.ParentClass = new RegexType( null, parent is RecordDeclarationSyntax rds2 ? $"{parent.Keyword.ValueText} {rds2.ClassOrStructKeyword}" : parent.Keyword.ValueText, ns ?? string.Empty, $"{parent.Identifier}{parent.TypeParameterList}"); current = current.ParentClass; parent = parent.Parent as TypeDeclarationSyntax; } return regexType; static bool IsAllowedKind(SyntaxKind kind) => kind == SyntaxKind.ClassDeclaration || kind == SyntaxKind.StructDeclaration || kind == SyntaxKind.RecordDeclaration || kind == SyntaxKind.RecordStructDeclaration || kind == SyntaxKind.InterfaceDeclaration; } /// <summary>A regex method.</summary> internal sealed record RegexMethod(MethodDeclarationSyntax MethodSyntax, string MethodName, string Modifiers, string Pattern, RegexOptions Options, int MatchTimeout, RegexTree Tree); /// <summary>A type holding a regex method.</summary> internal sealed record RegexType(RegexMethod? Method, string Keyword, string Namespace, string Name) { public RegexType? ParentClass { get; set; } } } }
// 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 Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.DotnetRuntime.Extensions; using System; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Threading; namespace System.Text.RegularExpressions.Generator { public partial class RegexGenerator { private const string RegexName = "System.Text.RegularExpressions.Regex"; private const string RegexGeneratorAttributeName = "System.Text.RegularExpressions.RegexGeneratorAttribute"; private static bool IsSyntaxTargetForGeneration(SyntaxNode node, CancellationToken cancellationToken) => // We don't have a semantic model here, so the best we can do is say whether there are any attributes. node is MethodDeclarationSyntax { AttributeLists: { Count: > 0 } }; private static bool IsSemanticTargetForGeneration(SemanticModel semanticModel, MethodDeclarationSyntax methodDeclarationSyntax, CancellationToken cancellationToken) { foreach (AttributeListSyntax attributeListSyntax in methodDeclarationSyntax.AttributeLists) { foreach (AttributeSyntax attributeSyntax in attributeListSyntax.Attributes) { if (semanticModel.GetSymbolInfo(attributeSyntax, cancellationToken).Symbol is IMethodSymbol attributeSymbol && attributeSymbol.ContainingType.ToDisplayString() == RegexGeneratorAttributeName) { return true; } } } return false; } // Returns null if nothing to do, Diagnostic if there's an error to report, or RegexType if the type was analyzed successfully. private static object? GetSemanticTargetForGeneration(GeneratorSyntaxContext context, CancellationToken cancellationToken) { var methodSyntax = (MethodDeclarationSyntax)context.Node; SemanticModel sm = context.SemanticModel; if (!IsSemanticTargetForGeneration(sm, methodSyntax, cancellationToken)) { return null; } Compilation compilation = sm.Compilation; INamedTypeSymbol? regexSymbol = compilation.GetBestTypeByMetadataName(RegexName); INamedTypeSymbol? regexGeneratorAttributeSymbol = compilation.GetBestTypeByMetadataName(RegexGeneratorAttributeName); if (regexSymbol is null || regexGeneratorAttributeSymbol is null) { // Required types aren't available return null; } TypeDeclarationSyntax? typeDec = methodSyntax.Parent as TypeDeclarationSyntax; if (typeDec is null) { return null; } IMethodSymbol? regexMethodSymbol = sm.GetDeclaredSymbol(methodSyntax, cancellationToken) as IMethodSymbol; if (regexMethodSymbol is null) { return null; } ImmutableArray<AttributeData>? boundAttributes = regexMethodSymbol.GetAttributes(); if (boundAttributes is null || boundAttributes.Value.Length == 0) { return null; } bool attributeFound = false; string? pattern = null; int? options = null; int? matchTimeout = null; foreach (AttributeData attributeData in boundAttributes) { if (attributeData.AttributeClass?.Equals(regexGeneratorAttributeSymbol) != true) { continue; } if (attributeData.ConstructorArguments.Any(ca => ca.Kind == TypedConstantKind.Error)) { return Diagnostic.Create(DiagnosticDescriptors.InvalidRegexGeneratorAttribute, methodSyntax.GetLocation()); } if (pattern is not null) { return Diagnostic.Create(DiagnosticDescriptors.MultipleRegexGeneratorAttributes, methodSyntax.GetLocation()); } ImmutableArray<TypedConstant> items = attributeData.ConstructorArguments; if (items.Length == 0 || items.Length > 3) { return Diagnostic.Create(DiagnosticDescriptors.InvalidRegexGeneratorAttribute, methodSyntax.GetLocation()); } attributeFound = true; pattern = items[0].Value as string; if (items.Length >= 2) { options = items[1].Value as int?; if (items.Length == 3) { matchTimeout = items[2].Value as int?; } } } if (!attributeFound) { return null; } if (pattern is null) { return Diagnostic.Create(DiagnosticDescriptors.InvalidRegexArguments, methodSyntax.GetLocation(), "(null)"); } if (!regexMethodSymbol.IsPartialDefinition || regexMethodSymbol.Parameters.Length != 0 || regexMethodSymbol.Arity != 0 || !regexMethodSymbol.ReturnType.Equals(regexSymbol)) { return Diagnostic.Create(DiagnosticDescriptors.RegexMethodMustHaveValidSignature, methodSyntax.GetLocation()); } if (typeDec.SyntaxTree.Options is CSharpParseOptions { LanguageVersion: <= LanguageVersion.CSharp10 }) { return Diagnostic.Create(DiagnosticDescriptors.InvalidLangVersion, methodSyntax.GetLocation()); } RegexOptions regexOptions = options is not null ? (RegexOptions)options : RegexOptions.None; // TODO: This is going to include the culture that's current at the time of compilation. // What should we do about that? We could: // - say not specifying CultureInvariant is invalid if anything about options or the expression will look at culture // - fall back to not generating source if it's not specified // - just use whatever culture is present at build time // - devise a new way of not using the culture present at build time // - ... CultureInfo culture = (regexOptions & RegexOptions.CultureInvariant) != 0 ? CultureInfo.InvariantCulture : CultureInfo.CurrentCulture; // Validate the options const RegexOptions SupportedOptions = RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.ECMAScript | RegexOptions.ExplicitCapture | RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline | RegexOptions.NonBacktracking | RegexOptions.RightToLeft | RegexOptions.Singleline; if ((regexOptions & ~SupportedOptions) != 0) { return Diagnostic.Create(DiagnosticDescriptors.InvalidRegexArguments, methodSyntax.GetLocation(), "options"); } // Validate the timeout if (matchTimeout is 0 or < -1) { return Diagnostic.Create(DiagnosticDescriptors.InvalidRegexArguments, methodSyntax.GetLocation(), "matchTimeout"); } // Parse the input pattern RegexTree tree; try { tree = RegexParser.Parse(pattern, regexOptions | RegexOptions.Compiled, culture); // make sure Compiled is included to get all optimizations applied to it } catch (Exception e) { return Diagnostic.Create(DiagnosticDescriptors.InvalidRegexArguments, methodSyntax.GetLocation(), e.Message); } // Determine the namespace the class is declared in, if any string? ns = regexMethodSymbol.ContainingType?.ContainingNamespace?.ToDisplayString( SymbolDisplayFormat.FullyQualifiedFormat.WithGlobalNamespaceStyle(SymbolDisplayGlobalNamespaceStyle.Omitted)); var regexMethod = new RegexMethod( methodSyntax, regexMethodSymbol.Name, methodSyntax.Modifiers.ToString(), pattern, regexOptions, matchTimeout ?? Timeout.Infinite, tree); var regexType = new RegexType( regexMethod, typeDec is RecordDeclarationSyntax rds ? $"{typeDec.Keyword.ValueText} {rds.ClassOrStructKeyword}" : typeDec.Keyword.ValueText, ns ?? string.Empty, $"{typeDec.Identifier}{typeDec.TypeParameterList}"); RegexType current = regexType; var parent = typeDec.Parent as TypeDeclarationSyntax; while (parent is not null && IsAllowedKind(parent.Kind())) { current.ParentClass = new RegexType( null, parent is RecordDeclarationSyntax rds2 ? $"{parent.Keyword.ValueText} {rds2.ClassOrStructKeyword}" : parent.Keyword.ValueText, ns ?? string.Empty, $"{parent.Identifier}{parent.TypeParameterList}"); current = current.ParentClass; parent = parent.Parent as TypeDeclarationSyntax; } return regexType; static bool IsAllowedKind(SyntaxKind kind) => kind == SyntaxKind.ClassDeclaration || kind == SyntaxKind.StructDeclaration || kind == SyntaxKind.RecordDeclaration || kind == SyntaxKind.RecordStructDeclaration || kind == SyntaxKind.InterfaceDeclaration; } /// <summary>A regex method.</summary> internal sealed record RegexMethod(MethodDeclarationSyntax MethodSyntax, string MethodName, string Modifiers, string Pattern, RegexOptions Options, int MatchTimeout, RegexTree Tree); /// <summary>A type holding a regex method.</summary> internal sealed record RegexType(RegexMethod? Method, string Keyword, string Namespace, string Name) { public RegexType? ParentClass { get; set; } } } }
1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./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) (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(); _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 - _code.Tree.MinRequiredLength) // { // base.runtextpos = inputSpan.Length; // return false; // } Ldloc(pos); Ldloca(inputSpan); Call(s_spanGetLengthMethod); if (minRequiredLength > 0) { Ldc(minRequiredLength); Sub(); } Ble(finishedLengthCheck); MarkLabel(returnFalse); Ldthis(); Ldloca(inputSpan); Call(s_spanGetLengthMethod); Stfld(s_runtextposField); Ldc(0); Ret(); MarkLabel(finishedLengthCheck); // Emit any anchors. if (GenerateAnchors()) { 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.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.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 GenerateAnchors() { 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: label = DefineLabel(); Ldloc(pos); Ldc(0); Ble(label); Br(returnFalse); MarkLabel(label); Ldc(1); Ret(); return true; case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_Start: label = DefineLabel(); Ldloc(pos); Ldthisfld(s_runtextstartField); Ble(label); Br(returnFalse); MarkLabel(label); Ldc(1); Ret(); return true; case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_EndZ: 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: 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.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. 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; } 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(); } 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 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; Ldthis(); Dup(); Ldc(0); Ldthisfld(s_runtextposField); Dup(); Ldc(node.Kind == RegexNodeKind.Multi ? node.Str!.Length : 1); Add(); Call(s_captureMethod); Ldthisfld(s_runtextposField); Ldc(node.Kind == RegexNodeKind.Multi ? node.Str!.Length : 1); 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, slices textspan by the corresponding amount, // and zeros out sliceStaticPos. void TransferSliceStaticPosToPos() { if (sliceStaticPos > 0) { // pos += sliceStaticPos; Ldloc(pos); Ldc(sliceStaticPos); Add(); Stloc(pos); // slice = slice.Slice(sliceStaticPos); Ldloca(slice); Ldc(sliceStaticPos); Call(s_spanSliceIntMethod); Stloc(slice); // sliceStaticPos = 0; sliceStaticPos = 0; } } // 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); 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 (slice.Length < matchLength) goto doneLabel; Ldloca(slice); Call(s_spanGetLengthMethod); 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; Ldloca(inputSpan); Ldloc(matchIndex); Ldloc(i); Add(); Call(s_spanGetItemMethod); LdindU2(); if (IsCaseInsensitive(node)) { CallToLower(); } Ldloca(slice); Ldloc(i); 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; Ldloc(pos); Ldloc(matchLength); Add(); Stloc(pos); 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 lookahead. 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 lookahead; however, a positive lookahead 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 lookahead. // 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 lookahead. // 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 lookahead assertion. void EmitPositiveLookaheadAssertion(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.PositiveLookaround, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); // Save off pos. We'll need to reset this upon successful completion of the lookahead. // 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 lookahead. // pos = startingPos; // slice = inputSpan.Slice(pos); Ldloc(startingPos); Stloc(pos); SliceInputSpan(); sliceStaticPos = startingTextSpanPos; } // Emits the code to handle a negative lookahead assertion. void EmitNegativeLookaheadAssertion(RegexNode node) { Debug.Assert(node.Kind is RegexNodeKind.NegativeLookaround, $"Unexpected type: {node.Kind}"); Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}"); Label originalDoneLabel = doneLabel; // Save off pos. We'll need to reset this upon successful completion of the lookahead. // 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 lookahead, which actually // means failure for a _negative_ lookahead, so we need to jump to the original done. // goto originalDoneLabel; BrFar(originalDoneLabel); // Failures (success for a negative lookahead) jump here. MarkLabel(negativeLookaheadDoneLabel); if (doneLabel == negativeLookaheadDoneLabel) { doneLabel = originalDoneLabel; } // After the child completes in failure (success for negative lookahead), 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; } 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: EmitPositiveLookaheadAssertion(node); break; case RegexNodeKind.NegativeLookaround: EmitNegativeLookaheadAssertion(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()}"); // 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 (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}"); // This only emits a single check, but it's called from the looping constructs in a loop // to generate the code for a single check, so we check for each "family" (one, notone, set) // rather than only for the specific single character nodes. // if ((uint)(sliceStaticPos + offset) >= slice.Length || slice[sliceStaticPos + offset] != ch) goto Done; if (emitLengthCheck) { EmitSpanLengthCheck(1, offset); } Ldloca(slice); EmitSum(sliceStaticPos, offset); Call(s_spanGetItemMethod); LdindU2(); 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); } } sliceStaticPos++; } // 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 (!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(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 runtext field directly: // if (pos > 0 && base.runtext[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 < slice.Length) goto doneLabel; Ldc(sliceStaticPos); Ldloca(slice); Call(s_spanGetLengthMethod); BltUnFar(doneLabel); break; case RegexNodeKind.EndZ: // if (sliceStaticPos < slice.Length - 1) goto doneLabel; Ldc(sliceStaticPos); Ldloca(slice); Call(s_spanGetLengthMethod); Ldc(1); Sub(); BltFar(doneLabel); goto case RegexNodeKind.Eol; case RegexNodeKind.Eol: // 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); } 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); } void EmitMultiCharString(string str, bool caseInsensitive, bool emitLengthCheck) { Debug.Assert(str.Length >= 2); 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; // 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); // pos += sliceStaticPos; // 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; if (node.M > 0) { Ldloc(startingPos); Ldc(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; Ldloc(startingPos); Ldloc(endingPos); BgeFar(doneLabel); if (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--; Ldloc(endingPos); Ldc(1); Sub(); Stloc(endingPos); } // pos = endingPos; Ldloc(endingPos); Stloc(pos); // 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); // 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 (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 (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; 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); 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; using RentedLocalBuilder iterationLocal = RentInt32Local(); Label atomicLoopDoneLabel = DefineLabel(); Span<char> setChars = stackalloc char[5]; // max optimized by IndexOfAny today int numSetChars = 0; 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. // slice = slice.Slice(i); Ldloca(slice); Ldloc(iterationLocal); Call(s_spanSliceIntMethod); Stloc(slice); // pos += i; Ldloc(pos); Ldloc(iterationLocal); Add(); 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); Label skipUpdatesLabel = DefineLabel(); // if ((uint)sliceStaticPos >= (uint)slice.Length) goto skipUpdatesLabel; Ldc(sliceStaticPos); Ldloca(slice); Call(s_spanGetLengthMethod); BgeUnFar(skipUpdatesLabel); // if (slice[sliceStaticPos] != ch) goto skipUpdatesLabel; Ldloca(slice); Ldc(sliceStaticPos); 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); } } // slice = slice.Slice(1); Ldloca(slice); Ldc(1); Call(s_spanSliceIntMethod); Stloc(slice); // pos++; Ldloc(pos); Ldc(1); Add(); 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(DynamicMethod tryFindNextStartingPositionMethod, DynamicMethod tryMatchAtCurrentPositionMethod) { 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) // return; Ldthis(); Ldarg_1(); Call(tryMatchAtCurrentPositionMethod); BrtrueFar(returnLabel); Ldthisfld(s_runtextposField); Ldarga_s(1); Call(s_spanGetLengthMethod); Ceq(); BrtrueFar(returnLabel); // runtextpos += 1 Ldthis(); Ldthisfld(s_runtextposField); Ldc(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); 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); } } }
1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexFindOptimizations.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; using System.Globalization; namespace System.Text.RegularExpressions { /// <summary>Contains state and provides operations related to finding the next location a match could possibly begin.</summary> internal sealed class RegexFindOptimizations { /// <summary>True if the input should be processed right-to-left rather than left-to-right.</summary> private readonly bool _rightToLeft; /// <summary>Provides the ToLower routine for lowercasing characters.</summary> private readonly TextInfo _textInfo; /// <summary>Lookup table used for optimizing ASCII when doing set queries.</summary> private readonly uint[]?[]? _asciiLookups; public RegexFindOptimizations(RegexNode root, RegexOptions options, CultureInfo culture) { _rightToLeft = (options & RegexOptions.RightToLeft) != 0; _textInfo = culture.TextInfo; MinRequiredLength = root.ComputeMinLength(); // Compute any anchor starting the expression. If there is one, we won't need to search for anything, // as we can just match at that single location. LeadingAnchor = RegexPrefixAnalyzer.FindLeadingAnchor(root); if (_rightToLeft && LeadingAnchor == RegexNodeKind.Bol) { // Filter out Bol for RightToLeft, as we don't currently optimize for it. LeadingAnchor = RegexNodeKind.Unknown; } if (LeadingAnchor is RegexNodeKind.Beginning or RegexNodeKind.Start or RegexNodeKind.EndZ or RegexNodeKind.End) { FindMode = (LeadingAnchor, _rightToLeft) switch { (RegexNodeKind.Beginning, false) => FindNextStartingPositionMode.LeadingAnchor_LeftToRight_Beginning, (RegexNodeKind.Beginning, true) => FindNextStartingPositionMode.LeadingAnchor_RightToLeft_Beginning, (RegexNodeKind.Start, false) => FindNextStartingPositionMode.LeadingAnchor_LeftToRight_Start, (RegexNodeKind.Start, true) => FindNextStartingPositionMode.LeadingAnchor_RightToLeft_Start, (RegexNodeKind.End, false) => FindNextStartingPositionMode.LeadingAnchor_LeftToRight_End, (RegexNodeKind.End, true) => FindNextStartingPositionMode.LeadingAnchor_RightToLeft_End, (_, false) => FindNextStartingPositionMode.LeadingAnchor_LeftToRight_EndZ, (_, true) => FindNextStartingPositionMode.LeadingAnchor_RightToLeft_EndZ, }; return; } // Compute any anchor trailing the expression. If there is one, and we can also compute a fixed length // for the whole expression, we can use that to quickly jump to the right location in the input. if (!_rightToLeft) // haven't added FindNextStartingPositionMode support for RTL { bool triedToComputeMaxLength = false; TrailingAnchor = RegexPrefixAnalyzer.FindTrailingAnchor(root); if (TrailingAnchor is RegexNodeKind.End or RegexNodeKind.EndZ) { triedToComputeMaxLength = true; if (root.ComputeMaxLength() is int maxLength) { Debug.Assert(maxLength >= MinRequiredLength, $"{maxLength} should have been greater than {MinRequiredLength} minimum"); MaxPossibleLength = maxLength; if (MinRequiredLength == maxLength) { FindMode = TrailingAnchor == RegexNodeKind.End ? FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_End : FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_EndZ; return; } } } if ((options & RegexOptions.NonBacktracking) != 0 && !triedToComputeMaxLength) { // NonBacktracking also benefits from knowing whether the pattern is a fixed length, as it can use that // knowledge to avoid multiple match phases in some situations. MaxPossibleLength = root.ComputeMaxLength(); } } // If there's a leading case-sensitive substring, just use IndexOf and inherit all of its optimizations. string caseSensitivePrefix = RegexPrefixAnalyzer.FindCaseSensitivePrefix(root); if (caseSensitivePrefix.Length > 1) { LeadingCaseSensitivePrefix = caseSensitivePrefix; FindMode = _rightToLeft ? FindNextStartingPositionMode.LeadingPrefix_RightToLeft_CaseSensitive : FindNextStartingPositionMode.LeadingPrefix_LeftToRight_CaseSensitive; return; } // At this point there are no fast-searchable anchors or case-sensitive prefixes. We can now analyze the // pattern for sets and then use any found sets to determine what kind of search to perform. // If we're compiling, then the compilation process already handles sets that reduce to a single literal, // so we can simplify and just always go for the sets. bool dfa = (options & RegexOptions.NonBacktracking) != 0; bool compiled = (options & RegexOptions.Compiled) != 0 && !dfa; // for now, we never generate code for NonBacktracking, so treat it as non-compiled bool interpreter = !compiled && !dfa; // For interpreter, we want to employ optimizations, but we don't want to make construction significantly // more expensive; someone who wants to pay to do more work can specify Compiled. So for the interpreter // we focus only on creating a set for the first character. Same for right-to-left, which is used very // rarely and thus we don't need to invest in special-casing it. if (_rightToLeft) { // Determine a set for anything that can possibly start the expression. if (RegexPrefixAnalyzer.FindFirstCharClass(root, culture) is (string CharClass, bool CaseInsensitive) set) { // See if the set is limited to holding only a few characters. Span<char> scratch = stackalloc char[5]; // max optimized by IndexOfAny today int scratchCount; char[]? chars = null; if (!RegexCharClass.IsNegated(set.CharClass) && (scratchCount = RegexCharClass.GetSetChars(set.CharClass, scratch)) > 0) { chars = scratch.Slice(0, scratchCount).ToArray(); } if (!compiled && chars is { Length: 1 }) { // The set contains one and only one character, meaning every match starts // with the same literal value (potentially case-insensitive). Search for that. FixedDistanceLiteral = (chars[0], 0); FindMode = set.CaseInsensitive ? FindNextStartingPositionMode.LeadingLiteral_RightToLeft_CaseInsensitive : FindNextStartingPositionMode.LeadingLiteral_RightToLeft_CaseSensitive; } else { // The set may match multiple characters. Search for that. FixedDistanceSets = new() { (chars, set.CharClass, 0, set.CaseInsensitive) }; FindMode = set.CaseInsensitive ? FindNextStartingPositionMode.LeadingSet_RightToLeft_CaseInsensitive : FindNextStartingPositionMode.LeadingSet_RightToLeft_CaseSensitive; _asciiLookups = new uint[1][]; } } return; } // We're now left-to-right only and looking for sets. // As a backup, see if we can find a literal after a leading atomic loop. That might be better than whatever sets we find, so // we want to know whether we have one in our pocket before deciding whether to use a leading set. (RegexNode LoopNode, (char Char, string? String, char[]? Chars) Literal)? literalAfterLoop = RegexPrefixAnalyzer.FindLiteralFollowingLeadingLoop(root); // Build up a list of all of the sets that are a fixed distance from the start of the expression. List<(char[]? Chars, string Set, int Distance, bool CaseInsensitive)>? fixedDistanceSets = RegexPrefixAnalyzer.FindFixedDistanceSets(root, culture, thorough: !interpreter); Debug.Assert(fixedDistanceSets is null || fixedDistanceSets.Count != 0); // If we got such sets, we'll likely use them. However, if the best of them is something that doesn't support a vectorized // search and we did successfully find a literal after an atomic loop we could search instead, we prefer the vectorizable search. if (fixedDistanceSets is not null && (fixedDistanceSets[0].Chars is not null || literalAfterLoop is null)) { // Determine whether to do searching based on one or more sets or on a single literal. Compiled engines // don't need to special-case literals as they already do codegen to create the optimal lookup based on // the set's characteristics. if (!compiled && fixedDistanceSets.Count == 1 && fixedDistanceSets[0].Chars is { Length: 1 }) { FixedDistanceLiteral = (fixedDistanceSets[0].Chars![0], fixedDistanceSets[0].Distance); FindMode = fixedDistanceSets[0].CaseInsensitive ? FindNextStartingPositionMode.FixedLiteral_LeftToRight_CaseInsensitive : FindNextStartingPositionMode.FixedLiteral_LeftToRight_CaseSensitive; } else { // Limit how many sets we use to avoid doing lots of unnecessary work. The list was already // sorted from best to worst, so just keep the first ones up to our limit. const int MaxSetsToUse = 3; // arbitrary tuned limit if (fixedDistanceSets.Count > MaxSetsToUse) { fixedDistanceSets.RemoveRange(MaxSetsToUse, fixedDistanceSets.Count - MaxSetsToUse); } // Store the sets, and compute which mode to use. FixedDistanceSets = fixedDistanceSets; FindMode = (fixedDistanceSets.Count == 1 && fixedDistanceSets[0].Distance == 0, fixedDistanceSets[0].CaseInsensitive) switch { (true, true) => FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseInsensitive, (true, false) => FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseSensitive, (false, true) => FindNextStartingPositionMode.FixedSets_LeftToRight_CaseInsensitive, (false, false) => FindNextStartingPositionMode.FixedSets_LeftToRight_CaseSensitive, }; _asciiLookups = new uint[fixedDistanceSets.Count][]; } return; } // If we found a literal we can search for after a leading set loop, use it. if (literalAfterLoop is not null) { FindMode = FindNextStartingPositionMode.LiteralAfterLoop_LeftToRight_CaseSensitive; LiteralAfterLoop = literalAfterLoop; _asciiLookups = new uint[1][]; return; } } /// <summary>Gets the selected mode for performing the next <see cref="TryFindNextStartingPosition"/> operation</summary> public FindNextStartingPositionMode FindMode { get; } = FindNextStartingPositionMode.NoSearch; /// <summary>Gets the leading anchor (e.g. RegexNodeKind.Bol) if one exists and was computed.</summary> public RegexNodeKind LeadingAnchor { get; } /// <summary>Gets the trailing anchor (e.g. RegexNodeKind.Bol) if one exists and was computed.</summary> public RegexNodeKind TrailingAnchor { get; } /// <summary>Gets the minimum required length an input need be to match the pattern.</summary> /// <remarks>0 is a valid minimum length. This value may also be the max (and hence fixed) length of the expression.</remarks> public int MinRequiredLength { get; } /// <summary>The maximum possible length an input could be to match the pattern.</summary> /// <remarks> /// This is currently only set when <see cref="TrailingAnchor"/> is found to be an end anchor. /// That can be expanded in the future as needed. /// </remarks> public int? MaxPossibleLength { get; } /// <summary>Gets the leading prefix. May be an empty string.</summary> public string LeadingCaseSensitivePrefix { get; } = string.Empty; /// <summary>When in fixed distance literal mode, gets the literal and how far it is from the start of the pattern.</summary> public (char Literal, int Distance) FixedDistanceLiteral { get; } /// <summary>When in fixed distance set mode, gets the set and how far it is from the start of the pattern.</summary> /// <remarks>The case-insensitivity of the 0th entry will always match the mode selected, but subsequent entries may not.</remarks> public List<(char[]? Chars, string Set, int Distance, bool CaseInsensitive)>? FixedDistanceSets { get; } /// <summary>When in literal after set loop node, gets the literal to search for and the RegexNode representing the leading loop.</summary> public (RegexNode LoopNode, (char Char, string? String, char[]? Chars) Literal)? LiteralAfterLoop { get; } /// <summary>Try to advance to the next starting position that might be a location for a match.</summary> /// <param name="textSpan">The text to search.</param> /// <param name="pos">The position in <paramref name="textSpan"/>. This is updated with the found position.</param> /// <param name="start">The index in <paramref name="textSpan"/> to consider the start for start anchor purposes.</param> /// <returns>true if a position to attempt a match was found; false if none was found.</returns> public bool TryFindNextStartingPosition(ReadOnlySpan<char> textSpan, ref int pos, int start) { // Return early if we know there's not enough input left to match. if (!_rightToLeft) { if (pos > textSpan.Length - MinRequiredLength) { pos = textSpan.Length; return false; } } else { if (pos < MinRequiredLength) { pos = 0; return false; } } // Optimize the handling of a Beginning-Of-Line (BOL) anchor (only for left-to-right). BOL is special, in that unlike // other anchors like Beginning, there are potentially multiple places a BOL can match. So unlike // the other anchors, which all skip all subsequent processing if found, with BOL we just use it // to boost our position to the next line, and then continue normally with any searches. if (LeadingAnchor == RegexNodeKind.Bol) { // If we're not currently positioned at the beginning of a line (either // the beginning of the string or just after a line feed), find the next // newline and position just after it. Debug.Assert(!_rightToLeft); int posm1 = pos - 1; if ((uint)posm1 < (uint)textSpan.Length && textSpan[posm1] != '\n') { int newline = textSpan.Slice(pos).IndexOf('\n'); if ((uint)newline > textSpan.Length - 1 - pos) { pos = textSpan.Length; return false; } // We've updated the position. Make sure there's still enough room in the input for a possible match. pos = newline + 1 + pos; if (pos > textSpan.Length - MinRequiredLength) { pos = textSpan.Length; return false; } } } switch (FindMode) { // There's an anchor. For some, we can simply compare against the current position. // For others, we can jump to the relevant location. case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_Beginning: if (pos > 0) { pos = textSpan.Length; return false; } return true; case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_Start: if (pos > start) { pos = textSpan.Length; return false; } return true; case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_EndZ: if (pos < textSpan.Length - 1) { pos = textSpan.Length - 1; } return true; case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_End: if (pos < textSpan.Length) { pos = textSpan.Length; } return true; case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_Beginning: if (pos > 0) { pos = 0; } return true; case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_Start: if (pos < start) { pos = 0; return false; } return true; case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_EndZ: if (pos < textSpan.Length - 1 || ((uint)pos < (uint)textSpan.Length && textSpan[pos] != '\n')) { pos = 0; return false; } return true; case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_End: if (pos < textSpan.Length) { pos = 0; return false; } return true; case FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_EndZ: if (pos < textSpan.Length - MinRequiredLength - 1) { pos = textSpan.Length - MinRequiredLength - 1; } return true; case FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_End: if (pos < textSpan.Length - MinRequiredLength) { pos = textSpan.Length - MinRequiredLength; } return true; // There's a case-sensitive prefix. Search for it with ordinal IndexOf. case FindNextStartingPositionMode.LeadingPrefix_LeftToRight_CaseSensitive: { int i = textSpan.Slice(pos).IndexOf(LeadingCaseSensitivePrefix.AsSpan()); if (i >= 0) { pos += i; return true; } pos = textSpan.Length; return false; } case FindNextStartingPositionMode.LeadingPrefix_RightToLeft_CaseSensitive: { int i = textSpan.Slice(0, pos).LastIndexOf(LeadingCaseSensitivePrefix.AsSpan()); if (i >= 0) { pos = i + LeadingCaseSensitivePrefix.Length; return true; } pos = 0; return false; } // There's a literal at the beginning of the pattern. Search for it. case FindNextStartingPositionMode.LeadingLiteral_RightToLeft_CaseSensitive: { int i = textSpan.Slice(0, pos).LastIndexOf(FixedDistanceLiteral.Literal); if (i >= 0) { pos = i + 1; return true; } pos = 0; return false; } case FindNextStartingPositionMode.LeadingLiteral_RightToLeft_CaseInsensitive: { char ch = FixedDistanceLiteral.Literal; TextInfo ti = _textInfo; ReadOnlySpan<char> span = textSpan.Slice(0, pos); for (int i = span.Length - 1; i >= 0; i--) { if (ti.ToLower(span[i]) == ch) { pos = i + 1; return true; } } pos = 0; return false; } // There's a set at the beginning of the pattern. Search for it. case FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseSensitive: { (char[]? chars, string set, _, _) = FixedDistanceSets![0]; ReadOnlySpan<char> span = textSpan.Slice(pos); if (chars is not null) { int i = span.IndexOfAny(chars); if (i >= 0) { pos += i; return true; } } else { ref uint[]? startingAsciiLookup = ref _asciiLookups![0]; for (int i = 0; i < span.Length; i++) { if (RegexCharClass.CharInClass(span[i], set, ref startingAsciiLookup)) { pos += i; return true; } } } pos = textSpan.Length; return false; } case FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseInsensitive: { ref uint[]? startingAsciiLookup = ref _asciiLookups![0]; string set = FixedDistanceSets![0].Set; TextInfo ti = _textInfo; ReadOnlySpan<char> span = textSpan.Slice(pos); for (int i = 0; i < span.Length; i++) { if (RegexCharClass.CharInClass(ti.ToLower(span[i]), set, ref startingAsciiLookup)) { pos += i; return true; } } pos = textSpan.Length; return false; } case FindNextStartingPositionMode.LeadingSet_RightToLeft_CaseSensitive: { ref uint[]? startingAsciiLookup = ref _asciiLookups![0]; string set = FixedDistanceSets![0].Set; ReadOnlySpan<char> span = textSpan.Slice(0, pos); for (int i = span.Length - 1; i >= 0; i--) { if (RegexCharClass.CharInClass(span[i], set, ref startingAsciiLookup)) { pos = i + 1; return true; } } pos = 0; return false; } case FindNextStartingPositionMode.LeadingSet_RightToLeft_CaseInsensitive: { ref uint[]? startingAsciiLookup = ref _asciiLookups![0]; string set = FixedDistanceSets![0].Set; TextInfo ti = _textInfo; ReadOnlySpan<char> span = textSpan.Slice(0, pos); for (int i = span.Length - 1; i >= 0; i--) { if (RegexCharClass.CharInClass(ti.ToLower(span[i]), set, ref startingAsciiLookup)) { pos = i + 1; return true; } } pos = 0; return false; } // There's a literal at a fixed offset from the beginning of the pattern. Search for it. case FindNextStartingPositionMode.FixedLiteral_LeftToRight_CaseSensitive: { Debug.Assert(FixedDistanceLiteral.Distance <= MinRequiredLength); int i = textSpan.Slice(pos + FixedDistanceLiteral.Distance).IndexOf(FixedDistanceLiteral.Literal); if (i >= 0) { pos += i; return true; } pos = textSpan.Length; return false; } case FindNextStartingPositionMode.FixedLiteral_LeftToRight_CaseInsensitive: { Debug.Assert(FixedDistanceLiteral.Distance <= MinRequiredLength); char ch = FixedDistanceLiteral.Literal; TextInfo ti = _textInfo; ReadOnlySpan<char> span = textSpan.Slice(pos + FixedDistanceLiteral.Distance); for (int i = 0; i < span.Length; i++) { if (ti.ToLower(span[i]) == ch) { pos += i; return true; } } pos = textSpan.Length; return false; } // There are one or more sets at fixed offsets from the start of the pattern. case FindNextStartingPositionMode.FixedSets_LeftToRight_CaseSensitive: { List<(char[]? Chars, string Set, int Distance, bool CaseInsensitive)> sets = FixedDistanceSets!; (char[]? primaryChars, string primarySet, int primaryDistance, _) = sets[0]; int endMinusRequiredLength = textSpan.Length - Math.Max(1, MinRequiredLength); if (primaryChars is not null) { for (int inputPosition = pos; inputPosition <= endMinusRequiredLength; inputPosition++) { int offset = inputPosition + primaryDistance; int index = textSpan.Slice(offset).IndexOfAny(primaryChars); if (index < 0) { break; } index += offset; // The index here will be offset indexed due to the use of span, so we add offset to get // real position on the string. inputPosition = index - primaryDistance; if (inputPosition > endMinusRequiredLength) { break; } for (int i = 1; i < sets.Count; i++) { (_, string nextSet, int nextDistance, bool nextCaseInsensitive) = sets[i]; char c = textSpan[inputPosition + nextDistance]; if (!RegexCharClass.CharInClass(nextCaseInsensitive ? _textInfo.ToLower(c) : c, nextSet, ref _asciiLookups![i])) { goto Bumpalong; } } pos = inputPosition; return true; Bumpalong:; } } else { ref uint[]? startingAsciiLookup = ref _asciiLookups![0]; for (int inputPosition = pos; inputPosition <= endMinusRequiredLength; inputPosition++) { char c = textSpan[inputPosition + primaryDistance]; if (!RegexCharClass.CharInClass(c, primarySet, ref startingAsciiLookup)) { goto Bumpalong; } for (int i = 1; i < sets.Count; i++) { (_, string nextSet, int nextDistance, bool nextCaseInsensitive) = sets[i]; c = textSpan[inputPosition + nextDistance]; if (!RegexCharClass.CharInClass(nextCaseInsensitive ? _textInfo.ToLower(c) : c, nextSet, ref _asciiLookups![i])) { goto Bumpalong; } } pos = inputPosition; return true; Bumpalong:; } } pos = textSpan.Length; return false; } case FindNextStartingPositionMode.FixedSets_LeftToRight_CaseInsensitive: { List<(char[]? Chars, string Set, int Distance, bool CaseInsensitive)> sets = FixedDistanceSets!; (_, string primarySet, int primaryDistance, _) = sets[0]; int endMinusRequiredLength = textSpan.Length - Math.Max(1, MinRequiredLength); TextInfo ti = _textInfo; ref uint[]? startingAsciiLookup = ref _asciiLookups![0]; for (int inputPosition = pos; inputPosition <= endMinusRequiredLength; inputPosition++) { char c = textSpan[inputPosition + primaryDistance]; if (!RegexCharClass.CharInClass(ti.ToLower(c), primarySet, ref startingAsciiLookup)) { goto Bumpalong; } for (int i = 1; i < sets.Count; i++) { (_, string nextSet, int nextDistance, bool nextCaseInsensitive) = sets[i]; c = textSpan[inputPosition + nextDistance]; if (!RegexCharClass.CharInClass(nextCaseInsensitive ? _textInfo.ToLower(c) : c, nextSet, ref _asciiLookups![i])) { goto Bumpalong; } } pos = inputPosition; return true; Bumpalong:; } pos = textSpan.Length; return false; } // There's a literal after a leading set loop. Find the literal, then walk backwards through the loop to find the starting position. case FindNextStartingPositionMode.LiteralAfterLoop_LeftToRight_CaseSensitive: { Debug.Assert(LiteralAfterLoop is not null); (RegexNode loopNode, (char Char, string? String, char[]? Chars) literal) = LiteralAfterLoop.GetValueOrDefault(); Debug.Assert(loopNode.Kind is RegexNodeKind.Setloop or RegexNodeKind.Setlazy or RegexNodeKind.Setloopatomic); Debug.Assert(loopNode.N == int.MaxValue); int startingPos = pos; while (true) { ReadOnlySpan<char> slice = textSpan.Slice(startingPos); // Find the literal. If we can't find it, we're done searching. int i = literal.String is not null ? slice.IndexOf(literal.String.AsSpan()) : literal.Chars is not null ? slice.IndexOfAny(literal.Chars.AsSpan()) : slice.IndexOf(literal.Char); if (i < 0) { break; } // We found the literal. Walk backwards from it finding as many matches as we can against the loop. int prev = i; while ((uint)--prev < (uint)slice.Length && RegexCharClass.CharInClass(slice[prev], loopNode.Str!, ref _asciiLookups![0])) ; // If we found fewer than needed, loop around to try again. The loop doesn't overlap with the literal, // so we can start from after the last place the literal matched. if ((i - prev - 1) < loopNode.M) { startingPos += i + 1; continue; } // We have a winner. The starting position is just after the last position that failed to match the loop. // TODO: It'd be nice to be able to communicate literalPos as a place the matching engine can start matching // after the loop, so that it doesn't need to re-match the loop. This might only be feasible for RegexCompiler // and the source generator after we refactor them to generate a single Scan method rather than separate // FindFirstChar / Go methods. pos = startingPos + prev + 1; return true; } pos = textSpan.Length; return false; } // Nothing special to look for. Just return true indicating this is a valid position to try to match. default: Debug.Assert(FindMode == FindNextStartingPositionMode.NoSearch); return true; } } } /// <summary>Mode to use for searching for the next location of a possible match.</summary> internal enum FindNextStartingPositionMode { /// <summary>A "beginning" anchor at the beginning of the pattern.</summary> LeadingAnchor_LeftToRight_Beginning, /// <summary>A "start" anchor at the beginning of the pattern.</summary> LeadingAnchor_LeftToRight_Start, /// <summary>An "endz" anchor at the beginning of the pattern. This is rare.</summary> LeadingAnchor_LeftToRight_EndZ, /// <summary>An "end" anchor at the beginning of the pattern. This is rare.</summary> LeadingAnchor_LeftToRight_End, /// <summary>A "beginning" anchor at the beginning of the right-to-left pattern.</summary> LeadingAnchor_RightToLeft_Beginning, /// <summary>A "start" anchor at the beginning of the right-to-left pattern.</summary> LeadingAnchor_RightToLeft_Start, /// <summary>An "endz" anchor at the beginning of the right-to-left pattern. This is rare.</summary> LeadingAnchor_RightToLeft_EndZ, /// <summary>An "end" anchor at the beginning of the right-to-left pattern. This is rare.</summary> LeadingAnchor_RightToLeft_End, /// <summary>An "end" anchor at the end of the pattern, with the pattern always matching a fixed-length expression.</summary> TrailingAnchor_FixedLength_LeftToRight_End, /// <summary>An "endz" anchor at the end of the pattern, with the pattern always matching a fixed-length expression.</summary> TrailingAnchor_FixedLength_LeftToRight_EndZ, /// <summary>A case-sensitive multi-character substring at the beginning of the pattern.</summary> LeadingPrefix_LeftToRight_CaseSensitive, /// <summary>A case-sensitive multi-character substring at the beginning of the right-to-left pattern.</summary> LeadingPrefix_RightToLeft_CaseSensitive, /// <summary>A case-sensitive set starting the pattern.</summary> LeadingSet_LeftToRight_CaseSensitive, /// <summary>A case-insensitive set starting the pattern.</summary> LeadingSet_LeftToRight_CaseInsensitive, /// <summary>A case-sensitive set starting the right-to-left pattern.</summary> LeadingSet_RightToLeft_CaseSensitive, /// <summary>A case-insensitive set starting the right-to-left pattern.</summary> LeadingSet_RightToLeft_CaseInsensitive, /// <summary>A case-sensitive single character at a fixed distance from the start of the right-to-left pattern.</summary> LeadingLiteral_RightToLeft_CaseSensitive, /// <summary>A case-insensitive single character at a fixed distance from the start of the right-to-left pattern.</summary> LeadingLiteral_RightToLeft_CaseInsensitive, /// <summary>A case-sensitive single character at a fixed distance from the start of the pattern.</summary> FixedLiteral_LeftToRight_CaseSensitive, /// <summary>A case-insensitive single character at a fixed distance from the start of the pattern.</summary> FixedLiteral_LeftToRight_CaseInsensitive, /// <summary>One or more sets at a fixed distance from the start of the pattern. At least the first set is case-sensitive.</summary> FixedSets_LeftToRight_CaseSensitive, /// <summary>One or more sets at a fixed distance from the start of the pattern. At least the first set is case-insensitive.</summary> FixedSets_LeftToRight_CaseInsensitive, /// <summary>A literal after a non-overlapping set loop at the start of the pattern. The literal is case-sensitive.</summary> LiteralAfterLoop_LeftToRight_CaseSensitive, /// <summary>Nothing to search for. Nop.</summary> NoSearch, } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; using System.Globalization; namespace System.Text.RegularExpressions { /// <summary>Contains state and provides operations related to finding the next location a match could possibly begin.</summary> internal sealed class RegexFindOptimizations { /// <summary>True if the input should be processed right-to-left rather than left-to-right.</summary> private readonly bool _rightToLeft; /// <summary>Provides the ToLower routine for lowercasing characters.</summary> private readonly TextInfo _textInfo; /// <summary>Lookup table used for optimizing ASCII when doing set queries.</summary> private readonly uint[]?[]? _asciiLookups; public RegexFindOptimizations(RegexNode root, RegexOptions options, CultureInfo culture) { _rightToLeft = (options & RegexOptions.RightToLeft) != 0; _textInfo = culture.TextInfo; MinRequiredLength = root.ComputeMinLength(); // Compute any anchor starting the expression. If there is one, we won't need to search for anything, // as we can just match at that single location. LeadingAnchor = RegexPrefixAnalyzer.FindLeadingAnchor(root); if (_rightToLeft && LeadingAnchor == RegexNodeKind.Bol) { // Filter out Bol for RightToLeft, as we don't currently optimize for it. LeadingAnchor = RegexNodeKind.Unknown; } if (LeadingAnchor is RegexNodeKind.Beginning or RegexNodeKind.Start or RegexNodeKind.EndZ or RegexNodeKind.End) { FindMode = (LeadingAnchor, _rightToLeft) switch { (RegexNodeKind.Beginning, false) => FindNextStartingPositionMode.LeadingAnchor_LeftToRight_Beginning, (RegexNodeKind.Beginning, true) => FindNextStartingPositionMode.LeadingAnchor_RightToLeft_Beginning, (RegexNodeKind.Start, false) => FindNextStartingPositionMode.LeadingAnchor_LeftToRight_Start, (RegexNodeKind.Start, true) => FindNextStartingPositionMode.LeadingAnchor_RightToLeft_Start, (RegexNodeKind.End, false) => FindNextStartingPositionMode.LeadingAnchor_LeftToRight_End, (RegexNodeKind.End, true) => FindNextStartingPositionMode.LeadingAnchor_RightToLeft_End, (_, false) => FindNextStartingPositionMode.LeadingAnchor_LeftToRight_EndZ, (_, true) => FindNextStartingPositionMode.LeadingAnchor_RightToLeft_EndZ, }; return; } // Compute any anchor trailing the expression. If there is one, and we can also compute a fixed length // for the whole expression, we can use that to quickly jump to the right location in the input. if (!_rightToLeft) // haven't added FindNextStartingPositionMode trailing anchor support for RTL { bool triedToComputeMaxLength = false; TrailingAnchor = RegexPrefixAnalyzer.FindTrailingAnchor(root); if (TrailingAnchor is RegexNodeKind.End or RegexNodeKind.EndZ) { triedToComputeMaxLength = true; if (root.ComputeMaxLength() is int maxLength) { Debug.Assert(maxLength >= MinRequiredLength, $"{maxLength} should have been greater than {MinRequiredLength} minimum"); MaxPossibleLength = maxLength; if (MinRequiredLength == maxLength) { FindMode = TrailingAnchor == RegexNodeKind.End ? FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_End : FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_EndZ; return; } } } if ((options & RegexOptions.NonBacktracking) != 0 && !triedToComputeMaxLength) { // NonBacktracking also benefits from knowing whether the pattern is a fixed length, as it can use that // knowledge to avoid multiple match phases in some situations. MaxPossibleLength = root.ComputeMaxLength(); } } // If there's a leading case-sensitive substring, just use IndexOf and inherit all of its optimizations. string caseSensitivePrefix = RegexPrefixAnalyzer.FindCaseSensitivePrefix(root); if (caseSensitivePrefix.Length > 1) { LeadingCaseSensitivePrefix = caseSensitivePrefix; FindMode = _rightToLeft ? FindNextStartingPositionMode.LeadingPrefix_RightToLeft_CaseSensitive : FindNextStartingPositionMode.LeadingPrefix_LeftToRight_CaseSensitive; return; } // At this point there are no fast-searchable anchors or case-sensitive prefixes. We can now analyze the // pattern for sets and then use any found sets to determine what kind of search to perform. // If we're compiling, then the compilation process already handles sets that reduce to a single literal, // so we can simplify and just always go for the sets. bool dfa = (options & RegexOptions.NonBacktracking) != 0; bool compiled = (options & RegexOptions.Compiled) != 0 && !dfa; // for now, we never generate code for NonBacktracking, so treat it as non-compiled bool interpreter = !compiled && !dfa; // For interpreter, we want to employ optimizations, but we don't want to make construction significantly // more expensive; someone who wants to pay to do more work can specify Compiled. So for the interpreter // we focus only on creating a set for the first character. Same for right-to-left, which is used very // rarely and thus we don't need to invest in special-casing it. if (_rightToLeft) { // Determine a set for anything that can possibly start the expression. if (RegexPrefixAnalyzer.FindFirstCharClass(root, culture) is (string CharClass, bool CaseInsensitive) set) { // See if the set is limited to holding only a few characters. Span<char> scratch = stackalloc char[5]; // max optimized by IndexOfAny today int scratchCount; char[]? chars = null; if (!RegexCharClass.IsNegated(set.CharClass) && (scratchCount = RegexCharClass.GetSetChars(set.CharClass, scratch)) > 0) { chars = scratch.Slice(0, scratchCount).ToArray(); } if (!compiled && chars is { Length: 1 }) { // The set contains one and only one character, meaning every match starts // with the same literal value (potentially case-insensitive). Search for that. FixedDistanceLiteral = (chars[0], 0); FindMode = set.CaseInsensitive ? FindNextStartingPositionMode.LeadingLiteral_RightToLeft_CaseInsensitive : FindNextStartingPositionMode.LeadingLiteral_RightToLeft_CaseSensitive; } else { // The set may match multiple characters. Search for that. FixedDistanceSets = new() { (chars, set.CharClass, 0, set.CaseInsensitive) }; FindMode = set.CaseInsensitive ? FindNextStartingPositionMode.LeadingSet_RightToLeft_CaseInsensitive : FindNextStartingPositionMode.LeadingSet_RightToLeft_CaseSensitive; _asciiLookups = new uint[1][]; } } return; } // We're now left-to-right only and looking for sets. // As a backup, see if we can find a literal after a leading atomic loop. That might be better than whatever sets we find, so // we want to know whether we have one in our pocket before deciding whether to use a leading set. (RegexNode LoopNode, (char Char, string? String, char[]? Chars) Literal)? literalAfterLoop = RegexPrefixAnalyzer.FindLiteralFollowingLeadingLoop(root); // Build up a list of all of the sets that are a fixed distance from the start of the expression. List<(char[]? Chars, string Set, int Distance, bool CaseInsensitive)>? fixedDistanceSets = RegexPrefixAnalyzer.FindFixedDistanceSets(root, culture, thorough: !interpreter); Debug.Assert(fixedDistanceSets is null || fixedDistanceSets.Count != 0); // If we got such sets, we'll likely use them. However, if the best of them is something that doesn't support a vectorized // search and we did successfully find a literal after an atomic loop we could search instead, we prefer the vectorizable search. if (fixedDistanceSets is not null && (fixedDistanceSets[0].Chars is not null || literalAfterLoop is null)) { // Determine whether to do searching based on one or more sets or on a single literal. Compiled engines // don't need to special-case literals as they already do codegen to create the optimal lookup based on // the set's characteristics. if (!compiled && fixedDistanceSets.Count == 1 && fixedDistanceSets[0].Chars is { Length: 1 }) { FixedDistanceLiteral = (fixedDistanceSets[0].Chars![0], fixedDistanceSets[0].Distance); FindMode = fixedDistanceSets[0].CaseInsensitive ? FindNextStartingPositionMode.FixedLiteral_LeftToRight_CaseInsensitive : FindNextStartingPositionMode.FixedLiteral_LeftToRight_CaseSensitive; } else { // Limit how many sets we use to avoid doing lots of unnecessary work. The list was already // sorted from best to worst, so just keep the first ones up to our limit. const int MaxSetsToUse = 3; // arbitrary tuned limit if (fixedDistanceSets.Count > MaxSetsToUse) { fixedDistanceSets.RemoveRange(MaxSetsToUse, fixedDistanceSets.Count - MaxSetsToUse); } // Store the sets, and compute which mode to use. FixedDistanceSets = fixedDistanceSets; FindMode = (fixedDistanceSets.Count == 1 && fixedDistanceSets[0].Distance == 0, fixedDistanceSets[0].CaseInsensitive) switch { (true, true) => FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseInsensitive, (true, false) => FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseSensitive, (false, true) => FindNextStartingPositionMode.FixedSets_LeftToRight_CaseInsensitive, (false, false) => FindNextStartingPositionMode.FixedSets_LeftToRight_CaseSensitive, }; _asciiLookups = new uint[fixedDistanceSets.Count][]; } return; } // If we found a literal we can search for after a leading set loop, use it. if (literalAfterLoop is not null) { FindMode = FindNextStartingPositionMode.LiteralAfterLoop_LeftToRight_CaseSensitive; LiteralAfterLoop = literalAfterLoop; _asciiLookups = new uint[1][]; return; } } /// <summary>Gets the selected mode for performing the next <see cref="TryFindNextStartingPosition"/> operation</summary> public FindNextStartingPositionMode FindMode { get; } = FindNextStartingPositionMode.NoSearch; /// <summary>Gets the leading anchor (e.g. RegexNodeKind.Bol) if one exists and was computed.</summary> public RegexNodeKind LeadingAnchor { get; } /// <summary>Gets the trailing anchor (e.g. RegexNodeKind.Bol) if one exists and was computed.</summary> public RegexNodeKind TrailingAnchor { get; } /// <summary>Gets the minimum required length an input need be to match the pattern.</summary> /// <remarks>0 is a valid minimum length. This value may also be the max (and hence fixed) length of the expression.</remarks> public int MinRequiredLength { get; } /// <summary>The maximum possible length an input could be to match the pattern.</summary> /// <remarks> /// This is currently only set when <see cref="TrailingAnchor"/> is found to be an end anchor. /// That can be expanded in the future as needed. /// </remarks> public int? MaxPossibleLength { get; } /// <summary>Gets the leading prefix. May be an empty string.</summary> public string LeadingCaseSensitivePrefix { get; } = string.Empty; /// <summary>When in fixed distance literal mode, gets the literal and how far it is from the start of the pattern.</summary> public (char Literal, int Distance) FixedDistanceLiteral { get; } /// <summary>When in fixed distance set mode, gets the set and how far it is from the start of the pattern.</summary> /// <remarks>The case-insensitivity of the 0th entry will always match the mode selected, but subsequent entries may not.</remarks> public List<(char[]? Chars, string Set, int Distance, bool CaseInsensitive)>? FixedDistanceSets { get; } /// <summary>When in literal after set loop node, gets the literal to search for and the RegexNode representing the leading loop.</summary> public (RegexNode LoopNode, (char Char, string? String, char[]? Chars) Literal)? LiteralAfterLoop { get; } /// <summary>Try to advance to the next starting position that might be a location for a match.</summary> /// <param name="textSpan">The text to search.</param> /// <param name="pos">The position in <paramref name="textSpan"/>. This is updated with the found position.</param> /// <param name="start">The index in <paramref name="textSpan"/> to consider the start for start anchor purposes.</param> /// <returns>true if a position to attempt a match was found; false if none was found.</returns> public bool TryFindNextStartingPosition(ReadOnlySpan<char> textSpan, ref int pos, int start) { // Return early if we know there's not enough input left to match. if (!_rightToLeft) { if (pos > textSpan.Length - MinRequiredLength) { pos = textSpan.Length; return false; } } else { if (pos < MinRequiredLength) { pos = 0; return false; } } // Optimize the handling of a Beginning-Of-Line (BOL) anchor (only for left-to-right). BOL is special, in that unlike // other anchors like Beginning, there are potentially multiple places a BOL can match. So unlike // the other anchors, which all skip all subsequent processing if found, with BOL we just use it // to boost our position to the next line, and then continue normally with any searches. if (LeadingAnchor == RegexNodeKind.Bol) { // If we're not currently positioned at the beginning of a line (either // the beginning of the string or just after a line feed), find the next // newline and position just after it. Debug.Assert(!_rightToLeft); int posm1 = pos - 1; if ((uint)posm1 < (uint)textSpan.Length && textSpan[posm1] != '\n') { int newline = textSpan.Slice(pos).IndexOf('\n'); if ((uint)newline > textSpan.Length - 1 - pos) { pos = textSpan.Length; return false; } // We've updated the position. Make sure there's still enough room in the input for a possible match. pos = newline + 1 + pos; if (pos > textSpan.Length - MinRequiredLength) { pos = textSpan.Length; return false; } } } switch (FindMode) { // There's an anchor. For some, we can simply compare against the current position. // For others, we can jump to the relevant location. case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_Beginning: if (pos != 0) { // If we're not currently at the beginning, we'll never be, so fail immediately. pos = textSpan.Length; return false; } return true; case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_Start: if (pos != start) { // If we're not currently at the start, we'll never be, so fail immediately. pos = textSpan.Length; return false; } return true; case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_EndZ: if (pos < textSpan.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. pos = textSpan.Length - 1; } return true; case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_End: if (pos < textSpan.Length) { // If we're not currently at the end (or a newline just before it), skip ahead // since nothing until then can possibly match. pos = textSpan.Length; } return true; case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_Beginning: 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.) pos = 0; } return true; case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_Start: if (pos != start) { // If we're not currently at the starting position, we'll never be, so fail immediately. // This is different from beginning, since beginning is the fixed location of 0 whereas // start is wherever the iteration actually starts from; in left-to-right, that's often // the same as beginning, but in RightToLeft it rarely is. pos = 0; return false; } return true; case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_EndZ: if (pos < textSpan.Length - 1 || ((uint)pos < (uint)textSpan.Length && textSpan[pos] != '\n')) { // If we're not currently at the end, we'll never be (we're iterating from end to beginning), // so fail immediately. pos = 0; return false; } return true; case FindNextStartingPositionMode.LeadingAnchor_RightToLeft_End: if (pos < textSpan.Length) { // If we're not currently at the end, we'll never be (we're iterating from end to beginning), // so fail immediately. pos = 0; return false; } return true; case FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_EndZ: if (pos < textSpan.Length - MinRequiredLength - 1) { pos = textSpan.Length - MinRequiredLength - 1; } return true; case FindNextStartingPositionMode.TrailingAnchor_FixedLength_LeftToRight_End: if (pos < textSpan.Length - MinRequiredLength) { pos = textSpan.Length - MinRequiredLength; } return true; // There's a case-sensitive prefix. Search for it with ordinal IndexOf. case FindNextStartingPositionMode.LeadingPrefix_LeftToRight_CaseSensitive: { int i = textSpan.Slice(pos).IndexOf(LeadingCaseSensitivePrefix.AsSpan()); if (i >= 0) { pos += i; return true; } pos = textSpan.Length; return false; } case FindNextStartingPositionMode.LeadingPrefix_RightToLeft_CaseSensitive: { int i = textSpan.Slice(0, pos).LastIndexOf(LeadingCaseSensitivePrefix.AsSpan()); if (i >= 0) { pos = i + LeadingCaseSensitivePrefix.Length; return true; } pos = 0; return false; } // There's a literal at the beginning of the pattern. Search for it. case FindNextStartingPositionMode.LeadingLiteral_RightToLeft_CaseSensitive: { int i = textSpan.Slice(0, pos).LastIndexOf(FixedDistanceLiteral.Literal); if (i >= 0) { pos = i + 1; return true; } pos = 0; return false; } case FindNextStartingPositionMode.LeadingLiteral_RightToLeft_CaseInsensitive: { char ch = FixedDistanceLiteral.Literal; TextInfo ti = _textInfo; ReadOnlySpan<char> span = textSpan.Slice(0, pos); for (int i = span.Length - 1; i >= 0; i--) { if (ti.ToLower(span[i]) == ch) { pos = i + 1; return true; } } pos = 0; return false; } // There's a set at the beginning of the pattern. Search for it. case FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseSensitive: { (char[]? chars, string set, _, _) = FixedDistanceSets![0]; ReadOnlySpan<char> span = textSpan.Slice(pos); if (chars is not null) { int i = span.IndexOfAny(chars); if (i >= 0) { pos += i; return true; } } else { ref uint[]? startingAsciiLookup = ref _asciiLookups![0]; for (int i = 0; i < span.Length; i++) { if (RegexCharClass.CharInClass(span[i], set, ref startingAsciiLookup)) { pos += i; return true; } } } pos = textSpan.Length; return false; } case FindNextStartingPositionMode.LeadingSet_LeftToRight_CaseInsensitive: { ref uint[]? startingAsciiLookup = ref _asciiLookups![0]; string set = FixedDistanceSets![0].Set; TextInfo ti = _textInfo; ReadOnlySpan<char> span = textSpan.Slice(pos); for (int i = 0; i < span.Length; i++) { if (RegexCharClass.CharInClass(ti.ToLower(span[i]), set, ref startingAsciiLookup)) { pos += i; return true; } } pos = textSpan.Length; return false; } case FindNextStartingPositionMode.LeadingSet_RightToLeft_CaseSensitive: { ref uint[]? startingAsciiLookup = ref _asciiLookups![0]; string set = FixedDistanceSets![0].Set; ReadOnlySpan<char> span = textSpan.Slice(0, pos); for (int i = span.Length - 1; i >= 0; i--) { if (RegexCharClass.CharInClass(span[i], set, ref startingAsciiLookup)) { pos = i + 1; return true; } } pos = 0; return false; } case FindNextStartingPositionMode.LeadingSet_RightToLeft_CaseInsensitive: { ref uint[]? startingAsciiLookup = ref _asciiLookups![0]; string set = FixedDistanceSets![0].Set; TextInfo ti = _textInfo; ReadOnlySpan<char> span = textSpan.Slice(0, pos); for (int i = span.Length - 1; i >= 0; i--) { if (RegexCharClass.CharInClass(ti.ToLower(span[i]), set, ref startingAsciiLookup)) { pos = i + 1; return true; } } pos = 0; return false; } // There's a literal at a fixed offset from the beginning of the pattern. Search for it. case FindNextStartingPositionMode.FixedLiteral_LeftToRight_CaseSensitive: { Debug.Assert(FixedDistanceLiteral.Distance <= MinRequiredLength); int i = textSpan.Slice(pos + FixedDistanceLiteral.Distance).IndexOf(FixedDistanceLiteral.Literal); if (i >= 0) { pos += i; return true; } pos = textSpan.Length; return false; } case FindNextStartingPositionMode.FixedLiteral_LeftToRight_CaseInsensitive: { Debug.Assert(FixedDistanceLiteral.Distance <= MinRequiredLength); char ch = FixedDistanceLiteral.Literal; TextInfo ti = _textInfo; ReadOnlySpan<char> span = textSpan.Slice(pos + FixedDistanceLiteral.Distance); for (int i = 0; i < span.Length; i++) { if (ti.ToLower(span[i]) == ch) { pos += i; return true; } } pos = textSpan.Length; return false; } // There are one or more sets at fixed offsets from the start of the pattern. case FindNextStartingPositionMode.FixedSets_LeftToRight_CaseSensitive: { List<(char[]? Chars, string Set, int Distance, bool CaseInsensitive)> sets = FixedDistanceSets!; (char[]? primaryChars, string primarySet, int primaryDistance, _) = sets[0]; int endMinusRequiredLength = textSpan.Length - Math.Max(1, MinRequiredLength); if (primaryChars is not null) { for (int inputPosition = pos; inputPosition <= endMinusRequiredLength; inputPosition++) { int offset = inputPosition + primaryDistance; int index = textSpan.Slice(offset).IndexOfAny(primaryChars); if (index < 0) { break; } index += offset; // The index here will be offset indexed due to the use of span, so we add offset to get // real position on the string. inputPosition = index - primaryDistance; if (inputPosition > endMinusRequiredLength) { break; } for (int i = 1; i < sets.Count; i++) { (_, string nextSet, int nextDistance, bool nextCaseInsensitive) = sets[i]; char c = textSpan[inputPosition + nextDistance]; if (!RegexCharClass.CharInClass(nextCaseInsensitive ? _textInfo.ToLower(c) : c, nextSet, ref _asciiLookups![i])) { goto Bumpalong; } } pos = inputPosition; return true; Bumpalong:; } } else { ref uint[]? startingAsciiLookup = ref _asciiLookups![0]; for (int inputPosition = pos; inputPosition <= endMinusRequiredLength; inputPosition++) { char c = textSpan[inputPosition + primaryDistance]; if (!RegexCharClass.CharInClass(c, primarySet, ref startingAsciiLookup)) { goto Bumpalong; } for (int i = 1; i < sets.Count; i++) { (_, string nextSet, int nextDistance, bool nextCaseInsensitive) = sets[i]; c = textSpan[inputPosition + nextDistance]; if (!RegexCharClass.CharInClass(nextCaseInsensitive ? _textInfo.ToLower(c) : c, nextSet, ref _asciiLookups![i])) { goto Bumpalong; } } pos = inputPosition; return true; Bumpalong:; } } pos = textSpan.Length; return false; } case FindNextStartingPositionMode.FixedSets_LeftToRight_CaseInsensitive: { List<(char[]? Chars, string Set, int Distance, bool CaseInsensitive)> sets = FixedDistanceSets!; (_, string primarySet, int primaryDistance, _) = sets[0]; int endMinusRequiredLength = textSpan.Length - Math.Max(1, MinRequiredLength); TextInfo ti = _textInfo; ref uint[]? startingAsciiLookup = ref _asciiLookups![0]; for (int inputPosition = pos; inputPosition <= endMinusRequiredLength; inputPosition++) { char c = textSpan[inputPosition + primaryDistance]; if (!RegexCharClass.CharInClass(ti.ToLower(c), primarySet, ref startingAsciiLookup)) { goto Bumpalong; } for (int i = 1; i < sets.Count; i++) { (_, string nextSet, int nextDistance, bool nextCaseInsensitive) = sets[i]; c = textSpan[inputPosition + nextDistance]; if (!RegexCharClass.CharInClass(nextCaseInsensitive ? _textInfo.ToLower(c) : c, nextSet, ref _asciiLookups![i])) { goto Bumpalong; } } pos = inputPosition; return true; Bumpalong:; } pos = textSpan.Length; return false; } // There's a literal after a leading set loop. Find the literal, then walk backwards through the loop to find the starting position. case FindNextStartingPositionMode.LiteralAfterLoop_LeftToRight_CaseSensitive: { Debug.Assert(LiteralAfterLoop is not null); (RegexNode loopNode, (char Char, string? String, char[]? Chars) literal) = LiteralAfterLoop.GetValueOrDefault(); Debug.Assert(loopNode.Kind is RegexNodeKind.Setloop or RegexNodeKind.Setlazy or RegexNodeKind.Setloopatomic); Debug.Assert(loopNode.N == int.MaxValue); int startingPos = pos; while (true) { ReadOnlySpan<char> slice = textSpan.Slice(startingPos); // Find the literal. If we can't find it, we're done searching. int i = literal.String is not null ? slice.IndexOf(literal.String.AsSpan()) : literal.Chars is not null ? slice.IndexOfAny(literal.Chars.AsSpan()) : slice.IndexOf(literal.Char); if (i < 0) { break; } // We found the literal. Walk backwards from it finding as many matches as we can against the loop. int prev = i; while ((uint)--prev < (uint)slice.Length && RegexCharClass.CharInClass(slice[prev], loopNode.Str!, ref _asciiLookups![0])) ; // If we found fewer than needed, loop around to try again. The loop doesn't overlap with the literal, // so we can start from after the last place the literal matched. if ((i - prev - 1) < loopNode.M) { startingPos += i + 1; continue; } // We have a winner. The starting position is just after the last position that failed to match the loop. // TODO: It'd be nice to be able to communicate literalPos as a place the matching engine can start matching // after the loop, so that it doesn't need to re-match the loop. This might only be feasible for RegexCompiler // and the source generator after we refactor them to generate a single Scan method rather than separate // FindFirstChar / Go methods. pos = startingPos + prev + 1; return true; } pos = textSpan.Length; return false; } // Nothing special to look for. Just return true indicating this is a valid position to try to match. default: Debug.Assert(FindMode == FindNextStartingPositionMode.NoSearch); return true; } } } /// <summary>Mode to use for searching for the next location of a possible match.</summary> internal enum FindNextStartingPositionMode { /// <summary>A "beginning" anchor at the beginning of the pattern.</summary> LeadingAnchor_LeftToRight_Beginning, /// <summary>A "start" anchor at the beginning of the pattern.</summary> LeadingAnchor_LeftToRight_Start, /// <summary>An "endz" anchor at the beginning of the pattern. This is rare.</summary> LeadingAnchor_LeftToRight_EndZ, /// <summary>An "end" anchor at the beginning of the pattern. This is rare.</summary> LeadingAnchor_LeftToRight_End, /// <summary>A "beginning" anchor at the beginning of the right-to-left pattern.</summary> LeadingAnchor_RightToLeft_Beginning, /// <summary>A "start" anchor at the beginning of the right-to-left pattern.</summary> LeadingAnchor_RightToLeft_Start, /// <summary>An "endz" anchor at the beginning of the right-to-left pattern. This is rare.</summary> LeadingAnchor_RightToLeft_EndZ, /// <summary>An "end" anchor at the beginning of the right-to-left pattern. This is rare.</summary> LeadingAnchor_RightToLeft_End, /// <summary>An "end" anchor at the end of the pattern, with the pattern always matching a fixed-length expression.</summary> TrailingAnchor_FixedLength_LeftToRight_End, /// <summary>An "endz" anchor at the end of the pattern, with the pattern always matching a fixed-length expression.</summary> TrailingAnchor_FixedLength_LeftToRight_EndZ, /// <summary>A case-sensitive multi-character substring at the beginning of the pattern.</summary> LeadingPrefix_LeftToRight_CaseSensitive, /// <summary>A case-sensitive multi-character substring at the beginning of the right-to-left pattern.</summary> LeadingPrefix_RightToLeft_CaseSensitive, /// <summary>A case-sensitive set starting the pattern.</summary> LeadingSet_LeftToRight_CaseSensitive, /// <summary>A case-insensitive set starting the pattern.</summary> LeadingSet_LeftToRight_CaseInsensitive, /// <summary>A case-sensitive set starting the right-to-left pattern.</summary> LeadingSet_RightToLeft_CaseSensitive, /// <summary>A case-insensitive set starting the right-to-left pattern.</summary> LeadingSet_RightToLeft_CaseInsensitive, /// <summary>A case-sensitive single character at a fixed distance from the start of the right-to-left pattern.</summary> LeadingLiteral_RightToLeft_CaseSensitive, /// <summary>A case-insensitive single character at a fixed distance from the start of the right-to-left pattern.</summary> LeadingLiteral_RightToLeft_CaseInsensitive, /// <summary>A case-sensitive single character at a fixed distance from the start of the pattern.</summary> FixedLiteral_LeftToRight_CaseSensitive, /// <summary>A case-insensitive single character at a fixed distance from the start of the pattern.</summary> FixedLiteral_LeftToRight_CaseInsensitive, /// <summary>One or more sets at a fixed distance from the start of the pattern. At least the first set is case-sensitive.</summary> FixedSets_LeftToRight_CaseSensitive, /// <summary>One or more sets at a fixed distance from the start of the pattern. At least the first set is case-insensitive.</summary> FixedSets_LeftToRight_CaseInsensitive, /// <summary>A literal after a non-overlapping set loop at the start of the pattern. The literal is case-sensitive.</summary> LiteralAfterLoop_LeftToRight_CaseSensitive, /// <summary>Nothing to search for. Nop.</summary> NoSearch, } }
1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexLWCGCompiler.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.Threading; using System.Reflection; using System.Reflection.Emit; namespace System.Text.RegularExpressions { internal sealed class RegexLWCGCompiler : RegexCompiler { /// <summary> /// Name of the environment variable used to opt-in to including the regex pattern in the DynamicMethod name. /// Set the environment variable to "1" to turn this on. /// </summary> private const string IncludePatternInNamesEnvVar = "DOTNET_SYSTEM_TEXT_REGULAREXPRESSIONS_PATTERNINNAME"; /// <summary> /// If true, the pattern (or a portion of it) are included in the generated DynamicMethod names. /// </summary> /// <remarks> /// This is opt-in to avoid exposing the pattern, which may itself be dynamically built in diagnostics by default. /// </remarks> private static readonly bool s_includePatternInName = Environment.GetEnvironmentVariable(IncludePatternInNamesEnvVar) == "1"; /// <summary>Parameter types for the generated Go and FindFirstChar methods.</summary> private static readonly Type[] s_paramTypes = new Type[] { typeof(RegexRunner), typeof(ReadOnlySpan<char>) }; /// <summary>Id number to use for the next compiled regex.</summary> private static int s_regexCount; /// <summary>The top-level driver. Initializes everything then calls the Generate* methods.</summary> public RegexRunnerFactory? FactoryInstanceFromCode(string pattern, RegexTree regexTree, RegexOptions options, bool hasTimeout) { if (!regexTree.Root.SupportsCompilation(out _)) { return null; } _regexTree = regexTree; _options = options; _hasTimeout = hasTimeout; // Pick a unique number for the methods we generate. uint regexNum = (uint)Interlocked.Increment(ref s_regexCount); // Get a description of the regex to use in the name. This is helpful when profiling, and is opt-in. string description = string.Empty; if (s_includePatternInName) { const int DescriptionLimit = 100; // arbitrary limit to avoid very long method names description = string.Concat("_", pattern.Length > DescriptionLimit ? pattern.AsSpan(0, DescriptionLimit) : pattern); } DynamicMethod tryfindNextPossibleStartPositionMethod = DefineDynamicMethod($"Regex{regexNum}_TryFindNextPossibleStartingPosition{description}", typeof(bool), typeof(CompiledRegexRunner), s_paramTypes); EmitTryFindNextPossibleStartingPosition(); DynamicMethod tryMatchAtCurrentPositionMethod = DefineDynamicMethod($"Regex{regexNum}_TryMatchAtCurrentPosition{description}", typeof(bool), typeof(CompiledRegexRunner), s_paramTypes); EmitTryMatchAtCurrentPosition(); DynamicMethod scanMethod = DefineDynamicMethod($"Regex{regexNum}_Scan{description}", null, typeof(CompiledRegexRunner), new[] { typeof(RegexRunner), typeof(ReadOnlySpan<char>) }); EmitScan(tryfindNextPossibleStartPositionMethod, tryMatchAtCurrentPositionMethod); return new CompiledRegexRunnerFactory(scanMethod); } /// <summary>Begins the definition of a new method (no args) with a specified return value.</summary> private DynamicMethod DefineDynamicMethod(string methname, Type? returntype, Type hostType, Type[] paramTypes) { // We're claiming that these are static methods, but really they are instance methods. // By giving them a parameter which represents "this", we're tricking them into // being instance methods. const MethodAttributes Attribs = MethodAttributes.Public | MethodAttributes.Static; const CallingConventions Conventions = CallingConventions.Standard; var dm = new DynamicMethod(methname, Attribs, Conventions, returntype, paramTypes, hostType, skipVisibility: false); _ilg = dm.GetILGenerator(); return dm; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Threading; using System.Reflection; using System.Reflection.Emit; namespace System.Text.RegularExpressions { internal sealed class RegexLWCGCompiler : RegexCompiler { /// <summary> /// Name of the environment variable used to opt-in to including the regex pattern in the DynamicMethod name. /// Set the environment variable to "1" to turn this on. /// </summary> private const string IncludePatternInNamesEnvVar = "DOTNET_SYSTEM_TEXT_REGULAREXPRESSIONS_PATTERNINNAME"; /// <summary> /// If true, the pattern (or a portion of it) are included in the generated DynamicMethod names. /// </summary> /// <remarks> /// This is opt-in to avoid exposing the pattern, which may itself be dynamically built in diagnostics by default. /// </remarks> private static readonly bool s_includePatternInName = Environment.GetEnvironmentVariable(IncludePatternInNamesEnvVar) == "1"; /// <summary>Parameter types for the generated Go and FindFirstChar methods.</summary> private static readonly Type[] s_paramTypes = new Type[] { typeof(RegexRunner), typeof(ReadOnlySpan<char>) }; /// <summary>Id number to use for the next compiled regex.</summary> private static int s_regexCount; /// <summary>The top-level driver. Initializes everything then calls the Generate* methods.</summary> public RegexRunnerFactory? FactoryInstanceFromCode(string pattern, RegexTree regexTree, RegexOptions options, bool hasTimeout) { if (!regexTree.Root.SupportsCompilation(out _)) { return null; } _regexTree = regexTree; _options = options; _hasTimeout = hasTimeout; // Pick a unique number for the methods we generate. uint regexNum = (uint)Interlocked.Increment(ref s_regexCount); // Get a description of the regex to use in the name. This is helpful when profiling, and is opt-in. string description = string.Empty; if (s_includePatternInName) { const int DescriptionLimit = 100; // arbitrary limit to avoid very long method names description = string.Concat("_", pattern.Length > DescriptionLimit ? pattern.AsSpan(0, DescriptionLimit) : pattern); } DynamicMethod tryfindNextPossibleStartPositionMethod = DefineDynamicMethod($"Regex{regexNum}_TryFindNextPossibleStartingPosition{description}", typeof(bool), typeof(CompiledRegexRunner), s_paramTypes); EmitTryFindNextPossibleStartingPosition(); DynamicMethod tryMatchAtCurrentPositionMethod = DefineDynamicMethod($"Regex{regexNum}_TryMatchAtCurrentPosition{description}", typeof(bool), typeof(CompiledRegexRunner), s_paramTypes); EmitTryMatchAtCurrentPosition(); DynamicMethod scanMethod = DefineDynamicMethod($"Regex{regexNum}_Scan{description}", null, typeof(CompiledRegexRunner), new[] { typeof(RegexRunner), typeof(ReadOnlySpan<char>) }); EmitScan(options, tryfindNextPossibleStartPositionMethod, tryMatchAtCurrentPositionMethod); return new CompiledRegexRunnerFactory(scanMethod); } /// <summary>Begins the definition of a new method (no args) with a specified return value.</summary> private DynamicMethod DefineDynamicMethod(string methname, Type? returntype, Type hostType, Type[] paramTypes) { // We're claiming that these are static methods, but really they are instance methods. // By giving them a parameter which represents "this", we're tricking them into // being instance methods. const MethodAttributes Attribs = MethodAttributes.Public | MethodAttributes.Static; const CallingConventions Conventions = CallingConventions.Standard; var dm = new DynamicMethod(methname, Attribs, Conventions, returntype, paramTypes, hostType, skipVisibility: false); _ilg = dm.GetILGenerator(); return dm; } } }
1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexNode.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.Threading; namespace System.Text.RegularExpressions { /// <summary>Represents a regex subexpression.</summary> internal sealed class RegexNode { /// <summary>empty bit from the node's options to store data on whether a node contains captures</summary> internal const RegexOptions HasCapturesFlag = (RegexOptions)(1 << 31); /// <summary>Arbitrary number of repetitions of the same character when we'd prefer to represent that as a repeater of that character rather than a string.</summary> internal const int MultiVsRepeaterLimit = 64; /// <summary>The node's children.</summary> /// <remarks>null if no children, a <see cref="RegexNode"/> if one child, or a <see cref="List{RegexNode}"/> if multiple children.</remarks> private object? Children; /// <summary>The kind of expression represented by this node.</summary> public RegexNodeKind Kind { get; private set; } /// <summary>A string associated with the node.</summary> /// <remarks>For a <see cref="RegexNodeKind.Multi"/>, this is the string from the expression. For an <see cref="IsSetFamily"/> node, this is the character class string from <see cref="RegexCharClass"/>.</remarks> public string? Str { get; private set; } /// <summary>The character associated with the node.</summary> /// <remarks>For a <see cref="IsOneFamily"/> or <see cref="IsNotoneFamily"/> node, the character from the expression.</remarks> public char Ch { get; private set; } /// <summary>The minimum number of iterations for a loop, or the capture group number for a capture or backreference.</summary> /// <remarks>No minimum is represented by 0. No capture group is represented by -1.</remarks> public int M { get; private set; } /// <summary>The maximum number of iterations for a loop, or the uncapture group number for a balancing group.</summary> /// <remarks>No upper bound is represented by <see cref="int.MaxValue"/>. No capture group is represented by -1.</remarks> public int N { get; private set; } /// <summary>The options associated with the node.</summary> public RegexOptions Options; /// <summary>The node's parent node in the tree.</summary> /// <remarks> /// During parsing, top-level nodes are also stacked onto a parse stack (a stack of trees) using <see cref="Parent"/>. /// After parsing, <see cref="Parent"/> is the node in the tree that has this node as or in <see cref="Children"/>. /// </remarks> public RegexNode? Parent; public RegexNode(RegexNodeKind kind, RegexOptions options) { Kind = kind; Options = options; } public RegexNode(RegexNodeKind kind, RegexOptions options, char ch) { Kind = kind; Options = options; Ch = ch; } public RegexNode(RegexNodeKind kind, RegexOptions options, string str) { Kind = kind; Options = options; Str = str; } public RegexNode(RegexNodeKind kind, RegexOptions options, int m) { Kind = kind; Options = options; M = m; } public RegexNode(RegexNodeKind kind, RegexOptions options, int m, int n) { Kind = kind; Options = options; M = m; N = n; } /// <summary>Creates a RegexNode representing a single character.</summary> /// <param name="ch">The character.</param> /// <param name="options">The node's options.</param> /// <param name="culture">The culture to use to perform any required transformations.</param> /// <returns>The created RegexNode. This might be a RegexNode.One or a RegexNode.Set.</returns> public static RegexNode CreateOneWithCaseConversion(char ch, RegexOptions options, CultureInfo? culture) { // If the options specify case-insensitivity, we try to create a node that fully encapsulates that. if ((options & RegexOptions.IgnoreCase) != 0) { Debug.Assert(culture is not null); // If the character is part of a Unicode category that doesn't participate in case conversion, // we can simply strip out the IgnoreCase option and make the node case-sensitive. if (!RegexCharClass.ParticipatesInCaseConversion(ch)) { return new RegexNode(RegexNodeKind.One, options & ~RegexOptions.IgnoreCase, ch); } // Create a set for the character, trying to include all case-insensitive equivalent characters. // If it's successful in doing so, resultIsCaseInsensitive will be false and we can strip // out RegexOptions.IgnoreCase as part of creating the set. string stringSet = RegexCharClass.OneToStringClass(ch, culture, out bool resultIsCaseInsensitive); if (!resultIsCaseInsensitive) { return new RegexNode(RegexNodeKind.Set, options & ~RegexOptions.IgnoreCase, stringSet); } // Otherwise, until we can get rid of ToLower usage at match time entirely (https://github.com/dotnet/runtime/issues/61048), // lowercase the character and proceed to create an IgnoreCase One node. ch = culture.TextInfo.ToLower(ch); } // Create a One node for the character. return new RegexNode(RegexNodeKind.One, options, ch); } /// <summary>Reverses all children of a concatenation when in RightToLeft mode.</summary> public RegexNode ReverseConcatenationIfRightToLeft() { if ((Options & RegexOptions.RightToLeft) != 0 && Kind == RegexNodeKind.Concatenate && ChildCount() > 1) { ((List<RegexNode>)Children!).Reverse(); } return this; } /// <summary> /// Pass type as OneLazy or OneLoop /// </summary> private void MakeRep(RegexNodeKind kind, int min, int max) { Kind += kind - RegexNodeKind.One; M = min; N = max; } private void MakeLoopAtomic() { switch (Kind) { case RegexNodeKind.Oneloop or RegexNodeKind.Notoneloop or RegexNodeKind.Setloop: // For loops, we simply change the Type to the atomic variant. // Atomic greedy loops should consume as many values as they can. Kind += RegexNodeKind.Oneloopatomic - RegexNodeKind.Oneloop; break; case RegexNodeKind.Onelazy or RegexNodeKind.Notonelazy or RegexNodeKind.Setlazy: // For lazy, we not only change the Type, we also lower the max number of iterations // to the minimum number of iterations, creating a repeater, as they should end up // matching as little as possible. Kind += RegexNodeKind.Oneloopatomic - RegexNodeKind.Onelazy; N = M; if (N == 0) { // If moving the max to be the same as the min dropped it to 0, there's no // work to be done for this node, and we can make it Empty. Kind = RegexNodeKind.Empty; Str = null; Ch = '\0'; } else if (Kind == RegexNodeKind.Oneloopatomic && N is >= 2 and <= MultiVsRepeaterLimit) { // If this is now a One repeater with a small enough length, // make it a Multi instead, as they're better optimized down the line. Kind = RegexNodeKind.Multi; Str = new string(Ch, N); Ch = '\0'; M = N = 0; } break; default: Debug.Fail($"Unexpected type: {Kind}"); break; } } #if DEBUG /// <summary>Validate invariants the rest of the implementation relies on for processing fully-built trees.</summary> [Conditional("DEBUG")] private void ValidateFinalTreeInvariants() { Debug.Assert(Kind == RegexNodeKind.Capture, "Every generated tree should begin with a capture node"); var toExamine = new Stack<RegexNode>(); toExamine.Push(this); while (toExamine.Count > 0) { RegexNode node = toExamine.Pop(); // Add all children to be examined int childCount = node.ChildCount(); for (int i = 0; i < childCount; i++) { RegexNode child = node.Child(i); Debug.Assert(child.Parent == node, $"{child.Describe()} missing reference to parent {node.Describe()}"); toExamine.Push(child); } // Validate that we never see certain node types. Debug.Assert(Kind != RegexNodeKind.Group, "All Group nodes should have been removed."); // Validate node types and expected child counts. switch (node.Kind) { case RegexNodeKind.Group: Debug.Fail("All Group nodes should have been removed."); break; case RegexNodeKind.Beginning: case RegexNodeKind.Bol: case RegexNodeKind.Boundary: case RegexNodeKind.ECMABoundary: case RegexNodeKind.Empty: case RegexNodeKind.End: case RegexNodeKind.EndZ: case RegexNodeKind.Eol: case RegexNodeKind.Multi: case RegexNodeKind.NonBoundary: case RegexNodeKind.NonECMABoundary: case RegexNodeKind.Nothing: case RegexNodeKind.Notone: case RegexNodeKind.Notonelazy: case RegexNodeKind.Notoneloop: case RegexNodeKind.Notoneloopatomic: case RegexNodeKind.One: case RegexNodeKind.Onelazy: case RegexNodeKind.Oneloop: case RegexNodeKind.Oneloopatomic: case RegexNodeKind.Backreference: case RegexNodeKind.Set: case RegexNodeKind.Setlazy: case RegexNodeKind.Setloop: case RegexNodeKind.Setloopatomic: case RegexNodeKind.Start: case RegexNodeKind.UpdateBumpalong: Debug.Assert(childCount == 0, $"Expected zero children for {node.Kind}, got {childCount}."); break; case RegexNodeKind.Atomic: case RegexNodeKind.Capture: case RegexNodeKind.Lazyloop: case RegexNodeKind.Loop: case RegexNodeKind.NegativeLookaround: case RegexNodeKind.PositiveLookaround: Debug.Assert(childCount == 1, $"Expected one and only one child for {node.Kind}, got {childCount}."); break; case RegexNodeKind.BackreferenceConditional: Debug.Assert(childCount == 2, $"Expected two children for {node.Kind}, got {childCount}"); break; case RegexNodeKind.ExpressionConditional: Debug.Assert(childCount == 3, $"Expected three children for {node.Kind}, got {childCount}"); break; case RegexNodeKind.Concatenate: case RegexNodeKind.Alternate: Debug.Assert(childCount >= 2, $"Expected at least two children for {node.Kind}, got {childCount}."); break; default: Debug.Fail($"Unexpected node type: {node.Kind}"); break; } // Validate node configuration. switch (node.Kind) { case RegexNodeKind.Multi: Debug.Assert(node.Str is not null, "Expect non-null multi string"); Debug.Assert(node.Str.Length >= 2, $"Expected {node.Str} to be at least two characters"); break; case RegexNodeKind.Set: case RegexNodeKind.Setloop: case RegexNodeKind.Setloopatomic: case RegexNodeKind.Setlazy: Debug.Assert(!string.IsNullOrEmpty(node.Str), $"Expected non-null, non-empty string for {node.Kind}."); break; default: Debug.Assert(node.Str is null, $"Expected null string for {node.Kind}, got \"{node.Str}\"."); break; } } } #endif /// <summary>Performs additional optimizations on an entire tree prior to being used.</summary> /// <remarks> /// Some optimizations are performed by the parser while parsing, and others are performed /// as nodes are being added to the tree. The optimizations here expect the tree to be fully /// formed, as they inspect relationships between nodes that may not have been in place as /// individual nodes were being processed/added to the tree. /// </remarks> internal RegexNode FinalOptimize() { RegexNode rootNode = this; Debug.Assert(rootNode.Kind == RegexNodeKind.Capture); Debug.Assert(rootNode.Parent is null); Debug.Assert(rootNode.ChildCount() == 1); // Only apply optimization when LTR to avoid needing additional code for the much rarer RTL case. // Also only apply these optimizations when not using NonBacktracking, as these optimizations are // all about avoiding things that are impactful for the backtracking engines but nops for non-backtracking. if ((Options & (RegexOptions.RightToLeft | RegexOptions.NonBacktracking)) == 0) { // Optimization: eliminate backtracking for loops. // For any single-character loop (Oneloop, Notoneloop, Setloop), see if we can automatically convert // that into its atomic counterpart (Oneloopatomic, Notoneloopatomic, Setloopatomic) based on what // comes after it in the expression tree. rootNode.FindAndMakeLoopsAtomic(); // Optimization: backtracking removal at expression end. // If we find backtracking construct at the end of the regex, we can instead make it non-backtracking, // since nothing would ever backtrack into it anyway. Doing this then makes the construct available // to implementations that don't support backtracking. rootNode.EliminateEndingBacktracking(); // Optimization: unnecessary re-processing of starting loops. // If an expression is guaranteed to begin with a single-character unbounded loop that isn't part of an alternation (in which case it // wouldn't be guaranteed to be at the beginning) or a capture (in which case a back reference could be influenced by its length), then we // can update the tree with a temporary node to indicate that the implementation should use that node's ending position in the input text // as the next starting position at which to start the next match. This avoids redoing matches we've already performed, e.g. matching // "\[email protected]" against "is this a valid [email protected]", the \w+ will initially match the "is" and then will fail to match the "@". // Rather than bumping the scan loop by 1 and trying again to match at the "s", we can instead start at the " ". For functional correctness // we can only consider unbounded loops, as to be able to start at the end of the loop we need the loop to have consumed all possible matches; // otherwise, you could end up with a pattern like "a{1,3}b" matching against "aaaabc", which should match, but if we pre-emptively stop consuming // after the first three a's and re-start from that position, we'll end up failing the match even though it should have succeeded. We can also // apply this optimization to non-atomic loops: even though backtracking could be necessary, such backtracking would be handled within the processing // of a single starting position. Lazy loops similarly benefit, as a failed match will result in exploring the exact same search space as with // a greedy loop, just in the opposite order (and a successful match will overwrite the bumpalong position); we need to avoid atomic lazy loops, // however, as they will only end up as a repeater for the minimum length and thus will effectively end up with a non-infinite upper bound, which // we've already outlined is problematic. { RegexNode node = rootNode.Child(0); // skip implicit root capture node bool atomicByAncestry = true; // the root is implicitly atomic because nothing comes after it (same for the implicit root capture) while (true) { switch (node.Kind) { case RegexNodeKind.Atomic: node = node.Child(0); continue; case RegexNodeKind.Concatenate: atomicByAncestry = false; node = node.Child(0); continue; case RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic when node.N == int.MaxValue: case RegexNodeKind.Onelazy or RegexNodeKind.Notonelazy or RegexNodeKind.Setlazy when node.N == int.MaxValue && !atomicByAncestry: if (node.Parent is { Kind: RegexNodeKind.Concatenate } parent) { parent.InsertChild(1, new RegexNode(RegexNodeKind.UpdateBumpalong, node.Options)); } break; } break; } } } // Done optimizing. Return the final tree. #if DEBUG rootNode.ValidateFinalTreeInvariants(); #endif return rootNode; } /// <summary>Converts nodes at the end of the node tree to be atomic.</summary> /// <remarks> /// The correctness of this optimization depends on nothing being able to backtrack into /// the provided node. That means it must be at the root of the overall expression, or /// it must be an Atomic node that nothing will backtrack into by the very nature of Atomic. /// </remarks> private void EliminateEndingBacktracking() { if (!StackHelper.TryEnsureSufficientExecutionStack() || (Options & (RegexOptions.RightToLeft | RegexOptions.NonBacktracking)) != 0) { // If we can't recur further, just stop optimizing. // We haven't done the work to validate this is correct for RTL. // And NonBacktracking doesn't support atomic groups and doesn't have backtracking to be eliminated. return; } // Walk the tree starting from the current node. RegexNode node = this; while (true) { switch (node.Kind) { // {One/Notone/Set}loops can be upgraded to {One/Notone/Set}loopatomic nodes, e.g. [abc]* => (?>[abc]*). // And {One/Notone/Set}lazys can similarly be upgraded to be atomic, which really makes them into repeaters // or even empty nodes. case RegexNodeKind.Oneloop or RegexNodeKind.Notoneloop or RegexNodeKind.Setloop: case RegexNodeKind.Onelazy or RegexNodeKind.Notonelazy or RegexNodeKind.Setlazy: node.MakeLoopAtomic(); break; // Just because a particular node is atomic doesn't mean all its descendants are. // Process them as well. Lookarounds are implicitly atomic. case RegexNodeKind.Atomic: case RegexNodeKind.PositiveLookaround: case RegexNodeKind.NegativeLookaround: node = node.Child(0); continue; // For Capture and Concatenate, we just recur into their last child (only child in the case // of Capture). However, if the child is an alternation or loop, we can also make the // node itself atomic by wrapping it in an Atomic node. Since we later check to see whether a // node is atomic based on its parent or grandparent, we don't bother wrapping such a node in // an Atomic one if its grandparent is already Atomic. // e.g. [xyz](?:abc|def) => [xyz](?>abc|def) case RegexNodeKind.Capture: case RegexNodeKind.Concatenate: RegexNode existingChild = node.Child(node.ChildCount() - 1); if ((existingChild.Kind is RegexNodeKind.Alternate or RegexNodeKind.BackreferenceConditional or RegexNodeKind.ExpressionConditional or RegexNodeKind.Loop or RegexNodeKind.Lazyloop) && (node.Parent is null || node.Parent.Kind != RegexNodeKind.Atomic)) // validate grandparent isn't atomic { var atomic = new RegexNode(RegexNodeKind.Atomic, existingChild.Options); atomic.AddChild(existingChild); node.ReplaceChild(node.ChildCount() - 1, atomic); } node = existingChild; continue; // For alternate, we can recur into each branch separately. We use this iteration for the first branch. // Conditionals are just like alternations in this regard. // e.g. abc*|def* => ab(?>c*)|de(?>f*) case RegexNodeKind.Alternate: case RegexNodeKind.BackreferenceConditional: case RegexNodeKind.ExpressionConditional: { int branches = node.ChildCount(); for (int i = 1; i < branches; i++) { node.Child(i).EliminateEndingBacktracking(); } if (node.Kind != RegexNodeKind.ExpressionConditional) // ReduceExpressionConditional will have already applied ending backtracking removal { node = node.Child(0); continue; } } break; // For {Lazy}Loop, we search to see if there's a viable last expression, and iff there // is we recur into processing it. Also, as with the single-char lazy loops, LazyLoop // can have its max iteration count dropped to its min iteration count, as there's no // reason for it to match more than the minimal at the end; that in turn makes it a // repeater, which results in better code generation. // e.g. (?:abc*)* => (?:ab(?>c*))* // e.g. (abc*?)+? => (ab){1} case RegexNodeKind.Lazyloop: node.N = node.M; goto case RegexNodeKind.Loop; case RegexNodeKind.Loop: { if (node.N == 1) { // If the loop has a max iteration count of 1 (e.g. it's an optional node), // there's no possibility for conflict between multiple iterations, so // we can process it. node = node.Child(0); continue; } RegexNode? loopDescendent = node.FindLastExpressionInLoopForAutoAtomic(); if (loopDescendent != null) { node = loopDescendent; continue; // loop around to process node } } break; } break; } } /// <summary> /// Removes redundant nodes from the subtree, and returns an optimized subtree. /// </summary> internal RegexNode Reduce() { // TODO: https://github.com/dotnet/runtime/issues/61048 // As part of overhauling IgnoreCase handling, the parser shouldn't produce any nodes other than Backreference // that ever have IgnoreCase set on them. For now, though, remove IgnoreCase from any nodes for which it // has no behavioral effect. switch (Kind) { default: // No effect Options &= ~RegexOptions.IgnoreCase; break; case RegexNodeKind.One or RegexNodeKind.Onelazy or RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic: case RegexNodeKind.Notone or RegexNodeKind.Notonelazy or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic: case RegexNodeKind.Set or RegexNodeKind.Setlazy or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic: case RegexNodeKind.Multi: case RegexNodeKind.Backreference: // Still meaningful break; } return Kind switch { RegexNodeKind.Alternate => ReduceAlternation(), RegexNodeKind.Atomic => ReduceAtomic(), RegexNodeKind.Concatenate => ReduceConcatenation(), RegexNodeKind.Group => ReduceGroup(), RegexNodeKind.Loop or RegexNodeKind.Lazyloop => ReduceLoops(), RegexNodeKind.PositiveLookaround or RegexNodeKind.NegativeLookaround => ReduceLookaround(), RegexNodeKind.Set or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic or RegexNodeKind.Setlazy => ReduceSet(), RegexNodeKind.ExpressionConditional => ReduceExpressionConditional(), RegexNodeKind.BackreferenceConditional => ReduceBackreferenceConditional(), _ => this, }; } /// <summary>Remove an unnecessary Concatenation or Alternation node</summary> /// <remarks> /// Simple optimization for a concatenation or alternation: /// - if the node has only one child, use it instead /// - if the node has zero children, turn it into an empty with Nothing for an alternation or Empty for a concatenation /// </remarks> private RegexNode ReplaceNodeIfUnnecessary() { Debug.Assert(Kind is RegexNodeKind.Alternate or RegexNodeKind.Concatenate); return ChildCount() switch { 0 => new RegexNode(Kind == RegexNodeKind.Alternate ? RegexNodeKind.Nothing : RegexNodeKind.Empty, Options), 1 => Child(0), _ => this, }; } /// <summary>Remove all non-capturing groups.</summary> /// <remark> /// Simple optimization: once parsed into a tree, non-capturing groups /// serve no function, so strip them out. /// e.g. (?:(?:(?:abc))) => abc /// </remark> private RegexNode ReduceGroup() { Debug.Assert(Kind == RegexNodeKind.Group); RegexNode u = this; while (u.Kind == RegexNodeKind.Group) { Debug.Assert(u.ChildCount() == 1); u = u.Child(0); } return u; } /// <summary> /// Remove unnecessary atomic nodes, and make appropriate descendents of the atomic node themselves atomic. /// </summary> /// <remarks> /// e.g. (?>(?>(?>a*))) => (?>a*) /// e.g. (?>(abc*)*) => (?>(abc(?>c*))*) /// </remarks> private RegexNode ReduceAtomic() { // RegexOptions.NonBacktracking doesn't support atomic groups, so when that option // is set we don't want to create atomic groups where they weren't explicitly authored. if ((Options & RegexOptions.NonBacktracking) != 0) { return this; } Debug.Assert(Kind == RegexNodeKind.Atomic); Debug.Assert(ChildCount() == 1); RegexNode atomic = this; RegexNode child = Child(0); while (child.Kind == RegexNodeKind.Atomic) { atomic = child; child = atomic.Child(0); } switch (child.Kind) { // If the child is empty/nothing, there's nothing to be made atomic so the Atomic // node can simply be removed. case RegexNodeKind.Empty: case RegexNodeKind.Nothing: return child; // If the child is already atomic, we can just remove the atomic node. case RegexNodeKind.Oneloopatomic: case RegexNodeKind.Notoneloopatomic: case RegexNodeKind.Setloopatomic: return child; // If an atomic subexpression contains only a {one/notone/set}{loop/lazy}, // change it to be an {one/notone/set}loopatomic and remove the atomic node. case RegexNodeKind.Oneloop: case RegexNodeKind.Notoneloop: case RegexNodeKind.Setloop: case RegexNodeKind.Onelazy: case RegexNodeKind.Notonelazy: case RegexNodeKind.Setlazy: child.MakeLoopAtomic(); return child; // Alternations have a variety of possible optimizations that can be applied // iff they're atomic. case RegexNodeKind.Alternate: if ((Options & RegexOptions.RightToLeft) == 0) { List<RegexNode>? branches = child.Children as List<RegexNode>; Debug.Assert(branches is not null && branches.Count != 0); // If an alternation is atomic and its first branch is Empty, the whole thing // is a nop, as Empty will match everything trivially, and no backtracking // into the node will be performed, making the remaining branches irrelevant. if (branches[0].Kind == RegexNodeKind.Empty) { return new RegexNode(RegexNodeKind.Empty, child.Options); } // Similarly, we can trim off any branches after an Empty, as they'll never be used. // An Empty will match anything, and thus branches after that would only be used // if we backtracked into it and advanced passed the Empty after trying the Empty... // but if the alternation is atomic, such backtracking won't happen. for (int i = 1; i < branches.Count - 1; i++) { if (branches[i].Kind == RegexNodeKind.Empty) { branches.RemoveRange(i + 1, branches.Count - (i + 1)); break; } } // If an alternation is atomic, we won't ever backtrack back into it, which // means order matters but not repetition. With backtracking, it would be incorrect // to convert an expression like "hi|there|hello" into "hi|hello|there", as doing // so could then change the order of results if we matched "hi" and then failed // based on what came after it, and both "hello" and "there" could be successful // with what came later. But without backtracking, we can reorder "hi|there|hello" // to instead be "hi|hello|there", as "hello" and "there" can't match the same text, // and once this atomic alternation has matched, we won't try another branch. This // reordering is valuable as it then enables further optimizations, e.g. // "hi|there|hello" => "hi|hello|there" => "h(?:i|ello)|there", which means we only // need to check the 'h' once in case it's not an 'h', and it's easier to employ different // code gen that, for example, switches on first character of the branches, enabling faster // choice of branch without always having to walk through each. bool reordered = false; for (int start = 0; start < branches.Count; start++) { // Get the node that may start our range. If it's a one, multi, or concat of those, proceed. RegexNode startNode = branches[start]; if (startNode.FindBranchOneOrMultiStart() is null) { continue; } // Find the contiguous range of nodes from this point that are similarly one, multi, or concat of those. int endExclusive = start + 1; while (endExclusive < branches.Count && branches[endExclusive].FindBranchOneOrMultiStart() is not null) { endExclusive++; } // If there's at least 3, there may be something to reorder (we won't reorder anything // before the starting position, and so only 2 items is considered ordered). if (endExclusive - start >= 3) { int compare = start; while (compare < endExclusive) { // Get the starting character char c = branches[compare].FindBranchOneOrMultiStart()!.FirstCharOfOneOrMulti(); // Move compare to point to the last branch that has the same starting value. while (compare < endExclusive && branches[compare].FindBranchOneOrMultiStart()!.FirstCharOfOneOrMulti() == c) { compare++; } // Compare now points to the first node that doesn't match the starting node. // If we've walked off our range, there's nothing left to reorder. if (compare < endExclusive) { // There may be something to reorder. See if there are any other nodes that begin with the same character. for (int next = compare + 1; next < endExclusive; next++) { RegexNode nextChild = branches[next]; if (nextChild.FindBranchOneOrMultiStart()!.FirstCharOfOneOrMulti() == c) { branches.RemoveAt(next); branches.Insert(compare++, nextChild); reordered = true; } } } } } // Move to the end of the range we've now explored. endExclusive is not a viable // starting position either, and the start++ for the loop will thus take us to // the next potential place to start a range. start = endExclusive; } // If anything was reordered, there may be new optimization opportunities inside // of the alternation, so reduce it again. if (reordered) { atomic.ReplaceChild(0, child); child = atomic.Child(0); } } goto default; // For everything else, try to reduce ending backtracking of the last contained expression. default: child.EliminateEndingBacktracking(); return atomic; } } /// <summary>Combine nested loops where applicable.</summary> /// <remarks> /// Nested repeaters just get multiplied with each other if they're not too lumpy. /// Other optimizations may have also resulted in {Lazy}loops directly containing /// sets, ones, and notones, in which case they can be transformed into the corresponding /// individual looping constructs. /// </remarks> private RegexNode ReduceLoops() { Debug.Assert(Kind is RegexNodeKind.Loop or RegexNodeKind.Lazyloop); RegexNode u = this; RegexNodeKind kind = Kind; int min = M; int max = N; while (u.ChildCount() > 0) { RegexNode child = u.Child(0); // multiply reps of the same type only if (child.Kind != kind) { bool valid = false; if (kind == RegexNodeKind.Loop) { switch (child.Kind) { case RegexNodeKind.Oneloop: case RegexNodeKind.Oneloopatomic: case RegexNodeKind.Notoneloop: case RegexNodeKind.Notoneloopatomic: case RegexNodeKind.Setloop: case RegexNodeKind.Setloopatomic: valid = true; break; } } else // type == Lazyloop { switch (child.Kind) { case RegexNodeKind.Onelazy: case RegexNodeKind.Notonelazy: case RegexNodeKind.Setlazy: valid = true; break; } } if (!valid) { break; } } // child can be too lumpy to blur, e.g., (a {100,105}) {3} or (a {2,})? // [but things like (a {2,})+ are not too lumpy...] if (u.M == 0 && child.M > 1 || child.N < child.M * 2) { break; } u = child; if (u.M > 0) { u.M = min = ((int.MaxValue - 1) / u.M < min) ? int.MaxValue : u.M * min; } if (u.N > 0) { u.N = max = ((int.MaxValue - 1) / u.N < max) ? int.MaxValue : u.N * max; } } if (min == int.MaxValue) { return new RegexNode(RegexNodeKind.Nothing, Options); } // If the Loop or Lazyloop now only has one child node and its a Set, One, or Notone, // reduce to just Setloop/lazy, Oneloop/lazy, or Notoneloop/lazy. The parser will // generally have only produced the latter, but other reductions could have exposed // this. if (u.ChildCount() == 1) { RegexNode child = u.Child(0); switch (child.Kind) { case RegexNodeKind.One: case RegexNodeKind.Notone: case RegexNodeKind.Set: child.MakeRep(u.Kind == RegexNodeKind.Lazyloop ? RegexNodeKind.Onelazy : RegexNodeKind.Oneloop, u.M, u.N); u = child; break; } } return u; } /// <summary> /// Reduces set-related nodes to simpler one-related and notone-related nodes, where applicable. /// </summary> /// <remarks> /// e.g. /// [a] => a /// [a]* => a* /// [a]*? => a*? /// (?>[a]*) => (?>a*) /// [^a] => ^a /// []* => Nothing /// </remarks> private RegexNode ReduceSet() { // Extract empty-set, one, and not-one case as special Debug.Assert(Kind is RegexNodeKind.Set or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic or RegexNodeKind.Setlazy); Debug.Assert(!string.IsNullOrEmpty(Str)); if (RegexCharClass.IsEmpty(Str)) { Kind = RegexNodeKind.Nothing; Str = null; } else if (RegexCharClass.IsSingleton(Str)) { Ch = RegexCharClass.SingletonChar(Str); Str = null; Kind = Kind == RegexNodeKind.Set ? RegexNodeKind.One : Kind == RegexNodeKind.Setloop ? RegexNodeKind.Oneloop : Kind == RegexNodeKind.Setloopatomic ? RegexNodeKind.Oneloopatomic : RegexNodeKind.Onelazy; } else if (RegexCharClass.IsSingletonInverse(Str)) { Ch = RegexCharClass.SingletonChar(Str); Str = null; Kind = Kind == RegexNodeKind.Set ? RegexNodeKind.Notone : Kind == RegexNodeKind.Setloop ? RegexNodeKind.Notoneloop : Kind == RegexNodeKind.Setloopatomic ? RegexNodeKind.Notoneloopatomic : RegexNodeKind.Notonelazy; } return this; } /// <summary>Optimize an alternation.</summary> private RegexNode ReduceAlternation() { Debug.Assert(Kind == RegexNodeKind.Alternate); switch (ChildCount()) { case 0: return new RegexNode(RegexNodeKind.Nothing, Options); case 1: return Child(0); default: ReduceSingleLetterAndNestedAlternations(); RegexNode node = ReplaceNodeIfUnnecessary(); if (node.Kind == RegexNodeKind.Alternate) { node = ExtractCommonPrefixText(node); if (node.Kind == RegexNodeKind.Alternate) { node = ExtractCommonPrefixOneNotoneSet(node); if (node.Kind == RegexNodeKind.Alternate) { node = RemoveRedundantEmptiesAndNothings(node); } } } return node; } // This function performs two optimizations: // - Single-letter alternations can be replaced by faster set specifications // e.g. "a|b|c|def|g|h" -> "[a-c]|def|[gh]" // - Nested alternations with no intervening operators can be flattened: // e.g. "apple|(?:orange|pear)|grape" -> "apple|orange|pear|grape" void ReduceSingleLetterAndNestedAlternations() { bool wasLastSet = false; bool lastNodeCannotMerge = false; RegexOptions optionsLast = 0; RegexOptions optionsAt; int i; int j; RegexNode at; RegexNode prev; List<RegexNode> children = (List<RegexNode>)Children!; for (i = 0, j = 0; i < children.Count; i++, j++) { at = children[i]; if (j < i) children[j] = at; while (true) { if (at.Kind == RegexNodeKind.Alternate) { if (at.Children is List<RegexNode> atChildren) { for (int k = 0; k < atChildren.Count; k++) { atChildren[k].Parent = this; } children.InsertRange(i + 1, atChildren); } else { RegexNode atChild = (RegexNode)at.Children!; atChild.Parent = this; children.Insert(i + 1, atChild); } j--; } else if (at.Kind is RegexNodeKind.Set or RegexNodeKind.One) { // Cannot merge sets if L or I options differ, or if either are negated. optionsAt = at.Options & (RegexOptions.RightToLeft | RegexOptions.IgnoreCase); if (at.Kind == RegexNodeKind.Set) { if (!wasLastSet || optionsLast != optionsAt || lastNodeCannotMerge || !RegexCharClass.IsMergeable(at.Str!)) { wasLastSet = true; lastNodeCannotMerge = !RegexCharClass.IsMergeable(at.Str!); optionsLast = optionsAt; break; } } else if (!wasLastSet || optionsLast != optionsAt || lastNodeCannotMerge) { wasLastSet = true; lastNodeCannotMerge = false; optionsLast = optionsAt; break; } // The last node was a Set or a One, we're a Set or One and our options are the same. // Merge the two nodes. j--; prev = children[j]; RegexCharClass prevCharClass; if (prev.Kind == RegexNodeKind.One) { prevCharClass = new RegexCharClass(); prevCharClass.AddChar(prev.Ch); } else { prevCharClass = RegexCharClass.Parse(prev.Str!); } if (at.Kind == RegexNodeKind.One) { prevCharClass.AddChar(at.Ch); } else { RegexCharClass atCharClass = RegexCharClass.Parse(at.Str!); prevCharClass.AddCharClass(atCharClass); } prev.Kind = RegexNodeKind.Set; prev.Str = prevCharClass.ToStringClass(Options); if ((prev.Options & RegexOptions.IgnoreCase) != 0 && RegexCharClass.MakeCaseSensitiveIfPossible(prev.Str, RegexParser.GetTargetCulture(prev.Options)) is string newSetString) { prev.Str = newSetString; prev.Options &= ~RegexOptions.IgnoreCase; } } else if (at.Kind == RegexNodeKind.Nothing) { j--; } else { wasLastSet = false; lastNodeCannotMerge = false; } break; } } if (j < i) { children.RemoveRange(j, i - j); } } // This function optimizes out prefix nodes from alternation branches that are // the same across multiple contiguous branches. // e.g. \w12|\d34|\d56|\w78|\w90 => \w12|\d(?:34|56)|\w(?:78|90) static RegexNode ExtractCommonPrefixOneNotoneSet(RegexNode alternation) { Debug.Assert(alternation.Kind == RegexNodeKind.Alternate); Debug.Assert(alternation.Children is List<RegexNode> { Count: >= 2 }); var children = (List<RegexNode>)alternation.Children; // Only process left-to-right prefixes. if ((alternation.Options & RegexOptions.RightToLeft) != 0) { return alternation; } // Only handle the case where each branch is a concatenation foreach (RegexNode child in children) { if (child.Kind != RegexNodeKind.Concatenate || child.ChildCount() < 2) { return alternation; } } for (int startingIndex = 0; startingIndex < children.Count - 1; startingIndex++) { Debug.Assert(children[startingIndex].Children is List<RegexNode> { Count: >= 2 }); // Only handle the case where each branch begins with the same One, Notone, or Set (individual or loop). // Note that while we can do this for individual characters, fixed length loops, and atomic loops, doing // it for non-atomic variable length loops could change behavior as each branch could otherwise have a // different number of characters consumed by the loop based on what's after it. RegexNode required = children[startingIndex].Child(0); switch (required.Kind) { case RegexNodeKind.One or RegexNodeKind.Notone or RegexNodeKind.Set: case RegexNodeKind.Oneloopatomic or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Setloopatomic: case RegexNodeKind.Oneloop or RegexNodeKind.Notoneloop or RegexNodeKind.Setloop or RegexNodeKind.Onelazy or RegexNodeKind.Notonelazy or RegexNodeKind.Setlazy when required.M == required.N: break; default: continue; } // Only handle the case where each branch begins with the exact same node value int endingIndex = startingIndex + 1; for (; endingIndex < children.Count; endingIndex++) { RegexNode other = children[endingIndex].Child(0); if (required.Kind != other.Kind || required.Options != other.Options || required.M != other.M || required.N != other.N || required.Ch != other.Ch || required.Str != other.Str) { break; } } if (endingIndex - startingIndex <= 1) { // Nothing to extract from this starting index. continue; } // Remove the prefix node from every branch, adding it to a new alternation var newAlternate = new RegexNode(RegexNodeKind.Alternate, alternation.Options); for (int i = startingIndex; i < endingIndex; i++) { ((List<RegexNode>)children[i].Children!).RemoveAt(0); newAlternate.AddChild(children[i]); } // If this alternation is wrapped as atomic, we need to do the same for the new alternation. if (alternation.Parent is RegexNode { Kind: RegexNodeKind.Atomic } parent) { var atomic = new RegexNode(RegexNodeKind.Atomic, alternation.Options); atomic.AddChild(newAlternate); newAlternate = atomic; } // Now create a concatenation of the prefix node with the new alternation for the combined // branches, and replace all of the branches in this alternation with that new concatenation. var newConcat = new RegexNode(RegexNodeKind.Concatenate, alternation.Options); newConcat.AddChild(required); newConcat.AddChild(newAlternate); alternation.ReplaceChild(startingIndex, newConcat); children.RemoveRange(startingIndex + 1, endingIndex - startingIndex - 1); } return alternation.ReplaceNodeIfUnnecessary(); } // Removes unnecessary Empty and Nothing nodes from the alternation. A Nothing will never // match, so it can be removed entirely, and an Empty can be removed if there's a previous // Empty in the alternation: it's an extreme case of just having a repeated branch in an // alternation, and while we don't check for all duplicates, checking for empty is easy. static RegexNode RemoveRedundantEmptiesAndNothings(RegexNode node) { Debug.Assert(node.Kind == RegexNodeKind.Alternate); Debug.Assert(node.ChildCount() >= 2); var children = (List<RegexNode>)node.Children!; int i = 0, j = 0; bool seenEmpty = false; while (i < children.Count) { RegexNode child = children[i]; switch (child.Kind) { case RegexNodeKind.Empty when !seenEmpty: seenEmpty = true; goto default; case RegexNodeKind.Empty: case RegexNodeKind.Nothing: i++; break; default: children[j] = children[i]; i++; j++; break; } } children.RemoveRange(j, children.Count - j); return node.ReplaceNodeIfUnnecessary(); } // Analyzes all the branches of the alternation for text that's identical at the beginning // of every branch. That text is then pulled out into its own one or multi node in a // concatenation with the alternation (whose branches are updated to remove that prefix). // This is valuable for a few reasons. One, it exposes potentially more text to the // expression prefix analyzer used to influence FindFirstChar. Second, it exposes more // potential alternation optimizations, e.g. if the same prefix is followed in two branches // by sets that can be merged. Third, it reduces the amount of duplicated comparisons required // if we end up backtracking into subsequent branches. // e.g. abc|ade => a(?bc|de) static RegexNode ExtractCommonPrefixText(RegexNode alternation) { Debug.Assert(alternation.Kind == RegexNodeKind.Alternate); Debug.Assert(alternation.Children is List<RegexNode> { Count: >= 2 }); var children = (List<RegexNode>)alternation.Children; // To keep things relatively simple, we currently only handle: // - Left to right (e.g. we don't process alternations in lookbehinds) // - Branches that are one or multi nodes, or that are concatenations beginning with one or multi nodes. // - All branches having the same options. // Only extract left-to-right prefixes. if ((alternation.Options & RegexOptions.RightToLeft) != 0) { return alternation; } Span<char> scratchChar = stackalloc char[1]; ReadOnlySpan<char> startingSpan = stackalloc char[0]; for (int startingIndex = 0; startingIndex < children.Count - 1; startingIndex++) { // Process the first branch to get the maximum possible common string. RegexNode? startingNode = children[startingIndex].FindBranchOneOrMultiStart(); if (startingNode is null) { return alternation; } RegexOptions startingNodeOptions = startingNode.Options; startingSpan = startingNode.Str.AsSpan(); if (startingNode.Kind == RegexNodeKind.One) { scratchChar[0] = startingNode.Ch; startingSpan = scratchChar; } Debug.Assert(startingSpan.Length > 0); // Now compare the rest of the branches against it. int endingIndex = startingIndex + 1; for (; endingIndex < children.Count; endingIndex++) { // Get the starting node of the next branch. startingNode = children[endingIndex].FindBranchOneOrMultiStart(); if (startingNode is null || startingNode.Options != startingNodeOptions) { break; } // See if the new branch's prefix has a shared prefix with the current one. // If it does, shorten to that; if it doesn't, bail. if (startingNode.Kind == RegexNodeKind.One) { if (startingSpan[0] != startingNode.Ch) { break; } if (startingSpan.Length != 1) { startingSpan = startingSpan.Slice(0, 1); } } else { Debug.Assert(startingNode.Kind == RegexNodeKind.Multi); Debug.Assert(startingNode.Str!.Length > 0); int minLength = Math.Min(startingSpan.Length, startingNode.Str.Length); int c = 0; while (c < minLength && startingSpan[c] == startingNode.Str[c]) c++; if (c == 0) { break; } startingSpan = startingSpan.Slice(0, c); } } // When we get here, we have a starting string prefix shared by all branches // in the range [startingIndex, endingIndex). if (endingIndex - startingIndex <= 1) { // There's nothing to consolidate for this starting node. continue; } // We should be able to consolidate something for the nodes in the range [startingIndex, endingIndex). Debug.Assert(startingSpan.Length > 0); // Create a new node of the form: // Concatenation(prefix, Alternation(each | node | with | prefix | removed)) // that replaces all these branches in this alternation. var prefix = startingSpan.Length == 1 ? new RegexNode(RegexNodeKind.One, startingNodeOptions, startingSpan[0]) : new RegexNode(RegexNodeKind.Multi, startingNodeOptions, startingSpan.ToString()); var newAlternate = new RegexNode(RegexNodeKind.Alternate, startingNodeOptions); for (int i = startingIndex; i < endingIndex; i++) { RegexNode branch = children[i]; ProcessOneOrMulti(branch.Kind == RegexNodeKind.Concatenate ? branch.Child(0) : branch, startingSpan); branch = branch.Reduce(); newAlternate.AddChild(branch); // Remove the starting text from the one or multi node. This may end up changing // the type of the node to be Empty if the starting text matches the node's full value. static void ProcessOneOrMulti(RegexNode node, ReadOnlySpan<char> startingSpan) { if (node.Kind == RegexNodeKind.One) { Debug.Assert(startingSpan.Length == 1); Debug.Assert(startingSpan[0] == node.Ch); node.Kind = RegexNodeKind.Empty; node.Ch = '\0'; } else { Debug.Assert(node.Kind == RegexNodeKind.Multi); Debug.Assert(node.Str.AsSpan().StartsWith(startingSpan, StringComparison.Ordinal)); if (node.Str!.Length == startingSpan.Length) { node.Kind = RegexNodeKind.Empty; node.Str = null; } else if (node.Str.Length - 1 == startingSpan.Length) { node.Kind = RegexNodeKind.One; node.Ch = node.Str[node.Str.Length - 1]; node.Str = null; } else { node.Str = node.Str.Substring(startingSpan.Length); } } } } if (alternation.Parent is RegexNode parent && parent.Kind == RegexNodeKind.Atomic) { var atomic = new RegexNode(RegexNodeKind.Atomic, startingNodeOptions); atomic.AddChild(newAlternate); newAlternate = atomic; } var newConcat = new RegexNode(RegexNodeKind.Concatenate, startingNodeOptions); newConcat.AddChild(prefix); newConcat.AddChild(newAlternate); alternation.ReplaceChild(startingIndex, newConcat); children.RemoveRange(startingIndex + 1, endingIndex - startingIndex - 1); } return alternation.ChildCount() == 1 ? alternation.Child(0) : alternation; } } /// <summary> /// Finds the starting one or multi of the branch, if it has one; otherwise, returns null. /// For simplicity, this only considers branches that are One or Multi, or a Concatenation /// beginning with a One or Multi. We don't traverse more than one level to avoid the /// complication of then having to later update that hierarchy when removing the prefix, /// but it could be done in the future if proven beneficial enough. /// </summary> public RegexNode? FindBranchOneOrMultiStart() { RegexNode branch = Kind == RegexNodeKind.Concatenate ? Child(0) : this; return branch.Kind is RegexNodeKind.One or RegexNodeKind.Multi ? branch : null; } /// <summary>Same as <see cref="FindBranchOneOrMultiStart"/> but also for Sets.</summary> public RegexNode? FindBranchOneMultiOrSetStart() { RegexNode branch = Kind == RegexNodeKind.Concatenate ? Child(0) : this; return branch.Kind is RegexNodeKind.One or RegexNodeKind.Multi or RegexNodeKind.Set ? branch : null; } /// <summary>Gets the character that begins a One or Multi.</summary> public char FirstCharOfOneOrMulti() { Debug.Assert(Kind is RegexNodeKind.One or RegexNodeKind.Multi); Debug.Assert((Options & RegexOptions.RightToLeft) == 0); return Kind == RegexNodeKind.One ? Ch : Str![0]; } /// <summary>Finds the guaranteed beginning literal(s) of the node, or null if none exists.</summary> public (char Char, string? String, string? SetChars)? FindStartingLiteral(int maxSetCharacters = 5) // 5 is max optimized by IndexOfAny today { Debug.Assert(maxSetCharacters >= 0 && maxSetCharacters <= 128, $"{nameof(maxSetCharacters)} == {maxSetCharacters} should be small enough to be stack allocated."); RegexNode? node = this; while (true) { if (node is not null && (node.Options & RegexOptions.RightToLeft) == 0) { switch (node.Kind) { case RegexNodeKind.One: case RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Onelazy when node.M > 0: if ((node.Options & RegexOptions.IgnoreCase) == 0 || !RegexCharClass.ParticipatesInCaseConversion(node.Ch)) { return (node.Ch, null, null); } break; case RegexNodeKind.Multi: if ((node.Options & RegexOptions.IgnoreCase) == 0 || !RegexCharClass.ParticipatesInCaseConversion(node.Str.AsSpan())) { return ('\0', node.Str, null); } break; case RegexNodeKind.Set: case RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic or RegexNodeKind.Setlazy when node.M > 0: Span<char> setChars = stackalloc char[maxSetCharacters]; int numChars; if (!RegexCharClass.IsNegated(node.Str!) && (numChars = RegexCharClass.GetSetChars(node.Str!, setChars)) != 0) { setChars = setChars.Slice(0, numChars); if ((node.Options & RegexOptions.IgnoreCase) == 0 || !RegexCharClass.ParticipatesInCaseConversion(setChars)) { return ('\0', null, setChars.ToString()); } } break; case RegexNodeKind.Atomic: case RegexNodeKind.Concatenate: case RegexNodeKind.Capture: case RegexNodeKind.Group: case RegexNodeKind.Loop or RegexNodeKind.Lazyloop when node.M > 0: case RegexNodeKind.PositiveLookaround: node = node.Child(0); continue; } } return null; } } /// <summary> /// Optimizes a concatenation by coalescing adjacent characters and strings, /// coalescing adjacent loops, converting loops to be atomic where applicable, /// and removing the concatenation itself if it's unnecessary. /// </summary> private RegexNode ReduceConcatenation() { Debug.Assert(Kind == RegexNodeKind.Concatenate); // If the concat node has zero or only one child, get rid of the concat. switch (ChildCount()) { case 0: return new RegexNode(RegexNodeKind.Empty, Options); case 1: return Child(0); } // Coalesce adjacent loops. This helps to minimize work done by the interpreter, minimize code gen, // and also help to reduce catastrophic backtracking. ReduceConcatenationWithAdjacentLoops(); // Coalesce adjacent characters/strings. This is done after the adjacent loop coalescing so that // a One adjacent to both a Multi and a Loop prefers being folded into the Loop rather than into // the Multi. Doing so helps with auto-atomicity when it's later applied. ReduceConcatenationWithAdjacentStrings(); // If the concatenation is now empty, return an empty node, or if it's got a single child, return that child. // Otherwise, return this. return ReplaceNodeIfUnnecessary(); } /// <summary> /// Combine adjacent characters/strings. /// e.g. (?:abc)(?:def) -> abcdef /// </summary> private void ReduceConcatenationWithAdjacentStrings() { Debug.Assert(Kind == RegexNodeKind.Concatenate); Debug.Assert(Children is List<RegexNode>); bool wasLastString = false; RegexOptions optionsLast = 0; int i, j; List<RegexNode> children = (List<RegexNode>)Children!; for (i = 0, j = 0; i < children.Count; i++, j++) { RegexNode at = children[i]; if (j < i) { children[j] = at; } if (at.Kind == RegexNodeKind.Concatenate && ((at.Options & RegexOptions.RightToLeft) == (Options & RegexOptions.RightToLeft))) { if (at.Children is List<RegexNode> atChildren) { for (int k = 0; k < atChildren.Count; k++) { atChildren[k].Parent = this; } children.InsertRange(i + 1, atChildren); } else { RegexNode atChild = (RegexNode)at.Children!; atChild.Parent = this; children.Insert(i + 1, atChild); } j--; } else if (at.Kind is RegexNodeKind.Multi or RegexNodeKind.One) { // Cannot merge strings if L or I options differ RegexOptions optionsAt = at.Options & (RegexOptions.RightToLeft | RegexOptions.IgnoreCase); if (!wasLastString || optionsLast != optionsAt) { wasLastString = true; optionsLast = optionsAt; continue; } RegexNode prev = children[--j]; if (prev.Kind == RegexNodeKind.One) { prev.Kind = RegexNodeKind.Multi; prev.Str = prev.Ch.ToString(); } if ((optionsAt & RegexOptions.RightToLeft) == 0) { prev.Str = (at.Kind == RegexNodeKind.One) ? $"{prev.Str}{at.Ch}" : prev.Str + at.Str; } else { prev.Str = (at.Kind == RegexNodeKind.One) ? $"{at.Ch}{prev.Str}" : at.Str + prev.Str; } } else if (at.Kind == RegexNodeKind.Empty) { j--; } else { wasLastString = false; } } if (j < i) { children.RemoveRange(j, i - j); } } /// <summary> /// Combine adjacent loops. /// e.g. a*a*a* => a* /// e.g. a+ab => a{2,}b /// </summary> private void ReduceConcatenationWithAdjacentLoops() { Debug.Assert(Kind == RegexNodeKind.Concatenate); Debug.Assert(Children is List<RegexNode>); var children = (List<RegexNode>)Children!; int current = 0, next = 1, nextSave = 1; while (next < children.Count) { RegexNode currentNode = children[current]; RegexNode nextNode = children[next]; if (currentNode.Options == nextNode.Options) { static bool CanCombineCounts(int nodeMin, int nodeMax, int nextMin, int nextMax) { // We shouldn't have an infinite minimum; bail if we find one. Also check for the // degenerate case where we'd make the min overflow or go infinite when it wasn't already. if (nodeMin == int.MaxValue || nextMin == int.MaxValue || (uint)nodeMin + (uint)nextMin >= int.MaxValue) { return false; } // Similar overflow / go infinite check for max (which can be infinite). if (nodeMax != int.MaxValue && nextMax != int.MaxValue && (uint)nodeMax + (uint)nextMax >= int.MaxValue) { return false; } return true; } switch (currentNode.Kind) { // Coalescing a loop with its same type case RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Onelazy or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Notonelazy when nextNode.Kind == currentNode.Kind && currentNode.Ch == nextNode.Ch: case RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic or RegexNodeKind.Setlazy when nextNode.Kind == currentNode.Kind && currentNode.Str == nextNode.Str: if (CanCombineCounts(currentNode.M, currentNode.N, nextNode.M, nextNode.N)) { currentNode.M += nextNode.M; if (currentNode.N != int.MaxValue) { currentNode.N = nextNode.N == int.MaxValue ? int.MaxValue : currentNode.N + nextNode.N; } next++; continue; } break; // Coalescing a loop with an additional item of the same type case RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Onelazy when nextNode.Kind == RegexNodeKind.One && currentNode.Ch == nextNode.Ch: case RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Notonelazy when nextNode.Kind == RegexNodeKind.Notone && currentNode.Ch == nextNode.Ch: case RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic or RegexNodeKind.Setlazy when nextNode.Kind == RegexNodeKind.Set && currentNode.Str == nextNode.Str: if (CanCombineCounts(currentNode.M, currentNode.N, 1, 1)) { currentNode.M++; if (currentNode.N != int.MaxValue) { currentNode.N++; } next++; continue; } break; // Coalescing a loop with a subsequent string case RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Onelazy when nextNode.Kind == RegexNodeKind.Multi && currentNode.Ch == nextNode.Str![0]: { // Determine how many of the multi's characters can be combined. // We already checked for the first, so we know it's at least one. int matchingCharsInMulti = 1; while (matchingCharsInMulti < nextNode.Str.Length && currentNode.Ch == nextNode.Str[matchingCharsInMulti]) { matchingCharsInMulti++; } if (CanCombineCounts(currentNode.M, currentNode.N, matchingCharsInMulti, matchingCharsInMulti)) { // Update the loop's bounds to include those characters from the multi currentNode.M += matchingCharsInMulti; if (currentNode.N != int.MaxValue) { currentNode.N += matchingCharsInMulti; } // If it was the full multi, skip/remove the multi and continue processing this loop. if (nextNode.Str.Length == matchingCharsInMulti) { next++; continue; } // Otherwise, trim the characters from the multiple that were absorbed into the loop. // If it now only has a single character, it becomes a One. Debug.Assert(matchingCharsInMulti < nextNode.Str.Length); if (nextNode.Str.Length - matchingCharsInMulti == 1) { nextNode.Kind = RegexNodeKind.One; nextNode.Ch = nextNode.Str[nextNode.Str.Length - 1]; nextNode.Str = null; } else { nextNode.Str = nextNode.Str.Substring(matchingCharsInMulti); } } } break; // NOTE: We could add support for coalescing a string with a subsequent loop, but the benefits of that // are limited. Pulling a subsequent string's prefix back into the loop helps with making the loop atomic, // but if the loop is after the string, pulling the suffix of the string forward into the loop may actually // be a deoptimization as those characters could end up matching more slowly as part of loop matching. // Coalescing an individual item with a loop. case RegexNodeKind.One when (nextNode.Kind is RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Onelazy) && currentNode.Ch == nextNode.Ch: case RegexNodeKind.Notone when (nextNode.Kind is RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Notonelazy) && currentNode.Ch == nextNode.Ch: case RegexNodeKind.Set when (nextNode.Kind is RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic or RegexNodeKind.Setlazy) && currentNode.Str == nextNode.Str: if (CanCombineCounts(1, 1, nextNode.M, nextNode.N)) { currentNode.Kind = nextNode.Kind; currentNode.M = nextNode.M + 1; currentNode.N = nextNode.N == int.MaxValue ? int.MaxValue : nextNode.N + 1; next++; continue; } break; // Coalescing an individual item with another individual item. // We don't coalesce adjacent One nodes into a Oneloop as we'd rather they be joined into a Multi. case RegexNodeKind.Notone when nextNode.Kind == currentNode.Kind && currentNode.Ch == nextNode.Ch: case RegexNodeKind.Set when nextNode.Kind == RegexNodeKind.Set && currentNode.Str == nextNode.Str: currentNode.MakeRep(RegexNodeKind.Oneloop, 2, 2); next++; continue; } } children[nextSave++] = children[next]; current = next; next++; } if (nextSave < children.Count) { children.RemoveRange(nextSave, children.Count - nextSave); } } /// <summary> /// Finds {one/notone/set}loop nodes in the concatenation that can be automatically upgraded /// to {one/notone/set}loopatomic nodes. Such changes avoid potential useless backtracking. /// e.g. A*B (where sets A and B don't overlap) => (?>A*)B. /// </summary> private void FindAndMakeLoopsAtomic() { Debug.Assert((Options & RegexOptions.NonBacktracking) == 0, "Atomic groups aren't supported and don't help performance with NonBacktracking"); if (!StackHelper.TryEnsureSufficientExecutionStack()) { // If we're too deep on the stack, give up optimizing further. return; } if ((Options & RegexOptions.RightToLeft) != 0) { // RTL is so rare, we don't need to spend additional time/code optimizing for it. return; } // For all node types that have children, recur into each of those children. int childCount = ChildCount(); if (childCount != 0) { for (int i = 0; i < childCount; i++) { Child(i).FindAndMakeLoopsAtomic(); } } // If this isn't a concatenation, nothing more to do. if (Kind is not RegexNodeKind.Concatenate) { return; } // This is a concatenation. Iterate through each pair of nodes in the concatenation seeing whether we can // make the first node (or its right-most child) atomic based on the second node (or its left-most child). Debug.Assert(Children is List<RegexNode>); var children = (List<RegexNode>)Children; for (int i = 0; i < childCount - 1; i++) { ProcessNode(children[i], children[i + 1]); static void ProcessNode(RegexNode node, RegexNode subsequent) { if (!StackHelper.TryEnsureSufficientExecutionStack()) { // If we can't recur further, just stop optimizing. return; } // Skip down the node past irrelevant nodes. while (true) { // We can always recur into captures and into the last node of concatenations. if (node.Kind is RegexNodeKind.Capture or RegexNodeKind.Concatenate) { node = node.Child(node.ChildCount() - 1); continue; } // For loops with at least one guaranteed iteration, we can recur into them, but // we need to be careful not to just always do so; the ending node of a loop can only // be made atomic if what comes after the loop but also the beginning of the loop are // compatible for the optimization. if (node.Kind == RegexNodeKind.Loop) { RegexNode? loopDescendent = node.FindLastExpressionInLoopForAutoAtomic(); if (loopDescendent != null) { node = loopDescendent; continue; } } // Can't skip any further. break; } // If the node can be changed to atomic based on what comes after it, do so. switch (node.Kind) { case RegexNodeKind.Oneloop or RegexNodeKind.Notoneloop or RegexNodeKind.Setloop when CanBeMadeAtomic(node, subsequent, allowSubsequentIteration: true): node.MakeLoopAtomic(); break; case RegexNodeKind.Alternate or RegexNodeKind.BackreferenceConditional or RegexNodeKind.ExpressionConditional: // In the case of alternation, we can't change the alternation node itself // based on what comes after it (at least not with more complicated analysis // that factors in all branches together), but we can look at each individual // branch, and analyze ending loops in each branch individually to see if they // can be made atomic. Then if we do end up backtracking into the alternation, // we at least won't need to backtrack into that loop. The same is true for // conditionals, though we don't want to process the condition expression // itself, as it's already considered atomic and handled as part of ReduceExpressionConditional. { int alternateBranches = node.ChildCount(); for (int b = node.Kind == RegexNodeKind.ExpressionConditional ? 1 : 0; b < alternateBranches; b++) { ProcessNode(node.Child(b), subsequent); } } break; } } } } /// <summary> /// Recurs into the last expression of a loop node, looking to see if it can find a node /// that could be made atomic _assuming_ the conditions exist for it with the loop's ancestors. /// </summary> /// <returns>The found node that should be explored further for auto-atomicity; null if it doesn't exist.</returns> private RegexNode? FindLastExpressionInLoopForAutoAtomic() { RegexNode node = this; Debug.Assert(node.Kind is RegexNodeKind.Loop or RegexNodeKind.Lazyloop); // Start by looking at the loop's sole child. node = node.Child(0); // Skip past captures. while (node.Kind == RegexNodeKind.Capture) { node = node.Child(0); } // If the loop's body is a concatenate, we can skip to its last child iff that // last child doesn't conflict with the first child, since this whole concatenation // could be repeated, such that the first node ends up following the last. For // example, in the expression (a+[def])*, the last child is [def] and the first is // a+, which can't possibly overlap with [def]. In contrast, if we had (a+[ade])*, // [ade] could potentially match the starting 'a'. if (node.Kind == RegexNodeKind.Concatenate) { int concatCount = node.ChildCount(); RegexNode lastConcatChild = node.Child(concatCount - 1); if (CanBeMadeAtomic(lastConcatChild, node.Child(0), allowSubsequentIteration: false)) { return lastConcatChild; } } // Otherwise, the loop has nothing that can participate in auto-atomicity. return null; } /// <summary>Optimizations for positive and negative lookaheads/behinds.</summary> private RegexNode ReduceLookaround() { Debug.Assert(Kind is RegexNodeKind.PositiveLookaround or RegexNodeKind.NegativeLookaround); Debug.Assert(ChildCount() == 1); // A lookaround is a zero-width atomic assertion. // As it's atomic, nothing will backtrack into it, and we can // eliminate any ending backtracking from it. EliminateEndingBacktracking(); // A positive lookaround wrapped around an empty is a nop, and we can reduce it // to simply Empty. A developer typically doesn't write this, but rather it evolves // due to optimizations resulting in empty. // A negative lookaround wrapped around an empty child, i.e. (?!), is // sometimes used as a way to insert a guaranteed no-match into the expression, // often as part of a conditional. We can reduce it to simply Nothing. if (Child(0).Kind == RegexNodeKind.Empty) { Kind = Kind == RegexNodeKind.PositiveLookaround ? RegexNodeKind.Empty : RegexNodeKind.Nothing; Children = null; } return this; } /// <summary>Optimizations for backreference conditionals.</summary> private RegexNode ReduceBackreferenceConditional() { Debug.Assert(Kind == RegexNodeKind.BackreferenceConditional); Debug.Assert(ChildCount() is 1 or 2); // This isn't so much an optimization as it is changing the tree for consistency. We want // all engines to be able to trust that every backreference conditional will have two children, // even though it's optional in the syntax. If it's missing a "not matched" branch, // we add one that will match empty. if (ChildCount() == 1) { AddChild(new RegexNode(RegexNodeKind.Empty, Options)); } return this; } /// <summary>Optimizations for expression conditionals.</summary> private RegexNode ReduceExpressionConditional() { Debug.Assert(Kind == RegexNodeKind.ExpressionConditional); Debug.Assert(ChildCount() is 2 or 3); // This isn't so much an optimization as it is changing the tree for consistency. We want // all engines to be able to trust that every expression conditional will have three children, // even though it's optional in the syntax. If it's missing a "not matched" branch, // we add one that will match empty. if (ChildCount() == 2) { AddChild(new RegexNode(RegexNodeKind.Empty, Options)); } // It's common for the condition to be an explicit positive lookahead, as specifying // that eliminates any ambiguity in syntax as to whether the expression is to be matched // as an expression or to be a reference to a capture group. After parsing, however, // there's no ambiguity, and we can remove an extra level of positive lookahead, as the // engines need to treat the condition as a zero-width positive, atomic assertion regardless. RegexNode condition = Child(0); if (condition.Kind == RegexNodeKind.PositiveLookaround && (condition.Options & RegexOptions.RightToLeft) == 0) { ReplaceChild(0, condition.Child(0)); } // We can also eliminate any ending backtracking in the condition, as the condition // is considered to be a positive lookahead, which is an atomic zero-width assertion. condition = Child(0); condition.EliminateEndingBacktracking(); return this; } /// <summary> /// Determines whether node can be switched to an atomic loop. Subsequent is the node /// immediately after 'node'. /// </summary> private static bool CanBeMadeAtomic(RegexNode node, RegexNode subsequent, bool allowSubsequentIteration) { if (!StackHelper.TryEnsureSufficientExecutionStack()) { // If we can't recur further, just stop optimizing. return false; } // In most case, we'll simply check the node against whatever subsequent is. However, in case // subsequent ends up being a loop with a min bound of 0, we'll also need to evaluate the node // against whatever comes after subsequent. In that case, we'll walk the tree to find the // next subsequent, and we'll loop around against to perform the comparison again. while (true) { // Skip the successor down to the closest node that's guaranteed to follow it. int childCount; while ((childCount = subsequent.ChildCount()) > 0) { Debug.Assert(subsequent.Kind != RegexNodeKind.Group); switch (subsequent.Kind) { case RegexNodeKind.Concatenate: case RegexNodeKind.Capture: case RegexNodeKind.Atomic: case RegexNodeKind.PositiveLookaround when (subsequent.Options & RegexOptions.RightToLeft) == 0: // only lookaheads, not lookbehinds (represented as RTL PositiveLookaround nodes) case RegexNodeKind.Loop or RegexNodeKind.Lazyloop when subsequent.M > 0: subsequent = subsequent.Child(0); continue; } break; } // If the two nodes don't agree on options in any way, don't try to optimize them. // TODO: Remove this once https://github.com/dotnet/runtime/issues/61048 is implemented. if (node.Options != subsequent.Options) { return false; } // If the successor is an alternation, all of its children need to be evaluated, since any of them // could come after this node. If any of them fail the optimization, then the whole node fails. // This applies to expression conditionals as well, as long as they have both a yes and a no branch (if there's // only a yes branch, we'd need to also check whatever comes after the conditional). It doesn't apply to // backreference conditionals, as the condition itself is unknown statically and could overlap with the // loop being considered for atomicity. switch (subsequent.Kind) { case RegexNodeKind.Alternate: case RegexNodeKind.ExpressionConditional when childCount == 3: // condition, yes, and no branch for (int i = 0; i < childCount; i++) { if (!CanBeMadeAtomic(node, subsequent.Child(i), allowSubsequentIteration)) { return false; } } return true; } // If this node is a {one/notone/set}loop, see if it overlaps with its successor in the concatenation. // If it doesn't, then we can upgrade it to being a {one/notone/set}loopatomic. // Doing so avoids unnecessary backtracking. switch (node.Kind) { case RegexNodeKind.Oneloop: switch (subsequent.Kind) { case RegexNodeKind.One when node.Ch != subsequent.Ch: case RegexNodeKind.Notone when node.Ch == subsequent.Ch: case RegexNodeKind.Set when !RegexCharClass.CharInClass(node.Ch, subsequent.Str!): case RegexNodeKind.Onelazy or RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic when subsequent.M > 0 && node.Ch != subsequent.Ch: case RegexNodeKind.Notonelazy or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic when subsequent.M > 0 && node.Ch == subsequent.Ch: case RegexNodeKind.Setlazy or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic when subsequent.M > 0 && !RegexCharClass.CharInClass(node.Ch, subsequent.Str!): case RegexNodeKind.Multi when node.Ch != subsequent.Str![0]: case RegexNodeKind.End: case RegexNodeKind.EndZ or RegexNodeKind.Eol when node.Ch != '\n': case RegexNodeKind.Boundary when RegexCharClass.IsBoundaryWordChar(node.Ch): case RegexNodeKind.NonBoundary when !RegexCharClass.IsBoundaryWordChar(node.Ch): case RegexNodeKind.ECMABoundary when RegexCharClass.IsECMAWordChar(node.Ch): case RegexNodeKind.NonECMABoundary when !RegexCharClass.IsECMAWordChar(node.Ch): return true; case RegexNodeKind.Onelazy or RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic when subsequent.M == 0 && node.Ch != subsequent.Ch: case RegexNodeKind.Notonelazy or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic when subsequent.M == 0 && node.Ch == subsequent.Ch: case RegexNodeKind.Setlazy or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic when subsequent.M == 0 && !RegexCharClass.CharInClass(node.Ch, subsequent.Str!): // The loop can be made atomic based on this subsequent node, but we'll need to evaluate the next one as well. break; default: return false; } break; case RegexNodeKind.Notoneloop: switch (subsequent.Kind) { case RegexNodeKind.One when node.Ch == subsequent.Ch: case RegexNodeKind.Onelazy or RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic when subsequent.M > 0 && node.Ch == subsequent.Ch: case RegexNodeKind.Multi when node.Ch == subsequent.Str![0]: case RegexNodeKind.End: return true; case RegexNodeKind.Onelazy or RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic when subsequent.M == 0 && node.Ch == subsequent.Ch: // The loop can be made atomic based on this subsequent node, but we'll need to evaluate the next one as well. break; default: return false; } break; case RegexNodeKind.Setloop: switch (subsequent.Kind) { case RegexNodeKind.One when !RegexCharClass.CharInClass(subsequent.Ch, node.Str!): case RegexNodeKind.Set when !RegexCharClass.MayOverlap(node.Str!, subsequent.Str!): case RegexNodeKind.Onelazy or RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic when subsequent.M > 0 && !RegexCharClass.CharInClass(subsequent.Ch, node.Str!): case RegexNodeKind.Setlazy or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic when subsequent.M > 0 && !RegexCharClass.MayOverlap(node.Str!, subsequent.Str!): case RegexNodeKind.Multi when !RegexCharClass.CharInClass(subsequent.Str![0], node.Str!): case RegexNodeKind.End: case RegexNodeKind.EndZ or RegexNodeKind.Eol when !RegexCharClass.CharInClass('\n', node.Str!): case RegexNodeKind.Boundary when node.Str is RegexCharClass.WordClass or RegexCharClass.DigitClass: case RegexNodeKind.NonBoundary when node.Str is RegexCharClass.NotWordClass or RegexCharClass.NotDigitClass: case RegexNodeKind.ECMABoundary when node.Str is RegexCharClass.ECMAWordClass or RegexCharClass.ECMADigitClass: case RegexNodeKind.NonECMABoundary when node.Str is RegexCharClass.NotECMAWordClass or RegexCharClass.NotDigitClass: return true; case RegexNodeKind.Onelazy or RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic when subsequent.M == 0 && !RegexCharClass.CharInClass(subsequent.Ch, node.Str!): case RegexNodeKind.Setlazy or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic when subsequent.M == 0 && !RegexCharClass.MayOverlap(node.Str!, subsequent.Str!): // The loop can be made atomic based on this subsequent node, but we'll need to evaluate the next one as well. break; default: return false; } break; default: return false; } // We only get here if the node could be made atomic based on subsequent but subsequent has a lower bound of zero // and thus we need to move subsequent to be the next node in sequence and loop around to try again. Debug.Assert(subsequent.Kind is RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Onelazy or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Notonelazy or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic or RegexNodeKind.Setlazy); Debug.Assert(subsequent.M == 0); if (!allowSubsequentIteration) { return false; } // To be conservative, we only walk up through a very limited set of constructs (even though we may have walked // down through more, like loops), looking for the next concatenation that we're not at the end of, at // which point subsequent becomes whatever node is next in that concatenation. while (true) { RegexNode? parent = subsequent.Parent; switch (parent?.Kind) { case RegexNodeKind.Atomic: case RegexNodeKind.Alternate: case RegexNodeKind.Capture: subsequent = parent; continue; case RegexNodeKind.Concatenate: var peers = (List<RegexNode>)parent.Children!; int currentIndex = peers.IndexOf(subsequent); Debug.Assert(currentIndex >= 0, "Node should have been in its parent's child list"); if (currentIndex + 1 == peers.Count) { subsequent = parent; continue; } else { subsequent = peers[currentIndex + 1]; break; } case null: // If we hit the root, we're at the end of the expression, at which point nothing could backtrack // in and we can declare success. return true; default: // Anything else, we don't know what to do, so we have to assume it could conflict with the loop. return false; } break; } } } /// <summary>Computes a min bound on the required length of any string that could possibly match.</summary> /// <returns>The min computed length. If the result is 0, there is no minimum we can enforce.</returns> /// <remarks> /// e.g. abc[def](ghijkl|mn) => 6 /// </remarks> public int ComputeMinLength() { if (!StackHelper.TryEnsureSufficientExecutionStack()) { // If we can't recur further, assume there's no minimum we can enforce. return 0; } switch (Kind) { case RegexNodeKind.One: case RegexNodeKind.Notone: case RegexNodeKind.Set: // Single character. return 1; case RegexNodeKind.Multi: // Every character in the string needs to match. return Str!.Length; case RegexNodeKind.Notonelazy: case RegexNodeKind.Notoneloop: case RegexNodeKind.Notoneloopatomic: case RegexNodeKind.Onelazy: case RegexNodeKind.Oneloop: case RegexNodeKind.Oneloopatomic: case RegexNodeKind.Setlazy: case RegexNodeKind.Setloop: case RegexNodeKind.Setloopatomic: // One character repeated at least M times. return M; case RegexNodeKind.Lazyloop: case RegexNodeKind.Loop: // A node graph repeated at least M times. return (int)Math.Min(int.MaxValue - 1, (long)M * Child(0).ComputeMinLength()); case RegexNodeKind.Alternate: // The minimum required length for any of the alternation's branches. { int childCount = ChildCount(); Debug.Assert(childCount >= 2); int min = Child(0).ComputeMinLength(); for (int i = 1; i < childCount && min > 0; i++) { min = Math.Min(min, Child(i).ComputeMinLength()); } return min; } case RegexNodeKind.BackreferenceConditional: // Minimum of its yes and no branches. The backreference doesn't add to the length. return Math.Min(Child(0).ComputeMinLength(), Child(1).ComputeMinLength()); case RegexNodeKind.ExpressionConditional: // Minimum of its yes and no branches. The condition is a zero-width assertion. return Math.Min(Child(1).ComputeMinLength(), Child(2).ComputeMinLength()); case RegexNodeKind.Concatenate: // The sum of all of the concatenation's children. { long sum = 0; int childCount = ChildCount(); for (int i = 0; i < childCount; i++) { sum += Child(i).ComputeMinLength(); } return (int)Math.Min(int.MaxValue - 1, sum); } case RegexNodeKind.Atomic: case RegexNodeKind.Capture: case RegexNodeKind.Group: // For groups, we just delegate to the sole child. Debug.Assert(ChildCount() == 1); return Child(0).ComputeMinLength(); case RegexNodeKind.Empty: case RegexNodeKind.Nothing: case RegexNodeKind.UpdateBumpalong: // Nothing to match. In the future, we could potentially use Nothing to say that the min length // is infinite, but that would require a different structure, as that would only apply if the // Nothing match is required in all cases (rather than, say, as one branch of an alternation). case RegexNodeKind.Beginning: case RegexNodeKind.Bol: case RegexNodeKind.Boundary: case RegexNodeKind.ECMABoundary: case RegexNodeKind.End: case RegexNodeKind.EndZ: case RegexNodeKind.Eol: case RegexNodeKind.NonBoundary: case RegexNodeKind.NonECMABoundary: case RegexNodeKind.Start: case RegexNodeKind.NegativeLookaround: case RegexNodeKind.PositiveLookaround: // Zero-width case RegexNodeKind.Backreference: // Requires matching data available only at run-time. In the future, we could choose to find // and follow the capture group this aligns with, while being careful not to end up in an // infinite cycle. return 0; default: Debug.Fail($"Unknown node: {Kind}"); goto case RegexNodeKind.Empty; } } /// <summary>Computes a maximum length of any string that could possibly match.</summary> /// <returns>The maximum length of any string that could possibly match, or null if the length may not always be the same.</returns> /// <remarks> /// e.g. abc[def](gh|ijklmnop) => 12 /// </remarks> public int? ComputeMaxLength() { if (!StackHelper.TryEnsureSufficientExecutionStack()) { // If we can't recur further, assume there's no minimum we can enforce. return null; } switch (Kind) { case RegexNodeKind.One: case RegexNodeKind.Notone: case RegexNodeKind.Set: // Single character. return 1; case RegexNodeKind.Multi: // Every character in the string needs to match. return Str!.Length; case RegexNodeKind.Notonelazy or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Onelazy or RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Setlazy or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic: // Return the max number of iterations if there's an upper bound, or null if it's infinite return N == int.MaxValue ? null : N; case RegexNodeKind.Loop or RegexNodeKind.Lazyloop: if (N != int.MaxValue) { // A node graph repeated a fixed number of times if (Child(0).ComputeMaxLength() is int childMaxLength) { long maxLength = (long)N * childMaxLength; if (maxLength < int.MaxValue) { return (int)maxLength; } } } return null; case RegexNodeKind.Alternate: // The maximum length of any child branch, as long as they all have one. { int childCount = ChildCount(); Debug.Assert(childCount >= 2); if (Child(0).ComputeMaxLength() is not int maxLength) { return null; } for (int i = 1; i < childCount; i++) { if (Child(i).ComputeMaxLength() is not int next) { return null; } maxLength = Math.Max(maxLength, next); } return maxLength; } case RegexNodeKind.BackreferenceConditional: case RegexNodeKind.ExpressionConditional: // The maximum length of either child branch, as long as they both have one.. The condition for an expression conditional is a zero-width assertion. { int i = Kind == RegexNodeKind.BackreferenceConditional ? 0 : 1; return Child(i).ComputeMaxLength() is int yes && Child(i + 1).ComputeMaxLength() is int no ? Math.Max(yes, no) : null; } case RegexNodeKind.Concatenate: // The sum of all of the concatenation's children's max lengths, as long as they all have one. { long sum = 0; int childCount = ChildCount(); for (int i = 0; i < childCount; i++) { if (Child(i).ComputeMaxLength() is not int length) { return null; } sum += length; } if (sum < int.MaxValue) { return (int)sum; } return null; } case RegexNodeKind.Atomic: case RegexNodeKind.Capture: // For groups, we just delegate to the sole child. Debug.Assert(ChildCount() == 1); return Child(0).ComputeMaxLength(); case RegexNodeKind.Empty: case RegexNodeKind.Nothing: case RegexNodeKind.UpdateBumpalong: case RegexNodeKind.Beginning: case RegexNodeKind.Bol: case RegexNodeKind.Boundary: case RegexNodeKind.ECMABoundary: case RegexNodeKind.End: case RegexNodeKind.EndZ: case RegexNodeKind.Eol: case RegexNodeKind.NonBoundary: case RegexNodeKind.NonECMABoundary: case RegexNodeKind.Start: case RegexNodeKind.PositiveLookaround: case RegexNodeKind.NegativeLookaround: // Zero-width return 0; case RegexNodeKind.Backreference: // Requires matching data available only at run-time. In the future, we could choose to find // and follow the capture group this aligns with, while being careful not to end up in an // infinite cycle. return null; default: Debug.Fail($"Unknown node: {Kind}"); goto case RegexNodeKind.Empty; } } /// <summary> /// Determine whether the specified child node is the beginning of a sequence that can /// trivially have length checks combined in order to avoid bounds checks. /// </summary> /// <param name="childIndex">The starting index of the child to check.</param> /// <param name="requiredLength">The sum of all the fixed lengths for the nodes in the sequence.</param> /// <param name="exclusiveEnd">The index of the node just after the last one in the sequence.</param> /// <returns>true if more than one node can have their length checks combined; otherwise, false.</returns> /// <remarks> /// There are additional node types for which we can prove a fixed length, e.g. examining all branches /// of an alternation and returning true if all their lengths are equal. However, the primary purpose /// of this method is to avoid bounds checks by consolidating length checks that guard accesses to /// strings/spans for which the JIT can see a fixed index within bounds, and alternations employ /// patterns that defeat that (e.g. reassigning the span in question). As such, the implementation /// remains focused on only a core subset of nodes that are a) likely to be used in concatenations and /// b) employ simple patterns of checks. /// </remarks> public bool TryGetJoinableLengthCheckChildRange(int childIndex, out int requiredLength, out int exclusiveEnd) { static bool CanJoinLengthCheck(RegexNode node) => node.Kind switch { RegexNodeKind.One or RegexNodeKind.Notone or RegexNodeKind.Set => true, RegexNodeKind.Multi => true, RegexNodeKind.Oneloop or RegexNodeKind.Onelazy or RegexNodeKind.Oneloopatomic or RegexNodeKind.Notoneloop or RegexNodeKind.Notonelazy or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Setloop or RegexNodeKind.Setlazy or RegexNodeKind.Setloopatomic when node.M == node.N => true, _ => false, }; RegexNode child = Child(childIndex); if (CanJoinLengthCheck(child)) { requiredLength = child.ComputeMinLength(); int childCount = ChildCount(); for (exclusiveEnd = childIndex + 1; exclusiveEnd < childCount; exclusiveEnd++) { child = Child(exclusiveEnd); if (!CanJoinLengthCheck(child)) { break; } requiredLength += child.ComputeMinLength(); } if (exclusiveEnd - childIndex > 1) { return true; } } requiredLength = 0; exclusiveEnd = 0; return false; } public RegexNode MakeQuantifier(bool lazy, int min, int max) { // Certain cases of repeaters (min == max) can be handled specially if (min == max) { switch (max) { case 0: // The node is repeated 0 times, so it's actually empty. return new RegexNode(RegexNodeKind.Empty, Options); case 1: // The node is repeated 1 time, so it's not actually a repeater. return this; case <= MultiVsRepeaterLimit when Kind == RegexNodeKind.One: // The same character is repeated a fixed number of times, so it's actually a multi. // While this could remain a repeater, multis are more readily optimized later in // processing. The counts used here in real-world expressions are invariably small (e.g. 4), // but we set an upper bound just to avoid creating really large strings. Debug.Assert(max >= 2); Kind = RegexNodeKind.Multi; Str = new string(Ch, max); Ch = '\0'; return this; } } switch (Kind) { case RegexNodeKind.One: case RegexNodeKind.Notone: case RegexNodeKind.Set: MakeRep(lazy ? RegexNodeKind.Onelazy : RegexNodeKind.Oneloop, min, max); return this; default: var result = new RegexNode(lazy ? RegexNodeKind.Lazyloop : RegexNodeKind.Loop, Options, min, max); result.AddChild(this); return result; } } public void AddChild(RegexNode newChild) { newChild.Parent = this; // so that the child can see its parent while being reduced newChild = newChild.Reduce(); newChild.Parent = this; // in case Reduce returns a different node that needs to be reparented if (Children is null) { Children = newChild; } else if (Children is RegexNode currentChild) { Children = new List<RegexNode>() { currentChild, newChild }; } else { ((List<RegexNode>)Children).Add(newChild); } } public void InsertChild(int index, RegexNode newChild) { Debug.Assert(Children is List<RegexNode>); newChild.Parent = this; // so that the child can see its parent while being reduced newChild = newChild.Reduce(); newChild.Parent = this; // in case Reduce returns a different node that needs to be reparented ((List<RegexNode>)Children).Insert(index, newChild); } public void ReplaceChild(int index, RegexNode newChild) { Debug.Assert(Children != null); Debug.Assert(index < ChildCount()); newChild.Parent = this; // so that the child can see its parent while being reduced newChild = newChild.Reduce(); newChild.Parent = this; // in case Reduce returns a different node that needs to be reparented if (Children is RegexNode) { Children = newChild; } else { ((List<RegexNode>)Children)[index] = newChild; } } public RegexNode Child(int i) => Children is RegexNode child ? child : ((List<RegexNode>)Children!)[i]; public int ChildCount() { if (Children is null) { return 0; } if (Children is List<RegexNode> children) { return children.Count; } Debug.Assert(Children is RegexNode); return 1; } // Determines whether the node supports a compilation / code generation strategy based on walking the node tree. // Also returns a human-readable string to explain the reason (it will be emitted by the source generator, hence // there's no need to localize). internal bool SupportsCompilation([NotNullWhen(false)] out string? reason) { if (!StackHelper.TryEnsureSufficientExecutionStack()) { reason = "run-time limits were exceeded"; return false; } // NonBacktracking isn't supported, nor RightToLeft. The latter applies to both the top-level // options as well as when used to specify positive and negative lookbehinds. if ((Options & RegexOptions.NonBacktracking) != 0) { reason = "RegexOptions.NonBacktracking was specified"; return false; } if ((Options & RegexOptions.RightToLeft) != 0) { reason = "RegexOptions.RightToLeft or a positive/negative lookbehind was used"; return false; } int childCount = ChildCount(); for (int i = 0; i < childCount; i++) { // The node isn't supported if any of its children aren't supported. if (!Child(i).SupportsCompilation(out reason)) { return false; } } // Supported. reason = null; return true; } /// <summary>Gets whether the node is a Set/Setloop/Setloopatomic/Setlazy node.</summary> public bool IsSetFamily => Kind is RegexNodeKind.Set or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic or RegexNodeKind.Setlazy; /// <summary>Gets whether the node is a One/Oneloop/Oneloopatomic/Onelazy node.</summary> public bool IsOneFamily => Kind is RegexNodeKind.One or RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Onelazy; /// <summary>Gets whether the node is a Notone/Notoneloop/Notoneloopatomic/Notonelazy node.</summary> public bool IsNotoneFamily => Kind is RegexNodeKind.Notone or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Notonelazy; /// <summary>Gets whether this node is contained inside of a loop.</summary> public bool IsInLoop() { for (RegexNode? parent = Parent; parent is not null; parent = parent.Parent) { if (parent.Kind is RegexNodeKind.Loop or RegexNodeKind.Lazyloop) { return true; } } return false; } #if DEBUG [ExcludeFromCodeCoverage] public override string ToString() { RegexNode? curNode = this; int curChild = 0; var sb = new StringBuilder().AppendLine(curNode.Describe()); var stack = new List<int>(); while (true) { if (curChild < curNode!.ChildCount()) { stack.Add(curChild + 1); curNode = curNode.Child(curChild); curChild = 0; sb.Append(new string(' ', stack.Count * 2)).Append(curNode.Describe()).AppendLine(); } else { if (stack.Count == 0) { break; } curChild = stack[stack.Count - 1]; stack.RemoveAt(stack.Count - 1); curNode = curNode.Parent; } } return sb.ToString(); } [ExcludeFromCodeCoverage] private string Describe() { var sb = new StringBuilder(Kind.ToString()); if ((Options & RegexOptions.ExplicitCapture) != 0) sb.Append("-C"); if ((Options & RegexOptions.IgnoreCase) != 0) sb.Append("-I"); if ((Options & RegexOptions.RightToLeft) != 0) sb.Append("-L"); if ((Options & RegexOptions.Multiline) != 0) sb.Append("-M"); if ((Options & RegexOptions.Singleline) != 0) sb.Append("-S"); if ((Options & RegexOptions.IgnorePatternWhitespace) != 0) sb.Append("-X"); if ((Options & RegexOptions.ECMAScript) != 0) sb.Append("-E"); switch (Kind) { case RegexNodeKind.Oneloop: case RegexNodeKind.Oneloopatomic: case RegexNodeKind.Notoneloop: case RegexNodeKind.Notoneloopatomic: case RegexNodeKind.Onelazy: case RegexNodeKind.Notonelazy: case RegexNodeKind.One: case RegexNodeKind.Notone: sb.Append(" '").Append(RegexCharClass.DescribeChar(Ch)).Append('\''); break; case RegexNodeKind.Capture: sb.Append(' ').Append($"index = {M}"); if (N != -1) { sb.Append($", unindex = {N}"); } break; case RegexNodeKind.Backreference: case RegexNodeKind.BackreferenceConditional: sb.Append(' ').Append($"index = {M}"); break; case RegexNodeKind.Multi: sb.Append(" \"").Append(Str).Append('"'); break; case RegexNodeKind.Set: case RegexNodeKind.Setloop: case RegexNodeKind.Setloopatomic: case RegexNodeKind.Setlazy: sb.Append(' ').Append(RegexCharClass.DescribeSet(Str!)); break; } switch (Kind) { case RegexNodeKind.Oneloop: case RegexNodeKind.Oneloopatomic: case RegexNodeKind.Notoneloop: case RegexNodeKind.Notoneloopatomic: case RegexNodeKind.Onelazy: case RegexNodeKind.Notonelazy: case RegexNodeKind.Setloop: case RegexNodeKind.Setloopatomic: case RegexNodeKind.Setlazy: case RegexNodeKind.Loop: case RegexNodeKind.Lazyloop: sb.Append( (M == 0 && N == int.MaxValue) ? "*" : (M == 0 && N == 1) ? "?" : (M == 1 && N == int.MaxValue) ? "+" : (N == int.MaxValue) ? $"{{{M}, *}}" : (N == M) ? $"{{{M}}}" : $"{{{M}, {N}}}"); break; } return sb.ToString(); } #endif } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Threading; namespace System.Text.RegularExpressions { /// <summary>Represents a regex subexpression.</summary> internal sealed class RegexNode { /// <summary>empty bit from the node's options to store data on whether a node contains captures</summary> internal const RegexOptions HasCapturesFlag = (RegexOptions)(1 << 31); /// <summary>Arbitrary number of repetitions of the same character when we'd prefer to represent that as a repeater of that character rather than a string.</summary> internal const int MultiVsRepeaterLimit = 64; /// <summary>The node's children.</summary> /// <remarks>null if no children, a <see cref="RegexNode"/> if one child, or a <see cref="List{RegexNode}"/> if multiple children.</remarks> private object? Children; /// <summary>The kind of expression represented by this node.</summary> public RegexNodeKind Kind { get; private set; } /// <summary>A string associated with the node.</summary> /// <remarks>For a <see cref="RegexNodeKind.Multi"/>, this is the string from the expression. For an <see cref="IsSetFamily"/> node, this is the character class string from <see cref="RegexCharClass"/>.</remarks> public string? Str { get; private set; } /// <summary>The character associated with the node.</summary> /// <remarks>For a <see cref="IsOneFamily"/> or <see cref="IsNotoneFamily"/> node, the character from the expression.</remarks> public char Ch { get; private set; } /// <summary>The minimum number of iterations for a loop, or the capture group number for a capture or backreference.</summary> /// <remarks>No minimum is represented by 0. No capture group is represented by -1.</remarks> public int M { get; private set; } /// <summary>The maximum number of iterations for a loop, or the uncapture group number for a balancing group.</summary> /// <remarks>No upper bound is represented by <see cref="int.MaxValue"/>. No capture group is represented by -1.</remarks> public int N { get; private set; } /// <summary>The options associated with the node.</summary> public RegexOptions Options; /// <summary>The node's parent node in the tree.</summary> /// <remarks> /// During parsing, top-level nodes are also stacked onto a parse stack (a stack of trees) using <see cref="Parent"/>. /// After parsing, <see cref="Parent"/> is the node in the tree that has this node as or in <see cref="Children"/>. /// </remarks> public RegexNode? Parent; public RegexNode(RegexNodeKind kind, RegexOptions options) { Kind = kind; Options = options; } public RegexNode(RegexNodeKind kind, RegexOptions options, char ch) { Kind = kind; Options = options; Ch = ch; } public RegexNode(RegexNodeKind kind, RegexOptions options, string str) { Kind = kind; Options = options; Str = str; } public RegexNode(RegexNodeKind kind, RegexOptions options, int m) { Kind = kind; Options = options; M = m; } public RegexNode(RegexNodeKind kind, RegexOptions options, int m, int n) { Kind = kind; Options = options; M = m; N = n; } /// <summary>Creates a RegexNode representing a single character.</summary> /// <param name="ch">The character.</param> /// <param name="options">The node's options.</param> /// <param name="culture">The culture to use to perform any required transformations.</param> /// <returns>The created RegexNode. This might be a RegexNode.One or a RegexNode.Set.</returns> public static RegexNode CreateOneWithCaseConversion(char ch, RegexOptions options, CultureInfo? culture) { // If the options specify case-insensitivity, we try to create a node that fully encapsulates that. if ((options & RegexOptions.IgnoreCase) != 0) { Debug.Assert(culture is not null); // If the character is part of a Unicode category that doesn't participate in case conversion, // we can simply strip out the IgnoreCase option and make the node case-sensitive. if (!RegexCharClass.ParticipatesInCaseConversion(ch)) { return new RegexNode(RegexNodeKind.One, options & ~RegexOptions.IgnoreCase, ch); } // Create a set for the character, trying to include all case-insensitive equivalent characters. // If it's successful in doing so, resultIsCaseInsensitive will be false and we can strip // out RegexOptions.IgnoreCase as part of creating the set. string stringSet = RegexCharClass.OneToStringClass(ch, culture, out bool resultIsCaseInsensitive); if (!resultIsCaseInsensitive) { return new RegexNode(RegexNodeKind.Set, options & ~RegexOptions.IgnoreCase, stringSet); } // Otherwise, until we can get rid of ToLower usage at match time entirely (https://github.com/dotnet/runtime/issues/61048), // lowercase the character and proceed to create an IgnoreCase One node. ch = culture.TextInfo.ToLower(ch); } // Create a One node for the character. return new RegexNode(RegexNodeKind.One, options, ch); } /// <summary>Reverses all children of a concatenation when in RightToLeft mode.</summary> public RegexNode ReverseConcatenationIfRightToLeft() { if ((Options & RegexOptions.RightToLeft) != 0 && Kind == RegexNodeKind.Concatenate && ChildCount() > 1) { ((List<RegexNode>)Children!).Reverse(); } return this; } /// <summary> /// Pass type as OneLazy or OneLoop /// </summary> private void MakeRep(RegexNodeKind kind, int min, int max) { Kind += kind - RegexNodeKind.One; M = min; N = max; } private void MakeLoopAtomic() { switch (Kind) { case RegexNodeKind.Oneloop or RegexNodeKind.Notoneloop or RegexNodeKind.Setloop: // For loops, we simply change the Type to the atomic variant. // Atomic greedy loops should consume as many values as they can. Kind += RegexNodeKind.Oneloopatomic - RegexNodeKind.Oneloop; break; case RegexNodeKind.Onelazy or RegexNodeKind.Notonelazy or RegexNodeKind.Setlazy: // For lazy, we not only change the Type, we also lower the max number of iterations // to the minimum number of iterations, creating a repeater, as they should end up // matching as little as possible. Kind += RegexNodeKind.Oneloopatomic - RegexNodeKind.Onelazy; N = M; if (N == 0) { // If moving the max to be the same as the min dropped it to 0, there's no // work to be done for this node, and we can make it Empty. Kind = RegexNodeKind.Empty; Str = null; Ch = '\0'; } else if (Kind == RegexNodeKind.Oneloopatomic && N is >= 2 and <= MultiVsRepeaterLimit) { // If this is now a One repeater with a small enough length, // make it a Multi instead, as they're better optimized down the line. Kind = RegexNodeKind.Multi; Str = new string(Ch, N); Ch = '\0'; M = N = 0; } break; default: Debug.Fail($"Unexpected type: {Kind}"); break; } } #if DEBUG /// <summary>Validate invariants the rest of the implementation relies on for processing fully-built trees.</summary> [Conditional("DEBUG")] private void ValidateFinalTreeInvariants() { Debug.Assert(Kind == RegexNodeKind.Capture, "Every generated tree should begin with a capture node"); var toExamine = new Stack<RegexNode>(); toExamine.Push(this); while (toExamine.Count > 0) { RegexNode node = toExamine.Pop(); // Add all children to be examined int childCount = node.ChildCount(); for (int i = 0; i < childCount; i++) { RegexNode child = node.Child(i); Debug.Assert(child.Parent == node, $"{child.Describe()} missing reference to parent {node.Describe()}"); toExamine.Push(child); } // Validate that we never see certain node types. Debug.Assert(Kind != RegexNodeKind.Group, "All Group nodes should have been removed."); // Validate node types and expected child counts. switch (node.Kind) { case RegexNodeKind.Group: Debug.Fail("All Group nodes should have been removed."); break; case RegexNodeKind.Beginning: case RegexNodeKind.Bol: case RegexNodeKind.Boundary: case RegexNodeKind.ECMABoundary: case RegexNodeKind.Empty: case RegexNodeKind.End: case RegexNodeKind.EndZ: case RegexNodeKind.Eol: case RegexNodeKind.Multi: case RegexNodeKind.NonBoundary: case RegexNodeKind.NonECMABoundary: case RegexNodeKind.Nothing: case RegexNodeKind.Notone: case RegexNodeKind.Notonelazy: case RegexNodeKind.Notoneloop: case RegexNodeKind.Notoneloopatomic: case RegexNodeKind.One: case RegexNodeKind.Onelazy: case RegexNodeKind.Oneloop: case RegexNodeKind.Oneloopatomic: case RegexNodeKind.Backreference: case RegexNodeKind.Set: case RegexNodeKind.Setlazy: case RegexNodeKind.Setloop: case RegexNodeKind.Setloopatomic: case RegexNodeKind.Start: case RegexNodeKind.UpdateBumpalong: Debug.Assert(childCount == 0, $"Expected zero children for {node.Kind}, got {childCount}."); break; case RegexNodeKind.Atomic: case RegexNodeKind.Capture: case RegexNodeKind.Lazyloop: case RegexNodeKind.Loop: case RegexNodeKind.NegativeLookaround: case RegexNodeKind.PositiveLookaround: Debug.Assert(childCount == 1, $"Expected one and only one child for {node.Kind}, got {childCount}."); break; case RegexNodeKind.BackreferenceConditional: Debug.Assert(childCount == 2, $"Expected two children for {node.Kind}, got {childCount}"); break; case RegexNodeKind.ExpressionConditional: Debug.Assert(childCount == 3, $"Expected three children for {node.Kind}, got {childCount}"); break; case RegexNodeKind.Concatenate: case RegexNodeKind.Alternate: Debug.Assert(childCount >= 2, $"Expected at least two children for {node.Kind}, got {childCount}."); break; default: Debug.Fail($"Unexpected node type: {node.Kind}"); break; } // Validate node configuration. switch (node.Kind) { case RegexNodeKind.Multi: Debug.Assert(node.Str is not null, "Expect non-null multi string"); Debug.Assert(node.Str.Length >= 2, $"Expected {node.Str} to be at least two characters"); break; case RegexNodeKind.Set: case RegexNodeKind.Setloop: case RegexNodeKind.Setloopatomic: case RegexNodeKind.Setlazy: Debug.Assert(!string.IsNullOrEmpty(node.Str), $"Expected non-null, non-empty string for {node.Kind}."); break; default: Debug.Assert(node.Str is null, $"Expected null string for {node.Kind}, got \"{node.Str}\"."); break; } } } #endif /// <summary>Performs additional optimizations on an entire tree prior to being used.</summary> /// <remarks> /// Some optimizations are performed by the parser while parsing, and others are performed /// as nodes are being added to the tree. The optimizations here expect the tree to be fully /// formed, as they inspect relationships between nodes that may not have been in place as /// individual nodes were being processed/added to the tree. /// </remarks> internal RegexNode FinalOptimize() { RegexNode rootNode = this; Debug.Assert(rootNode.Kind == RegexNodeKind.Capture); Debug.Assert(rootNode.Parent is null); Debug.Assert(rootNode.ChildCount() == 1); // Only apply optimization when LTR to avoid needing additional code for the much rarer RTL case. // Also only apply these optimizations when not using NonBacktracking, as these optimizations are // all about avoiding things that are impactful for the backtracking engines but nops for non-backtracking. if ((Options & (RegexOptions.RightToLeft | RegexOptions.NonBacktracking)) == 0) { // Optimization: eliminate backtracking for loops. // For any single-character loop (Oneloop, Notoneloop, Setloop), see if we can automatically convert // that into its atomic counterpart (Oneloopatomic, Notoneloopatomic, Setloopatomic) based on what // comes after it in the expression tree. rootNode.FindAndMakeLoopsAtomic(); // Optimization: backtracking removal at expression end. // If we find backtracking construct at the end of the regex, we can instead make it non-backtracking, // since nothing would ever backtrack into it anyway. Doing this then makes the construct available // to implementations that don't support backtracking. rootNode.EliminateEndingBacktracking(); // Optimization: unnecessary re-processing of starting loops. // If an expression is guaranteed to begin with a single-character unbounded loop that isn't part of an alternation (in which case it // wouldn't be guaranteed to be at the beginning) or a capture (in which case a back reference could be influenced by its length), then we // can update the tree with a temporary node to indicate that the implementation should use that node's ending position in the input text // as the next starting position at which to start the next match. This avoids redoing matches we've already performed, e.g. matching // "\[email protected]" against "is this a valid [email protected]", the \w+ will initially match the "is" and then will fail to match the "@". // Rather than bumping the scan loop by 1 and trying again to match at the "s", we can instead start at the " ". For functional correctness // we can only consider unbounded loops, as to be able to start at the end of the loop we need the loop to have consumed all possible matches; // otherwise, you could end up with a pattern like "a{1,3}b" matching against "aaaabc", which should match, but if we pre-emptively stop consuming // after the first three a's and re-start from that position, we'll end up failing the match even though it should have succeeded. We can also // apply this optimization to non-atomic loops: even though backtracking could be necessary, such backtracking would be handled within the processing // of a single starting position. Lazy loops similarly benefit, as a failed match will result in exploring the exact same search space as with // a greedy loop, just in the opposite order (and a successful match will overwrite the bumpalong position); we need to avoid atomic lazy loops, // however, as they will only end up as a repeater for the minimum length and thus will effectively end up with a non-infinite upper bound, which // we've already outlined is problematic. { RegexNode node = rootNode.Child(0); // skip implicit root capture node bool atomicByAncestry = true; // the root is implicitly atomic because nothing comes after it (same for the implicit root capture) while (true) { switch (node.Kind) { case RegexNodeKind.Atomic: node = node.Child(0); continue; case RegexNodeKind.Concatenate: atomicByAncestry = false; node = node.Child(0); continue; case RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic when node.N == int.MaxValue: case RegexNodeKind.Onelazy or RegexNodeKind.Notonelazy or RegexNodeKind.Setlazy when node.N == int.MaxValue && !atomicByAncestry: if (node.Parent is { Kind: RegexNodeKind.Concatenate } parent) { parent.InsertChild(1, new RegexNode(RegexNodeKind.UpdateBumpalong, node.Options)); } break; } break; } } } // Done optimizing. Return the final tree. #if DEBUG rootNode.ValidateFinalTreeInvariants(); #endif return rootNode; } /// <summary>Converts nodes at the end of the node tree to be atomic.</summary> /// <remarks> /// The correctness of this optimization depends on nothing being able to backtrack into /// the provided node. That means it must be at the root of the overall expression, or /// it must be an Atomic node that nothing will backtrack into by the very nature of Atomic. /// </remarks> private void EliminateEndingBacktracking() { if (!StackHelper.TryEnsureSufficientExecutionStack() || (Options & (RegexOptions.RightToLeft | RegexOptions.NonBacktracking)) != 0) { // If we can't recur further, just stop optimizing. // We haven't done the work to validate this is correct for RTL. // And NonBacktracking doesn't support atomic groups and doesn't have backtracking to be eliminated. return; } // Walk the tree starting from the current node. RegexNode node = this; while (true) { switch (node.Kind) { // {One/Notone/Set}loops can be upgraded to {One/Notone/Set}loopatomic nodes, e.g. [abc]* => (?>[abc]*). // And {One/Notone/Set}lazys can similarly be upgraded to be atomic, which really makes them into repeaters // or even empty nodes. case RegexNodeKind.Oneloop or RegexNodeKind.Notoneloop or RegexNodeKind.Setloop: case RegexNodeKind.Onelazy or RegexNodeKind.Notonelazy or RegexNodeKind.Setlazy: node.MakeLoopAtomic(); break; // Just because a particular node is atomic doesn't mean all its descendants are. // Process them as well. Lookarounds are implicitly atomic. case RegexNodeKind.Atomic: case RegexNodeKind.PositiveLookaround: case RegexNodeKind.NegativeLookaround: node = node.Child(0); continue; // For Capture and Concatenate, we just recur into their last child (only child in the case // of Capture). However, if the child is an alternation or loop, we can also make the // node itself atomic by wrapping it in an Atomic node. Since we later check to see whether a // node is atomic based on its parent or grandparent, we don't bother wrapping such a node in // an Atomic one if its grandparent is already Atomic. // e.g. [xyz](?:abc|def) => [xyz](?>abc|def) case RegexNodeKind.Capture: case RegexNodeKind.Concatenate: RegexNode existingChild = node.Child(node.ChildCount() - 1); if ((existingChild.Kind is RegexNodeKind.Alternate or RegexNodeKind.BackreferenceConditional or RegexNodeKind.ExpressionConditional or RegexNodeKind.Loop or RegexNodeKind.Lazyloop) && (node.Parent is null || node.Parent.Kind != RegexNodeKind.Atomic)) // validate grandparent isn't atomic { var atomic = new RegexNode(RegexNodeKind.Atomic, existingChild.Options); atomic.AddChild(existingChild); node.ReplaceChild(node.ChildCount() - 1, atomic); } node = existingChild; continue; // For alternate, we can recur into each branch separately. We use this iteration for the first branch. // Conditionals are just like alternations in this regard. // e.g. abc*|def* => ab(?>c*)|de(?>f*) case RegexNodeKind.Alternate: case RegexNodeKind.BackreferenceConditional: case RegexNodeKind.ExpressionConditional: { int branches = node.ChildCount(); for (int i = 1; i < branches; i++) { node.Child(i).EliminateEndingBacktracking(); } if (node.Kind != RegexNodeKind.ExpressionConditional) // ReduceExpressionConditional will have already applied ending backtracking removal { node = node.Child(0); continue; } } break; // For {Lazy}Loop, we search to see if there's a viable last expression, and iff there // is we recur into processing it. Also, as with the single-char lazy loops, LazyLoop // can have its max iteration count dropped to its min iteration count, as there's no // reason for it to match more than the minimal at the end; that in turn makes it a // repeater, which results in better code generation. // e.g. (?:abc*)* => (?:ab(?>c*))* // e.g. (abc*?)+? => (ab){1} case RegexNodeKind.Lazyloop: node.N = node.M; goto case RegexNodeKind.Loop; case RegexNodeKind.Loop: { if (node.N == 1) { // If the loop has a max iteration count of 1 (e.g. it's an optional node), // there's no possibility for conflict between multiple iterations, so // we can process it. node = node.Child(0); continue; } RegexNode? loopDescendent = node.FindLastExpressionInLoopForAutoAtomic(); if (loopDescendent != null) { node = loopDescendent; continue; // loop around to process node } } break; } break; } } /// <summary> /// Removes redundant nodes from the subtree, and returns an optimized subtree. /// </summary> internal RegexNode Reduce() { // TODO: https://github.com/dotnet/runtime/issues/61048 // As part of overhauling IgnoreCase handling, the parser shouldn't produce any nodes other than Backreference // that ever have IgnoreCase set on them. For now, though, remove IgnoreCase from any nodes for which it // has no behavioral effect. switch (Kind) { default: // No effect Options &= ~RegexOptions.IgnoreCase; break; case RegexNodeKind.One or RegexNodeKind.Onelazy or RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic: case RegexNodeKind.Notone or RegexNodeKind.Notonelazy or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic: case RegexNodeKind.Set or RegexNodeKind.Setlazy or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic: case RegexNodeKind.Multi: case RegexNodeKind.Backreference: // Still meaningful break; } return Kind switch { RegexNodeKind.Alternate => ReduceAlternation(), RegexNodeKind.Atomic => ReduceAtomic(), RegexNodeKind.Concatenate => ReduceConcatenation(), RegexNodeKind.Group => ReduceGroup(), RegexNodeKind.Loop or RegexNodeKind.Lazyloop => ReduceLoops(), RegexNodeKind.PositiveLookaround or RegexNodeKind.NegativeLookaround => ReduceLookaround(), RegexNodeKind.Set or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic or RegexNodeKind.Setlazy => ReduceSet(), RegexNodeKind.ExpressionConditional => ReduceExpressionConditional(), RegexNodeKind.BackreferenceConditional => ReduceBackreferenceConditional(), _ => this, }; } /// <summary>Remove an unnecessary Concatenation or Alternation node</summary> /// <remarks> /// Simple optimization for a concatenation or alternation: /// - if the node has only one child, use it instead /// - if the node has zero children, turn it into an empty with Nothing for an alternation or Empty for a concatenation /// </remarks> private RegexNode ReplaceNodeIfUnnecessary() { Debug.Assert(Kind is RegexNodeKind.Alternate or RegexNodeKind.Concatenate); return ChildCount() switch { 0 => new RegexNode(Kind == RegexNodeKind.Alternate ? RegexNodeKind.Nothing : RegexNodeKind.Empty, Options), 1 => Child(0), _ => this, }; } /// <summary>Remove all non-capturing groups.</summary> /// <remark> /// Simple optimization: once parsed into a tree, non-capturing groups /// serve no function, so strip them out. /// e.g. (?:(?:(?:abc))) => abc /// </remark> private RegexNode ReduceGroup() { Debug.Assert(Kind == RegexNodeKind.Group); RegexNode u = this; while (u.Kind == RegexNodeKind.Group) { Debug.Assert(u.ChildCount() == 1); u = u.Child(0); } return u; } /// <summary> /// Remove unnecessary atomic nodes, and make appropriate descendents of the atomic node themselves atomic. /// </summary> /// <remarks> /// e.g. (?>(?>(?>a*))) => (?>a*) /// e.g. (?>(abc*)*) => (?>(abc(?>c*))*) /// </remarks> private RegexNode ReduceAtomic() { // RegexOptions.NonBacktracking doesn't support atomic groups, so when that option // is set we don't want to create atomic groups where they weren't explicitly authored. if ((Options & RegexOptions.NonBacktracking) != 0) { return this; } Debug.Assert(Kind == RegexNodeKind.Atomic); Debug.Assert(ChildCount() == 1); RegexNode atomic = this; RegexNode child = Child(0); while (child.Kind == RegexNodeKind.Atomic) { atomic = child; child = atomic.Child(0); } switch (child.Kind) { // If the child is empty/nothing, there's nothing to be made atomic so the Atomic // node can simply be removed. case RegexNodeKind.Empty: case RegexNodeKind.Nothing: return child; // If the child is already atomic, we can just remove the atomic node. case RegexNodeKind.Oneloopatomic: case RegexNodeKind.Notoneloopatomic: case RegexNodeKind.Setloopatomic: return child; // If an atomic subexpression contains only a {one/notone/set}{loop/lazy}, // change it to be an {one/notone/set}loopatomic and remove the atomic node. case RegexNodeKind.Oneloop: case RegexNodeKind.Notoneloop: case RegexNodeKind.Setloop: case RegexNodeKind.Onelazy: case RegexNodeKind.Notonelazy: case RegexNodeKind.Setlazy: child.MakeLoopAtomic(); return child; // Alternations have a variety of possible optimizations that can be applied // iff they're atomic. case RegexNodeKind.Alternate: if ((Options & RegexOptions.RightToLeft) == 0) { List<RegexNode>? branches = child.Children as List<RegexNode>; Debug.Assert(branches is not null && branches.Count != 0); // If an alternation is atomic and its first branch is Empty, the whole thing // is a nop, as Empty will match everything trivially, and no backtracking // into the node will be performed, making the remaining branches irrelevant. if (branches[0].Kind == RegexNodeKind.Empty) { return new RegexNode(RegexNodeKind.Empty, child.Options); } // Similarly, we can trim off any branches after an Empty, as they'll never be used. // An Empty will match anything, and thus branches after that would only be used // if we backtracked into it and advanced passed the Empty after trying the Empty... // but if the alternation is atomic, such backtracking won't happen. for (int i = 1; i < branches.Count - 1; i++) { if (branches[i].Kind == RegexNodeKind.Empty) { branches.RemoveRange(i + 1, branches.Count - (i + 1)); break; } } // If an alternation is atomic, we won't ever backtrack back into it, which // means order matters but not repetition. With backtracking, it would be incorrect // to convert an expression like "hi|there|hello" into "hi|hello|there", as doing // so could then change the order of results if we matched "hi" and then failed // based on what came after it, and both "hello" and "there" could be successful // with what came later. But without backtracking, we can reorder "hi|there|hello" // to instead be "hi|hello|there", as "hello" and "there" can't match the same text, // and once this atomic alternation has matched, we won't try another branch. This // reordering is valuable as it then enables further optimizations, e.g. // "hi|there|hello" => "hi|hello|there" => "h(?:i|ello)|there", which means we only // need to check the 'h' once in case it's not an 'h', and it's easier to employ different // code gen that, for example, switches on first character of the branches, enabling faster // choice of branch without always having to walk through each. bool reordered = false; for (int start = 0; start < branches.Count; start++) { // Get the node that may start our range. If it's a one, multi, or concat of those, proceed. RegexNode startNode = branches[start]; if (startNode.FindBranchOneOrMultiStart() is null) { continue; } // Find the contiguous range of nodes from this point that are similarly one, multi, or concat of those. int endExclusive = start + 1; while (endExclusive < branches.Count && branches[endExclusive].FindBranchOneOrMultiStart() is not null) { endExclusive++; } // If there's at least 3, there may be something to reorder (we won't reorder anything // before the starting position, and so only 2 items is considered ordered). if (endExclusive - start >= 3) { int compare = start; while (compare < endExclusive) { // Get the starting character char c = branches[compare].FindBranchOneOrMultiStart()!.FirstCharOfOneOrMulti(); // Move compare to point to the last branch that has the same starting value. while (compare < endExclusive && branches[compare].FindBranchOneOrMultiStart()!.FirstCharOfOneOrMulti() == c) { compare++; } // Compare now points to the first node that doesn't match the starting node. // If we've walked off our range, there's nothing left to reorder. if (compare < endExclusive) { // There may be something to reorder. See if there are any other nodes that begin with the same character. for (int next = compare + 1; next < endExclusive; next++) { RegexNode nextChild = branches[next]; if (nextChild.FindBranchOneOrMultiStart()!.FirstCharOfOneOrMulti() == c) { branches.RemoveAt(next); branches.Insert(compare++, nextChild); reordered = true; } } } } } // Move to the end of the range we've now explored. endExclusive is not a viable // starting position either, and the start++ for the loop will thus take us to // the next potential place to start a range. start = endExclusive; } // If anything was reordered, there may be new optimization opportunities inside // of the alternation, so reduce it again. if (reordered) { atomic.ReplaceChild(0, child); child = atomic.Child(0); } } goto default; // For everything else, try to reduce ending backtracking of the last contained expression. default: child.EliminateEndingBacktracking(); return atomic; } } /// <summary>Combine nested loops where applicable.</summary> /// <remarks> /// Nested repeaters just get multiplied with each other if they're not too lumpy. /// Other optimizations may have also resulted in {Lazy}loops directly containing /// sets, ones, and notones, in which case they can be transformed into the corresponding /// individual looping constructs. /// </remarks> private RegexNode ReduceLoops() { Debug.Assert(Kind is RegexNodeKind.Loop or RegexNodeKind.Lazyloop); RegexNode u = this; RegexNodeKind kind = Kind; int min = M; int max = N; while (u.ChildCount() > 0) { RegexNode child = u.Child(0); // multiply reps of the same type only if (child.Kind != kind) { bool valid = false; if (kind == RegexNodeKind.Loop) { switch (child.Kind) { case RegexNodeKind.Oneloop: case RegexNodeKind.Oneloopatomic: case RegexNodeKind.Notoneloop: case RegexNodeKind.Notoneloopatomic: case RegexNodeKind.Setloop: case RegexNodeKind.Setloopatomic: valid = true; break; } } else // type == Lazyloop { switch (child.Kind) { case RegexNodeKind.Onelazy: case RegexNodeKind.Notonelazy: case RegexNodeKind.Setlazy: valid = true; break; } } if (!valid) { break; } } // child can be too lumpy to blur, e.g., (a {100,105}) {3} or (a {2,})? // [but things like (a {2,})+ are not too lumpy...] if (u.M == 0 && child.M > 1 || child.N < child.M * 2) { break; } u = child; if (u.M > 0) { u.M = min = ((int.MaxValue - 1) / u.M < min) ? int.MaxValue : u.M * min; } if (u.N > 0) { u.N = max = ((int.MaxValue - 1) / u.N < max) ? int.MaxValue : u.N * max; } } if (min == int.MaxValue) { return new RegexNode(RegexNodeKind.Nothing, Options); } // If the Loop or Lazyloop now only has one child node and its a Set, One, or Notone, // reduce to just Setloop/lazy, Oneloop/lazy, or Notoneloop/lazy. The parser will // generally have only produced the latter, but other reductions could have exposed // this. if (u.ChildCount() == 1) { RegexNode child = u.Child(0); switch (child.Kind) { case RegexNodeKind.One: case RegexNodeKind.Notone: case RegexNodeKind.Set: child.MakeRep(u.Kind == RegexNodeKind.Lazyloop ? RegexNodeKind.Onelazy : RegexNodeKind.Oneloop, u.M, u.N); u = child; break; } } return u; } /// <summary> /// Reduces set-related nodes to simpler one-related and notone-related nodes, where applicable. /// </summary> /// <remarks> /// e.g. /// [a] => a /// [a]* => a* /// [a]*? => a*? /// (?>[a]*) => (?>a*) /// [^a] => ^a /// []* => Nothing /// </remarks> private RegexNode ReduceSet() { // Extract empty-set, one, and not-one case as special Debug.Assert(Kind is RegexNodeKind.Set or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic or RegexNodeKind.Setlazy); Debug.Assert(!string.IsNullOrEmpty(Str)); if (RegexCharClass.IsEmpty(Str)) { Kind = RegexNodeKind.Nothing; Str = null; } else if (RegexCharClass.IsSingleton(Str)) { Ch = RegexCharClass.SingletonChar(Str); Str = null; Kind = Kind == RegexNodeKind.Set ? RegexNodeKind.One : Kind == RegexNodeKind.Setloop ? RegexNodeKind.Oneloop : Kind == RegexNodeKind.Setloopatomic ? RegexNodeKind.Oneloopatomic : RegexNodeKind.Onelazy; } else if (RegexCharClass.IsSingletonInverse(Str)) { Ch = RegexCharClass.SingletonChar(Str); Str = null; Kind = Kind == RegexNodeKind.Set ? RegexNodeKind.Notone : Kind == RegexNodeKind.Setloop ? RegexNodeKind.Notoneloop : Kind == RegexNodeKind.Setloopatomic ? RegexNodeKind.Notoneloopatomic : RegexNodeKind.Notonelazy; } return this; } /// <summary>Optimize an alternation.</summary> private RegexNode ReduceAlternation() { Debug.Assert(Kind == RegexNodeKind.Alternate); switch (ChildCount()) { case 0: return new RegexNode(RegexNodeKind.Nothing, Options); case 1: return Child(0); default: ReduceSingleLetterAndNestedAlternations(); RegexNode node = ReplaceNodeIfUnnecessary(); if (node.Kind == RegexNodeKind.Alternate) { node = ExtractCommonPrefixText(node); if (node.Kind == RegexNodeKind.Alternate) { node = ExtractCommonPrefixOneNotoneSet(node); if (node.Kind == RegexNodeKind.Alternate) { node = RemoveRedundantEmptiesAndNothings(node); } } } return node; } // This function performs two optimizations: // - Single-letter alternations can be replaced by faster set specifications // e.g. "a|b|c|def|g|h" -> "[a-c]|def|[gh]" // - Nested alternations with no intervening operators can be flattened: // e.g. "apple|(?:orange|pear)|grape" -> "apple|orange|pear|grape" void ReduceSingleLetterAndNestedAlternations() { bool wasLastSet = false; bool lastNodeCannotMerge = false; RegexOptions optionsLast = 0; RegexOptions optionsAt; int i; int j; RegexNode at; RegexNode prev; List<RegexNode> children = (List<RegexNode>)Children!; for (i = 0, j = 0; i < children.Count; i++, j++) { at = children[i]; if (j < i) children[j] = at; while (true) { if (at.Kind == RegexNodeKind.Alternate) { if (at.Children is List<RegexNode> atChildren) { for (int k = 0; k < atChildren.Count; k++) { atChildren[k].Parent = this; } children.InsertRange(i + 1, atChildren); } else { RegexNode atChild = (RegexNode)at.Children!; atChild.Parent = this; children.Insert(i + 1, atChild); } j--; } else if (at.Kind is RegexNodeKind.Set or RegexNodeKind.One) { // Cannot merge sets if L or I options differ, or if either are negated. optionsAt = at.Options & (RegexOptions.RightToLeft | RegexOptions.IgnoreCase); if (at.Kind == RegexNodeKind.Set) { if (!wasLastSet || optionsLast != optionsAt || lastNodeCannotMerge || !RegexCharClass.IsMergeable(at.Str!)) { wasLastSet = true; lastNodeCannotMerge = !RegexCharClass.IsMergeable(at.Str!); optionsLast = optionsAt; break; } } else if (!wasLastSet || optionsLast != optionsAt || lastNodeCannotMerge) { wasLastSet = true; lastNodeCannotMerge = false; optionsLast = optionsAt; break; } // The last node was a Set or a One, we're a Set or One and our options are the same. // Merge the two nodes. j--; prev = children[j]; RegexCharClass prevCharClass; if (prev.Kind == RegexNodeKind.One) { prevCharClass = new RegexCharClass(); prevCharClass.AddChar(prev.Ch); } else { prevCharClass = RegexCharClass.Parse(prev.Str!); } if (at.Kind == RegexNodeKind.One) { prevCharClass.AddChar(at.Ch); } else { RegexCharClass atCharClass = RegexCharClass.Parse(at.Str!); prevCharClass.AddCharClass(atCharClass); } prev.Kind = RegexNodeKind.Set; prev.Str = prevCharClass.ToStringClass(Options); if ((prev.Options & RegexOptions.IgnoreCase) != 0 && RegexCharClass.MakeCaseSensitiveIfPossible(prev.Str, RegexParser.GetTargetCulture(prev.Options)) is string newSetString) { prev.Str = newSetString; prev.Options &= ~RegexOptions.IgnoreCase; } } else if (at.Kind == RegexNodeKind.Nothing) { j--; } else { wasLastSet = false; lastNodeCannotMerge = false; } break; } } if (j < i) { children.RemoveRange(j, i - j); } } // This function optimizes out prefix nodes from alternation branches that are // the same across multiple contiguous branches. // e.g. \w12|\d34|\d56|\w78|\w90 => \w12|\d(?:34|56)|\w(?:78|90) static RegexNode ExtractCommonPrefixOneNotoneSet(RegexNode alternation) { Debug.Assert(alternation.Kind == RegexNodeKind.Alternate); Debug.Assert(alternation.Children is List<RegexNode> { Count: >= 2 }); var children = (List<RegexNode>)alternation.Children; // Only process left-to-right prefixes. if ((alternation.Options & RegexOptions.RightToLeft) != 0) { return alternation; } // Only handle the case where each branch is a concatenation foreach (RegexNode child in children) { if (child.Kind != RegexNodeKind.Concatenate || child.ChildCount() < 2) { return alternation; } } for (int startingIndex = 0; startingIndex < children.Count - 1; startingIndex++) { Debug.Assert(children[startingIndex].Children is List<RegexNode> { Count: >= 2 }); // Only handle the case where each branch begins with the same One, Notone, or Set (individual or loop). // Note that while we can do this for individual characters, fixed length loops, and atomic loops, doing // it for non-atomic variable length loops could change behavior as each branch could otherwise have a // different number of characters consumed by the loop based on what's after it. RegexNode required = children[startingIndex].Child(0); switch (required.Kind) { case RegexNodeKind.One or RegexNodeKind.Notone or RegexNodeKind.Set: case RegexNodeKind.Oneloopatomic or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Setloopatomic: case RegexNodeKind.Oneloop or RegexNodeKind.Notoneloop or RegexNodeKind.Setloop or RegexNodeKind.Onelazy or RegexNodeKind.Notonelazy or RegexNodeKind.Setlazy when required.M == required.N: break; default: continue; } // Only handle the case where each branch begins with the exact same node value int endingIndex = startingIndex + 1; for (; endingIndex < children.Count; endingIndex++) { RegexNode other = children[endingIndex].Child(0); if (required.Kind != other.Kind || required.Options != other.Options || required.M != other.M || required.N != other.N || required.Ch != other.Ch || required.Str != other.Str) { break; } } if (endingIndex - startingIndex <= 1) { // Nothing to extract from this starting index. continue; } // Remove the prefix node from every branch, adding it to a new alternation var newAlternate = new RegexNode(RegexNodeKind.Alternate, alternation.Options); for (int i = startingIndex; i < endingIndex; i++) { ((List<RegexNode>)children[i].Children!).RemoveAt(0); newAlternate.AddChild(children[i]); } // If this alternation is wrapped as atomic, we need to do the same for the new alternation. if (alternation.Parent is RegexNode { Kind: RegexNodeKind.Atomic } parent) { var atomic = new RegexNode(RegexNodeKind.Atomic, alternation.Options); atomic.AddChild(newAlternate); newAlternate = atomic; } // Now create a concatenation of the prefix node with the new alternation for the combined // branches, and replace all of the branches in this alternation with that new concatenation. var newConcat = new RegexNode(RegexNodeKind.Concatenate, alternation.Options); newConcat.AddChild(required); newConcat.AddChild(newAlternate); alternation.ReplaceChild(startingIndex, newConcat); children.RemoveRange(startingIndex + 1, endingIndex - startingIndex - 1); } return alternation.ReplaceNodeIfUnnecessary(); } // Removes unnecessary Empty and Nothing nodes from the alternation. A Nothing will never // match, so it can be removed entirely, and an Empty can be removed if there's a previous // Empty in the alternation: it's an extreme case of just having a repeated branch in an // alternation, and while we don't check for all duplicates, checking for empty is easy. static RegexNode RemoveRedundantEmptiesAndNothings(RegexNode node) { Debug.Assert(node.Kind == RegexNodeKind.Alternate); Debug.Assert(node.ChildCount() >= 2); var children = (List<RegexNode>)node.Children!; int i = 0, j = 0; bool seenEmpty = false; while (i < children.Count) { RegexNode child = children[i]; switch (child.Kind) { case RegexNodeKind.Empty when !seenEmpty: seenEmpty = true; goto default; case RegexNodeKind.Empty: case RegexNodeKind.Nothing: i++; break; default: children[j] = children[i]; i++; j++; break; } } children.RemoveRange(j, children.Count - j); return node.ReplaceNodeIfUnnecessary(); } // Analyzes all the branches of the alternation for text that's identical at the beginning // of every branch. That text is then pulled out into its own one or multi node in a // concatenation with the alternation (whose branches are updated to remove that prefix). // This is valuable for a few reasons. One, it exposes potentially more text to the // expression prefix analyzer used to influence FindFirstChar. Second, it exposes more // potential alternation optimizations, e.g. if the same prefix is followed in two branches // by sets that can be merged. Third, it reduces the amount of duplicated comparisons required // if we end up backtracking into subsequent branches. // e.g. abc|ade => a(?bc|de) static RegexNode ExtractCommonPrefixText(RegexNode alternation) { Debug.Assert(alternation.Kind == RegexNodeKind.Alternate); Debug.Assert(alternation.Children is List<RegexNode> { Count: >= 2 }); var children = (List<RegexNode>)alternation.Children; // To keep things relatively simple, we currently only handle: // - Left to right (e.g. we don't process alternations in lookbehinds) // - Branches that are one or multi nodes, or that are concatenations beginning with one or multi nodes. // - All branches having the same options. // Only extract left-to-right prefixes. if ((alternation.Options & RegexOptions.RightToLeft) != 0) { return alternation; } Span<char> scratchChar = stackalloc char[1]; ReadOnlySpan<char> startingSpan = stackalloc char[0]; for (int startingIndex = 0; startingIndex < children.Count - 1; startingIndex++) { // Process the first branch to get the maximum possible common string. RegexNode? startingNode = children[startingIndex].FindBranchOneOrMultiStart(); if (startingNode is null) { return alternation; } RegexOptions startingNodeOptions = startingNode.Options; startingSpan = startingNode.Str.AsSpan(); if (startingNode.Kind == RegexNodeKind.One) { scratchChar[0] = startingNode.Ch; startingSpan = scratchChar; } Debug.Assert(startingSpan.Length > 0); // Now compare the rest of the branches against it. int endingIndex = startingIndex + 1; for (; endingIndex < children.Count; endingIndex++) { // Get the starting node of the next branch. startingNode = children[endingIndex].FindBranchOneOrMultiStart(); if (startingNode is null || startingNode.Options != startingNodeOptions) { break; } // See if the new branch's prefix has a shared prefix with the current one. // If it does, shorten to that; if it doesn't, bail. if (startingNode.Kind == RegexNodeKind.One) { if (startingSpan[0] != startingNode.Ch) { break; } if (startingSpan.Length != 1) { startingSpan = startingSpan.Slice(0, 1); } } else { Debug.Assert(startingNode.Kind == RegexNodeKind.Multi); Debug.Assert(startingNode.Str!.Length > 0); int minLength = Math.Min(startingSpan.Length, startingNode.Str.Length); int c = 0; while (c < minLength && startingSpan[c] == startingNode.Str[c]) c++; if (c == 0) { break; } startingSpan = startingSpan.Slice(0, c); } } // When we get here, we have a starting string prefix shared by all branches // in the range [startingIndex, endingIndex). if (endingIndex - startingIndex <= 1) { // There's nothing to consolidate for this starting node. continue; } // We should be able to consolidate something for the nodes in the range [startingIndex, endingIndex). Debug.Assert(startingSpan.Length > 0); // Create a new node of the form: // Concatenation(prefix, Alternation(each | node | with | prefix | removed)) // that replaces all these branches in this alternation. var prefix = startingSpan.Length == 1 ? new RegexNode(RegexNodeKind.One, startingNodeOptions, startingSpan[0]) : new RegexNode(RegexNodeKind.Multi, startingNodeOptions, startingSpan.ToString()); var newAlternate = new RegexNode(RegexNodeKind.Alternate, startingNodeOptions); for (int i = startingIndex; i < endingIndex; i++) { RegexNode branch = children[i]; ProcessOneOrMulti(branch.Kind == RegexNodeKind.Concatenate ? branch.Child(0) : branch, startingSpan); branch = branch.Reduce(); newAlternate.AddChild(branch); // Remove the starting text from the one or multi node. This may end up changing // the type of the node to be Empty if the starting text matches the node's full value. static void ProcessOneOrMulti(RegexNode node, ReadOnlySpan<char> startingSpan) { if (node.Kind == RegexNodeKind.One) { Debug.Assert(startingSpan.Length == 1); Debug.Assert(startingSpan[0] == node.Ch); node.Kind = RegexNodeKind.Empty; node.Ch = '\0'; } else { Debug.Assert(node.Kind == RegexNodeKind.Multi); Debug.Assert(node.Str.AsSpan().StartsWith(startingSpan, StringComparison.Ordinal)); if (node.Str!.Length == startingSpan.Length) { node.Kind = RegexNodeKind.Empty; node.Str = null; } else if (node.Str.Length - 1 == startingSpan.Length) { node.Kind = RegexNodeKind.One; node.Ch = node.Str[node.Str.Length - 1]; node.Str = null; } else { node.Str = node.Str.Substring(startingSpan.Length); } } } } if (alternation.Parent is RegexNode parent && parent.Kind == RegexNodeKind.Atomic) { var atomic = new RegexNode(RegexNodeKind.Atomic, startingNodeOptions); atomic.AddChild(newAlternate); newAlternate = atomic; } var newConcat = new RegexNode(RegexNodeKind.Concatenate, startingNodeOptions); newConcat.AddChild(prefix); newConcat.AddChild(newAlternate); alternation.ReplaceChild(startingIndex, newConcat); children.RemoveRange(startingIndex + 1, endingIndex - startingIndex - 1); } return alternation.ChildCount() == 1 ? alternation.Child(0) : alternation; } } /// <summary> /// Finds the starting one or multi of the branch, if it has one; otherwise, returns null. /// For simplicity, this only considers branches that are One or Multi, or a Concatenation /// beginning with a One or Multi. We don't traverse more than one level to avoid the /// complication of then having to later update that hierarchy when removing the prefix, /// but it could be done in the future if proven beneficial enough. /// </summary> public RegexNode? FindBranchOneOrMultiStart() { RegexNode branch = Kind == RegexNodeKind.Concatenate ? Child(0) : this; return branch.Kind is RegexNodeKind.One or RegexNodeKind.Multi ? branch : null; } /// <summary>Same as <see cref="FindBranchOneOrMultiStart"/> but also for Sets.</summary> public RegexNode? FindBranchOneMultiOrSetStart() { RegexNode branch = Kind == RegexNodeKind.Concatenate ? Child(0) : this; return branch.Kind is RegexNodeKind.One or RegexNodeKind.Multi or RegexNodeKind.Set ? branch : null; } /// <summary>Gets the character that begins a One or Multi.</summary> public char FirstCharOfOneOrMulti() { Debug.Assert(Kind is RegexNodeKind.One or RegexNodeKind.Multi); Debug.Assert((Options & RegexOptions.RightToLeft) == 0); return Kind == RegexNodeKind.One ? Ch : Str![0]; } /// <summary>Finds the guaranteed beginning literal(s) of the node, or null if none exists.</summary> public (char Char, string? String, string? SetChars)? FindStartingLiteral(int maxSetCharacters = 5) // 5 is max optimized by IndexOfAny today { Debug.Assert(maxSetCharacters >= 0 && maxSetCharacters <= 128, $"{nameof(maxSetCharacters)} == {maxSetCharacters} should be small enough to be stack allocated."); RegexNode? node = this; while (true) { if (node is not null && (node.Options & RegexOptions.RightToLeft) == 0) { switch (node.Kind) { case RegexNodeKind.One: case RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Onelazy when node.M > 0: if ((node.Options & RegexOptions.IgnoreCase) == 0 || !RegexCharClass.ParticipatesInCaseConversion(node.Ch)) { return (node.Ch, null, null); } break; case RegexNodeKind.Multi: if ((node.Options & RegexOptions.IgnoreCase) == 0 || !RegexCharClass.ParticipatesInCaseConversion(node.Str.AsSpan())) { return ('\0', node.Str, null); } break; case RegexNodeKind.Set: case RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic or RegexNodeKind.Setlazy when node.M > 0: Span<char> setChars = stackalloc char[maxSetCharacters]; int numChars; if (!RegexCharClass.IsNegated(node.Str!) && (numChars = RegexCharClass.GetSetChars(node.Str!, setChars)) != 0) { setChars = setChars.Slice(0, numChars); if ((node.Options & RegexOptions.IgnoreCase) == 0 || !RegexCharClass.ParticipatesInCaseConversion(setChars)) { return ('\0', null, setChars.ToString()); } } break; case RegexNodeKind.Atomic: case RegexNodeKind.Concatenate: case RegexNodeKind.Capture: case RegexNodeKind.Group: case RegexNodeKind.Loop or RegexNodeKind.Lazyloop when node.M > 0: case RegexNodeKind.PositiveLookaround: node = node.Child(0); continue; } } return null; } } /// <summary> /// Optimizes a concatenation by coalescing adjacent characters and strings, /// coalescing adjacent loops, converting loops to be atomic where applicable, /// and removing the concatenation itself if it's unnecessary. /// </summary> private RegexNode ReduceConcatenation() { Debug.Assert(Kind == RegexNodeKind.Concatenate); // If the concat node has zero or only one child, get rid of the concat. switch (ChildCount()) { case 0: return new RegexNode(RegexNodeKind.Empty, Options); case 1: return Child(0); } // Coalesce adjacent loops. This helps to minimize work done by the interpreter, minimize code gen, // and also help to reduce catastrophic backtracking. ReduceConcatenationWithAdjacentLoops(); // Coalesce adjacent characters/strings. This is done after the adjacent loop coalescing so that // a One adjacent to both a Multi and a Loop prefers being folded into the Loop rather than into // the Multi. Doing so helps with auto-atomicity when it's later applied. ReduceConcatenationWithAdjacentStrings(); // If the concatenation is now empty, return an empty node, or if it's got a single child, return that child. // Otherwise, return this. return ReplaceNodeIfUnnecessary(); } /// <summary> /// Combine adjacent characters/strings. /// e.g. (?:abc)(?:def) -> abcdef /// </summary> private void ReduceConcatenationWithAdjacentStrings() { Debug.Assert(Kind == RegexNodeKind.Concatenate); Debug.Assert(Children is List<RegexNode>); bool wasLastString = false; RegexOptions optionsLast = 0; int i, j; List<RegexNode> children = (List<RegexNode>)Children!; for (i = 0, j = 0; i < children.Count; i++, j++) { RegexNode at = children[i]; if (j < i) { children[j] = at; } if (at.Kind == RegexNodeKind.Concatenate && ((at.Options & RegexOptions.RightToLeft) == (Options & RegexOptions.RightToLeft))) { if (at.Children is List<RegexNode> atChildren) { for (int k = 0; k < atChildren.Count; k++) { atChildren[k].Parent = this; } children.InsertRange(i + 1, atChildren); } else { RegexNode atChild = (RegexNode)at.Children!; atChild.Parent = this; children.Insert(i + 1, atChild); } j--; } else if (at.Kind is RegexNodeKind.Multi or RegexNodeKind.One) { // Cannot merge strings if L or I options differ RegexOptions optionsAt = at.Options & (RegexOptions.RightToLeft | RegexOptions.IgnoreCase); if (!wasLastString || optionsLast != optionsAt) { wasLastString = true; optionsLast = optionsAt; continue; } RegexNode prev = children[--j]; if (prev.Kind == RegexNodeKind.One) { prev.Kind = RegexNodeKind.Multi; prev.Str = prev.Ch.ToString(); } if ((optionsAt & RegexOptions.RightToLeft) == 0) { prev.Str = (at.Kind == RegexNodeKind.One) ? $"{prev.Str}{at.Ch}" : prev.Str + at.Str; } else { prev.Str = (at.Kind == RegexNodeKind.One) ? $"{at.Ch}{prev.Str}" : at.Str + prev.Str; } } else if (at.Kind == RegexNodeKind.Empty) { j--; } else { wasLastString = false; } } if (j < i) { children.RemoveRange(j, i - j); } } /// <summary> /// Combine adjacent loops. /// e.g. a*a*a* => a* /// e.g. a+ab => a{2,}b /// </summary> private void ReduceConcatenationWithAdjacentLoops() { Debug.Assert(Kind == RegexNodeKind.Concatenate); Debug.Assert(Children is List<RegexNode>); var children = (List<RegexNode>)Children!; int current = 0, next = 1, nextSave = 1; while (next < children.Count) { RegexNode currentNode = children[current]; RegexNode nextNode = children[next]; if (currentNode.Options == nextNode.Options) { static bool CanCombineCounts(int nodeMin, int nodeMax, int nextMin, int nextMax) { // We shouldn't have an infinite minimum; bail if we find one. Also check for the // degenerate case where we'd make the min overflow or go infinite when it wasn't already. if (nodeMin == int.MaxValue || nextMin == int.MaxValue || (uint)nodeMin + (uint)nextMin >= int.MaxValue) { return false; } // Similar overflow / go infinite check for max (which can be infinite). if (nodeMax != int.MaxValue && nextMax != int.MaxValue && (uint)nodeMax + (uint)nextMax >= int.MaxValue) { return false; } return true; } switch (currentNode.Kind) { // Coalescing a loop with its same type case RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Onelazy or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Notonelazy when nextNode.Kind == currentNode.Kind && currentNode.Ch == nextNode.Ch: case RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic or RegexNodeKind.Setlazy when nextNode.Kind == currentNode.Kind && currentNode.Str == nextNode.Str: if (CanCombineCounts(currentNode.M, currentNode.N, nextNode.M, nextNode.N)) { currentNode.M += nextNode.M; if (currentNode.N != int.MaxValue) { currentNode.N = nextNode.N == int.MaxValue ? int.MaxValue : currentNode.N + nextNode.N; } next++; continue; } break; // Coalescing a loop with an additional item of the same type case RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Onelazy when nextNode.Kind == RegexNodeKind.One && currentNode.Ch == nextNode.Ch: case RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Notonelazy when nextNode.Kind == RegexNodeKind.Notone && currentNode.Ch == nextNode.Ch: case RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic or RegexNodeKind.Setlazy when nextNode.Kind == RegexNodeKind.Set && currentNode.Str == nextNode.Str: if (CanCombineCounts(currentNode.M, currentNode.N, 1, 1)) { currentNode.M++; if (currentNode.N != int.MaxValue) { currentNode.N++; } next++; continue; } break; // Coalescing a loop with a subsequent string case RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Onelazy when nextNode.Kind == RegexNodeKind.Multi && currentNode.Ch == nextNode.Str![0]: { // Determine how many of the multi's characters can be combined. // We already checked for the first, so we know it's at least one. int matchingCharsInMulti = 1; while (matchingCharsInMulti < nextNode.Str.Length && currentNode.Ch == nextNode.Str[matchingCharsInMulti]) { matchingCharsInMulti++; } if (CanCombineCounts(currentNode.M, currentNode.N, matchingCharsInMulti, matchingCharsInMulti)) { // Update the loop's bounds to include those characters from the multi currentNode.M += matchingCharsInMulti; if (currentNode.N != int.MaxValue) { currentNode.N += matchingCharsInMulti; } // If it was the full multi, skip/remove the multi and continue processing this loop. if (nextNode.Str.Length == matchingCharsInMulti) { next++; continue; } // Otherwise, trim the characters from the multiple that were absorbed into the loop. // If it now only has a single character, it becomes a One. Debug.Assert(matchingCharsInMulti < nextNode.Str.Length); if (nextNode.Str.Length - matchingCharsInMulti == 1) { nextNode.Kind = RegexNodeKind.One; nextNode.Ch = nextNode.Str[nextNode.Str.Length - 1]; nextNode.Str = null; } else { nextNode.Str = nextNode.Str.Substring(matchingCharsInMulti); } } } break; // NOTE: We could add support for coalescing a string with a subsequent loop, but the benefits of that // are limited. Pulling a subsequent string's prefix back into the loop helps with making the loop atomic, // but if the loop is after the string, pulling the suffix of the string forward into the loop may actually // be a deoptimization as those characters could end up matching more slowly as part of loop matching. // Coalescing an individual item with a loop. case RegexNodeKind.One when (nextNode.Kind is RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Onelazy) && currentNode.Ch == nextNode.Ch: case RegexNodeKind.Notone when (nextNode.Kind is RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Notonelazy) && currentNode.Ch == nextNode.Ch: case RegexNodeKind.Set when (nextNode.Kind is RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic or RegexNodeKind.Setlazy) && currentNode.Str == nextNode.Str: if (CanCombineCounts(1, 1, nextNode.M, nextNode.N)) { currentNode.Kind = nextNode.Kind; currentNode.M = nextNode.M + 1; currentNode.N = nextNode.N == int.MaxValue ? int.MaxValue : nextNode.N + 1; next++; continue; } break; // Coalescing an individual item with another individual item. // We don't coalesce adjacent One nodes into a Oneloop as we'd rather they be joined into a Multi. case RegexNodeKind.Notone when nextNode.Kind == currentNode.Kind && currentNode.Ch == nextNode.Ch: case RegexNodeKind.Set when nextNode.Kind == RegexNodeKind.Set && currentNode.Str == nextNode.Str: currentNode.MakeRep(RegexNodeKind.Oneloop, 2, 2); next++; continue; } } children[nextSave++] = children[next]; current = next; next++; } if (nextSave < children.Count) { children.RemoveRange(nextSave, children.Count - nextSave); } } /// <summary> /// Finds {one/notone/set}loop nodes in the concatenation that can be automatically upgraded /// to {one/notone/set}loopatomic nodes. Such changes avoid potential useless backtracking. /// e.g. A*B (where sets A and B don't overlap) => (?>A*)B. /// </summary> private void FindAndMakeLoopsAtomic() { Debug.Assert((Options & RegexOptions.NonBacktracking) == 0, "Atomic groups aren't supported and don't help performance with NonBacktracking"); if (!StackHelper.TryEnsureSufficientExecutionStack()) { // If we're too deep on the stack, give up optimizing further. return; } if ((Options & RegexOptions.RightToLeft) != 0) { // RTL is so rare, we don't need to spend additional time/code optimizing for it. return; } // For all node types that have children, recur into each of those children. int childCount = ChildCount(); if (childCount != 0) { for (int i = 0; i < childCount; i++) { Child(i).FindAndMakeLoopsAtomic(); } } // If this isn't a concatenation, nothing more to do. if (Kind is not RegexNodeKind.Concatenate) { return; } // This is a concatenation. Iterate through each pair of nodes in the concatenation seeing whether we can // make the first node (or its right-most child) atomic based on the second node (or its left-most child). Debug.Assert(Children is List<RegexNode>); var children = (List<RegexNode>)Children; for (int i = 0; i < childCount - 1; i++) { ProcessNode(children[i], children[i + 1]); static void ProcessNode(RegexNode node, RegexNode subsequent) { if (!StackHelper.TryEnsureSufficientExecutionStack()) { // If we can't recur further, just stop optimizing. return; } // Skip down the node past irrelevant nodes. while (true) { // We can always recur into captures and into the last node of concatenations. if (node.Kind is RegexNodeKind.Capture or RegexNodeKind.Concatenate) { node = node.Child(node.ChildCount() - 1); continue; } // For loops with at least one guaranteed iteration, we can recur into them, but // we need to be careful not to just always do so; the ending node of a loop can only // be made atomic if what comes after the loop but also the beginning of the loop are // compatible for the optimization. if (node.Kind == RegexNodeKind.Loop) { RegexNode? loopDescendent = node.FindLastExpressionInLoopForAutoAtomic(); if (loopDescendent != null) { node = loopDescendent; continue; } } // Can't skip any further. break; } // If the node can be changed to atomic based on what comes after it, do so. switch (node.Kind) { case RegexNodeKind.Oneloop or RegexNodeKind.Notoneloop or RegexNodeKind.Setloop when CanBeMadeAtomic(node, subsequent, allowSubsequentIteration: true): node.MakeLoopAtomic(); break; case RegexNodeKind.Alternate or RegexNodeKind.BackreferenceConditional or RegexNodeKind.ExpressionConditional: // In the case of alternation, we can't change the alternation node itself // based on what comes after it (at least not with more complicated analysis // that factors in all branches together), but we can look at each individual // branch, and analyze ending loops in each branch individually to see if they // can be made atomic. Then if we do end up backtracking into the alternation, // we at least won't need to backtrack into that loop. The same is true for // conditionals, though we don't want to process the condition expression // itself, as it's already considered atomic and handled as part of ReduceExpressionConditional. { int alternateBranches = node.ChildCount(); for (int b = node.Kind == RegexNodeKind.ExpressionConditional ? 1 : 0; b < alternateBranches; b++) { ProcessNode(node.Child(b), subsequent); } } break; } } } } /// <summary> /// Recurs into the last expression of a loop node, looking to see if it can find a node /// that could be made atomic _assuming_ the conditions exist for it with the loop's ancestors. /// </summary> /// <returns>The found node that should be explored further for auto-atomicity; null if it doesn't exist.</returns> private RegexNode? FindLastExpressionInLoopForAutoAtomic() { RegexNode node = this; Debug.Assert(node.Kind is RegexNodeKind.Loop or RegexNodeKind.Lazyloop); // Start by looking at the loop's sole child. node = node.Child(0); // Skip past captures. while (node.Kind == RegexNodeKind.Capture) { node = node.Child(0); } // If the loop's body is a concatenate, we can skip to its last child iff that // last child doesn't conflict with the first child, since this whole concatenation // could be repeated, such that the first node ends up following the last. For // example, in the expression (a+[def])*, the last child is [def] and the first is // a+, which can't possibly overlap with [def]. In contrast, if we had (a+[ade])*, // [ade] could potentially match the starting 'a'. if (node.Kind == RegexNodeKind.Concatenate) { int concatCount = node.ChildCount(); RegexNode lastConcatChild = node.Child(concatCount - 1); if (CanBeMadeAtomic(lastConcatChild, node.Child(0), allowSubsequentIteration: false)) { return lastConcatChild; } } // Otherwise, the loop has nothing that can participate in auto-atomicity. return null; } /// <summary>Optimizations for positive and negative lookaheads/behinds.</summary> private RegexNode ReduceLookaround() { Debug.Assert(Kind is RegexNodeKind.PositiveLookaround or RegexNodeKind.NegativeLookaround); Debug.Assert(ChildCount() == 1); // A lookaround is a zero-width atomic assertion. // As it's atomic, nothing will backtrack into it, and we can // eliminate any ending backtracking from it. EliminateEndingBacktracking(); // A positive lookaround wrapped around an empty is a nop, and we can reduce it // to simply Empty. A developer typically doesn't write this, but rather it evolves // due to optimizations resulting in empty. // A negative lookaround wrapped around an empty child, i.e. (?!), is // sometimes used as a way to insert a guaranteed no-match into the expression, // often as part of a conditional. We can reduce it to simply Nothing. if (Child(0).Kind == RegexNodeKind.Empty) { Kind = Kind == RegexNodeKind.PositiveLookaround ? RegexNodeKind.Empty : RegexNodeKind.Nothing; Children = null; } return this; } /// <summary>Optimizations for backreference conditionals.</summary> private RegexNode ReduceBackreferenceConditional() { Debug.Assert(Kind == RegexNodeKind.BackreferenceConditional); Debug.Assert(ChildCount() is 1 or 2); // This isn't so much an optimization as it is changing the tree for consistency. We want // all engines to be able to trust that every backreference conditional will have two children, // even though it's optional in the syntax. If it's missing a "not matched" branch, // we add one that will match empty. if (ChildCount() == 1) { AddChild(new RegexNode(RegexNodeKind.Empty, Options)); } return this; } /// <summary>Optimizations for expression conditionals.</summary> private RegexNode ReduceExpressionConditional() { Debug.Assert(Kind == RegexNodeKind.ExpressionConditional); Debug.Assert(ChildCount() is 2 or 3); // This isn't so much an optimization as it is changing the tree for consistency. We want // all engines to be able to trust that every expression conditional will have three children, // even though it's optional in the syntax. If it's missing a "not matched" branch, // we add one that will match empty. if (ChildCount() == 2) { AddChild(new RegexNode(RegexNodeKind.Empty, Options)); } // It's common for the condition to be an explicit positive lookahead, as specifying // that eliminates any ambiguity in syntax as to whether the expression is to be matched // as an expression or to be a reference to a capture group. After parsing, however, // there's no ambiguity, and we can remove an extra level of positive lookahead, as the // engines need to treat the condition as a zero-width positive, atomic assertion regardless. RegexNode condition = Child(0); if (condition.Kind == RegexNodeKind.PositiveLookaround && (condition.Options & RegexOptions.RightToLeft) == 0) { ReplaceChild(0, condition.Child(0)); } // We can also eliminate any ending backtracking in the condition, as the condition // is considered to be a positive lookahead, which is an atomic zero-width assertion. condition = Child(0); condition.EliminateEndingBacktracking(); return this; } /// <summary> /// Determines whether node can be switched to an atomic loop. Subsequent is the node /// immediately after 'node'. /// </summary> private static bool CanBeMadeAtomic(RegexNode node, RegexNode subsequent, bool allowSubsequentIteration) { if (!StackHelper.TryEnsureSufficientExecutionStack()) { // If we can't recur further, just stop optimizing. return false; } // In most case, we'll simply check the node against whatever subsequent is. However, in case // subsequent ends up being a loop with a min bound of 0, we'll also need to evaluate the node // against whatever comes after subsequent. In that case, we'll walk the tree to find the // next subsequent, and we'll loop around against to perform the comparison again. while (true) { // Skip the successor down to the closest node that's guaranteed to follow it. int childCount; while ((childCount = subsequent.ChildCount()) > 0) { Debug.Assert(subsequent.Kind != RegexNodeKind.Group); switch (subsequent.Kind) { case RegexNodeKind.Concatenate: case RegexNodeKind.Capture: case RegexNodeKind.Atomic: case RegexNodeKind.PositiveLookaround when (subsequent.Options & RegexOptions.RightToLeft) == 0: // only lookaheads, not lookbehinds (represented as RTL PositiveLookaround nodes) case RegexNodeKind.Loop or RegexNodeKind.Lazyloop when subsequent.M > 0: subsequent = subsequent.Child(0); continue; } break; } // If the two nodes don't agree on options in any way, don't try to optimize them. // TODO: Remove this once https://github.com/dotnet/runtime/issues/61048 is implemented. if (node.Options != subsequent.Options) { return false; } // If the successor is an alternation, all of its children need to be evaluated, since any of them // could come after this node. If any of them fail the optimization, then the whole node fails. // This applies to expression conditionals as well, as long as they have both a yes and a no branch (if there's // only a yes branch, we'd need to also check whatever comes after the conditional). It doesn't apply to // backreference conditionals, as the condition itself is unknown statically and could overlap with the // loop being considered for atomicity. switch (subsequent.Kind) { case RegexNodeKind.Alternate: case RegexNodeKind.ExpressionConditional when childCount == 3: // condition, yes, and no branch for (int i = 0; i < childCount; i++) { if (!CanBeMadeAtomic(node, subsequent.Child(i), allowSubsequentIteration)) { return false; } } return true; } // If this node is a {one/notone/set}loop, see if it overlaps with its successor in the concatenation. // If it doesn't, then we can upgrade it to being a {one/notone/set}loopatomic. // Doing so avoids unnecessary backtracking. switch (node.Kind) { case RegexNodeKind.Oneloop: switch (subsequent.Kind) { case RegexNodeKind.One when node.Ch != subsequent.Ch: case RegexNodeKind.Notone when node.Ch == subsequent.Ch: case RegexNodeKind.Set when !RegexCharClass.CharInClass(node.Ch, subsequent.Str!): case RegexNodeKind.Onelazy or RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic when subsequent.M > 0 && node.Ch != subsequent.Ch: case RegexNodeKind.Notonelazy or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic when subsequent.M > 0 && node.Ch == subsequent.Ch: case RegexNodeKind.Setlazy or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic when subsequent.M > 0 && !RegexCharClass.CharInClass(node.Ch, subsequent.Str!): case RegexNodeKind.Multi when node.Ch != subsequent.Str![0]: case RegexNodeKind.End: case RegexNodeKind.EndZ or RegexNodeKind.Eol when node.Ch != '\n': case RegexNodeKind.Boundary when RegexCharClass.IsBoundaryWordChar(node.Ch): case RegexNodeKind.NonBoundary when !RegexCharClass.IsBoundaryWordChar(node.Ch): case RegexNodeKind.ECMABoundary when RegexCharClass.IsECMAWordChar(node.Ch): case RegexNodeKind.NonECMABoundary when !RegexCharClass.IsECMAWordChar(node.Ch): return true; case RegexNodeKind.Onelazy or RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic when subsequent.M == 0 && node.Ch != subsequent.Ch: case RegexNodeKind.Notonelazy or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic when subsequent.M == 0 && node.Ch == subsequent.Ch: case RegexNodeKind.Setlazy or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic when subsequent.M == 0 && !RegexCharClass.CharInClass(node.Ch, subsequent.Str!): // The loop can be made atomic based on this subsequent node, but we'll need to evaluate the next one as well. break; default: return false; } break; case RegexNodeKind.Notoneloop: switch (subsequent.Kind) { case RegexNodeKind.One when node.Ch == subsequent.Ch: case RegexNodeKind.Onelazy or RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic when subsequent.M > 0 && node.Ch == subsequent.Ch: case RegexNodeKind.Multi when node.Ch == subsequent.Str![0]: case RegexNodeKind.End: return true; case RegexNodeKind.Onelazy or RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic when subsequent.M == 0 && node.Ch == subsequent.Ch: // The loop can be made atomic based on this subsequent node, but we'll need to evaluate the next one as well. break; default: return false; } break; case RegexNodeKind.Setloop: switch (subsequent.Kind) { case RegexNodeKind.One when !RegexCharClass.CharInClass(subsequent.Ch, node.Str!): case RegexNodeKind.Set when !RegexCharClass.MayOverlap(node.Str!, subsequent.Str!): case RegexNodeKind.Onelazy or RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic when subsequent.M > 0 && !RegexCharClass.CharInClass(subsequent.Ch, node.Str!): case RegexNodeKind.Setlazy or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic when subsequent.M > 0 && !RegexCharClass.MayOverlap(node.Str!, subsequent.Str!): case RegexNodeKind.Multi when !RegexCharClass.CharInClass(subsequent.Str![0], node.Str!): case RegexNodeKind.End: case RegexNodeKind.EndZ or RegexNodeKind.Eol when !RegexCharClass.CharInClass('\n', node.Str!): case RegexNodeKind.Boundary when node.Str is RegexCharClass.WordClass or RegexCharClass.DigitClass: case RegexNodeKind.NonBoundary when node.Str is RegexCharClass.NotWordClass or RegexCharClass.NotDigitClass: case RegexNodeKind.ECMABoundary when node.Str is RegexCharClass.ECMAWordClass or RegexCharClass.ECMADigitClass: case RegexNodeKind.NonECMABoundary when node.Str is RegexCharClass.NotECMAWordClass or RegexCharClass.NotDigitClass: return true; case RegexNodeKind.Onelazy or RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic when subsequent.M == 0 && !RegexCharClass.CharInClass(subsequent.Ch, node.Str!): case RegexNodeKind.Setlazy or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic when subsequent.M == 0 && !RegexCharClass.MayOverlap(node.Str!, subsequent.Str!): // The loop can be made atomic based on this subsequent node, but we'll need to evaluate the next one as well. break; default: return false; } break; default: return false; } // We only get here if the node could be made atomic based on subsequent but subsequent has a lower bound of zero // and thus we need to move subsequent to be the next node in sequence and loop around to try again. Debug.Assert(subsequent.Kind is RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Onelazy or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Notonelazy or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic or RegexNodeKind.Setlazy); Debug.Assert(subsequent.M == 0); if (!allowSubsequentIteration) { return false; } // To be conservative, we only walk up through a very limited set of constructs (even though we may have walked // down through more, like loops), looking for the next concatenation that we're not at the end of, at // which point subsequent becomes whatever node is next in that concatenation. while (true) { RegexNode? parent = subsequent.Parent; switch (parent?.Kind) { case RegexNodeKind.Atomic: case RegexNodeKind.Alternate: case RegexNodeKind.Capture: subsequent = parent; continue; case RegexNodeKind.Concatenate: var peers = (List<RegexNode>)parent.Children!; int currentIndex = peers.IndexOf(subsequent); Debug.Assert(currentIndex >= 0, "Node should have been in its parent's child list"); if (currentIndex + 1 == peers.Count) { subsequent = parent; continue; } else { subsequent = peers[currentIndex + 1]; break; } case null: // If we hit the root, we're at the end of the expression, at which point nothing could backtrack // in and we can declare success. return true; default: // Anything else, we don't know what to do, so we have to assume it could conflict with the loop. return false; } break; } } } /// <summary>Computes a min bound on the required length of any string that could possibly match.</summary> /// <returns>The min computed length. If the result is 0, there is no minimum we can enforce.</returns> /// <remarks> /// e.g. abc[def](ghijkl|mn) => 6 /// </remarks> public int ComputeMinLength() { if (!StackHelper.TryEnsureSufficientExecutionStack()) { // If we can't recur further, assume there's no minimum we can enforce. return 0; } switch (Kind) { case RegexNodeKind.One: case RegexNodeKind.Notone: case RegexNodeKind.Set: // Single character. return 1; case RegexNodeKind.Multi: // Every character in the string needs to match. return Str!.Length; case RegexNodeKind.Notonelazy: case RegexNodeKind.Notoneloop: case RegexNodeKind.Notoneloopatomic: case RegexNodeKind.Onelazy: case RegexNodeKind.Oneloop: case RegexNodeKind.Oneloopatomic: case RegexNodeKind.Setlazy: case RegexNodeKind.Setloop: case RegexNodeKind.Setloopatomic: // One character repeated at least M times. return M; case RegexNodeKind.Lazyloop: case RegexNodeKind.Loop: // A node graph repeated at least M times. return (int)Math.Min(int.MaxValue - 1, (long)M * Child(0).ComputeMinLength()); case RegexNodeKind.Alternate: // The minimum required length for any of the alternation's branches. { int childCount = ChildCount(); Debug.Assert(childCount >= 2); int min = Child(0).ComputeMinLength(); for (int i = 1; i < childCount && min > 0; i++) { min = Math.Min(min, Child(i).ComputeMinLength()); } return min; } case RegexNodeKind.BackreferenceConditional: // Minimum of its yes and no branches. The backreference doesn't add to the length. return Math.Min(Child(0).ComputeMinLength(), Child(1).ComputeMinLength()); case RegexNodeKind.ExpressionConditional: // Minimum of its yes and no branches. The condition is a zero-width assertion. return Math.Min(Child(1).ComputeMinLength(), Child(2).ComputeMinLength()); case RegexNodeKind.Concatenate: // The sum of all of the concatenation's children. { long sum = 0; int childCount = ChildCount(); for (int i = 0; i < childCount; i++) { sum += Child(i).ComputeMinLength(); } return (int)Math.Min(int.MaxValue - 1, sum); } case RegexNodeKind.Atomic: case RegexNodeKind.Capture: case RegexNodeKind.Group: // For groups, we just delegate to the sole child. Debug.Assert(ChildCount() == 1); return Child(0).ComputeMinLength(); case RegexNodeKind.Empty: case RegexNodeKind.Nothing: case RegexNodeKind.UpdateBumpalong: // Nothing to match. In the future, we could potentially use Nothing to say that the min length // is infinite, but that would require a different structure, as that would only apply if the // Nothing match is required in all cases (rather than, say, as one branch of an alternation). case RegexNodeKind.Beginning: case RegexNodeKind.Bol: case RegexNodeKind.Boundary: case RegexNodeKind.ECMABoundary: case RegexNodeKind.End: case RegexNodeKind.EndZ: case RegexNodeKind.Eol: case RegexNodeKind.NonBoundary: case RegexNodeKind.NonECMABoundary: case RegexNodeKind.Start: case RegexNodeKind.NegativeLookaround: case RegexNodeKind.PositiveLookaround: // Zero-width case RegexNodeKind.Backreference: // Requires matching data available only at run-time. In the future, we could choose to find // and follow the capture group this aligns with, while being careful not to end up in an // infinite cycle. return 0; default: Debug.Fail($"Unknown node: {Kind}"); goto case RegexNodeKind.Empty; } } /// <summary>Computes a maximum length of any string that could possibly match.</summary> /// <returns>The maximum length of any string that could possibly match, or null if the length may not always be the same.</returns> /// <remarks> /// e.g. abc[def](gh|ijklmnop) => 12 /// </remarks> public int? ComputeMaxLength() { if (!StackHelper.TryEnsureSufficientExecutionStack()) { // If we can't recur further, assume there's no minimum we can enforce. return null; } switch (Kind) { case RegexNodeKind.One: case RegexNodeKind.Notone: case RegexNodeKind.Set: // Single character. return 1; case RegexNodeKind.Multi: // Every character in the string needs to match. return Str!.Length; case RegexNodeKind.Notonelazy or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Onelazy or RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Setlazy or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic: // Return the max number of iterations if there's an upper bound, or null if it's infinite return N == int.MaxValue ? null : N; case RegexNodeKind.Loop or RegexNodeKind.Lazyloop: if (N != int.MaxValue) { // A node graph repeated a fixed number of times if (Child(0).ComputeMaxLength() is int childMaxLength) { long maxLength = (long)N * childMaxLength; if (maxLength < int.MaxValue) { return (int)maxLength; } } } return null; case RegexNodeKind.Alternate: // The maximum length of any child branch, as long as they all have one. { int childCount = ChildCount(); Debug.Assert(childCount >= 2); if (Child(0).ComputeMaxLength() is not int maxLength) { return null; } for (int i = 1; i < childCount; i++) { if (Child(i).ComputeMaxLength() is not int next) { return null; } maxLength = Math.Max(maxLength, next); } return maxLength; } case RegexNodeKind.BackreferenceConditional: case RegexNodeKind.ExpressionConditional: // The maximum length of either child branch, as long as they both have one.. The condition for an expression conditional is a zero-width assertion. { int i = Kind == RegexNodeKind.BackreferenceConditional ? 0 : 1; return Child(i).ComputeMaxLength() is int yes && Child(i + 1).ComputeMaxLength() is int no ? Math.Max(yes, no) : null; } case RegexNodeKind.Concatenate: // The sum of all of the concatenation's children's max lengths, as long as they all have one. { long sum = 0; int childCount = ChildCount(); for (int i = 0; i < childCount; i++) { if (Child(i).ComputeMaxLength() is not int length) { return null; } sum += length; } if (sum < int.MaxValue) { return (int)sum; } return null; } case RegexNodeKind.Atomic: case RegexNodeKind.Capture: // For groups, we just delegate to the sole child. Debug.Assert(ChildCount() == 1); return Child(0).ComputeMaxLength(); case RegexNodeKind.Empty: case RegexNodeKind.Nothing: case RegexNodeKind.UpdateBumpalong: case RegexNodeKind.Beginning: case RegexNodeKind.Bol: case RegexNodeKind.Boundary: case RegexNodeKind.ECMABoundary: case RegexNodeKind.End: case RegexNodeKind.EndZ: case RegexNodeKind.Eol: case RegexNodeKind.NonBoundary: case RegexNodeKind.NonECMABoundary: case RegexNodeKind.Start: case RegexNodeKind.PositiveLookaround: case RegexNodeKind.NegativeLookaround: // Zero-width return 0; case RegexNodeKind.Backreference: // Requires matching data available only at run-time. In the future, we could choose to find // and follow the capture group this aligns with, while being careful not to end up in an // infinite cycle. return null; default: Debug.Fail($"Unknown node: {Kind}"); goto case RegexNodeKind.Empty; } } /// <summary> /// Determine whether the specified child node is the beginning of a sequence that can /// trivially have length checks combined in order to avoid bounds checks. /// </summary> /// <param name="childIndex">The starting index of the child to check.</param> /// <param name="requiredLength">The sum of all the fixed lengths for the nodes in the sequence.</param> /// <param name="exclusiveEnd">The index of the node just after the last one in the sequence.</param> /// <returns>true if more than one node can have their length checks combined; otherwise, false.</returns> /// <remarks> /// There are additional node types for which we can prove a fixed length, e.g. examining all branches /// of an alternation and returning true if all their lengths are equal. However, the primary purpose /// of this method is to avoid bounds checks by consolidating length checks that guard accesses to /// strings/spans for which the JIT can see a fixed index within bounds, and alternations employ /// patterns that defeat that (e.g. reassigning the span in question). As such, the implementation /// remains focused on only a core subset of nodes that are a) likely to be used in concatenations and /// b) employ simple patterns of checks. /// </remarks> public bool TryGetJoinableLengthCheckChildRange(int childIndex, out int requiredLength, out int exclusiveEnd) { static bool CanJoinLengthCheck(RegexNode node) => node.Kind switch { RegexNodeKind.One or RegexNodeKind.Notone or RegexNodeKind.Set => true, RegexNodeKind.Multi => true, RegexNodeKind.Oneloop or RegexNodeKind.Onelazy or RegexNodeKind.Oneloopatomic or RegexNodeKind.Notoneloop or RegexNodeKind.Notonelazy or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Setloop or RegexNodeKind.Setlazy or RegexNodeKind.Setloopatomic when node.M == node.N => true, _ => false, }; RegexNode child = Child(childIndex); if (CanJoinLengthCheck(child)) { requiredLength = child.ComputeMinLength(); int childCount = ChildCount(); for (exclusiveEnd = childIndex + 1; exclusiveEnd < childCount; exclusiveEnd++) { child = Child(exclusiveEnd); if (!CanJoinLengthCheck(child)) { break; } requiredLength += child.ComputeMinLength(); } if (exclusiveEnd - childIndex > 1) { return true; } } requiredLength = 0; exclusiveEnd = 0; return false; } public RegexNode MakeQuantifier(bool lazy, int min, int max) { // Certain cases of repeaters (min == max) can be handled specially if (min == max) { switch (max) { case 0: // The node is repeated 0 times, so it's actually empty. return new RegexNode(RegexNodeKind.Empty, Options); case 1: // The node is repeated 1 time, so it's not actually a repeater. return this; case <= MultiVsRepeaterLimit when Kind == RegexNodeKind.One: // The same character is repeated a fixed number of times, so it's actually a multi. // While this could remain a repeater, multis are more readily optimized later in // processing. The counts used here in real-world expressions are invariably small (e.g. 4), // but we set an upper bound just to avoid creating really large strings. Debug.Assert(max >= 2); Kind = RegexNodeKind.Multi; Str = new string(Ch, max); Ch = '\0'; return this; } } switch (Kind) { case RegexNodeKind.One: case RegexNodeKind.Notone: case RegexNodeKind.Set: MakeRep(lazy ? RegexNodeKind.Onelazy : RegexNodeKind.Oneloop, min, max); return this; default: var result = new RegexNode(lazy ? RegexNodeKind.Lazyloop : RegexNodeKind.Loop, Options, min, max); result.AddChild(this); return result; } } public void AddChild(RegexNode newChild) { newChild.Parent = this; // so that the child can see its parent while being reduced newChild = newChild.Reduce(); newChild.Parent = this; // in case Reduce returns a different node that needs to be reparented if (Children is null) { Children = newChild; } else if (Children is RegexNode currentChild) { Children = new List<RegexNode>() { currentChild, newChild }; } else { ((List<RegexNode>)Children).Add(newChild); } } public void InsertChild(int index, RegexNode newChild) { Debug.Assert(Children is List<RegexNode>); newChild.Parent = this; // so that the child can see its parent while being reduced newChild = newChild.Reduce(); newChild.Parent = this; // in case Reduce returns a different node that needs to be reparented ((List<RegexNode>)Children).Insert(index, newChild); } public void ReplaceChild(int index, RegexNode newChild) { Debug.Assert(Children != null); Debug.Assert(index < ChildCount()); newChild.Parent = this; // so that the child can see its parent while being reduced newChild = newChild.Reduce(); newChild.Parent = this; // in case Reduce returns a different node that needs to be reparented if (Children is RegexNode) { Children = newChild; } else { ((List<RegexNode>)Children)[index] = newChild; } } public RegexNode Child(int i) => Children is RegexNode child ? child : ((List<RegexNode>)Children!)[i]; public int ChildCount() { if (Children is null) { return 0; } if (Children is List<RegexNode> children) { return children.Count; } Debug.Assert(Children is RegexNode); return 1; } // Determines whether the node supports a compilation / code generation strategy based on walking the node tree. // Also returns a human-readable string to explain the reason (it will be emitted by the source generator, hence // there's no need to localize). internal bool SupportsCompilation([NotNullWhen(false)] out string? reason) { if ((Options & RegexOptions.NonBacktracking) != 0) { reason = "RegexOptions.NonBacktracking isn't supported"; return false; } if (ExceedsMaxDepthAllowedDepth(this, allowedDepth: 40)) { // For the source generator, deep RegexNode trees can result in emitting C# code that exceeds C# compiler // limitations, leading to "CS8078: An expression is too long or complex to compile". As such, we place // an artificial limit on max tree depth in order to mitigate such issues. The allowed depth can be tweaked // as needed; its exceedingly rare to find expressions with such deep trees. And while RegexCompiler doesn't // have to deal with C# compiler limitations, we still want to limit max tree depth as we want to limit // how deep recursion we'll employ as part of code generation. reason = "the expression may result exceeding run-time or compiler limits"; return false; } // Supported. reason = null; return true; static bool ExceedsMaxDepthAllowedDepth(RegexNode node, int allowedDepth) { if (allowedDepth <= 0) { return true; } int childCount = node.ChildCount(); for (int i = 0; i < childCount; i++) { if (ExceedsMaxDepthAllowedDepth(node.Child(i), allowedDepth - 1)) { return true; } } return false; } } /// <summary>Gets whether the node is a Set/Setloop/Setloopatomic/Setlazy node.</summary> public bool IsSetFamily => Kind is RegexNodeKind.Set or RegexNodeKind.Setloop or RegexNodeKind.Setloopatomic or RegexNodeKind.Setlazy; /// <summary>Gets whether the node is a One/Oneloop/Oneloopatomic/Onelazy node.</summary> public bool IsOneFamily => Kind is RegexNodeKind.One or RegexNodeKind.Oneloop or RegexNodeKind.Oneloopatomic or RegexNodeKind.Onelazy; /// <summary>Gets whether the node is a Notone/Notoneloop/Notoneloopatomic/Notonelazy node.</summary> public bool IsNotoneFamily => Kind is RegexNodeKind.Notone or RegexNodeKind.Notoneloop or RegexNodeKind.Notoneloopatomic or RegexNodeKind.Notonelazy; /// <summary>Gets whether this node is contained inside of a loop.</summary> public bool IsInLoop() { for (RegexNode? parent = Parent; parent is not null; parent = parent.Parent) { if (parent.Kind is RegexNodeKind.Loop or RegexNodeKind.Lazyloop) { return true; } } return false; } #if DEBUG [ExcludeFromCodeCoverage] public override string ToString() { RegexNode? curNode = this; int curChild = 0; var sb = new StringBuilder().AppendLine(curNode.Describe()); var stack = new List<int>(); while (true) { if (curChild < curNode!.ChildCount()) { stack.Add(curChild + 1); curNode = curNode.Child(curChild); curChild = 0; sb.Append(new string(' ', stack.Count * 2)).Append(curNode.Describe()).AppendLine(); } else { if (stack.Count == 0) { break; } curChild = stack[stack.Count - 1]; stack.RemoveAt(stack.Count - 1); curNode = curNode.Parent; } } return sb.ToString(); } [ExcludeFromCodeCoverage] private string Describe() { var sb = new StringBuilder(Kind.ToString()); if ((Options & RegexOptions.ExplicitCapture) != 0) sb.Append("-C"); if ((Options & RegexOptions.IgnoreCase) != 0) sb.Append("-I"); if ((Options & RegexOptions.RightToLeft) != 0) sb.Append("-L"); if ((Options & RegexOptions.Multiline) != 0) sb.Append("-M"); if ((Options & RegexOptions.Singleline) != 0) sb.Append("-S"); if ((Options & RegexOptions.IgnorePatternWhitespace) != 0) sb.Append("-X"); if ((Options & RegexOptions.ECMAScript) != 0) sb.Append("-E"); switch (Kind) { case RegexNodeKind.Oneloop: case RegexNodeKind.Oneloopatomic: case RegexNodeKind.Notoneloop: case RegexNodeKind.Notoneloopatomic: case RegexNodeKind.Onelazy: case RegexNodeKind.Notonelazy: case RegexNodeKind.One: case RegexNodeKind.Notone: sb.Append(" '").Append(RegexCharClass.DescribeChar(Ch)).Append('\''); break; case RegexNodeKind.Capture: sb.Append(' ').Append($"index = {M}"); if (N != -1) { sb.Append($", unindex = {N}"); } break; case RegexNodeKind.Backreference: case RegexNodeKind.BackreferenceConditional: sb.Append(' ').Append($"index = {M}"); break; case RegexNodeKind.Multi: sb.Append(" \"").Append(Str).Append('"'); break; case RegexNodeKind.Set: case RegexNodeKind.Setloop: case RegexNodeKind.Setloopatomic: case RegexNodeKind.Setlazy: sb.Append(' ').Append(RegexCharClass.DescribeSet(Str!)); break; } switch (Kind) { case RegexNodeKind.Oneloop: case RegexNodeKind.Oneloopatomic: case RegexNodeKind.Notoneloop: case RegexNodeKind.Notoneloopatomic: case RegexNodeKind.Onelazy: case RegexNodeKind.Notonelazy: case RegexNodeKind.Setloop: case RegexNodeKind.Setloopatomic: case RegexNodeKind.Setlazy: case RegexNodeKind.Loop: case RegexNodeKind.Lazyloop: sb.Append( (M == 0 && N == int.MaxValue) ? "*" : (M == 0 && N == 1) ? "?" : (M == 1 && N == int.MaxValue) ? "+" : (N == int.MaxValue) ? $"{{{M}, *}}" : (N == M) ? $"{{{M}}}" : $"{{{M}, {N}}}"); break; } return sb.ToString(); } #endif } }
1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexTreeAnalyzer.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.Threading; namespace System.Text.RegularExpressions { /// <summary>Analyzes a <see cref="RegexTree"/> of <see cref="RegexNode"/>s to produce data on the tree structure, in particular in support of code generation.</summary> internal static class RegexTreeAnalyzer { /// <summary>Analyzes a <see cref="RegexInterpreterCode"/> to learn about the structure of the tree.</summary> public static AnalysisResults Analyze(RegexTree regexTree) { var results = new AnalysisResults(regexTree); results._complete = TryAnalyze(regexTree.Root, results, isAtomicByAncestor: true); return results; static bool TryAnalyze(RegexNode node, AnalysisResults results, bool isAtomicByAncestor) { if (!StackHelper.TryEnsureSufficientExecutionStack()) { return false; } // Track whether we've seen any node with IgnoreCase set. results._hasIgnoreCase |= (node.Options & RegexOptions.IgnoreCase) != 0; if (isAtomicByAncestor) { // We've been told by our parent that we should be considered atomic, so add ourselves // to the atomic collection. results._isAtomicByAncestor.Add(node); } else { // Certain kinds of nodes incur backtracking logic themselves: add them to the backtracking collection. // We may later find that a node contains another that has backtracking; we'll add nodes based on that // after examining the children. switch (node.Kind) { case RegexNodeKind.Alternate: case RegexNodeKind.Loop or RegexNodeKind.Lazyloop when node.M != node.N: case RegexNodeKind.Oneloop or RegexNodeKind.Notoneloop or RegexNodeKind.Setloop or RegexNodeKind.Onelazy or RegexNodeKind.Notonelazy or RegexNodeKind.Setlazy when node.M != node.N: (results._mayBacktrack ??= new()).Add(node); break; } } // Update state for certain node types. bool isAtomicBySelf = false; switch (node.Kind) { // Some node types add atomicity around what they wrap. Set isAtomicBySelfOrParent to true for such nodes // even if it was false upon entering the method. case RegexNodeKind.Atomic: case RegexNodeKind.NegativeLookaround: case RegexNodeKind.PositiveLookaround: isAtomicBySelf = true; break; // Track any nodes that are themselves captures. case RegexNodeKind.Capture: results._containsCapture.Add(node); break; } // Process each child. int childCount = node.ChildCount(); for (int i = 0; i < childCount; i++) { RegexNode child = node.Child(i); // Determine whether the child should be treated as atomic (whether anything // can backtrack into it), which is influenced by whether this node (the child's // parent) is considered atomic by itself or by its parent. bool treatChildAsAtomic = (isAtomicByAncestor | isAtomicBySelf) && node.Kind switch { // If the parent is atomic, so is the child. That's the whole purpose // of the Atomic node, and lookarounds are also implicitly atomic. RegexNodeKind.Atomic or RegexNodeKind.NegativeLookaround or RegexNodeKind.PositiveLookaround => true, // Each branch is considered independently, so any atomicity applied to the alternation also applies // to each individual branch. This is true as well for conditionals. RegexNodeKind.Alternate or RegexNodeKind.BackreferenceConditional or RegexNodeKind.ExpressionConditional => true, // Captures don't impact atomicity: if the parent of a capture is atomic, the capture is also atomic. RegexNodeKind.Capture => true, // If the parent is a concatenation and this is the last node, any atomicity // applying to the concatenation applies to this node, too. RegexNodeKind.Concatenate => i == childCount - 1, // For loops with a max iteration count of 1, they themselves can be considered // atomic as can whatever they wrap, as they won't ever iterate more than once // and thus we don't need to worry about one iteration consuming input destined // for a subsequent iteration. RegexNodeKind.Loop or RegexNodeKind.Lazyloop when node.N == 1 => true, // For any other parent type, give up on trying to prove atomicity. _ => false, }; // Now analyze the child. if (!TryAnalyze(child, results, treatChildAsAtomic)) { return false; } // If the child contains captures, so too does this parent. if (results._containsCapture.Contains(child)) { results._containsCapture.Add(node); } // If the child might require backtracking into it, so too might the parent, // unless the parent is itself considered atomic. Here we don't consider parental // atomicity, as we need to surface upwards to the parent whether any backtracking // will be visible from this node to it. if (!isAtomicBySelf && (results._mayBacktrack?.Contains(child) == true)) { (results._mayBacktrack ??= new()).Add(node); } } // Successfully analyzed the node. return true; } } } /// <summary>Provides results of a tree analysis.</summary> internal sealed class AnalysisResults { /// <summary>Indicates whether the whole tree was successfully processed.</summary> /// <remarks> /// If it wasn't successfully processed, we have to assume the "worst", e.g. if it's /// false, we need to assume we didn't fully determine which nodes contain captures, /// and thus we need to assume they all do and not discard logic necessary to support /// captures. It should be exceedingly rare that this is false. /// </remarks> internal bool _complete; /// <summary>Set of nodes that are considered to be atomic based on themselves or their ancestry.</summary> internal readonly HashSet<RegexNode> _isAtomicByAncestor = new(); // since the root is implicitly atomic, every tree will contain atomic-by-ancestor nodes /// <summary>Set of nodes that directly or indirectly contain capture groups.</summary> internal readonly HashSet<RegexNode> _containsCapture = new(); // the root is a capture, so this will always contain at least the root node /// <summary>Set of nodes that directly or indirectly contain backtracking constructs that aren't hidden internaly by atomic constructs.</summary> internal HashSet<RegexNode>? _mayBacktrack; /// <summary>Whether any node has <see cref="RegexOptions.IgnoreCase"/> set.</summary> internal bool _hasIgnoreCase; /// <summary>Initializes the instance.</summary> /// <param name="regexTree">The code being analyzed.</param> internal AnalysisResults(RegexTree regexTree) => RegexTree = regexTree; /// <summary>Gets the code that was analyzed.</summary> public RegexTree RegexTree { get; } /// <summary>Gets whether a node is considered atomic based on its ancestry.</summary> public bool IsAtomicByAncestor(RegexNode node) => _isAtomicByAncestor.Contains(node); /// <summary>Gets whether a node directly or indirectly contains captures.</summary> public bool MayContainCapture(RegexNode node) => !_complete || _containsCapture.Contains(node); /// <summary>Gets whether a node is or directory or indirectly contains a backtracking construct that isn't hidden by an internal atomic construct.</summary> /// <remarks> /// In most code generation situations, we only need to know after we emit the child code whether /// the child may backtrack, and that we can see with 100% certainty. This method is useful in situations /// where we need to predict without traversing the child at code generation time whether it may /// incur backtracking. This method may have (few) false positives, but won't have any false negatives, /// meaning it might claim a node requires backtracking even if it doesn't, but it will always return /// true for any node that requires backtracking. /// </remarks> public bool MayBacktrack(RegexNode node) => !_complete || (_mayBacktrack?.Contains(node) ?? false); /// <summary>Gets whether a node might have <see cref="RegexOptions.IgnoreCase"/> set.</summary> public bool HasIgnoreCase => _complete && _hasIgnoreCase; } }
// 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.Threading; namespace System.Text.RegularExpressions { /// <summary>Analyzes a <see cref="RegexTree"/> of <see cref="RegexNode"/>s to produce data on the tree structure, in particular in support of code generation.</summary> internal static class RegexTreeAnalyzer { /// <summary>Analyzes a <see cref="RegexInterpreterCode"/> to learn about the structure of the tree.</summary> public static AnalysisResults Analyze(RegexTree regexTree) { var results = new AnalysisResults(regexTree); results._complete = TryAnalyze(regexTree.Root, results, isAtomicByAncestor: true); return results; static bool TryAnalyze(RegexNode node, AnalysisResults results, bool isAtomicByAncestor) { if (!StackHelper.TryEnsureSufficientExecutionStack()) { return false; } // Track whether we've seen any nodes with various options set. results._hasIgnoreCase |= (node.Options & RegexOptions.IgnoreCase) != 0; results._hasRightToLeft |= (node.Options & RegexOptions.RightToLeft) != 0; if (isAtomicByAncestor) { // We've been told by our parent that we should be considered atomic, so add ourselves // to the atomic collection. results._isAtomicByAncestor.Add(node); } else { // Certain kinds of nodes incur backtracking logic themselves: add them to the backtracking collection. // We may later find that a node contains another that has backtracking; we'll add nodes based on that // after examining the children. switch (node.Kind) { case RegexNodeKind.Alternate: case RegexNodeKind.Loop or RegexNodeKind.Lazyloop when node.M != node.N: case RegexNodeKind.Oneloop or RegexNodeKind.Notoneloop or RegexNodeKind.Setloop or RegexNodeKind.Onelazy or RegexNodeKind.Notonelazy or RegexNodeKind.Setlazy when node.M != node.N: (results._mayBacktrack ??= new()).Add(node); break; } } // Update state for certain node types. bool isAtomicBySelf = false; switch (node.Kind) { // Some node types add atomicity around what they wrap. Set isAtomicBySelfOrParent to true for such nodes // even if it was false upon entering the method. case RegexNodeKind.Atomic: case RegexNodeKind.NegativeLookaround: case RegexNodeKind.PositiveLookaround: isAtomicBySelf = true; break; // Track any nodes that are themselves captures. case RegexNodeKind.Capture: results._containsCapture.Add(node); break; } // Process each child. int childCount = node.ChildCount(); for (int i = 0; i < childCount; i++) { RegexNode child = node.Child(i); // Determine whether the child should be treated as atomic (whether anything // can backtrack into it), which is influenced by whether this node (the child's // parent) is considered atomic by itself or by its parent. bool treatChildAsAtomic = (isAtomicByAncestor | isAtomicBySelf) && node.Kind switch { // If the parent is atomic, so is the child. That's the whole purpose // of the Atomic node, and lookarounds are also implicitly atomic. RegexNodeKind.Atomic or RegexNodeKind.NegativeLookaround or RegexNodeKind.PositiveLookaround => true, // Each branch is considered independently, so any atomicity applied to the alternation also applies // to each individual branch. This is true as well for conditionals. RegexNodeKind.Alternate or RegexNodeKind.BackreferenceConditional or RegexNodeKind.ExpressionConditional => true, // Captures don't impact atomicity: if the parent of a capture is atomic, the capture is also atomic. RegexNodeKind.Capture => true, // If the parent is a concatenation and this is the last node, any atomicity // applying to the concatenation applies to this node, too. RegexNodeKind.Concatenate => i == childCount - 1, // For loops with a max iteration count of 1, they themselves can be considered // atomic as can whatever they wrap, as they won't ever iterate more than once // and thus we don't need to worry about one iteration consuming input destined // for a subsequent iteration. RegexNodeKind.Loop or RegexNodeKind.Lazyloop when node.N == 1 => true, // For any other parent type, give up on trying to prove atomicity. _ => false, }; // Now analyze the child. if (!TryAnalyze(child, results, treatChildAsAtomic)) { return false; } // If the child contains captures, so too does this parent. if (results._containsCapture.Contains(child)) { results._containsCapture.Add(node); } // If the child might require backtracking into it, so too might the parent, // unless the parent is itself considered atomic. Here we don't consider parental // atomicity, as we need to surface upwards to the parent whether any backtracking // will be visible from this node to it. if (!isAtomicBySelf && (results._mayBacktrack?.Contains(child) == true)) { (results._mayBacktrack ??= new()).Add(node); } } // Successfully analyzed the node. return true; } } } /// <summary>Provides results of a tree analysis.</summary> internal sealed class AnalysisResults { /// <summary>Indicates whether the whole tree was successfully processed.</summary> /// <remarks> /// If it wasn't successfully processed, we have to assume the "worst", e.g. if it's /// false, we need to assume we didn't fully determine which nodes contain captures, /// and thus we need to assume they all do and not discard logic necessary to support /// captures. It should be exceedingly rare that this is false. /// </remarks> internal bool _complete; /// <summary>Set of nodes that are considered to be atomic based on themselves or their ancestry.</summary> internal readonly HashSet<RegexNode> _isAtomicByAncestor = new(); // since the root is implicitly atomic, every tree will contain atomic-by-ancestor nodes /// <summary>Set of nodes that directly or indirectly contain capture groups.</summary> internal readonly HashSet<RegexNode> _containsCapture = new(); // the root is a capture, so this will always contain at least the root node /// <summary>Set of nodes that directly or indirectly contain backtracking constructs that aren't hidden internaly by atomic constructs.</summary> internal HashSet<RegexNode>? _mayBacktrack; /// <summary>Whether any node has <see cref="RegexOptions.IgnoreCase"/> set.</summary> internal bool _hasIgnoreCase; /// <summary>Whether any node has <see cref="RegexOptions.RightToLeft"/> set.</summary> internal bool _hasRightToLeft; /// <summary>Initializes the instance.</summary> /// <param name="regexTree">The code being analyzed.</param> internal AnalysisResults(RegexTree regexTree) => RegexTree = regexTree; /// <summary>Gets the code that was analyzed.</summary> public RegexTree RegexTree { get; } /// <summary>Gets whether a node is considered atomic based on its ancestry.</summary> /// <remarks> /// If the whole tree couldn't be examined, this returns false. That could lead to additional /// code being output as nodes that could have been made atomic aren't, but functionally it's /// the safe choice. /// </remarks> public bool IsAtomicByAncestor(RegexNode node) => _isAtomicByAncestor.Contains(node); /// <summary>Gets whether a node directly or indirectly contains captures.</summary> /// <remarks> /// If the whole tree couldn't be examined, this returns true. That could lead to additional /// code being emitted to deal with captures that can't occur, but functionally it's the /// safe choice. /// </remarks> public bool MayContainCapture(RegexNode node) => !_complete || _containsCapture.Contains(node); /// <summary>Gets whether a node is or directory or indirectly contains a backtracking construct that isn't hidden by an internal atomic construct.</summary> /// <remarks> /// In most code generation situations, we only need to know after we emit the child code whether /// the child may backtrack, and that we can see with 100% certainty. This method is useful in situations /// where we need to predict without traversing the child at code generation time whether it may /// incur backtracking. This method may have (few) false positives (return true when it could have /// returned false), but won't have any false negatives (return false when it should have returned true), /// meaning it might claim a node requires backtracking even if it doesn't, but it will always return /// true for any node that requires backtracking. In that vein, if the whole tree couldn't be examined, /// this returns true. /// </remarks> public bool MayBacktrack(RegexNode node) => !_complete || (_mayBacktrack?.Contains(node) ?? false); /// <summary>Gets whether a node might have <see cref="RegexOptions.IgnoreCase"/> set.</summary> /// <remarks> /// If the whole tree couldn't be examined, this returns true. That could lead to additional /// code being emitted to support case-insensitivity in expressions that don't actually need /// it, but functionally it's the safe choice. /// </remarks> public bool HasIgnoreCase => !_complete || _hasIgnoreCase; /// <summary>Gets whether a node might have <see cref="RegexOptions.RightToLeft"/> set.</summary> /// <remarks> /// If the whole tree couldn't be examined, this returns true. That could lead to additional /// code being emitted to support expressions that don't actually contain any RightToLeft /// nodes, but functionally it's the safe choice. /// </remarks> public bool HasRightToLeft => !_complete || _hasRightToLeft; } }
1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./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: Actual - "abc(?!XXX)\\w+" yield return (@"abc(?!XXX)\w+", "abcXXXdef", RegexOptions.None, 0, 9, false, string.Empty); // Zero-width positive lookbehind assertion: Actual - "(\\w){6}(?<=XXX)def" yield return (@"(\w){6}(?<=XXX)def", "abcXXXdef", RegexOptions.None, 0, 9, true, "abcXXXdef"); // 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 (@"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) } }; } } } }
1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./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_RightToLeft_LimitedSupport() { IReadOnlyList<Diagnostic> diagnostics = await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; partial class C { [RegexGenerator(""ab"", RegexOptions.RightToLeft)] private static partial Regex RightToLeftNotSupported(); } "); Assert.Equal("SYSLIB1045", 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_PositiveLookbehind_LimitedSupport() { IReadOnlyList<Diagnostic> diagnostics = await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; partial class C { [RegexGenerator(""(?<=\b20)\d{2}\b"")] private static partial Regex PositiveLookbehindNotSupported(); } "); Assert.Equal("SYSLIB1045", Assert.Single(diagnostics).Id); } [Fact] public async Task Diagnostic_NegativeLookbehind_LimitedSupport() { IReadOnlyList<Diagnostic> diagnostics = await RegexGeneratorHelper.RunGenerator(@" using System.Text.RegularExpressions; partial class C { [RegexGenerator(""(?<!(Saturday|Sunday) )\b\w+ \d{1,2}, \d{4}\b"")] private static partial Regex NegativeLookbehindNotSupported(); } "); 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 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) })); } } }
1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/libraries/System.Text.RegularExpressions/tests/UnitTests/RegexTreeAnalyzerTests.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 Xunit; using Xunit.Sdk; namespace System.Text.RegularExpressions.Tests { public class RegexTreeAnalyzerTests { [Fact] public void SimpleString() { (RegexTree tree, AnalysisResults analysis) = Analyze("abc"); RegexNode rootCapture = AssertNode(analysis, tree.Root, RegexNodeKind.Capture, atomicByAncestor: true, backtracks: false, captures: true); RegexNode abc = AssertNode(analysis, rootCapture.Child(0), RegexNodeKind.Multi, atomicByAncestor: true, backtracks: false, captures: false); } [Fact] public void AlternationWithCaptures() { (RegexTree tree, AnalysisResults analysis) = Analyze("abc|d(e)f|(ghi)"); RegexNode rootCapture = AssertNode(analysis, tree.Root, RegexNodeKind.Capture, atomicByAncestor: true, backtracks: false, captures: true); RegexNode implicitAtomic = AssertNode(analysis, rootCapture.Child(0), RegexNodeKind.Atomic, atomicByAncestor: true, backtracks: false, captures: true); RegexNode alternation = AssertNode(analysis, implicitAtomic.Child(0), RegexNodeKind.Alternate, atomicByAncestor: true, backtracks: false, captures: true); RegexNode abc = AssertNode(analysis, alternation.Child(0), RegexNodeKind.Multi, atomicByAncestor: true, backtracks: false, captures: false); RegexNode def = AssertNode(analysis, alternation.Child(1), RegexNodeKind.Concatenate, atomicByAncestor: true, backtracks: false, captures: true); RegexNode ghiCapture = AssertNode(analysis, alternation.Child(2), RegexNodeKind.Capture, atomicByAncestor: true, backtracks: false, captures: true); RegexNode d = AssertNode(analysis, def.Child(0), RegexNodeKind.One, atomicByAncestor: false, backtracks: false, captures: false); RegexNode eCapture = AssertNode(analysis, def.Child(1), RegexNodeKind.Capture, atomicByAncestor: false, backtracks: false, captures: true); RegexNode f = AssertNode(analysis, def.Child(2), RegexNodeKind.One, atomicByAncestor: true, backtracks: false, captures: false); RegexNode e = AssertNode(analysis, eCapture.Child(0), RegexNodeKind.One, atomicByAncestor: false, backtracks: false, captures: false); RegexNode ghi = AssertNode(analysis, ghiCapture.Child(0), RegexNodeKind.Multi, atomicByAncestor: true, backtracks: false, captures: false); } [Fact] public void LoopsReducedWithAutoAtomic() { (RegexTree tree, AnalysisResults analysis) = Analyze("a*(b*)c*"); RegexNode rootCapture = AssertNode(analysis, tree.Root, RegexNodeKind.Capture, atomicByAncestor: true, backtracks: false, captures: true); RegexNode concat = AssertNode(analysis, rootCapture.Child(0), RegexNodeKind.Concatenate, atomicByAncestor: true, backtracks: false, captures: true); RegexNode aStar = AssertNode(analysis, concat.Child(0), RegexNodeKind.Oneloopatomic, atomicByAncestor: false, backtracks: false, captures: false); RegexNode implicitBumpalong = AssertNode(analysis, concat.Child(1), RegexNodeKind.UpdateBumpalong, atomicByAncestor: false, backtracks: false, captures: false); RegexNode bStarCapture = AssertNode(analysis, concat.Child(2), RegexNodeKind.Capture, atomicByAncestor: false, backtracks: false, captures: true); RegexNode cStar = AssertNode(analysis, concat.Child(3), RegexNodeKind.Oneloopatomic, atomicByAncestor: true, backtracks: false, captures: false); RegexNode bStar = AssertNode(analysis, bStarCapture.Child(0), RegexNodeKind.Oneloopatomic, atomicByAncestor: false, backtracks: false, captures: false); } [Fact] public void AtomicGroupAroundBacktracking() { (RegexTree tree, AnalysisResults analysis) = Analyze("[ab]*(?>[bc]*[cd])[ef]"); RegexNode rootCapture = AssertNode(analysis, tree.Root, RegexNodeKind.Capture, atomicByAncestor: true, backtracks: true, captures: true); RegexNode rootConcat = AssertNode(analysis, rootCapture.Child(0), RegexNodeKind.Concatenate, atomicByAncestor: true, backtracks: true, captures: false); RegexNode abStar = AssertNode(analysis, rootConcat.Child(0), RegexNodeKind.Setloop, atomicByAncestor: false, backtracks: true, captures: false); RegexNode implicitBumpalong = AssertNode(analysis, rootConcat.Child(1), RegexNodeKind.UpdateBumpalong, atomicByAncestor: false, backtracks: false, captures: false); RegexNode atomic = AssertNode(analysis, rootConcat.Child(2), RegexNodeKind.Atomic, atomicByAncestor: false, backtracks: false, captures: false); RegexNode ef = AssertNode(analysis, rootConcat.Child(3), RegexNodeKind.Set, atomicByAncestor: true, backtracks: false, captures: false); // TODO: fix backtracking for concat RegexNode atomicConcat = AssertNode(analysis, atomic.Child(0), RegexNodeKind.Concatenate, atomicByAncestor: true, backtracks: true, captures: false); RegexNode bcStar = AssertNode(analysis, atomicConcat.Child(0), RegexNodeKind.Setloop, atomicByAncestor: false, backtracks: true, captures: false); RegexNode cd = AssertNode(analysis, atomicConcat.Child(1), RegexNodeKind.Set, atomicByAncestor: true, backtracks: false, captures: false); } private static (RegexTree Tree, AnalysisResults Analysis) Analyze(string pattern) { RegexTree tree = RegexParser.Parse(pattern, RegexOptions.None, CultureInfo.InvariantCulture); return (tree, RegexTreeAnalyzer.Analyze(tree)); } private static RegexNode AssertNode(AnalysisResults analysis, RegexNode node, RegexNodeKind kind, bool atomicByAncestor, bool backtracks, bool captures) { Assert.Equal(kind, node.Kind); if (atomicByAncestor != analysis.IsAtomicByAncestor(node)) { throw new XunitException($"Expected atomicByParent == {atomicByAncestor} for {node.Kind}, got {!atomicByAncestor}"); } if (backtracks != analysis.MayBacktrack(node)) { throw new XunitException($"Expected backtracks == {backtracks} for {node.Kind}, got {!backtracks}"); } if (captures != analysis.MayContainCapture(node)) { throw new XunitException($"Expected captures == {captures} for {node.Kind}, got {!captures}"); } return node; } } }
// 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 Xunit; using Xunit.Sdk; namespace System.Text.RegularExpressions.Tests { public class RegexTreeAnalyzerTests { [Fact] public void SimpleString() { (RegexTree tree, AnalysisResults analysis) = Analyze("abc"); RegexNode rootCapture = AssertNode(analysis, tree.Root, RegexNodeKind.Capture, atomicByAncestor: true, backtracks: false, captures: true); RegexNode abc = AssertNode(analysis, rootCapture.Child(0), RegexNodeKind.Multi, atomicByAncestor: true, backtracks: false, captures: false); } [Fact] public void AlternationWithCaptures() { (RegexTree tree, AnalysisResults analysis) = Analyze("abc|d(e)f|(ghi)"); RegexNode rootCapture = AssertNode(analysis, tree.Root, RegexNodeKind.Capture, atomicByAncestor: true, backtracks: false, captures: true); RegexNode implicitAtomic = AssertNode(analysis, rootCapture.Child(0), RegexNodeKind.Atomic, atomicByAncestor: true, backtracks: false, captures: true); RegexNode alternation = AssertNode(analysis, implicitAtomic.Child(0), RegexNodeKind.Alternate, atomicByAncestor: true, backtracks: false, captures: true); RegexNode abc = AssertNode(analysis, alternation.Child(0), RegexNodeKind.Multi, atomicByAncestor: true, backtracks: false, captures: false); RegexNode def = AssertNode(analysis, alternation.Child(1), RegexNodeKind.Concatenate, atomicByAncestor: true, backtracks: false, captures: true); RegexNode ghiCapture = AssertNode(analysis, alternation.Child(2), RegexNodeKind.Capture, atomicByAncestor: true, backtracks: false, captures: true); RegexNode d = AssertNode(analysis, def.Child(0), RegexNodeKind.One, atomicByAncestor: false, backtracks: false, captures: false); RegexNode eCapture = AssertNode(analysis, def.Child(1), RegexNodeKind.Capture, atomicByAncestor: false, backtracks: false, captures: true); RegexNode f = AssertNode(analysis, def.Child(2), RegexNodeKind.One, atomicByAncestor: true, backtracks: false, captures: false); RegexNode e = AssertNode(analysis, eCapture.Child(0), RegexNodeKind.One, atomicByAncestor: false, backtracks: false, captures: false); RegexNode ghi = AssertNode(analysis, ghiCapture.Child(0), RegexNodeKind.Multi, atomicByAncestor: true, backtracks: false, captures: false); } [Fact] public void LoopsReducedWithAutoAtomic() { (RegexTree tree, AnalysisResults analysis) = Analyze("a*(b*)c*"); RegexNode rootCapture = AssertNode(analysis, tree.Root, RegexNodeKind.Capture, atomicByAncestor: true, backtracks: false, captures: true); RegexNode concat = AssertNode(analysis, rootCapture.Child(0), RegexNodeKind.Concatenate, atomicByAncestor: true, backtracks: false, captures: true); RegexNode aStar = AssertNode(analysis, concat.Child(0), RegexNodeKind.Oneloopatomic, atomicByAncestor: false, backtracks: false, captures: false); RegexNode implicitBumpalong = AssertNode(analysis, concat.Child(1), RegexNodeKind.UpdateBumpalong, atomicByAncestor: false, backtracks: false, captures: false); RegexNode bStarCapture = AssertNode(analysis, concat.Child(2), RegexNodeKind.Capture, atomicByAncestor: false, backtracks: false, captures: true); RegexNode cStar = AssertNode(analysis, concat.Child(3), RegexNodeKind.Oneloopatomic, atomicByAncestor: true, backtracks: false, captures: false); RegexNode bStar = AssertNode(analysis, bStarCapture.Child(0), RegexNodeKind.Oneloopatomic, atomicByAncestor: false, backtracks: false, captures: false); } [Fact] public void AtomicGroupAroundBacktracking() { (RegexTree tree, AnalysisResults analysis) = Analyze("[ab]*(?>[bc]*[cd])[ef]"); RegexNode rootCapture = AssertNode(analysis, tree.Root, RegexNodeKind.Capture, atomicByAncestor: true, backtracks: true, captures: true); RegexNode rootConcat = AssertNode(analysis, rootCapture.Child(0), RegexNodeKind.Concatenate, atomicByAncestor: true, backtracks: true, captures: false); RegexNode abStar = AssertNode(analysis, rootConcat.Child(0), RegexNodeKind.Setloop, atomicByAncestor: false, backtracks: true, captures: false); RegexNode implicitBumpalong = AssertNode(analysis, rootConcat.Child(1), RegexNodeKind.UpdateBumpalong, atomicByAncestor: false, backtracks: false, captures: false); RegexNode atomic = AssertNode(analysis, rootConcat.Child(2), RegexNodeKind.Atomic, atomicByAncestor: false, backtracks: false, captures: false); RegexNode ef = AssertNode(analysis, rootConcat.Child(3), RegexNodeKind.Set, atomicByAncestor: true, backtracks: false, captures: false); RegexNode atomicConcat = AssertNode(analysis, atomic.Child(0), RegexNodeKind.Concatenate, atomicByAncestor: true, backtracks: true, captures: false); RegexNode bcStar = AssertNode(analysis, atomicConcat.Child(0), RegexNodeKind.Setloop, atomicByAncestor: false, backtracks: true, captures: false); RegexNode cd = AssertNode(analysis, atomicConcat.Child(1), RegexNodeKind.Set, atomicByAncestor: true, backtracks: false, captures: false); } private static (RegexTree Tree, AnalysisResults Analysis) Analyze(string pattern) { RegexTree tree = RegexParser.Parse(pattern, RegexOptions.None, CultureInfo.InvariantCulture); return (tree, RegexTreeAnalyzer.Analyze(tree)); } private static RegexNode AssertNode(AnalysisResults analysis, RegexNode node, RegexNodeKind kind, bool atomicByAncestor, bool backtracks, bool captures) { Assert.Equal(kind, node.Kind); if (atomicByAncestor != analysis.IsAtomicByAncestor(node)) { throw new XunitException($"Expected atomicByParent == {atomicByAncestor} for {node.Kind}, got {!atomicByAncestor}"); } if (backtracks != analysis.MayBacktrack(node)) { throw new XunitException($"Expected backtracks == {backtracks} for {node.Kind}, got {!backtracks}"); } if (captures != analysis.MayContainCapture(node)) { throw new XunitException($"Expected captures == {captures} for {node.Kind}, got {!captures}"); } return node; } } }
1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/tests/JIT/HardwareIntrinsics/General/Vector256_1/op_Equality.Single.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void op_EqualitySingle() { var test = new VectorBooleanBinaryOpTest__op_EqualitySingle(); // 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_EqualitySingle { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private GCHandle inHandle1; private GCHandle inHandle2; private ulong alignment; public DataTable(Single[] inArray1, Single[] inArray2, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>(); 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<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void 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<Single> _fld1; public Vector256<Single> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); return testStruct; } public void RunStructFldScenario(VectorBooleanBinaryOpTest__op_EqualitySingle testClass) { var result = _fld1 == _fld2; testClass.ValidateResult(_fld1, _fld2, result); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Single[] _data2 = new Single[Op2ElementCount]; private static Vector256<Single> _clsVar1; private static Vector256<Single> _clsVar2; private Vector256<Single> _fld1; private Vector256<Single> _fld2; private DataTable _dataTable; static VectorBooleanBinaryOpTest__op_EqualitySingle() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); } public VectorBooleanBinaryOpTest__op_EqualitySingle() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } _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<Vector256<Single>>(_dataTable.inArray1Ptr) == Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Vector256<Single>).GetMethod("op_Equality", new Type[] { typeof(Vector256<Single>), typeof(Vector256<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Single>>(_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<Vector256<Single>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr); var result = op1 == op2; ValidateResult(op1, op2, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBooleanBinaryOpTest__op_EqualitySingle(); 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(Vector256<Single> op1, Vector256<Single> op2, bool result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Single>>()); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(Single[] left, Single[] 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)}.op_Equality<Single>(Vector256<Single>, Vector256<Single>): {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_EqualitySingle() { var test = new VectorBooleanBinaryOpTest__op_EqualitySingle(); // 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_EqualitySingle { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private GCHandle inHandle1; private GCHandle inHandle2; private ulong alignment; public DataTable(Single[] inArray1, Single[] inArray2, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>(); 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<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void 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<Single> _fld1; public Vector256<Single> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); return testStruct; } public void RunStructFldScenario(VectorBooleanBinaryOpTest__op_EqualitySingle testClass) { var result = _fld1 == _fld2; testClass.ValidateResult(_fld1, _fld2, result); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Single[] _data2 = new Single[Op2ElementCount]; private static Vector256<Single> _clsVar1; private static Vector256<Single> _clsVar2; private Vector256<Single> _fld1; private Vector256<Single> _fld2; private DataTable _dataTable; static VectorBooleanBinaryOpTest__op_EqualitySingle() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); } public VectorBooleanBinaryOpTest__op_EqualitySingle() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } _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<Vector256<Single>>(_dataTable.inArray1Ptr) == Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Vector256<Single>).GetMethod("op_Equality", new Type[] { typeof(Vector256<Single>), typeof(Vector256<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Single>>(_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<Vector256<Single>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr); var result = op1 == op2; ValidateResult(op1, op2, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBooleanBinaryOpTest__op_EqualitySingle(); 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(Vector256<Single> op1, Vector256<Single> op2, bool result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Single>>()); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(Single[] left, Single[] 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)}.op_Equality<Single>(Vector256<Single>, Vector256<Single>): {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,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/CompilationRelaxations.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Runtime.CompilerServices { /// IMPORTANT: Keep this in sync with corhdr.h [Flags] public enum CompilationRelaxations : int { NoStringInterning = 0x0008 // Start in 0x0008, we had other non public flags in this enum before, // so we'll start here just in case somebody used them. This flag is only // valid when set for Assemblies. } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Runtime.CompilerServices { /// IMPORTANT: Keep this in sync with corhdr.h [Flags] public enum CompilationRelaxations : int { NoStringInterning = 0x0008 // Start in 0x0008, we had other non public flags in this enum before, // so we'll start here just in case somebody used them. This flag is only // valid when set for Assemblies. } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/libraries/System.CodeDom/src/System/CodeDom/CodeVariableDeclarationStatement.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.CodeDom { public class CodeVariableDeclarationStatement : CodeStatement { private CodeTypeReference _type; private string _name; public CodeVariableDeclarationStatement() { } public CodeVariableDeclarationStatement(CodeTypeReference type, string name) { Type = type; Name = name; } public CodeVariableDeclarationStatement(string type, string name) { Type = new CodeTypeReference(type); Name = name; } public CodeVariableDeclarationStatement(Type type, string name) { Type = new CodeTypeReference(type); Name = name; } public CodeVariableDeclarationStatement(CodeTypeReference type, string name, CodeExpression initExpression) { Type = type; Name = name; InitExpression = initExpression; } public CodeVariableDeclarationStatement(string type, string name, CodeExpression initExpression) { Type = new CodeTypeReference(type); Name = name; InitExpression = initExpression; } public CodeVariableDeclarationStatement(Type type, string name, CodeExpression initExpression) { Type = new CodeTypeReference(type); Name = name; InitExpression = initExpression; } public CodeExpression InitExpression { get; set; } public string Name { get => _name ?? string.Empty; set => _name = value; } public CodeTypeReference Type { get => _type ?? (_type = new CodeTypeReference("")); set => _type = value; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.CodeDom { public class CodeVariableDeclarationStatement : CodeStatement { private CodeTypeReference _type; private string _name; public CodeVariableDeclarationStatement() { } public CodeVariableDeclarationStatement(CodeTypeReference type, string name) { Type = type; Name = name; } public CodeVariableDeclarationStatement(string type, string name) { Type = new CodeTypeReference(type); Name = name; } public CodeVariableDeclarationStatement(Type type, string name) { Type = new CodeTypeReference(type); Name = name; } public CodeVariableDeclarationStatement(CodeTypeReference type, string name, CodeExpression initExpression) { Type = type; Name = name; InitExpression = initExpression; } public CodeVariableDeclarationStatement(string type, string name, CodeExpression initExpression) { Type = new CodeTypeReference(type); Name = name; InitExpression = initExpression; } public CodeVariableDeclarationStatement(Type type, string name, CodeExpression initExpression) { Type = new CodeTypeReference(type); Name = name; InitExpression = initExpression; } public CodeExpression InitExpression { get; set; } public string Name { get => _name ?? string.Empty; set => _name = value; } public CodeTypeReference Type { get => _type ?? (_type = new CodeTypeReference("")); set => _type = value; } } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/libraries/System.Private.CoreLib/src/System/Runtime/Intrinsics/X86/Avx.PlatformNotSupported.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.Intrinsics; namespace System.Runtime.Intrinsics.X86 { /// <summary> /// This class provides access to Intel AVX hardware instructions via intrinsics /// </summary> [CLSCompliant(false)] public abstract class Avx : Sse42 { internal Avx() { } public static new bool IsSupported { [Intrinsic] get { return false; } } public new abstract class X64 : Sse42.X64 { internal X64() { } public static new bool IsSupported { [Intrinsic] get { return false; } } } /// <summary> /// __m256 _mm256_add_ps (__m256 a, __m256 b) /// VADDPS ymm, ymm, ymm/m256 /// </summary> public static Vector256<float> Add(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_add_pd (__m256d a, __m256d b) /// VADDPD ymm, ymm, ymm/m256 /// </summary> public static Vector256<double> Add(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_addsub_ps (__m256 a, __m256 b) /// VADDSUBPS ymm, ymm, ymm/m256 /// </summary> public static Vector256<float> AddSubtract(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_addsub_pd (__m256d a, __m256d b) /// VADDSUBPD ymm, ymm, ymm/m256 /// </summary> public static Vector256<double> AddSubtract(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_and_ps (__m256 a, __m256 b) /// VANDPS ymm, ymm, ymm/m256 /// </summary> public static Vector256<float> And(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_and_pd (__m256d a, __m256d b) /// VANDPD ymm, ymm, ymm/m256 /// </summary> public static Vector256<double> And(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_andnot_ps (__m256 a, __m256 b) /// VANDNPS ymm, ymm, ymm/m256 /// </summary> public static Vector256<float> AndNot(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_andnot_pd (__m256d a, __m256d b) /// VANDNPD ymm, ymm, ymm/m256 /// </summary> public static Vector256<double> AndNot(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_blend_ps (__m256 a, __m256 b, const int imm8) /// VBLENDPS ymm, ymm, ymm/m256, imm8 /// </summary> public static Vector256<float> Blend(Vector256<float> left, Vector256<float> right, byte control) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_blend_pd (__m256d a, __m256d b, const int imm8) /// VBLENDPD ymm, ymm, ymm/m256, imm8 /// </summary> public static Vector256<double> Blend(Vector256<double> left, Vector256<double> right, byte control) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_blendv_ps (__m256 a, __m256 b, __m256 mask) /// VBLENDVPS ymm, ymm, ymm/m256, ymm /// </summary> public static Vector256<float> BlendVariable(Vector256<float> left, Vector256<float> right, Vector256<float> mask) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_blendv_pd (__m256d a, __m256d b, __m256d mask) /// VBLENDVPD ymm, ymm, ymm/m256, ymm /// </summary> public static Vector256<double> BlendVariable(Vector256<double> left, Vector256<double> right, Vector256<double> mask) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_broadcast_ss (float const * mem_addr) /// VBROADCASTSS xmm, m32 /// </summary> public static unsafe Vector128<float> BroadcastScalarToVector128(float* source) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_broadcast_ss (float const * mem_addr) /// VBROADCASTSS ymm, m32 /// </summary> public static unsafe Vector256<float> BroadcastScalarToVector256(float* source) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_broadcast_sd (double const * mem_addr) /// VBROADCASTSD ymm, m64 /// </summary> public static unsafe Vector256<double> BroadcastScalarToVector256(double* source) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_broadcast_ps (__m128 const * mem_addr) /// VBROADCASTF128, ymm, m128 /// </summary> public static unsafe Vector256<float> BroadcastVector128ToVector256(float* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_broadcast_pd (__m128d const * mem_addr) /// VBROADCASTF128, ymm, m128 /// </summary> public static unsafe Vector256<double> BroadcastVector128ToVector256(double* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_ceil_ps (__m256 a) /// VROUNDPS ymm, ymm/m256, imm8(10) /// </summary> public static Vector256<float> Ceiling(Vector256<float> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_ceil_pd (__m256d a) /// VROUNDPD ymm, ymm/m256, imm8(10) /// </summary> public static Vector256<double> Ceiling(Vector256<double> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_cmp_ps (__m128 a, __m128 b, const int imm8) /// VCMPPS xmm, xmm, xmm/m128, imm8 /// </summary> public static Vector128<float> Compare(Vector128<float> left, Vector128<float> right, FloatComparisonMode mode) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128d _mm_cmp_pd (__m128d a, __m128d b, const int imm8) /// VCMPPD xmm, xmm, xmm/m128, imm8 /// </summary> public static Vector128<double> Compare(Vector128<double> left, Vector128<double> right, FloatComparisonMode mode) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_cmp_ps (__m256 a, __m256 b, const int imm8) /// VCMPPS ymm, ymm, ymm/m256, imm8 /// </summary> public static Vector256<float> Compare(Vector256<float> left, Vector256<float> right, FloatComparisonMode mode) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_cmp_pd (__m256d a, __m256d b, const int imm8) /// VCMPPD ymm, ymm, ymm/m256, imm8 /// </summary> public static Vector256<double> Compare(Vector256<double> left, Vector256<double> right, FloatComparisonMode mode) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_cmpeq_ps (__m256 a, __m256 b) /// CMPPS ymm, ymm/m256, imm8(0) /// The above native signature does not exist. We provide this additional overload for completeness. /// </summary> public static Vector256<float> CompareEqual(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_cmpeq_pd (__m256d a, __m256d b) /// CMPPD ymm, ymm/m256, imm8(0) /// The above native signature does not exist. We provide this additional overload for completeness. /// </summary> public static Vector256<double> CompareEqual(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_cmpgt_ps (__m256 a, __m256 b) /// CMPPS ymm, ymm/m256, imm8(14) /// The above native signature does not exist. We provide this additional overload for completeness. /// </summary> public static Vector256<float> CompareGreaterThan(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_cmpgt_pd (__m256d a, __m256d b) /// CMPPD ymm, ymm/m256, imm8(14) /// The above native signature does not exist. We provide this additional overload for completeness. /// </summary> public static Vector256<double> CompareGreaterThan(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_cmpge_ps (__m256 a, __m256 b) /// CMPPS ymm, ymm/m256, imm8(13) /// The above native signature does not exist. We provide this additional overload for completeness. /// </summary> public static Vector256<float> CompareGreaterThanOrEqual(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_cmpge_pd (__m256d a, __m256d b) /// CMPPD ymm, ymm/m256, imm8(13) /// The above native signature does not exist. We provide this additional overload for completeness. /// </summary> public static Vector256<double> CompareGreaterThanOrEqual(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_cmplt_ps (__m256 a, __m256 b) /// CMPPS ymm, ymm/m256, imm8(1) /// The above native signature does not exist. We provide this additional overload for completeness. /// </summary> public static Vector256<float> CompareLessThan(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_cmplt_pd (__m256d a, __m256d b) /// CMPPD ymm, ymm/m256, imm8(1) /// The above native signature does not exist. We provide this additional overload for completeness. /// </summary> public static Vector256<double> CompareLessThan(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_cmple_ps (__m256 a, __m256 b) /// CMPPS ymm, ymm/m256, imm8(2) /// The above native signature does not exist. We provide this additional overload for completeness. /// </summary> public static Vector256<float> CompareLessThanOrEqual(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_cmple_pd (__m256d a, __m256d b) /// CMPPD ymm, ymm/m256, imm8(2) /// The above native signature does not exist. We provide this additional overload for completeness. /// </summary> public static Vector256<double> CompareLessThanOrEqual(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_cmpneq_ps (__m256 a, __m256 b) /// CMPPS ymm, ymm/m256, imm8(4) /// The above native signature does not exist. We provide this additional overload for completeness. /// </summary> public static Vector256<float> CompareNotEqual(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_cmpneq_pd (__m256d a, __m256d b) /// CMPPD ymm, ymm/m256, imm8(4) /// The above native signature does not exist. We provide this additional overload for completeness. /// </summary> public static Vector256<double> CompareNotEqual(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_cmpngt_ps (__m256 a, __m256 b) /// CMPPS ymm, ymm/m256, imm8(10) /// The above native signature does not exist. We provide this additional overload for completeness. /// </summary> public static Vector256<float> CompareNotGreaterThan(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_cmpngt_pd (__m256d a, __m256d b) /// CMPPD ymm, ymm/m256, imm8(10) /// The above native signature does not exist. We provide this additional overload for completeness. /// </summary> public static Vector256<double> CompareNotGreaterThan(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_cmpnge_ps (__m256 a, __m256 b) /// CMPPS ymm, ymm/m256, imm8(9) /// The above native signature does not exist. We provide this additional overload for completeness. /// </summary> public static Vector256<float> CompareNotGreaterThanOrEqual(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_cmpnge_pd (__m256d a, __m256d b) /// CMPPD ymm, ymm/m256, imm8(9) /// The above native signature does not exist. We provide this additional overload for completeness. /// </summary> public static Vector256<double> CompareNotGreaterThanOrEqual(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_cmpnlt_ps (__m256 a, __m256 b) /// CMPPS ymm, ymm/m256, imm8(5) /// The above native signature does not exist. We provide this additional overload for completeness. /// </summary> public static Vector256<float> CompareNotLessThan(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_cmpnlt_pd (__m256d a, __m256d b) /// CMPPD ymm, ymm/m256, imm8(5) /// The above native signature does not exist. We provide this additional overload for completeness. /// </summary> public static Vector256<double> CompareNotLessThan(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_cmpnle_ps (__m256 a, __m256 b) /// CMPPS ymm, ymm/m256, imm8(6) /// The above native signature does not exist. We provide this additional overload for completeness. /// </summary> public static Vector256<float> CompareNotLessThanOrEqual(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_cmpnle_pd (__m256d a, __m256d b) /// CMPPD ymm, ymm/m256, imm8(6) /// The above native signature does not exist. We provide this additional overload for completeness. /// </summary> public static Vector256<double> CompareNotLessThanOrEqual(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_cmpord_ps (__m256 a, __m256 b) /// CMPPS ymm, ymm/m256, imm8(7) /// The above native signature does not exist. We provide this additional overload for completeness. /// </summary> public static Vector256<float> CompareOrdered(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_cmpord_pd (__m256d a, __m256d b) /// CMPPD ymm, ymm/m256, imm8(7) /// The above native signature does not exist. We provide this additional overload for completeness. /// </summary> public static Vector256<double> CompareOrdered(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128d _mm_cmp_sd (__m128d a, __m128d b, const int imm8) /// VCMPSS xmm, xmm, xmm/m32, imm8 /// </summary> public static Vector128<double> CompareScalar(Vector128<double> left, Vector128<double> right, FloatComparisonMode mode) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_cmp_ss (__m128 a, __m128 b, const int imm8) /// VCMPSD xmm, xmm, xmm/m64, imm8 /// </summary> public static Vector128<float> CompareScalar(Vector128<float> left, Vector128<float> right, FloatComparisonMode mode) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_cmpunord_ps (__m256 a, __m256 b) /// CMPPS ymm, ymm/m256, imm8(3) /// The above native signature does not exist. We provide this additional overload for completeness. /// </summary> public static Vector256<float> CompareUnordered(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_cmpunord_pd (__m256d a, __m256d b) /// CMPPD ymm, ymm/m256, imm8(3) /// The above native signature does not exist. We provide this additional overload for completeness. /// </summary> public static Vector256<double> CompareUnordered(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128i _mm256_cvtpd_epi32 (__m256d a) /// VCVTPD2DQ xmm, ymm/m256 /// </summary> public static Vector128<int> ConvertToVector128Int32(Vector256<double> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm256_cvtpd_ps (__m256d a) /// VCVTPD2PS xmm, ymm/m256 /// </summary> public static Vector128<float> ConvertToVector128Single(Vector256<double> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_cvtps_epi32 (__m256 a) /// VCVTPS2DQ ymm, ymm/m256 /// </summary> public static Vector256<int> ConvertToVector256Int32(Vector256<float> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_cvtepi32_ps (__m256i a) /// VCVTDQ2PS ymm, ymm/m256 /// </summary> public static Vector256<float> ConvertToVector256Single(Vector256<int> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_cvtps_pd (__m128 a) /// VCVTPS2PD ymm, xmm/m128 /// </summary> public static Vector256<double> ConvertToVector256Double(Vector128<float> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_cvtepi32_pd (__m128i a) /// VCVTDQ2PD ymm, xmm/m128 /// </summary> public static Vector256<double> ConvertToVector256Double(Vector128<int> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128i _mm256_cvttpd_epi32 (__m256d a) /// VCVTTPD2DQ xmm, ymm/m256 /// </summary> public static Vector128<int> ConvertToVector128Int32WithTruncation(Vector256<double> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_cvttps_epi32 (__m256 a) /// VCVTTPS2DQ ymm, ymm/m256 /// </summary> public static Vector256<int> ConvertToVector256Int32WithTruncation(Vector256<float> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_div_ps (__m256 a, __m256 b) /// VDIVPS ymm, ymm, ymm/m256 /// </summary> public static Vector256<float> Divide(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_div_pd (__m256d a, __m256d b) /// VDIVPD ymm, ymm, ymm/m256 /// </summary> public static Vector256<double> Divide(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_dp_ps (__m256 a, __m256 b, const int imm8) /// VDPPS ymm, ymm, ymm/m256, imm8 /// </summary> public static Vector256<float> DotProduct(Vector256<float> left, Vector256<float> right, byte control) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_moveldup_ps (__m256 a) /// VMOVSLDUP ymm, ymm/m256 /// </summary> public static Vector256<float> DuplicateEvenIndexed(Vector256<float> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_movedup_pd (__m256d a) /// VMOVDDUP ymm, ymm/m256 /// </summary> public static Vector256<double> DuplicateEvenIndexed(Vector256<double> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_movehdup_ps (__m256 a) /// VMOVSHDUP ymm, ymm/m256 /// </summary> public static Vector256<float> DuplicateOddIndexed(Vector256<float> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128i _mm256_extractf128_si256 (__m256i a, const int imm8) /// VEXTRACTF128 xmm/m128, ymm, imm8 /// </summary> public static Vector128<byte> ExtractVector128(Vector256<byte> value, byte index) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128i _mm256_extractf128_si256 (__m256i a, const int imm8) /// VEXTRACTF128 xmm/m128, ymm, imm8 /// </summary> public static Vector128<sbyte> ExtractVector128(Vector256<sbyte> value, byte index) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128i _mm256_extractf128_si256 (__m256i a, const int imm8) /// VEXTRACTF128 xmm/m128, ymm, imm8 /// </summary> public static Vector128<short> ExtractVector128(Vector256<short> value, byte index) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128i _mm256_extractf128_si256 (__m256i a, const int imm8) /// VEXTRACTF128 xmm/m128, ymm, imm8 /// </summary> public static Vector128<ushort> ExtractVector128(Vector256<ushort> value, byte index) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128i _mm256_extractf128_si256 (__m256i a, const int imm8) /// VEXTRACTF128 xmm/m128, ymm, imm8 /// </summary> public static Vector128<int> ExtractVector128(Vector256<int> value, byte index) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128i _mm256_extractf128_si256 (__m256i a, const int imm8) /// VEXTRACTF128 xmm/m128, ymm, imm8 /// </summary> public static Vector128<uint> ExtractVector128(Vector256<uint> value, byte index) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128i _mm256_extractf128_si256 (__m256i a, const int imm8) /// VEXTRACTF128 xmm/m128, ymm, imm8 /// </summary> public static Vector128<long> ExtractVector128(Vector256<long> value, byte index) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128i _mm256_extractf128_si256 (__m256i a, const int imm8) /// VEXTRACTF128 xmm/m128, ymm, imm8 /// </summary> public static Vector128<ulong> ExtractVector128(Vector256<ulong> value, byte index) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm256_extractf128_ps (__m256 a, const int imm8) /// VEXTRACTF128 xmm/m128, ymm, imm8 /// </summary> public static Vector128<float> ExtractVector128(Vector256<float> value, byte index) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128d _mm256_extractf128_pd (__m256d a, const int imm8) /// VEXTRACTF128 xmm/m128, ymm, imm8 /// </summary> public static Vector128<double> ExtractVector128(Vector256<double> value, byte index) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_floor_ps (__m256 a) /// VROUNDPS ymm, ymm/m256, imm8(9) /// </summary> public static Vector256<float> Floor(Vector256<float> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_floor_pd (__m256d a) /// VROUNDPS ymm, ymm/m256, imm8(9) /// </summary> public static Vector256<double> Floor(Vector256<double> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_hadd_ps (__m256 a, __m256 b) /// VHADDPS ymm, ymm, ymm/m256 /// </summary> public static Vector256<float> HorizontalAdd(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_hadd_pd (__m256d a, __m256d b) /// VHADDPD ymm, ymm, ymm/m256 /// </summary> public static Vector256<double> HorizontalAdd(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_hsub_ps (__m256 a, __m256 b) /// VHSUBPS ymm, ymm, ymm/m256 /// </summary> public static Vector256<float> HorizontalSubtract(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_hsub_pd (__m256d a, __m256d b) /// VHSUBPD ymm, ymm, ymm/m256 /// </summary> public static Vector256<double> HorizontalSubtract(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_insertf128_si256 (__m256i a, __m128i b, int imm8) /// VINSERTF128 ymm, ymm, xmm/m128, imm8 /// </summary> public static Vector256<byte> InsertVector128(Vector256<byte> value, Vector128<byte> data, byte index) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_insertf128_si256 (__m256i a, __m128i b, int imm8) /// VINSERTF128 ymm, ymm, xmm/m128, imm8 /// </summary> public static Vector256<sbyte> InsertVector128(Vector256<sbyte> value, Vector128<sbyte> data, byte index) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_insertf128_si256 (__m256i a, __m128i b, int imm8) /// VINSERTF128 ymm, ymm, xmm/m128, imm8 /// </summary> public static Vector256<short> InsertVector128(Vector256<short> value, Vector128<short> data, byte index) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_insertf128_si256 (__m256i a, __m128i b, int imm8) /// VINSERTF128 ymm, ymm, xmm/m128, imm8 /// </summary> public static Vector256<ushort> InsertVector128(Vector256<ushort> value, Vector128<ushort> data, byte index) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_insertf128_si256 (__m256i a, __m128i b, int imm8) /// VINSERTF128 ymm, ymm, xmm/m128, imm8 /// </summary> public static Vector256<int> InsertVector128(Vector256<int> value, Vector128<int> data, byte index) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_insertf128_si256 (__m256i a, __m128i b, int imm8) /// VINSERTF128 ymm, ymm, xmm/m128, imm8 /// </summary> public static Vector256<uint> InsertVector128(Vector256<uint> value, Vector128<uint> data, byte index) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_insertf128_si256 (__m256i a, __m128i b, int imm8) /// VINSERTF128 ymm, ymm, xmm/m128, imm8 /// </summary> public static Vector256<long> InsertVector128(Vector256<long> value, Vector128<long> data, byte index) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_insertf128_si256 (__m256i a, __m128i b, int imm8) /// VINSERTF128 ymm, ymm, xmm/m128, imm8 /// </summary> public static Vector256<ulong> InsertVector128(Vector256<ulong> value, Vector128<ulong> data, byte index) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_insertf128_ps (__m256 a, __m128 b, int imm8) /// VINSERTF128 ymm, ymm, xmm/m128, imm8 /// </summary> public static Vector256<float> InsertVector128(Vector256<float> value, Vector128<float> data, byte index) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_insertf128_pd (__m256d a, __m128d b, int imm8) /// VINSERTF128 ymm, ymm, xmm/m128, imm8 /// </summary> public static Vector256<double> InsertVector128(Vector256<double> value, Vector128<double> data, byte index) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_loadu_si256 (__m256i const * mem_addr) /// VMOVDQU ymm, m256 /// </summary> public static unsafe Vector256<sbyte> LoadVector256(sbyte* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_loadu_si256 (__m256i const * mem_addr) /// VMOVDQU ymm, m256 /// </summary> public static unsafe Vector256<byte> LoadVector256(byte* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_loadu_si256 (__m256i const * mem_addr) /// VMOVDQU ymm, m256 /// </summary> public static unsafe Vector256<short> LoadVector256(short* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_loadu_si256 (__m256i const * mem_addr) /// VMOVDQU ymm, m256 /// </summary> public static unsafe Vector256<ushort> LoadVector256(ushort* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_loadu_si256 (__m256i const * mem_addr) /// VMOVDQU ymm, m256 /// </summary> public static unsafe Vector256<int> LoadVector256(int* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_loadu_si256 (__m256i const * mem_addr) /// VMOVDQU ymm, m256 /// </summary> public static unsafe Vector256<uint> LoadVector256(uint* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_loadu_si256 (__m256i const * mem_addr) /// VMOVDQU ymm, m256 /// </summary> public static unsafe Vector256<long> LoadVector256(long* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_loadu_si256 (__m256i const * mem_addr) /// VMOVDQU ymm, m256 /// </summary> public static unsafe Vector256<ulong> LoadVector256(ulong* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_loadu_ps (float const * mem_addr) /// VMOVUPS ymm, ymm/m256 /// </summary> public static unsafe Vector256<float> LoadVector256(float* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_loadu_pd (double const * mem_addr) /// VMOVUPD ymm, ymm/m256 /// </summary> public static unsafe Vector256<double> LoadVector256(double* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_load_si256 (__m256i const * mem_addr) /// VMOVDQA ymm, m256 /// </summary> public static unsafe Vector256<sbyte> LoadAlignedVector256(sbyte* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_load_si256 (__m256i const * mem_addr) /// VMOVDQA ymm, m256 /// </summary> public static unsafe Vector256<byte> LoadAlignedVector256(byte* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_load_si256 (__m256i const * mem_addr) /// VMOVDQA ymm, m256 /// </summary> public static unsafe Vector256<short> LoadAlignedVector256(short* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_load_si256 (__m256i const * mem_addr) /// VMOVDQA ymm, m256 /// </summary> public static unsafe Vector256<ushort> LoadAlignedVector256(ushort* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_load_si256 (__m256i const * mem_addr) /// VMOVDQA ymm, m256 /// </summary> public static unsafe Vector256<int> LoadAlignedVector256(int* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_load_si256 (__m256i const * mem_addr) /// VMOVDQA ymm, m256 /// </summary> public static unsafe Vector256<uint> LoadAlignedVector256(uint* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_load_si256 (__m256i const * mem_addr) /// VMOVDQA ymm, m256 /// </summary> public static unsafe Vector256<long> LoadAlignedVector256(long* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_load_si256 (__m256i const * mem_addr) /// VMOVDQA ymm, m256 /// </summary> public static unsafe Vector256<ulong> LoadAlignedVector256(ulong* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_load_ps (float const * mem_addr) /// VMOVAPS ymm, ymm/m256 /// </summary> public static unsafe Vector256<float> LoadAlignedVector256(float* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_load_pd (double const * mem_addr) /// VMOVAPD ymm, ymm/m256 /// </summary> public static unsafe Vector256<double> LoadAlignedVector256(double* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_lddqu_si256 (__m256i const * mem_addr) /// VLDDQU ymm, m256 /// </summary> public static unsafe Vector256<sbyte> LoadDquVector256(sbyte* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_lddqu_si256 (__m256i const * mem_addr) /// VLDDQU ymm, m256 /// </summary> public static unsafe Vector256<byte> LoadDquVector256(byte* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_lddqu_si256 (__m256i const * mem_addr) /// VLDDQU ymm, m256 /// </summary> public static unsafe Vector256<short> LoadDquVector256(short* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_lddqu_si256 (__m256i const * mem_addr) /// VLDDQU ymm, m256 /// </summary> public static unsafe Vector256<ushort> LoadDquVector256(ushort* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_lddqu_si256 (__m256i const * mem_addr) /// VLDDQU ymm, m256 /// </summary> public static unsafe Vector256<int> LoadDquVector256(int* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_lddqu_si256 (__m256i const * mem_addr) /// VLDDQU ymm, m256 /// </summary> public static unsafe Vector256<uint> LoadDquVector256(uint* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_lddqu_si256 (__m256i const * mem_addr) /// VLDDQU ymm, m256 /// </summary> public static unsafe Vector256<long> LoadDquVector256(long* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_lddqu_si256 (__m256i const * mem_addr) /// VLDDQU ymm, m256 /// </summary> public static unsafe Vector256<ulong> LoadDquVector256(ulong* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_maskload_ps (float const * mem_addr, __m128i mask) /// VMASKMOVPS xmm, xmm, m128 /// </summary> public static unsafe Vector128<float> MaskLoad(float* address, Vector128<float> mask) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128d _mm_maskload_pd (double const * mem_addr, __m128i mask) /// VMASKMOVPD xmm, xmm, m128 /// </summary> public static unsafe Vector128<double> MaskLoad(double* address, Vector128<double> mask) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_maskload_ps (float const * mem_addr, __m256i mask) /// VMASKMOVPS ymm, ymm, m256 /// </summary> public static unsafe Vector256<float> MaskLoad(float* address, Vector256<float> mask) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_maskload_pd (double const * mem_addr, __m256i mask) /// VMASKMOVPD ymm, ymm, m256 /// </summary> public static unsafe Vector256<double> MaskLoad(double* address, Vector256<double> mask) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm_maskstore_ps (float * mem_addr, __m128i mask, __m128 a) /// VMASKMOVPS m128, xmm, xmm /// </summary> public static unsafe void MaskStore(float* address, Vector128<float> mask, Vector128<float> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm_maskstore_pd (double * mem_addr, __m128i mask, __m128d a) /// VMASKMOVPD m128, xmm, xmm /// </summary> public static unsafe void MaskStore(double* address, Vector128<double> mask, Vector128<double> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_maskstore_ps (float * mem_addr, __m256i mask, __m256 a) /// VMASKMOVPS m256, ymm, ymm /// </summary> public static unsafe void MaskStore(float* address, Vector256<float> mask, Vector256<float> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_maskstore_pd (double * mem_addr, __m256i mask, __m256d a) /// VMASKMOVPD m256, ymm, ymm /// </summary> public static unsafe void MaskStore(double* address, Vector256<double> mask, Vector256<double> source) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_max_ps (__m256 a, __m256 b) /// VMAXPS ymm, ymm, ymm/m256 /// </summary> public static Vector256<float> Max(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_max_pd (__m256d a, __m256d b) /// VMAXPD ymm, ymm, ymm/m256 /// </summary> public static Vector256<double> Max(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_min_ps (__m256 a, __m256 b) /// VMINPS ymm, ymm, ymm/m256 /// </summary> public static Vector256<float> Min(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_min_pd (__m256d a, __m256d b) /// VMINPD ymm, ymm, ymm/m256 /// </summary> public static Vector256<double> Min(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_movemask_ps (__m256 a) /// VMOVMSKPS reg, ymm /// </summary> public static int MoveMask(Vector256<float> value) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_movemask_pd (__m256d a) /// VMOVMSKPD reg, ymm /// </summary> public static int MoveMask(Vector256<double> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_mul_ps (__m256 a, __m256 b) /// VMULPS ymm, ymm, ymm/m256 /// </summary> public static Vector256<float> Multiply(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_mul_pd (__m256d a, __m256d b) /// VMULPD ymm, ymm, ymm/m256 /// </summary> public static Vector256<double> Multiply(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_or_ps (__m256 a, __m256 b) /// VORPS ymm, ymm, ymm/m256 /// </summary> public static Vector256<float> Or(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_or_pd (__m256d a, __m256d b) /// VORPD ymm, ymm, ymm/m256 /// </summary> public static Vector256<double> Or(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_permute_ps (__m128 a, int imm8) /// VPERMILPS xmm, xmm, imm8 /// </summary> public static Vector128<float> Permute(Vector128<float> value, byte control) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128d _mm_permute_pd (__m128d a, int imm8) /// VPERMILPD xmm, xmm, imm8 /// </summary> public static Vector128<double> Permute(Vector128<double> value, byte control) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_permute_ps (__m256 a, int imm8) /// VPERMILPS ymm, ymm, imm8 /// </summary> public static Vector256<float> Permute(Vector256<float> value, byte control) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_permute_pd (__m256d a, int imm8) /// VPERMILPD ymm, ymm, imm8 /// </summary> public static Vector256<double> Permute(Vector256<double> value, byte control) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_permute2f128_si256 (__m256i a, __m256i b, int imm8) /// VPERM2F128 ymm, ymm, ymm/m256, imm8 /// </summary> public static Vector256<byte> Permute2x128(Vector256<byte> left, Vector256<byte> right, byte control) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_permute2f128_si256 (__m256i a, __m256i b, int imm8) /// VPERM2F128 ymm, ymm, ymm/m256, imm8 /// </summary> public static Vector256<sbyte> Permute2x128(Vector256<sbyte> left, Vector256<sbyte> right, byte control) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_permute2f128_si256 (__m256i a, __m256i b, int imm8) /// VPERM2F128 ymm, ymm, ymm/m256, imm8 /// </summary> public static Vector256<short> Permute2x128(Vector256<short> left, Vector256<short> right, byte control) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_permute2f128_si256 (__m256i a, __m256i b, int imm8) /// VPERM2F128 ymm, ymm, ymm/m256, imm8 /// </summary> public static Vector256<ushort> Permute2x128(Vector256<ushort> left, Vector256<ushort> right, byte control) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_permute2f128_si256 (__m256i a, __m256i b, int imm8) /// VPERM2F128 ymm, ymm, ymm/m256, imm8 /// </summary> public static Vector256<int> Permute2x128(Vector256<int> left, Vector256<int> right, byte control) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_permute2f128_si256 (__m256i a, __m256i b, int imm8) /// VPERM2F128 ymm, ymm, ymm/m256, imm8 /// </summary> public static Vector256<uint> Permute2x128(Vector256<uint> left, Vector256<uint> right, byte control) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_permute2f128_si256 (__m256i a, __m256i b, int imm8) /// VPERM2F128 ymm, ymm, ymm/m256, imm8 /// </summary> public static Vector256<long> Permute2x128(Vector256<long> left, Vector256<long> right, byte control) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_permute2f128_si256 (__m256i a, __m256i b, int imm8) /// VPERM2F128 ymm, ymm, ymm/m256, imm8 /// </summary> public static Vector256<ulong> Permute2x128(Vector256<ulong> left, Vector256<ulong> right, byte control) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_permute2f128_ps (__m256 a, __m256 b, int imm8) /// VPERM2F128 ymm, ymm, ymm/m256, imm8 /// </summary> public static Vector256<float> Permute2x128(Vector256<float> left, Vector256<float> right, byte control) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_permute2f128_pd (__m256d a, __m256d b, int imm8) /// VPERM2F128 ymm, ymm, ymm/m256, imm8 /// </summary> public static Vector256<double> Permute2x128(Vector256<double> left, Vector256<double> right, byte control) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_permutevar_ps (__m128 a, __m128i b) /// VPERMILPS xmm, xmm, xmm/m128 /// </summary> public static Vector128<float> PermuteVar(Vector128<float> left, Vector128<int> control) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128d _mm_permutevar_pd (__m128d a, __m128i b) /// VPERMILPD xmm, xmm, xmm/m128 /// </summary> public static Vector128<double> PermuteVar(Vector128<double> left, Vector128<long> control) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_permutevar_ps (__m256 a, __m256i b) /// VPERMILPS ymm, ymm, ymm/m256 /// </summary> public static Vector256<float> PermuteVar(Vector256<float> left, Vector256<int> control) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_permutevar_pd (__m256d a, __m256i b) /// VPERMILPD ymm, ymm, ymm/m256 /// </summary> public static Vector256<double> PermuteVar(Vector256<double> left, Vector256<long> control) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_rcp_ps (__m256 a) /// VRCPPS ymm, ymm/m256 /// </summary> public static Vector256<float> Reciprocal(Vector256<float> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_rsqrt_ps (__m256 a) /// VRSQRTPS ymm, ymm/m256 /// </summary> public static Vector256<float> ReciprocalSqrt(Vector256<float> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_round_ps (__m256 a, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC) /// VROUNDPS ymm, ymm/m256, imm8(8) /// </summary> public static Vector256<float> RoundToNearestInteger(Vector256<float> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_round_ps (__m256 a, _MM_FROUND_TO_NEG_INF | _MM_FROUND_NO_EXC) /// VROUNDPS ymm, ymm/m256, imm8(9) /// </summary> public static Vector256<float> RoundToNegativeInfinity(Vector256<float> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_round_ps (__m256 a, _MM_FROUND_TO_POS_INF | _MM_FROUND_NO_EXC) /// VROUNDPS ymm, ymm/m256, imm8(10) /// </summary> public static Vector256<float> RoundToPositiveInfinity(Vector256<float> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_round_ps (__m256 a, _MM_FROUND_TO_ZERO | _MM_FROUND_NO_EXC) /// VROUNDPS ymm, ymm/m256, imm8(11) /// </summary> public static Vector256<float> RoundToZero(Vector256<float> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_round_ps (__m256 a, _MM_FROUND_CUR_DIRECTION) /// VROUNDPS ymm, ymm/m256, imm8(4) /// </summary> public static Vector256<float> RoundCurrentDirection(Vector256<float> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_round_pd (__m256d a, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC) /// VROUNDPD ymm, ymm/m256, imm8(8) /// </summary> public static Vector256<double> RoundToNearestInteger(Vector256<double> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_round_pd (__m256d a, _MM_FROUND_TO_NEG_INF | _MM_FROUND_NO_EXC) /// VROUNDPD ymm, ymm/m256, imm8(9) /// </summary> public static Vector256<double> RoundToNegativeInfinity(Vector256<double> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_round_pd (__m256d a, _MM_FROUND_TO_POS_INF | _MM_FROUND_NO_EXC) /// VROUNDPD ymm, ymm/m256, imm8(10) /// </summary> public static Vector256<double> RoundToPositiveInfinity(Vector256<double> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_round_pd (__m256d a, _MM_FROUND_TO_ZERO | _MM_FROUND_NO_EXC) /// VROUNDPD ymm, ymm/m256, imm8(11) /// </summary> public static Vector256<double> RoundToZero(Vector256<double> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_round_pd (__m256d a, _MM_FROUND_CUR_DIRECTION) /// VROUNDPD ymm, ymm/m256, imm8(4) /// </summary> public static Vector256<double> RoundCurrentDirection(Vector256<double> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_shuffle_ps (__m256 a, __m256 b, const int imm8) /// VSHUFPS ymm, ymm, ymm/m256, imm8 /// </summary> public static Vector256<float> Shuffle(Vector256<float> value, Vector256<float> right, byte control) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_shuffle_pd (__m256d a, __m256d b, const int imm8) /// VSHUFPD ymm, ymm, ymm/m256, imm8 /// </summary> public static Vector256<double> Shuffle(Vector256<double> value, Vector256<double> right, byte control) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_sqrt_ps (__m256 a) /// VSQRTPS ymm, ymm/m256 /// </summary> public static Vector256<float> Sqrt(Vector256<float> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_sqrt_pd (__m256d a) /// VSQRTPD ymm, ymm/m256 /// </summary> public static Vector256<double> Sqrt(Vector256<double> value) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_store_si256 (__m256i * mem_addr, __m256i a) /// MOVDQA m256, ymm /// </summary> public static unsafe void StoreAligned(sbyte* address, Vector256<sbyte> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_store_si256 (__m256i * mem_addr, __m256i a) /// MOVDQA m256, ymm /// </summary> public static unsafe void StoreAligned(byte* address, Vector256<byte> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_store_si256 (__m256i * mem_addr, __m256i a) /// MOVDQA m256, ymm /// </summary> public static unsafe void StoreAligned(short* address, Vector256<short> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_store_si256 (__m256i * mem_addr, __m256i a) /// MOVDQA m256, ymm /// </summary> public static unsafe void StoreAligned(ushort* address, Vector256<ushort> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_store_si256 (__m256i * mem_addr, __m256i a) /// MOVDQA m256, ymm /// </summary> public static unsafe void StoreAligned(int* address, Vector256<int> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_store_si256 (__m256i * mem_addr, __m256i a) /// MOVDQA m256, ymm /// </summary> public static unsafe void StoreAligned(uint* address, Vector256<uint> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_store_si256 (__m256i * mem_addr, __m256i a) /// MOVDQA m256, ymm /// </summary> public static unsafe void StoreAligned(long* address, Vector256<long> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_store_si256 (__m256i * mem_addr, __m256i a) /// MOVDQA m256, ymm /// </summary> public static unsafe void StoreAligned(ulong* address, Vector256<ulong> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_store_ps (float * mem_addr, __m256 a) /// VMOVAPS m256, ymm /// </summary> public static unsafe void StoreAligned(float* address, Vector256<float> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_store_pd (double * mem_addr, __m256d a) /// VMOVAPD m256, ymm /// </summary> public static unsafe void StoreAligned(double* address, Vector256<double> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_stream_si256 (__m256i * mem_addr, __m256i a) /// VMOVNTDQ m256, ymm /// </summary> public static unsafe void StoreAlignedNonTemporal(sbyte* address, Vector256<sbyte> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_stream_si256 (__m256i * mem_addr, __m256i a) /// VMOVNTDQ m256, ymm /// </summary> public static unsafe void StoreAlignedNonTemporal(byte* address, Vector256<byte> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_stream_si256 (__m256i * mem_addr, __m256i a) /// VMOVNTDQ m256, ymm /// </summary> public static unsafe void StoreAlignedNonTemporal(short* address, Vector256<short> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_stream_si256 (__m256i * mem_addr, __m256i a) /// VMOVNTDQ m256, ymm /// </summary> public static unsafe void StoreAlignedNonTemporal(ushort* address, Vector256<ushort> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_stream_si256 (__m256i * mem_addr, __m256i a) /// VMOVNTDQ m256, ymm /// </summary> public static unsafe void StoreAlignedNonTemporal(int* address, Vector256<int> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_stream_si256 (__m256i * mem_addr, __m256i a) /// VMOVNTDQ m256, ymm /// </summary> public static unsafe void StoreAlignedNonTemporal(uint* address, Vector256<uint> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_stream_si256 (__m256i * mem_addr, __m256i a) /// VMOVNTDQ m256, ymm /// </summary> public static unsafe void StoreAlignedNonTemporal(long* address, Vector256<long> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_stream_si256 (__m256i * mem_addr, __m256i a) /// VMOVNTDQ m256, ymm /// </summary> public static unsafe void StoreAlignedNonTemporal(ulong* address, Vector256<ulong> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_stream_ps (float * mem_addr, __m256 a) /// MOVNTPS m256, ymm /// </summary> public static unsafe void StoreAlignedNonTemporal(float* address, Vector256<float> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_stream_pd (double * mem_addr, __m256d a) /// MOVNTPD m256, ymm /// </summary> public static unsafe void StoreAlignedNonTemporal(double* address, Vector256<double> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_storeu_si256 (__m256i * mem_addr, __m256i a) /// MOVDQU m256, ymm /// </summary> public static unsafe void Store(sbyte* address, Vector256<sbyte> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_storeu_si256 (__m256i * mem_addr, __m256i a) /// MOVDQU m256, ymm /// </summary> public static unsafe void Store(byte* address, Vector256<byte> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_storeu_si256 (__m256i * mem_addr, __m256i a) /// MOVDQU m256, ymm /// </summary> public static unsafe void Store(short* address, Vector256<short> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_storeu_si256 (__m256i * mem_addr, __m256i a) /// MOVDQU m256, ymm /// </summary> public static unsafe void Store(ushort* address, Vector256<ushort> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_storeu_si256 (__m256i * mem_addr, __m256i a) /// MOVDQU m256, ymm /// </summary> public static unsafe void Store(int* address, Vector256<int> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_storeu_si256 (__m256i * mem_addr, __m256i a) /// MOVDQU m256, ymm /// </summary> public static unsafe void Store(uint* address, Vector256<uint> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_storeu_si256 (__m256i * mem_addr, __m256i a) /// MOVDQU m256, ymm /// </summary> public static unsafe void Store(long* address, Vector256<long> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_storeu_si256 (__m256i * mem_addr, __m256i a) /// MOVDQU m256, ymm /// </summary> public static unsafe void Store(ulong* address, Vector256<ulong> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_storeu_ps (float * mem_addr, __m256 a) /// MOVUPS m256, ymm /// </summary> public static unsafe void Store(float* address, Vector256<float> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_storeu_pd (double * mem_addr, __m256d a) /// MOVUPD m256, ymm /// </summary> public static unsafe void Store(double* address, Vector256<double> source) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_sub_ps (__m256 a, __m256 b) /// VSUBPS ymm, ymm, ymm/m256 /// </summary> public static Vector256<float> Subtract(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_sub_pd (__m256d a, __m256d b) /// VSUBPD ymm, ymm, ymm/m256 /// </summary> public static Vector256<double> Subtract(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm_testc_ps (__m128 a, __m128 b) /// VTESTPS xmm, xmm/m128 /// </summary> public static bool TestC(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm_testc_pd (__m128d a, __m128d b) /// VTESTPD xmm, xmm/m128 /// </summary> public static bool TestC(Vector128<double> left, Vector128<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testc_si256 (__m256i a, __m256i b) /// VPTEST ymm, ymm/m256 /// </summary> public static bool TestC(Vector256<byte> left, Vector256<byte> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testc_si256 (__m256i a, __m256i b) /// VPTEST ymm, ymm/m256 /// </summary> public static bool TestC(Vector256<sbyte> left, Vector256<sbyte> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testc_si256 (__m256i a, __m256i b) /// VPTEST ymm, ymm/m256 /// </summary> public static bool TestC(Vector256<short> left, Vector256<short> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testc_si256 (__m256i a, __m256i b) /// VPTEST ymm, ymm/m256 /// </summary> public static bool TestC(Vector256<ushort> left, Vector256<ushort> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testc_si256 (__m256i a, __m256i b) /// VPTEST ymm, ymm/m256 /// </summary> public static bool TestC(Vector256<int> left, Vector256<int> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testc_si256 (__m256i a, __m256i b) /// VPTEST ymm, ymm/m256 /// </summary> public static bool TestC(Vector256<uint> left, Vector256<uint> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testc_si256 (__m256i a, __m256i b) /// VPTEST ymm, ymm/m256 /// </summary> public static bool TestC(Vector256<long> left, Vector256<long> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testc_si256 (__m256i a, __m256i b) /// VPTEST ymm, ymm/m256 /// </summary> public static bool TestC(Vector256<ulong> left, Vector256<ulong> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testc_ps (__m256 a, __m256 b) /// VTESTPS ymm, ymm/m256 /// </summary> public static bool TestC(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testc_pd (__m256d a, __m256d b) /// VTESTPS ymm, ymm/m256 /// </summary> public static bool TestC(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm_testnzc_ps (__m128 a, __m128 b) /// VTESTPS xmm, xmm/m128 /// </summary> public static bool TestNotZAndNotC(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm_testnzc_pd (__m128d a, __m128d b) /// VTESTPD xmm, xmm/m128 /// </summary> public static bool TestNotZAndNotC(Vector128<double> left, Vector128<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testnzc_si256 (__m256i a, __m256i b) /// VPTEST ymm, ymm/m256 /// </summary> public static bool TestNotZAndNotC(Vector256<byte> left, Vector256<byte> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testnzc_si256 (__m256i a, __m256i b) /// VPTEST ymm, ymm/m256 /// </summary> public static bool TestNotZAndNotC(Vector256<sbyte> left, Vector256<sbyte> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testnzc_si256 (__m256i a, __m256i b) /// VPTEST ymm, ymm/m256 /// </summary> public static bool TestNotZAndNotC(Vector256<short> left, Vector256<short> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testnzc_si256 (__m256i a, __m256i b) /// VPTEST ymm, ymm/m256 /// </summary> public static bool TestNotZAndNotC(Vector256<ushort> left, Vector256<ushort> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testnzc_si256 (__m256i a, __m256i b) /// VPTEST ymm, ymm/m256 /// </summary> public static bool TestNotZAndNotC(Vector256<int> left, Vector256<int> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testnzc_si256 (__m256i a, __m256i b) /// VPTEST ymm, ymm/m256 /// </summary> public static bool TestNotZAndNotC(Vector256<uint> left, Vector256<uint> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testnzc_si256 (__m256i a, __m256i b) /// VPTEST ymm, ymm/m256 /// </summary> public static bool TestNotZAndNotC(Vector256<long> left, Vector256<long> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testnzc_si256 (__m256i a, __m256i b) /// VPTEST ymm, ymm/m256 /// </summary> public static bool TestNotZAndNotC(Vector256<ulong> left, Vector256<ulong> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testnzc_ps (__m256 a, __m256 b) /// VTESTPS ymm, ymm/m256 /// </summary> public static bool TestNotZAndNotC(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testnzc_pd (__m256d a, __m256d b) /// VTESTPD ymm, ymm/m256 /// </summary> public static bool TestNotZAndNotC(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm_testz_ps (__m128 a, __m128 b) /// VTESTPS xmm, xmm/m128 /// </summary> public static bool TestZ(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm_testz_pd (__m128d a, __m128d b) /// VTESTPD xmm, xmm/m128 /// </summary> public static bool TestZ(Vector128<double> left, Vector128<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testz_si256 (__m256i a, __m256i b) /// VPTEST ymm, ymm/m256 /// </summary> public static bool TestZ(Vector256<byte> left, Vector256<byte> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testz_si256 (__m256i a, __m256i b) /// VPTEST ymm, ymm/m256 /// </summary> public static bool TestZ(Vector256<sbyte> left, Vector256<sbyte> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testz_si256 (__m256i a, __m256i b) /// VPTEST ymm, ymm/m256 /// </summary> public static bool TestZ(Vector256<short> left, Vector256<short> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testz_si256 (__m256i a, __m256i b) /// VPTEST ymm, ymm/m256 /// </summary> public static bool TestZ(Vector256<ushort> left, Vector256<ushort> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testz_si256 (__m256i a, __m256i b) /// VPTEST ymm, ymm/m256 /// </summary> public static bool TestZ(Vector256<int> left, Vector256<int> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testz_si256 (__m256i a, __m256i b) /// VPTEST ymm, ymm/m256 /// </summary> public static bool TestZ(Vector256<uint> left, Vector256<uint> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testz_si256 (__m256i a, __m256i b) /// VPTEST ymm, ymm/m256 /// </summary> public static bool TestZ(Vector256<long> left, Vector256<long> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testz_si256 (__m256i a, __m256i b) /// VPTEST ymm, ymm/m256 /// </summary> public static bool TestZ(Vector256<ulong> left, Vector256<ulong> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testz_ps (__m256 a, __m256 b) /// VTESTPS ymm, ymm/m256 /// </summary> public static bool TestZ(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testz_pd (__m256d a, __m256d b) /// VTESTPD ymm, ymm/m256 /// </summary> public static bool TestZ(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_unpackhi_ps (__m256 a, __m256 b) /// VUNPCKHPS ymm, ymm, ymm/m256 /// </summary> public static Vector256<float> UnpackHigh(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_unpackhi_pd (__m256d a, __m256d b) /// VUNPCKHPD ymm, ymm, ymm/m256 /// </summary> public static Vector256<double> UnpackHigh(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_unpacklo_ps (__m256 a, __m256 b) /// VUNPCKLPS ymm, ymm, ymm/m256 /// </summary> public static Vector256<float> UnpackLow(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_unpacklo_pd (__m256d a, __m256d b) /// VUNPCKLPD ymm, ymm, ymm/m256 /// </summary> public static Vector256<double> UnpackLow(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_xor_ps (__m256 a, __m256 b) /// VXORPS ymm, ymm, ymm/m256 /// </summary> public static Vector256<float> Xor(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_xor_pd (__m256d a, __m256d b) /// VXORPS ymm, ymm, ymm/m256 /// </summary> public static Vector256<double> Xor(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } } }
// 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.Intrinsics; namespace System.Runtime.Intrinsics.X86 { /// <summary> /// This class provides access to Intel AVX hardware instructions via intrinsics /// </summary> [CLSCompliant(false)] public abstract class Avx : Sse42 { internal Avx() { } public static new bool IsSupported { [Intrinsic] get { return false; } } public new abstract class X64 : Sse42.X64 { internal X64() { } public static new bool IsSupported { [Intrinsic] get { return false; } } } /// <summary> /// __m256 _mm256_add_ps (__m256 a, __m256 b) /// VADDPS ymm, ymm, ymm/m256 /// </summary> public static Vector256<float> Add(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_add_pd (__m256d a, __m256d b) /// VADDPD ymm, ymm, ymm/m256 /// </summary> public static Vector256<double> Add(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_addsub_ps (__m256 a, __m256 b) /// VADDSUBPS ymm, ymm, ymm/m256 /// </summary> public static Vector256<float> AddSubtract(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_addsub_pd (__m256d a, __m256d b) /// VADDSUBPD ymm, ymm, ymm/m256 /// </summary> public static Vector256<double> AddSubtract(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_and_ps (__m256 a, __m256 b) /// VANDPS ymm, ymm, ymm/m256 /// </summary> public static Vector256<float> And(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_and_pd (__m256d a, __m256d b) /// VANDPD ymm, ymm, ymm/m256 /// </summary> public static Vector256<double> And(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_andnot_ps (__m256 a, __m256 b) /// VANDNPS ymm, ymm, ymm/m256 /// </summary> public static Vector256<float> AndNot(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_andnot_pd (__m256d a, __m256d b) /// VANDNPD ymm, ymm, ymm/m256 /// </summary> public static Vector256<double> AndNot(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_blend_ps (__m256 a, __m256 b, const int imm8) /// VBLENDPS ymm, ymm, ymm/m256, imm8 /// </summary> public static Vector256<float> Blend(Vector256<float> left, Vector256<float> right, byte control) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_blend_pd (__m256d a, __m256d b, const int imm8) /// VBLENDPD ymm, ymm, ymm/m256, imm8 /// </summary> public static Vector256<double> Blend(Vector256<double> left, Vector256<double> right, byte control) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_blendv_ps (__m256 a, __m256 b, __m256 mask) /// VBLENDVPS ymm, ymm, ymm/m256, ymm /// </summary> public static Vector256<float> BlendVariable(Vector256<float> left, Vector256<float> right, Vector256<float> mask) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_blendv_pd (__m256d a, __m256d b, __m256d mask) /// VBLENDVPD ymm, ymm, ymm/m256, ymm /// </summary> public static Vector256<double> BlendVariable(Vector256<double> left, Vector256<double> right, Vector256<double> mask) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_broadcast_ss (float const * mem_addr) /// VBROADCASTSS xmm, m32 /// </summary> public static unsafe Vector128<float> BroadcastScalarToVector128(float* source) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_broadcast_ss (float const * mem_addr) /// VBROADCASTSS ymm, m32 /// </summary> public static unsafe Vector256<float> BroadcastScalarToVector256(float* source) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_broadcast_sd (double const * mem_addr) /// VBROADCASTSD ymm, m64 /// </summary> public static unsafe Vector256<double> BroadcastScalarToVector256(double* source) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_broadcast_ps (__m128 const * mem_addr) /// VBROADCASTF128, ymm, m128 /// </summary> public static unsafe Vector256<float> BroadcastVector128ToVector256(float* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_broadcast_pd (__m128d const * mem_addr) /// VBROADCASTF128, ymm, m128 /// </summary> public static unsafe Vector256<double> BroadcastVector128ToVector256(double* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_ceil_ps (__m256 a) /// VROUNDPS ymm, ymm/m256, imm8(10) /// </summary> public static Vector256<float> Ceiling(Vector256<float> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_ceil_pd (__m256d a) /// VROUNDPD ymm, ymm/m256, imm8(10) /// </summary> public static Vector256<double> Ceiling(Vector256<double> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_cmp_ps (__m128 a, __m128 b, const int imm8) /// VCMPPS xmm, xmm, xmm/m128, imm8 /// </summary> public static Vector128<float> Compare(Vector128<float> left, Vector128<float> right, FloatComparisonMode mode) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128d _mm_cmp_pd (__m128d a, __m128d b, const int imm8) /// VCMPPD xmm, xmm, xmm/m128, imm8 /// </summary> public static Vector128<double> Compare(Vector128<double> left, Vector128<double> right, FloatComparisonMode mode) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_cmp_ps (__m256 a, __m256 b, const int imm8) /// VCMPPS ymm, ymm, ymm/m256, imm8 /// </summary> public static Vector256<float> Compare(Vector256<float> left, Vector256<float> right, FloatComparisonMode mode) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_cmp_pd (__m256d a, __m256d b, const int imm8) /// VCMPPD ymm, ymm, ymm/m256, imm8 /// </summary> public static Vector256<double> Compare(Vector256<double> left, Vector256<double> right, FloatComparisonMode mode) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_cmpeq_ps (__m256 a, __m256 b) /// CMPPS ymm, ymm/m256, imm8(0) /// The above native signature does not exist. We provide this additional overload for completeness. /// </summary> public static Vector256<float> CompareEqual(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_cmpeq_pd (__m256d a, __m256d b) /// CMPPD ymm, ymm/m256, imm8(0) /// The above native signature does not exist. We provide this additional overload for completeness. /// </summary> public static Vector256<double> CompareEqual(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_cmpgt_ps (__m256 a, __m256 b) /// CMPPS ymm, ymm/m256, imm8(14) /// The above native signature does not exist. We provide this additional overload for completeness. /// </summary> public static Vector256<float> CompareGreaterThan(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_cmpgt_pd (__m256d a, __m256d b) /// CMPPD ymm, ymm/m256, imm8(14) /// The above native signature does not exist. We provide this additional overload for completeness. /// </summary> public static Vector256<double> CompareGreaterThan(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_cmpge_ps (__m256 a, __m256 b) /// CMPPS ymm, ymm/m256, imm8(13) /// The above native signature does not exist. We provide this additional overload for completeness. /// </summary> public static Vector256<float> CompareGreaterThanOrEqual(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_cmpge_pd (__m256d a, __m256d b) /// CMPPD ymm, ymm/m256, imm8(13) /// The above native signature does not exist. We provide this additional overload for completeness. /// </summary> public static Vector256<double> CompareGreaterThanOrEqual(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_cmplt_ps (__m256 a, __m256 b) /// CMPPS ymm, ymm/m256, imm8(1) /// The above native signature does not exist. We provide this additional overload for completeness. /// </summary> public static Vector256<float> CompareLessThan(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_cmplt_pd (__m256d a, __m256d b) /// CMPPD ymm, ymm/m256, imm8(1) /// The above native signature does not exist. We provide this additional overload for completeness. /// </summary> public static Vector256<double> CompareLessThan(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_cmple_ps (__m256 a, __m256 b) /// CMPPS ymm, ymm/m256, imm8(2) /// The above native signature does not exist. We provide this additional overload for completeness. /// </summary> public static Vector256<float> CompareLessThanOrEqual(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_cmple_pd (__m256d a, __m256d b) /// CMPPD ymm, ymm/m256, imm8(2) /// The above native signature does not exist. We provide this additional overload for completeness. /// </summary> public static Vector256<double> CompareLessThanOrEqual(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_cmpneq_ps (__m256 a, __m256 b) /// CMPPS ymm, ymm/m256, imm8(4) /// The above native signature does not exist. We provide this additional overload for completeness. /// </summary> public static Vector256<float> CompareNotEqual(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_cmpneq_pd (__m256d a, __m256d b) /// CMPPD ymm, ymm/m256, imm8(4) /// The above native signature does not exist. We provide this additional overload for completeness. /// </summary> public static Vector256<double> CompareNotEqual(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_cmpngt_ps (__m256 a, __m256 b) /// CMPPS ymm, ymm/m256, imm8(10) /// The above native signature does not exist. We provide this additional overload for completeness. /// </summary> public static Vector256<float> CompareNotGreaterThan(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_cmpngt_pd (__m256d a, __m256d b) /// CMPPD ymm, ymm/m256, imm8(10) /// The above native signature does not exist. We provide this additional overload for completeness. /// </summary> public static Vector256<double> CompareNotGreaterThan(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_cmpnge_ps (__m256 a, __m256 b) /// CMPPS ymm, ymm/m256, imm8(9) /// The above native signature does not exist. We provide this additional overload for completeness. /// </summary> public static Vector256<float> CompareNotGreaterThanOrEqual(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_cmpnge_pd (__m256d a, __m256d b) /// CMPPD ymm, ymm/m256, imm8(9) /// The above native signature does not exist. We provide this additional overload for completeness. /// </summary> public static Vector256<double> CompareNotGreaterThanOrEqual(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_cmpnlt_ps (__m256 a, __m256 b) /// CMPPS ymm, ymm/m256, imm8(5) /// The above native signature does not exist. We provide this additional overload for completeness. /// </summary> public static Vector256<float> CompareNotLessThan(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_cmpnlt_pd (__m256d a, __m256d b) /// CMPPD ymm, ymm/m256, imm8(5) /// The above native signature does not exist. We provide this additional overload for completeness. /// </summary> public static Vector256<double> CompareNotLessThan(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_cmpnle_ps (__m256 a, __m256 b) /// CMPPS ymm, ymm/m256, imm8(6) /// The above native signature does not exist. We provide this additional overload for completeness. /// </summary> public static Vector256<float> CompareNotLessThanOrEqual(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_cmpnle_pd (__m256d a, __m256d b) /// CMPPD ymm, ymm/m256, imm8(6) /// The above native signature does not exist. We provide this additional overload for completeness. /// </summary> public static Vector256<double> CompareNotLessThanOrEqual(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_cmpord_ps (__m256 a, __m256 b) /// CMPPS ymm, ymm/m256, imm8(7) /// The above native signature does not exist. We provide this additional overload for completeness. /// </summary> public static Vector256<float> CompareOrdered(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_cmpord_pd (__m256d a, __m256d b) /// CMPPD ymm, ymm/m256, imm8(7) /// The above native signature does not exist. We provide this additional overload for completeness. /// </summary> public static Vector256<double> CompareOrdered(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128d _mm_cmp_sd (__m128d a, __m128d b, const int imm8) /// VCMPSS xmm, xmm, xmm/m32, imm8 /// </summary> public static Vector128<double> CompareScalar(Vector128<double> left, Vector128<double> right, FloatComparisonMode mode) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_cmp_ss (__m128 a, __m128 b, const int imm8) /// VCMPSD xmm, xmm, xmm/m64, imm8 /// </summary> public static Vector128<float> CompareScalar(Vector128<float> left, Vector128<float> right, FloatComparisonMode mode) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_cmpunord_ps (__m256 a, __m256 b) /// CMPPS ymm, ymm/m256, imm8(3) /// The above native signature does not exist. We provide this additional overload for completeness. /// </summary> public static Vector256<float> CompareUnordered(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_cmpunord_pd (__m256d a, __m256d b) /// CMPPD ymm, ymm/m256, imm8(3) /// The above native signature does not exist. We provide this additional overload for completeness. /// </summary> public static Vector256<double> CompareUnordered(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128i _mm256_cvtpd_epi32 (__m256d a) /// VCVTPD2DQ xmm, ymm/m256 /// </summary> public static Vector128<int> ConvertToVector128Int32(Vector256<double> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm256_cvtpd_ps (__m256d a) /// VCVTPD2PS xmm, ymm/m256 /// </summary> public static Vector128<float> ConvertToVector128Single(Vector256<double> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_cvtps_epi32 (__m256 a) /// VCVTPS2DQ ymm, ymm/m256 /// </summary> public static Vector256<int> ConvertToVector256Int32(Vector256<float> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_cvtepi32_ps (__m256i a) /// VCVTDQ2PS ymm, ymm/m256 /// </summary> public static Vector256<float> ConvertToVector256Single(Vector256<int> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_cvtps_pd (__m128 a) /// VCVTPS2PD ymm, xmm/m128 /// </summary> public static Vector256<double> ConvertToVector256Double(Vector128<float> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_cvtepi32_pd (__m128i a) /// VCVTDQ2PD ymm, xmm/m128 /// </summary> public static Vector256<double> ConvertToVector256Double(Vector128<int> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128i _mm256_cvttpd_epi32 (__m256d a) /// VCVTTPD2DQ xmm, ymm/m256 /// </summary> public static Vector128<int> ConvertToVector128Int32WithTruncation(Vector256<double> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_cvttps_epi32 (__m256 a) /// VCVTTPS2DQ ymm, ymm/m256 /// </summary> public static Vector256<int> ConvertToVector256Int32WithTruncation(Vector256<float> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_div_ps (__m256 a, __m256 b) /// VDIVPS ymm, ymm, ymm/m256 /// </summary> public static Vector256<float> Divide(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_div_pd (__m256d a, __m256d b) /// VDIVPD ymm, ymm, ymm/m256 /// </summary> public static Vector256<double> Divide(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_dp_ps (__m256 a, __m256 b, const int imm8) /// VDPPS ymm, ymm, ymm/m256, imm8 /// </summary> public static Vector256<float> DotProduct(Vector256<float> left, Vector256<float> right, byte control) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_moveldup_ps (__m256 a) /// VMOVSLDUP ymm, ymm/m256 /// </summary> public static Vector256<float> DuplicateEvenIndexed(Vector256<float> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_movedup_pd (__m256d a) /// VMOVDDUP ymm, ymm/m256 /// </summary> public static Vector256<double> DuplicateEvenIndexed(Vector256<double> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_movehdup_ps (__m256 a) /// VMOVSHDUP ymm, ymm/m256 /// </summary> public static Vector256<float> DuplicateOddIndexed(Vector256<float> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128i _mm256_extractf128_si256 (__m256i a, const int imm8) /// VEXTRACTF128 xmm/m128, ymm, imm8 /// </summary> public static Vector128<byte> ExtractVector128(Vector256<byte> value, byte index) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128i _mm256_extractf128_si256 (__m256i a, const int imm8) /// VEXTRACTF128 xmm/m128, ymm, imm8 /// </summary> public static Vector128<sbyte> ExtractVector128(Vector256<sbyte> value, byte index) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128i _mm256_extractf128_si256 (__m256i a, const int imm8) /// VEXTRACTF128 xmm/m128, ymm, imm8 /// </summary> public static Vector128<short> ExtractVector128(Vector256<short> value, byte index) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128i _mm256_extractf128_si256 (__m256i a, const int imm8) /// VEXTRACTF128 xmm/m128, ymm, imm8 /// </summary> public static Vector128<ushort> ExtractVector128(Vector256<ushort> value, byte index) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128i _mm256_extractf128_si256 (__m256i a, const int imm8) /// VEXTRACTF128 xmm/m128, ymm, imm8 /// </summary> public static Vector128<int> ExtractVector128(Vector256<int> value, byte index) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128i _mm256_extractf128_si256 (__m256i a, const int imm8) /// VEXTRACTF128 xmm/m128, ymm, imm8 /// </summary> public static Vector128<uint> ExtractVector128(Vector256<uint> value, byte index) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128i _mm256_extractf128_si256 (__m256i a, const int imm8) /// VEXTRACTF128 xmm/m128, ymm, imm8 /// </summary> public static Vector128<long> ExtractVector128(Vector256<long> value, byte index) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128i _mm256_extractf128_si256 (__m256i a, const int imm8) /// VEXTRACTF128 xmm/m128, ymm, imm8 /// </summary> public static Vector128<ulong> ExtractVector128(Vector256<ulong> value, byte index) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm256_extractf128_ps (__m256 a, const int imm8) /// VEXTRACTF128 xmm/m128, ymm, imm8 /// </summary> public static Vector128<float> ExtractVector128(Vector256<float> value, byte index) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128d _mm256_extractf128_pd (__m256d a, const int imm8) /// VEXTRACTF128 xmm/m128, ymm, imm8 /// </summary> public static Vector128<double> ExtractVector128(Vector256<double> value, byte index) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_floor_ps (__m256 a) /// VROUNDPS ymm, ymm/m256, imm8(9) /// </summary> public static Vector256<float> Floor(Vector256<float> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_floor_pd (__m256d a) /// VROUNDPS ymm, ymm/m256, imm8(9) /// </summary> public static Vector256<double> Floor(Vector256<double> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_hadd_ps (__m256 a, __m256 b) /// VHADDPS ymm, ymm, ymm/m256 /// </summary> public static Vector256<float> HorizontalAdd(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_hadd_pd (__m256d a, __m256d b) /// VHADDPD ymm, ymm, ymm/m256 /// </summary> public static Vector256<double> HorizontalAdd(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_hsub_ps (__m256 a, __m256 b) /// VHSUBPS ymm, ymm, ymm/m256 /// </summary> public static Vector256<float> HorizontalSubtract(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_hsub_pd (__m256d a, __m256d b) /// VHSUBPD ymm, ymm, ymm/m256 /// </summary> public static Vector256<double> HorizontalSubtract(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_insertf128_si256 (__m256i a, __m128i b, int imm8) /// VINSERTF128 ymm, ymm, xmm/m128, imm8 /// </summary> public static Vector256<byte> InsertVector128(Vector256<byte> value, Vector128<byte> data, byte index) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_insertf128_si256 (__m256i a, __m128i b, int imm8) /// VINSERTF128 ymm, ymm, xmm/m128, imm8 /// </summary> public static Vector256<sbyte> InsertVector128(Vector256<sbyte> value, Vector128<sbyte> data, byte index) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_insertf128_si256 (__m256i a, __m128i b, int imm8) /// VINSERTF128 ymm, ymm, xmm/m128, imm8 /// </summary> public static Vector256<short> InsertVector128(Vector256<short> value, Vector128<short> data, byte index) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_insertf128_si256 (__m256i a, __m128i b, int imm8) /// VINSERTF128 ymm, ymm, xmm/m128, imm8 /// </summary> public static Vector256<ushort> InsertVector128(Vector256<ushort> value, Vector128<ushort> data, byte index) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_insertf128_si256 (__m256i a, __m128i b, int imm8) /// VINSERTF128 ymm, ymm, xmm/m128, imm8 /// </summary> public static Vector256<int> InsertVector128(Vector256<int> value, Vector128<int> data, byte index) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_insertf128_si256 (__m256i a, __m128i b, int imm8) /// VINSERTF128 ymm, ymm, xmm/m128, imm8 /// </summary> public static Vector256<uint> InsertVector128(Vector256<uint> value, Vector128<uint> data, byte index) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_insertf128_si256 (__m256i a, __m128i b, int imm8) /// VINSERTF128 ymm, ymm, xmm/m128, imm8 /// </summary> public static Vector256<long> InsertVector128(Vector256<long> value, Vector128<long> data, byte index) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_insertf128_si256 (__m256i a, __m128i b, int imm8) /// VINSERTF128 ymm, ymm, xmm/m128, imm8 /// </summary> public static Vector256<ulong> InsertVector128(Vector256<ulong> value, Vector128<ulong> data, byte index) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_insertf128_ps (__m256 a, __m128 b, int imm8) /// VINSERTF128 ymm, ymm, xmm/m128, imm8 /// </summary> public static Vector256<float> InsertVector128(Vector256<float> value, Vector128<float> data, byte index) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_insertf128_pd (__m256d a, __m128d b, int imm8) /// VINSERTF128 ymm, ymm, xmm/m128, imm8 /// </summary> public static Vector256<double> InsertVector128(Vector256<double> value, Vector128<double> data, byte index) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_loadu_si256 (__m256i const * mem_addr) /// VMOVDQU ymm, m256 /// </summary> public static unsafe Vector256<sbyte> LoadVector256(sbyte* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_loadu_si256 (__m256i const * mem_addr) /// VMOVDQU ymm, m256 /// </summary> public static unsafe Vector256<byte> LoadVector256(byte* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_loadu_si256 (__m256i const * mem_addr) /// VMOVDQU ymm, m256 /// </summary> public static unsafe Vector256<short> LoadVector256(short* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_loadu_si256 (__m256i const * mem_addr) /// VMOVDQU ymm, m256 /// </summary> public static unsafe Vector256<ushort> LoadVector256(ushort* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_loadu_si256 (__m256i const * mem_addr) /// VMOVDQU ymm, m256 /// </summary> public static unsafe Vector256<int> LoadVector256(int* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_loadu_si256 (__m256i const * mem_addr) /// VMOVDQU ymm, m256 /// </summary> public static unsafe Vector256<uint> LoadVector256(uint* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_loadu_si256 (__m256i const * mem_addr) /// VMOVDQU ymm, m256 /// </summary> public static unsafe Vector256<long> LoadVector256(long* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_loadu_si256 (__m256i const * mem_addr) /// VMOVDQU ymm, m256 /// </summary> public static unsafe Vector256<ulong> LoadVector256(ulong* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_loadu_ps (float const * mem_addr) /// VMOVUPS ymm, ymm/m256 /// </summary> public static unsafe Vector256<float> LoadVector256(float* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_loadu_pd (double const * mem_addr) /// VMOVUPD ymm, ymm/m256 /// </summary> public static unsafe Vector256<double> LoadVector256(double* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_load_si256 (__m256i const * mem_addr) /// VMOVDQA ymm, m256 /// </summary> public static unsafe Vector256<sbyte> LoadAlignedVector256(sbyte* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_load_si256 (__m256i const * mem_addr) /// VMOVDQA ymm, m256 /// </summary> public static unsafe Vector256<byte> LoadAlignedVector256(byte* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_load_si256 (__m256i const * mem_addr) /// VMOVDQA ymm, m256 /// </summary> public static unsafe Vector256<short> LoadAlignedVector256(short* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_load_si256 (__m256i const * mem_addr) /// VMOVDQA ymm, m256 /// </summary> public static unsafe Vector256<ushort> LoadAlignedVector256(ushort* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_load_si256 (__m256i const * mem_addr) /// VMOVDQA ymm, m256 /// </summary> public static unsafe Vector256<int> LoadAlignedVector256(int* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_load_si256 (__m256i const * mem_addr) /// VMOVDQA ymm, m256 /// </summary> public static unsafe Vector256<uint> LoadAlignedVector256(uint* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_load_si256 (__m256i const * mem_addr) /// VMOVDQA ymm, m256 /// </summary> public static unsafe Vector256<long> LoadAlignedVector256(long* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_load_si256 (__m256i const * mem_addr) /// VMOVDQA ymm, m256 /// </summary> public static unsafe Vector256<ulong> LoadAlignedVector256(ulong* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_load_ps (float const * mem_addr) /// VMOVAPS ymm, ymm/m256 /// </summary> public static unsafe Vector256<float> LoadAlignedVector256(float* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_load_pd (double const * mem_addr) /// VMOVAPD ymm, ymm/m256 /// </summary> public static unsafe Vector256<double> LoadAlignedVector256(double* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_lddqu_si256 (__m256i const * mem_addr) /// VLDDQU ymm, m256 /// </summary> public static unsafe Vector256<sbyte> LoadDquVector256(sbyte* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_lddqu_si256 (__m256i const * mem_addr) /// VLDDQU ymm, m256 /// </summary> public static unsafe Vector256<byte> LoadDquVector256(byte* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_lddqu_si256 (__m256i const * mem_addr) /// VLDDQU ymm, m256 /// </summary> public static unsafe Vector256<short> LoadDquVector256(short* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_lddqu_si256 (__m256i const * mem_addr) /// VLDDQU ymm, m256 /// </summary> public static unsafe Vector256<ushort> LoadDquVector256(ushort* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_lddqu_si256 (__m256i const * mem_addr) /// VLDDQU ymm, m256 /// </summary> public static unsafe Vector256<int> LoadDquVector256(int* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_lddqu_si256 (__m256i const * mem_addr) /// VLDDQU ymm, m256 /// </summary> public static unsafe Vector256<uint> LoadDquVector256(uint* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_lddqu_si256 (__m256i const * mem_addr) /// VLDDQU ymm, m256 /// </summary> public static unsafe Vector256<long> LoadDquVector256(long* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_lddqu_si256 (__m256i const * mem_addr) /// VLDDQU ymm, m256 /// </summary> public static unsafe Vector256<ulong> LoadDquVector256(ulong* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_maskload_ps (float const * mem_addr, __m128i mask) /// VMASKMOVPS xmm, xmm, m128 /// </summary> public static unsafe Vector128<float> MaskLoad(float* address, Vector128<float> mask) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128d _mm_maskload_pd (double const * mem_addr, __m128i mask) /// VMASKMOVPD xmm, xmm, m128 /// </summary> public static unsafe Vector128<double> MaskLoad(double* address, Vector128<double> mask) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_maskload_ps (float const * mem_addr, __m256i mask) /// VMASKMOVPS ymm, ymm, m256 /// </summary> public static unsafe Vector256<float> MaskLoad(float* address, Vector256<float> mask) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_maskload_pd (double const * mem_addr, __m256i mask) /// VMASKMOVPD ymm, ymm, m256 /// </summary> public static unsafe Vector256<double> MaskLoad(double* address, Vector256<double> mask) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm_maskstore_ps (float * mem_addr, __m128i mask, __m128 a) /// VMASKMOVPS m128, xmm, xmm /// </summary> public static unsafe void MaskStore(float* address, Vector128<float> mask, Vector128<float> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm_maskstore_pd (double * mem_addr, __m128i mask, __m128d a) /// VMASKMOVPD m128, xmm, xmm /// </summary> public static unsafe void MaskStore(double* address, Vector128<double> mask, Vector128<double> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_maskstore_ps (float * mem_addr, __m256i mask, __m256 a) /// VMASKMOVPS m256, ymm, ymm /// </summary> public static unsafe void MaskStore(float* address, Vector256<float> mask, Vector256<float> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_maskstore_pd (double * mem_addr, __m256i mask, __m256d a) /// VMASKMOVPD m256, ymm, ymm /// </summary> public static unsafe void MaskStore(double* address, Vector256<double> mask, Vector256<double> source) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_max_ps (__m256 a, __m256 b) /// VMAXPS ymm, ymm, ymm/m256 /// </summary> public static Vector256<float> Max(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_max_pd (__m256d a, __m256d b) /// VMAXPD ymm, ymm, ymm/m256 /// </summary> public static Vector256<double> Max(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_min_ps (__m256 a, __m256 b) /// VMINPS ymm, ymm, ymm/m256 /// </summary> public static Vector256<float> Min(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_min_pd (__m256d a, __m256d b) /// VMINPD ymm, ymm, ymm/m256 /// </summary> public static Vector256<double> Min(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_movemask_ps (__m256 a) /// VMOVMSKPS reg, ymm /// </summary> public static int MoveMask(Vector256<float> value) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_movemask_pd (__m256d a) /// VMOVMSKPD reg, ymm /// </summary> public static int MoveMask(Vector256<double> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_mul_ps (__m256 a, __m256 b) /// VMULPS ymm, ymm, ymm/m256 /// </summary> public static Vector256<float> Multiply(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_mul_pd (__m256d a, __m256d b) /// VMULPD ymm, ymm, ymm/m256 /// </summary> public static Vector256<double> Multiply(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_or_ps (__m256 a, __m256 b) /// VORPS ymm, ymm, ymm/m256 /// </summary> public static Vector256<float> Or(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_or_pd (__m256d a, __m256d b) /// VORPD ymm, ymm, ymm/m256 /// </summary> public static Vector256<double> Or(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_permute_ps (__m128 a, int imm8) /// VPERMILPS xmm, xmm, imm8 /// </summary> public static Vector128<float> Permute(Vector128<float> value, byte control) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128d _mm_permute_pd (__m128d a, int imm8) /// VPERMILPD xmm, xmm, imm8 /// </summary> public static Vector128<double> Permute(Vector128<double> value, byte control) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_permute_ps (__m256 a, int imm8) /// VPERMILPS ymm, ymm, imm8 /// </summary> public static Vector256<float> Permute(Vector256<float> value, byte control) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_permute_pd (__m256d a, int imm8) /// VPERMILPD ymm, ymm, imm8 /// </summary> public static Vector256<double> Permute(Vector256<double> value, byte control) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_permute2f128_si256 (__m256i a, __m256i b, int imm8) /// VPERM2F128 ymm, ymm, ymm/m256, imm8 /// </summary> public static Vector256<byte> Permute2x128(Vector256<byte> left, Vector256<byte> right, byte control) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_permute2f128_si256 (__m256i a, __m256i b, int imm8) /// VPERM2F128 ymm, ymm, ymm/m256, imm8 /// </summary> public static Vector256<sbyte> Permute2x128(Vector256<sbyte> left, Vector256<sbyte> right, byte control) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_permute2f128_si256 (__m256i a, __m256i b, int imm8) /// VPERM2F128 ymm, ymm, ymm/m256, imm8 /// </summary> public static Vector256<short> Permute2x128(Vector256<short> left, Vector256<short> right, byte control) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_permute2f128_si256 (__m256i a, __m256i b, int imm8) /// VPERM2F128 ymm, ymm, ymm/m256, imm8 /// </summary> public static Vector256<ushort> Permute2x128(Vector256<ushort> left, Vector256<ushort> right, byte control) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_permute2f128_si256 (__m256i a, __m256i b, int imm8) /// VPERM2F128 ymm, ymm, ymm/m256, imm8 /// </summary> public static Vector256<int> Permute2x128(Vector256<int> left, Vector256<int> right, byte control) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_permute2f128_si256 (__m256i a, __m256i b, int imm8) /// VPERM2F128 ymm, ymm, ymm/m256, imm8 /// </summary> public static Vector256<uint> Permute2x128(Vector256<uint> left, Vector256<uint> right, byte control) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_permute2f128_si256 (__m256i a, __m256i b, int imm8) /// VPERM2F128 ymm, ymm, ymm/m256, imm8 /// </summary> public static Vector256<long> Permute2x128(Vector256<long> left, Vector256<long> right, byte control) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256i _mm256_permute2f128_si256 (__m256i a, __m256i b, int imm8) /// VPERM2F128 ymm, ymm, ymm/m256, imm8 /// </summary> public static Vector256<ulong> Permute2x128(Vector256<ulong> left, Vector256<ulong> right, byte control) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_permute2f128_ps (__m256 a, __m256 b, int imm8) /// VPERM2F128 ymm, ymm, ymm/m256, imm8 /// </summary> public static Vector256<float> Permute2x128(Vector256<float> left, Vector256<float> right, byte control) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_permute2f128_pd (__m256d a, __m256d b, int imm8) /// VPERM2F128 ymm, ymm, ymm/m256, imm8 /// </summary> public static Vector256<double> Permute2x128(Vector256<double> left, Vector256<double> right, byte control) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_permutevar_ps (__m128 a, __m128i b) /// VPERMILPS xmm, xmm, xmm/m128 /// </summary> public static Vector128<float> PermuteVar(Vector128<float> left, Vector128<int> control) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128d _mm_permutevar_pd (__m128d a, __m128i b) /// VPERMILPD xmm, xmm, xmm/m128 /// </summary> public static Vector128<double> PermuteVar(Vector128<double> left, Vector128<long> control) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_permutevar_ps (__m256 a, __m256i b) /// VPERMILPS ymm, ymm, ymm/m256 /// </summary> public static Vector256<float> PermuteVar(Vector256<float> left, Vector256<int> control) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_permutevar_pd (__m256d a, __m256i b) /// VPERMILPD ymm, ymm, ymm/m256 /// </summary> public static Vector256<double> PermuteVar(Vector256<double> left, Vector256<long> control) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_rcp_ps (__m256 a) /// VRCPPS ymm, ymm/m256 /// </summary> public static Vector256<float> Reciprocal(Vector256<float> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_rsqrt_ps (__m256 a) /// VRSQRTPS ymm, ymm/m256 /// </summary> public static Vector256<float> ReciprocalSqrt(Vector256<float> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_round_ps (__m256 a, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC) /// VROUNDPS ymm, ymm/m256, imm8(8) /// </summary> public static Vector256<float> RoundToNearestInteger(Vector256<float> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_round_ps (__m256 a, _MM_FROUND_TO_NEG_INF | _MM_FROUND_NO_EXC) /// VROUNDPS ymm, ymm/m256, imm8(9) /// </summary> public static Vector256<float> RoundToNegativeInfinity(Vector256<float> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_round_ps (__m256 a, _MM_FROUND_TO_POS_INF | _MM_FROUND_NO_EXC) /// VROUNDPS ymm, ymm/m256, imm8(10) /// </summary> public static Vector256<float> RoundToPositiveInfinity(Vector256<float> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_round_ps (__m256 a, _MM_FROUND_TO_ZERO | _MM_FROUND_NO_EXC) /// VROUNDPS ymm, ymm/m256, imm8(11) /// </summary> public static Vector256<float> RoundToZero(Vector256<float> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_round_ps (__m256 a, _MM_FROUND_CUR_DIRECTION) /// VROUNDPS ymm, ymm/m256, imm8(4) /// </summary> public static Vector256<float> RoundCurrentDirection(Vector256<float> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_round_pd (__m256d a, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC) /// VROUNDPD ymm, ymm/m256, imm8(8) /// </summary> public static Vector256<double> RoundToNearestInteger(Vector256<double> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_round_pd (__m256d a, _MM_FROUND_TO_NEG_INF | _MM_FROUND_NO_EXC) /// VROUNDPD ymm, ymm/m256, imm8(9) /// </summary> public static Vector256<double> RoundToNegativeInfinity(Vector256<double> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_round_pd (__m256d a, _MM_FROUND_TO_POS_INF | _MM_FROUND_NO_EXC) /// VROUNDPD ymm, ymm/m256, imm8(10) /// </summary> public static Vector256<double> RoundToPositiveInfinity(Vector256<double> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_round_pd (__m256d a, _MM_FROUND_TO_ZERO | _MM_FROUND_NO_EXC) /// VROUNDPD ymm, ymm/m256, imm8(11) /// </summary> public static Vector256<double> RoundToZero(Vector256<double> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_round_pd (__m256d a, _MM_FROUND_CUR_DIRECTION) /// VROUNDPD ymm, ymm/m256, imm8(4) /// </summary> public static Vector256<double> RoundCurrentDirection(Vector256<double> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_shuffle_ps (__m256 a, __m256 b, const int imm8) /// VSHUFPS ymm, ymm, ymm/m256, imm8 /// </summary> public static Vector256<float> Shuffle(Vector256<float> value, Vector256<float> right, byte control) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_shuffle_pd (__m256d a, __m256d b, const int imm8) /// VSHUFPD ymm, ymm, ymm/m256, imm8 /// </summary> public static Vector256<double> Shuffle(Vector256<double> value, Vector256<double> right, byte control) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_sqrt_ps (__m256 a) /// VSQRTPS ymm, ymm/m256 /// </summary> public static Vector256<float> Sqrt(Vector256<float> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_sqrt_pd (__m256d a) /// VSQRTPD ymm, ymm/m256 /// </summary> public static Vector256<double> Sqrt(Vector256<double> value) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_store_si256 (__m256i * mem_addr, __m256i a) /// MOVDQA m256, ymm /// </summary> public static unsafe void StoreAligned(sbyte* address, Vector256<sbyte> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_store_si256 (__m256i * mem_addr, __m256i a) /// MOVDQA m256, ymm /// </summary> public static unsafe void StoreAligned(byte* address, Vector256<byte> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_store_si256 (__m256i * mem_addr, __m256i a) /// MOVDQA m256, ymm /// </summary> public static unsafe void StoreAligned(short* address, Vector256<short> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_store_si256 (__m256i * mem_addr, __m256i a) /// MOVDQA m256, ymm /// </summary> public static unsafe void StoreAligned(ushort* address, Vector256<ushort> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_store_si256 (__m256i * mem_addr, __m256i a) /// MOVDQA m256, ymm /// </summary> public static unsafe void StoreAligned(int* address, Vector256<int> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_store_si256 (__m256i * mem_addr, __m256i a) /// MOVDQA m256, ymm /// </summary> public static unsafe void StoreAligned(uint* address, Vector256<uint> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_store_si256 (__m256i * mem_addr, __m256i a) /// MOVDQA m256, ymm /// </summary> public static unsafe void StoreAligned(long* address, Vector256<long> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_store_si256 (__m256i * mem_addr, __m256i a) /// MOVDQA m256, ymm /// </summary> public static unsafe void StoreAligned(ulong* address, Vector256<ulong> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_store_ps (float * mem_addr, __m256 a) /// VMOVAPS m256, ymm /// </summary> public static unsafe void StoreAligned(float* address, Vector256<float> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_store_pd (double * mem_addr, __m256d a) /// VMOVAPD m256, ymm /// </summary> public static unsafe void StoreAligned(double* address, Vector256<double> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_stream_si256 (__m256i * mem_addr, __m256i a) /// VMOVNTDQ m256, ymm /// </summary> public static unsafe void StoreAlignedNonTemporal(sbyte* address, Vector256<sbyte> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_stream_si256 (__m256i * mem_addr, __m256i a) /// VMOVNTDQ m256, ymm /// </summary> public static unsafe void StoreAlignedNonTemporal(byte* address, Vector256<byte> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_stream_si256 (__m256i * mem_addr, __m256i a) /// VMOVNTDQ m256, ymm /// </summary> public static unsafe void StoreAlignedNonTemporal(short* address, Vector256<short> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_stream_si256 (__m256i * mem_addr, __m256i a) /// VMOVNTDQ m256, ymm /// </summary> public static unsafe void StoreAlignedNonTemporal(ushort* address, Vector256<ushort> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_stream_si256 (__m256i * mem_addr, __m256i a) /// VMOVNTDQ m256, ymm /// </summary> public static unsafe void StoreAlignedNonTemporal(int* address, Vector256<int> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_stream_si256 (__m256i * mem_addr, __m256i a) /// VMOVNTDQ m256, ymm /// </summary> public static unsafe void StoreAlignedNonTemporal(uint* address, Vector256<uint> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_stream_si256 (__m256i * mem_addr, __m256i a) /// VMOVNTDQ m256, ymm /// </summary> public static unsafe void StoreAlignedNonTemporal(long* address, Vector256<long> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_stream_si256 (__m256i * mem_addr, __m256i a) /// VMOVNTDQ m256, ymm /// </summary> public static unsafe void StoreAlignedNonTemporal(ulong* address, Vector256<ulong> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_stream_ps (float * mem_addr, __m256 a) /// MOVNTPS m256, ymm /// </summary> public static unsafe void StoreAlignedNonTemporal(float* address, Vector256<float> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_stream_pd (double * mem_addr, __m256d a) /// MOVNTPD m256, ymm /// </summary> public static unsafe void StoreAlignedNonTemporal(double* address, Vector256<double> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_storeu_si256 (__m256i * mem_addr, __m256i a) /// MOVDQU m256, ymm /// </summary> public static unsafe void Store(sbyte* address, Vector256<sbyte> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_storeu_si256 (__m256i * mem_addr, __m256i a) /// MOVDQU m256, ymm /// </summary> public static unsafe void Store(byte* address, Vector256<byte> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_storeu_si256 (__m256i * mem_addr, __m256i a) /// MOVDQU m256, ymm /// </summary> public static unsafe void Store(short* address, Vector256<short> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_storeu_si256 (__m256i * mem_addr, __m256i a) /// MOVDQU m256, ymm /// </summary> public static unsafe void Store(ushort* address, Vector256<ushort> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_storeu_si256 (__m256i * mem_addr, __m256i a) /// MOVDQU m256, ymm /// </summary> public static unsafe void Store(int* address, Vector256<int> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_storeu_si256 (__m256i * mem_addr, __m256i a) /// MOVDQU m256, ymm /// </summary> public static unsafe void Store(uint* address, Vector256<uint> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_storeu_si256 (__m256i * mem_addr, __m256i a) /// MOVDQU m256, ymm /// </summary> public static unsafe void Store(long* address, Vector256<long> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_storeu_si256 (__m256i * mem_addr, __m256i a) /// MOVDQU m256, ymm /// </summary> public static unsafe void Store(ulong* address, Vector256<ulong> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_storeu_ps (float * mem_addr, __m256 a) /// MOVUPS m256, ymm /// </summary> public static unsafe void Store(float* address, Vector256<float> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm256_storeu_pd (double * mem_addr, __m256d a) /// MOVUPD m256, ymm /// </summary> public static unsafe void Store(double* address, Vector256<double> source) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_sub_ps (__m256 a, __m256 b) /// VSUBPS ymm, ymm, ymm/m256 /// </summary> public static Vector256<float> Subtract(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_sub_pd (__m256d a, __m256d b) /// VSUBPD ymm, ymm, ymm/m256 /// </summary> public static Vector256<double> Subtract(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm_testc_ps (__m128 a, __m128 b) /// VTESTPS xmm, xmm/m128 /// </summary> public static bool TestC(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm_testc_pd (__m128d a, __m128d b) /// VTESTPD xmm, xmm/m128 /// </summary> public static bool TestC(Vector128<double> left, Vector128<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testc_si256 (__m256i a, __m256i b) /// VPTEST ymm, ymm/m256 /// </summary> public static bool TestC(Vector256<byte> left, Vector256<byte> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testc_si256 (__m256i a, __m256i b) /// VPTEST ymm, ymm/m256 /// </summary> public static bool TestC(Vector256<sbyte> left, Vector256<sbyte> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testc_si256 (__m256i a, __m256i b) /// VPTEST ymm, ymm/m256 /// </summary> public static bool TestC(Vector256<short> left, Vector256<short> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testc_si256 (__m256i a, __m256i b) /// VPTEST ymm, ymm/m256 /// </summary> public static bool TestC(Vector256<ushort> left, Vector256<ushort> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testc_si256 (__m256i a, __m256i b) /// VPTEST ymm, ymm/m256 /// </summary> public static bool TestC(Vector256<int> left, Vector256<int> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testc_si256 (__m256i a, __m256i b) /// VPTEST ymm, ymm/m256 /// </summary> public static bool TestC(Vector256<uint> left, Vector256<uint> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testc_si256 (__m256i a, __m256i b) /// VPTEST ymm, ymm/m256 /// </summary> public static bool TestC(Vector256<long> left, Vector256<long> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testc_si256 (__m256i a, __m256i b) /// VPTEST ymm, ymm/m256 /// </summary> public static bool TestC(Vector256<ulong> left, Vector256<ulong> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testc_ps (__m256 a, __m256 b) /// VTESTPS ymm, ymm/m256 /// </summary> public static bool TestC(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testc_pd (__m256d a, __m256d b) /// VTESTPS ymm, ymm/m256 /// </summary> public static bool TestC(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm_testnzc_ps (__m128 a, __m128 b) /// VTESTPS xmm, xmm/m128 /// </summary> public static bool TestNotZAndNotC(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm_testnzc_pd (__m128d a, __m128d b) /// VTESTPD xmm, xmm/m128 /// </summary> public static bool TestNotZAndNotC(Vector128<double> left, Vector128<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testnzc_si256 (__m256i a, __m256i b) /// VPTEST ymm, ymm/m256 /// </summary> public static bool TestNotZAndNotC(Vector256<byte> left, Vector256<byte> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testnzc_si256 (__m256i a, __m256i b) /// VPTEST ymm, ymm/m256 /// </summary> public static bool TestNotZAndNotC(Vector256<sbyte> left, Vector256<sbyte> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testnzc_si256 (__m256i a, __m256i b) /// VPTEST ymm, ymm/m256 /// </summary> public static bool TestNotZAndNotC(Vector256<short> left, Vector256<short> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testnzc_si256 (__m256i a, __m256i b) /// VPTEST ymm, ymm/m256 /// </summary> public static bool TestNotZAndNotC(Vector256<ushort> left, Vector256<ushort> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testnzc_si256 (__m256i a, __m256i b) /// VPTEST ymm, ymm/m256 /// </summary> public static bool TestNotZAndNotC(Vector256<int> left, Vector256<int> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testnzc_si256 (__m256i a, __m256i b) /// VPTEST ymm, ymm/m256 /// </summary> public static bool TestNotZAndNotC(Vector256<uint> left, Vector256<uint> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testnzc_si256 (__m256i a, __m256i b) /// VPTEST ymm, ymm/m256 /// </summary> public static bool TestNotZAndNotC(Vector256<long> left, Vector256<long> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testnzc_si256 (__m256i a, __m256i b) /// VPTEST ymm, ymm/m256 /// </summary> public static bool TestNotZAndNotC(Vector256<ulong> left, Vector256<ulong> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testnzc_ps (__m256 a, __m256 b) /// VTESTPS ymm, ymm/m256 /// </summary> public static bool TestNotZAndNotC(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testnzc_pd (__m256d a, __m256d b) /// VTESTPD ymm, ymm/m256 /// </summary> public static bool TestNotZAndNotC(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm_testz_ps (__m128 a, __m128 b) /// VTESTPS xmm, xmm/m128 /// </summary> public static bool TestZ(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm_testz_pd (__m128d a, __m128d b) /// VTESTPD xmm, xmm/m128 /// </summary> public static bool TestZ(Vector128<double> left, Vector128<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testz_si256 (__m256i a, __m256i b) /// VPTEST ymm, ymm/m256 /// </summary> public static bool TestZ(Vector256<byte> left, Vector256<byte> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testz_si256 (__m256i a, __m256i b) /// VPTEST ymm, ymm/m256 /// </summary> public static bool TestZ(Vector256<sbyte> left, Vector256<sbyte> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testz_si256 (__m256i a, __m256i b) /// VPTEST ymm, ymm/m256 /// </summary> public static bool TestZ(Vector256<short> left, Vector256<short> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testz_si256 (__m256i a, __m256i b) /// VPTEST ymm, ymm/m256 /// </summary> public static bool TestZ(Vector256<ushort> left, Vector256<ushort> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testz_si256 (__m256i a, __m256i b) /// VPTEST ymm, ymm/m256 /// </summary> public static bool TestZ(Vector256<int> left, Vector256<int> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testz_si256 (__m256i a, __m256i b) /// VPTEST ymm, ymm/m256 /// </summary> public static bool TestZ(Vector256<uint> left, Vector256<uint> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testz_si256 (__m256i a, __m256i b) /// VPTEST ymm, ymm/m256 /// </summary> public static bool TestZ(Vector256<long> left, Vector256<long> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testz_si256 (__m256i a, __m256i b) /// VPTEST ymm, ymm/m256 /// </summary> public static bool TestZ(Vector256<ulong> left, Vector256<ulong> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testz_ps (__m256 a, __m256 b) /// VTESTPS ymm, ymm/m256 /// </summary> public static bool TestZ(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// int _mm256_testz_pd (__m256d a, __m256d b) /// VTESTPD ymm, ymm/m256 /// </summary> public static bool TestZ(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_unpackhi_ps (__m256 a, __m256 b) /// VUNPCKHPS ymm, ymm, ymm/m256 /// </summary> public static Vector256<float> UnpackHigh(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_unpackhi_pd (__m256d a, __m256d b) /// VUNPCKHPD ymm, ymm, ymm/m256 /// </summary> public static Vector256<double> UnpackHigh(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_unpacklo_ps (__m256 a, __m256 b) /// VUNPCKLPS ymm, ymm, ymm/m256 /// </summary> public static Vector256<float> UnpackLow(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_unpacklo_pd (__m256d a, __m256d b) /// VUNPCKLPD ymm, ymm, ymm/m256 /// </summary> public static Vector256<double> UnpackLow(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256 _mm256_xor_ps (__m256 a, __m256 b) /// VXORPS ymm, ymm, ymm/m256 /// </summary> public static Vector256<float> Xor(Vector256<float> left, Vector256<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m256d _mm256_xor_pd (__m256d a, __m256d b) /// VXORPS ymm, ymm, ymm/m256 /// </summary> public static Vector256<double> Xor(Vector256<double> left, Vector256<double> right) { throw new PlatformNotSupportedException(); } } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/Store.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.Reflection; 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 Store_Vector128_UInt64() { var test = new StoreUnaryOpTest__Store_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 StoreUnaryOpTest__Store_Vector128_UInt64 { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(UInt64[] inArray1, UInt64[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt64>(); 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<UInt64, 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<UInt64> _fld1; 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>>()); return testStruct; } public void RunStructFldScenario(StoreUnaryOpTest__Store_Vector128_UInt64 testClass) { AdvSimd.Store((UInt64*)testClass._dataTable.outArrayPtr, _fld1); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(StoreUnaryOpTest__Store_Vector128_UInt64 testClass) { fixed (Vector128<UInt64>* pFld1 = &_fld1) { AdvSimd.Store((UInt64*)testClass._dataTable.outArrayPtr, AdvSimd.LoadVector128((UInt64*)(pFld1))); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = 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 Vector128<UInt64> _clsVar1; private Vector128<UInt64> _fld1; private DataTable _dataTable; static StoreUnaryOpTest__Store_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>>()); } public StoreUnaryOpTest__Store_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 < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } _dataTable = new DataTable(_data1, new UInt64[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); AdvSimd.Store((UInt64*)_dataTable.outArrayPtr, Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); AdvSimd.Store((UInt64*)_dataTable.outArrayPtr, AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray1Ptr))); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); typeof(AdvSimd).GetMethod(nameof(AdvSimd.Store), new Type[] { typeof(UInt64*), typeof(Vector128<UInt64>) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.outArrayPtr, typeof(UInt64*)), Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); typeof(AdvSimd).GetMethod(nameof(AdvSimd.Store), new Type[] { typeof(UInt64*), typeof(Vector128<UInt64>) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.outArrayPtr, typeof(UInt64*)), AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); AdvSimd.Store((UInt64*)_dataTable.outArrayPtr, _clsVar1); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<UInt64>* pClsVar1 = &_clsVar1) { AdvSimd.Store((UInt64*)_dataTable.outArrayPtr, AdvSimd.LoadVector128((UInt64*)(pClsVar1))); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr); AdvSimd.Store((UInt64*)_dataTable.outArrayPtr, op1); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)); AdvSimd.Store((UInt64*)_dataTable.outArrayPtr, op1); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new StoreUnaryOpTest__Store_Vector128_UInt64(); AdvSimd.Store((UInt64*)_dataTable.outArrayPtr, test._fld1); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new StoreUnaryOpTest__Store_Vector128_UInt64(); fixed (Vector128<UInt64>* pFld1 = &test._fld1) { AdvSimd.Store((UInt64*)_dataTable.outArrayPtr, AdvSimd.LoadVector128((UInt64*)(pFld1))); ValidateResult(test._fld1, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); AdvSimd.Store((UInt64*)_dataTable.outArrayPtr, _fld1); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<UInt64>* pFld1 = &_fld1) { AdvSimd.Store((UInt64*)_dataTable.outArrayPtr, AdvSimd.LoadVector128((UInt64*)(pFld1))); ValidateResult(_fld1, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); AdvSimd.Store((UInt64*)_dataTable.outArrayPtr, test._fld1); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); AdvSimd.Store((UInt64*)_dataTable.outArrayPtr, AdvSimd.LoadVector128((UInt64*)(&test._fld1))); 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<UInt64> op1, void* result, [CallerMemberName] string method = "") { UInt64[] inArray1 = new UInt64[Op1ElementCount]; UInt64[] outArray = new UInt64[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, 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 = "") { UInt64[] inArray1 = new UInt64[Op1ElementCount]; 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 outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(UInt64[] firstOp, UInt64[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (int i = 0; i < RetElementCount; i++) { if (firstOp[i] != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.Store)}<UInt64>(Vector128<UInt64>): {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.Reflection; 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 Store_Vector128_UInt64() { var test = new StoreUnaryOpTest__Store_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 StoreUnaryOpTest__Store_Vector128_UInt64 { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(UInt64[] inArray1, UInt64[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt64>(); 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<UInt64, 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<UInt64> _fld1; 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>>()); return testStruct; } public void RunStructFldScenario(StoreUnaryOpTest__Store_Vector128_UInt64 testClass) { AdvSimd.Store((UInt64*)testClass._dataTable.outArrayPtr, _fld1); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(StoreUnaryOpTest__Store_Vector128_UInt64 testClass) { fixed (Vector128<UInt64>* pFld1 = &_fld1) { AdvSimd.Store((UInt64*)testClass._dataTable.outArrayPtr, AdvSimd.LoadVector128((UInt64*)(pFld1))); testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = 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 Vector128<UInt64> _clsVar1; private Vector128<UInt64> _fld1; private DataTable _dataTable; static StoreUnaryOpTest__Store_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>>()); } public StoreUnaryOpTest__Store_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 < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt64(); } _dataTable = new DataTable(_data1, new UInt64[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); AdvSimd.Store((UInt64*)_dataTable.outArrayPtr, Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); AdvSimd.Store((UInt64*)_dataTable.outArrayPtr, AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray1Ptr))); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); typeof(AdvSimd).GetMethod(nameof(AdvSimd.Store), new Type[] { typeof(UInt64*), typeof(Vector128<UInt64>) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.outArrayPtr, typeof(UInt64*)), Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); typeof(AdvSimd).GetMethod(nameof(AdvSimd.Store), new Type[] { typeof(UInt64*), typeof(Vector128<UInt64>) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.outArrayPtr, typeof(UInt64*)), AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); AdvSimd.Store((UInt64*)_dataTable.outArrayPtr, _clsVar1); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<UInt64>* pClsVar1 = &_clsVar1) { AdvSimd.Store((UInt64*)_dataTable.outArrayPtr, AdvSimd.LoadVector128((UInt64*)(pClsVar1))); ValidateResult(_clsVar1, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr); AdvSimd.Store((UInt64*)_dataTable.outArrayPtr, op1); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)); AdvSimd.Store((UInt64*)_dataTable.outArrayPtr, op1); ValidateResult(op1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new StoreUnaryOpTest__Store_Vector128_UInt64(); AdvSimd.Store((UInt64*)_dataTable.outArrayPtr, test._fld1); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new StoreUnaryOpTest__Store_Vector128_UInt64(); fixed (Vector128<UInt64>* pFld1 = &test._fld1) { AdvSimd.Store((UInt64*)_dataTable.outArrayPtr, AdvSimd.LoadVector128((UInt64*)(pFld1))); ValidateResult(test._fld1, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); AdvSimd.Store((UInt64*)_dataTable.outArrayPtr, _fld1); ValidateResult(_fld1, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<UInt64>* pFld1 = &_fld1) { AdvSimd.Store((UInt64*)_dataTable.outArrayPtr, AdvSimd.LoadVector128((UInt64*)(pFld1))); ValidateResult(_fld1, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); AdvSimd.Store((UInt64*)_dataTable.outArrayPtr, test._fld1); ValidateResult(test._fld1, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); AdvSimd.Store((UInt64*)_dataTable.outArrayPtr, AdvSimd.LoadVector128((UInt64*)(&test._fld1))); 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<UInt64> op1, void* result, [CallerMemberName] string method = "") { UInt64[] inArray1 = new UInt64[Op1ElementCount]; UInt64[] outArray = new UInt64[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, 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 = "") { UInt64[] inArray1 = new UInt64[Op1ElementCount]; 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 outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(UInt64[] firstOp, UInt64[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (int i = 0; i < RetElementCount; i++) { if (firstOp[i] != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.Store)}<UInt64>(Vector128<UInt64>): {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,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/tests/baseservices/compilerservices/RuntimeHelpers/ExecuteCodeWithGuaranteedCleanup.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; class GCD { private int _val = -2; private int _exitcode = -1; public GCD() {} public int GetExitCode(){ return _exitcode;} public void g () { throw new System.Exception("TryCode test"); } public void TryCode0 (object obj) { _val = (int)obj; g(); } public void CleanupCode0 (object obj, bool excpThrown) { if(excpThrown && ((int)obj == _val)) { _exitcode = 100; } } } class ExecuteCodeWithGuaranteedCleanupTest { public static void Run() { GCD gcd = new GCD(); RuntimeHelpers.TryCode t = new RuntimeHelpers.TryCode(gcd.TryCode0); RuntimeHelpers.CleanupCode c = new RuntimeHelpers.CleanupCode(gcd.CleanupCode0); int val = 21; try { #pragma warning disable SYSLIB0004 // CER is obsolete RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(t, c, val); #pragma warning restore SYSLIB0004 } catch (Exception Ex) { } int res = gcd.GetExitCode(); if (res != 100) throw new Exception($"{nameof(ExecuteCodeWithGuaranteedCleanupTest)} failed. Result: {res}"); } }
// 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; class GCD { private int _val = -2; private int _exitcode = -1; public GCD() {} public int GetExitCode(){ return _exitcode;} public void g () { throw new System.Exception("TryCode test"); } public void TryCode0 (object obj) { _val = (int)obj; g(); } public void CleanupCode0 (object obj, bool excpThrown) { if(excpThrown && ((int)obj == _val)) { _exitcode = 100; } } } class ExecuteCodeWithGuaranteedCleanupTest { public static void Run() { GCD gcd = new GCD(); RuntimeHelpers.TryCode t = new RuntimeHelpers.TryCode(gcd.TryCode0); RuntimeHelpers.CleanupCode c = new RuntimeHelpers.CleanupCode(gcd.CleanupCode0); int val = 21; try { #pragma warning disable SYSLIB0004 // CER is obsolete RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(t, c, val); #pragma warning restore SYSLIB0004 } catch (Exception Ex) { } int res = gcd.GetExitCode(); if (res != 100) throw new Exception($"{nameof(ExecuteCodeWithGuaranteedCleanupTest)} failed. Result: {res}"); } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/libraries/Common/src/Interop/Windows/Kernel32/Interop.CreateNamedPipeClient.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.IO; using System.Runtime.InteropServices; internal static partial class Interop { internal static partial class Kernel32 { [GeneratedDllImport(Libraries.Kernel32, EntryPoint = "CreateFileW", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)] internal static partial SafePipeHandle CreateNamedPipeClient( string? lpFileName, int dwDesiredAccess, System.IO.FileShare dwShareMode, ref SECURITY_ATTRIBUTES secAttrs, FileMode dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile); } }
// 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.IO; using System.Runtime.InteropServices; internal static partial class Interop { internal static partial class Kernel32 { [GeneratedDllImport(Libraries.Kernel32, EntryPoint = "CreateFileW", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)] internal static partial SafePipeHandle CreateNamedPipeClient( string? lpFileName, int dwDesiredAccess, System.IO.FileShare dwShareMode, ref SECURITY_ATTRIBUTES secAttrs, FileMode dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile); } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/tests/JIT/HardwareIntrinsics/Arm/Rdm/MultiplyRoundedDoublingAndAddSaturateHigh.Vector128.Int32.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void MultiplyRoundedDoublingAndAddSaturateHigh_Vector128_Int32() { var test = new SimpleTernaryOpTest__MultiplyRoundedDoublingAndAddSaturateHigh_Vector128_Int32(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleTernaryOpTest__MultiplyRoundedDoublingAndAddSaturateHigh_Vector128_Int32 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] inArray3; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle inHandle3; private GCHandle outHandle; private ulong alignment; public DataTable(Int32[] inArray1, Int32[] inArray2, Int32[] inArray3, Int32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>(); int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Int32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inArray3 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Int32, byte>(ref inArray3[0]), (uint)sizeOfinArray3); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); inHandle3.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Int32> _fld1; public Vector128<Int32> _fld2; public Vector128<Int32> _fld3; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld3), ref Unsafe.As<Int32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); return testStruct; } public void RunStructFldScenario(SimpleTernaryOpTest__MultiplyRoundedDoublingAndAddSaturateHigh_Vector128_Int32 testClass) { var result = Rdm.MultiplyRoundedDoublingAndAddSaturateHigh(_fld1, _fld2, _fld3); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleTernaryOpTest__MultiplyRoundedDoublingAndAddSaturateHigh_Vector128_Int32 testClass) { fixed (Vector128<Int32>* pFld1 = &_fld1) fixed (Vector128<Int32>* pFld2 = &_fld2) fixed (Vector128<Int32>* pFld3 = &_fld3) { var result = Rdm.MultiplyRoundedDoublingAndAddSaturateHigh( AdvSimd.LoadVector128((Int32*)(pFld1)), AdvSimd.LoadVector128((Int32*)(pFld2)), AdvSimd.LoadVector128((Int32*)(pFld3)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Int32[] _data3 = new Int32[Op3ElementCount]; private static Vector128<Int32> _clsVar1; private static Vector128<Int32> _clsVar2; private static Vector128<Int32> _clsVar3; private Vector128<Int32> _fld1; private Vector128<Int32> _fld2; private Vector128<Int32> _fld3; private DataTable _dataTable; static SimpleTernaryOpTest__MultiplyRoundedDoublingAndAddSaturateHigh_Vector128_Int32() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar3), ref Unsafe.As<Int32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); } public SimpleTernaryOpTest__MultiplyRoundedDoublingAndAddSaturateHigh_Vector128_Int32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld3), ref Unsafe.As<Int32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new DataTable(_data1, _data2, _data3, new Int32[RetElementCount], LargestVectorSize); } public bool IsSupported => Rdm.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Rdm.MultiplyRoundedDoublingAndAddSaturateHigh( Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray3Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Rdm.MultiplyRoundedDoublingAndAddSaturateHigh( AdvSimd.LoadVector128((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int32*)(_dataTable.inArray2Ptr)), AdvSimd.LoadVector128((Int32*)(_dataTable.inArray3Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Rdm).GetMethod(nameof(Rdm.MultiplyRoundedDoublingAndAddSaturateHigh), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray3Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Rdm).GetMethod(nameof(Rdm.MultiplyRoundedDoublingAndAddSaturateHigh), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int32*)(_dataTable.inArray2Ptr)), AdvSimd.LoadVector128((Int32*)(_dataTable.inArray3Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Rdm.MultiplyRoundedDoublingAndAddSaturateHigh( _clsVar1, _clsVar2, _clsVar3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Int32>* pClsVar1 = &_clsVar1) fixed (Vector128<Int32>* pClsVar2 = &_clsVar2) fixed (Vector128<Int32>* pClsVar3 = &_clsVar3) { var result = Rdm.MultiplyRoundedDoublingAndAddSaturateHigh( AdvSimd.LoadVector128((Int32*)(pClsVar1)), AdvSimd.LoadVector128((Int32*)(pClsVar2)), AdvSimd.LoadVector128((Int32*)(pClsVar3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr); var op3 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray3Ptr); var result = Rdm.MultiplyRoundedDoublingAndAddSaturateHigh(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((Int32*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((Int32*)(_dataTable.inArray2Ptr)); var op3 = AdvSimd.LoadVector128((Int32*)(_dataTable.inArray3Ptr)); var result = Rdm.MultiplyRoundedDoublingAndAddSaturateHigh(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleTernaryOpTest__MultiplyRoundedDoublingAndAddSaturateHigh_Vector128_Int32(); var result = Rdm.MultiplyRoundedDoublingAndAddSaturateHigh(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleTernaryOpTest__MultiplyRoundedDoublingAndAddSaturateHigh_Vector128_Int32(); fixed (Vector128<Int32>* pFld1 = &test._fld1) fixed (Vector128<Int32>* pFld2 = &test._fld2) fixed (Vector128<Int32>* pFld3 = &test._fld3) { var result = Rdm.MultiplyRoundedDoublingAndAddSaturateHigh( AdvSimd.LoadVector128((Int32*)(pFld1)), AdvSimd.LoadVector128((Int32*)(pFld2)), AdvSimd.LoadVector128((Int32*)(pFld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Rdm.MultiplyRoundedDoublingAndAddSaturateHigh(_fld1, _fld2, _fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Int32>* pFld1 = &_fld1) fixed (Vector128<Int32>* pFld2 = &_fld2) fixed (Vector128<Int32>* pFld3 = &_fld3) { var result = Rdm.MultiplyRoundedDoublingAndAddSaturateHigh( AdvSimd.LoadVector128((Int32*)(pFld1)), AdvSimd.LoadVector128((Int32*)(pFld2)), AdvSimd.LoadVector128((Int32*)(pFld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Rdm.MultiplyRoundedDoublingAndAddSaturateHigh(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Rdm.MultiplyRoundedDoublingAndAddSaturateHigh( AdvSimd.LoadVector128((Int32*)(&test._fld1)), AdvSimd.LoadVector128((Int32*)(&test._fld2)), AdvSimd.LoadVector128((Int32*)(&test._fld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Int32> op1, Vector128<Int32> op2, Vector128<Int32> op3, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] inArray3 = new Int32[Op3ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray3[0]), op3); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] inArray3 = new Int32[Op3ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector128<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(Int32[] firstOp, Int32[] secondOp, Int32[] thirdOp, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.MultiplyRoundedDoublingAndAddSaturateHigh(firstOp[i], secondOp[i], thirdOp[i]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Rdm)}.{nameof(Rdm.MultiplyRoundedDoublingAndAddSaturateHigh)}<Int32>(Vector128<Int32>, Vector128<Int32>, Vector128<Int32>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})"); TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void MultiplyRoundedDoublingAndAddSaturateHigh_Vector128_Int32() { var test = new SimpleTernaryOpTest__MultiplyRoundedDoublingAndAddSaturateHigh_Vector128_Int32(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleTernaryOpTest__MultiplyRoundedDoublingAndAddSaturateHigh_Vector128_Int32 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] inArray3; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle inHandle3; private GCHandle outHandle; private ulong alignment; public DataTable(Int32[] inArray1, Int32[] inArray2, Int32[] inArray3, Int32[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>(); int sizeOfinArray3 = inArray3.Length * Unsafe.SizeOf<Int32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfinArray3 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inArray3 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.inHandle3 = GCHandle.Alloc(this.inArray3, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray3Ptr), ref Unsafe.As<Int32, byte>(ref inArray3[0]), (uint)sizeOfinArray3); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray3Ptr => Align((byte*)(inHandle3.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); inHandle3.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Int32> _fld1; public Vector128<Int32> _fld2; public Vector128<Int32> _fld3; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld3), ref Unsafe.As<Int32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); return testStruct; } public void RunStructFldScenario(SimpleTernaryOpTest__MultiplyRoundedDoublingAndAddSaturateHigh_Vector128_Int32 testClass) { var result = Rdm.MultiplyRoundedDoublingAndAddSaturateHigh(_fld1, _fld2, _fld3); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleTernaryOpTest__MultiplyRoundedDoublingAndAddSaturateHigh_Vector128_Int32 testClass) { fixed (Vector128<Int32>* pFld1 = &_fld1) fixed (Vector128<Int32>* pFld2 = &_fld2) fixed (Vector128<Int32>* pFld3 = &_fld3) { var result = Rdm.MultiplyRoundedDoublingAndAddSaturateHigh( AdvSimd.LoadVector128((Int32*)(pFld1)), AdvSimd.LoadVector128((Int32*)(pFld2)), AdvSimd.LoadVector128((Int32*)(pFld3)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, _fld3, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static readonly int Op3ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Int32[] _data3 = new Int32[Op3ElementCount]; private static Vector128<Int32> _clsVar1; private static Vector128<Int32> _clsVar2; private static Vector128<Int32> _clsVar3; private Vector128<Int32> _fld1; private Vector128<Int32> _fld2; private Vector128<Int32> _fld3; private DataTable _dataTable; static SimpleTernaryOpTest__MultiplyRoundedDoublingAndAddSaturateHigh_Vector128_Int32() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar3), ref Unsafe.As<Int32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); } public SimpleTernaryOpTest__MultiplyRoundedDoublingAndAddSaturateHigh_Vector128_Int32() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld3), ref Unsafe.As<Int32, byte>(ref _data3[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new DataTable(_data1, _data2, _data3, new Int32[RetElementCount], LargestVectorSize); } public bool IsSupported => Rdm.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Rdm.MultiplyRoundedDoublingAndAddSaturateHigh( Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray3Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Rdm.MultiplyRoundedDoublingAndAddSaturateHigh( AdvSimd.LoadVector128((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int32*)(_dataTable.inArray2Ptr)), AdvSimd.LoadVector128((Int32*)(_dataTable.inArray3Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Rdm).GetMethod(nameof(Rdm.MultiplyRoundedDoublingAndAddSaturateHigh), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray3Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Rdm).GetMethod(nameof(Rdm.MultiplyRoundedDoublingAndAddSaturateHigh), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Int32*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Int32*)(_dataTable.inArray2Ptr)), AdvSimd.LoadVector128((Int32*)(_dataTable.inArray3Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Rdm.MultiplyRoundedDoublingAndAddSaturateHigh( _clsVar1, _clsVar2, _clsVar3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Int32>* pClsVar1 = &_clsVar1) fixed (Vector128<Int32>* pClsVar2 = &_clsVar2) fixed (Vector128<Int32>* pClsVar3 = &_clsVar3) { var result = Rdm.MultiplyRoundedDoublingAndAddSaturateHigh( AdvSimd.LoadVector128((Int32*)(pClsVar1)), AdvSimd.LoadVector128((Int32*)(pClsVar2)), AdvSimd.LoadVector128((Int32*)(pClsVar3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr); var op3 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray3Ptr); var result = Rdm.MultiplyRoundedDoublingAndAddSaturateHigh(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((Int32*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((Int32*)(_dataTable.inArray2Ptr)); var op3 = AdvSimd.LoadVector128((Int32*)(_dataTable.inArray3Ptr)); var result = Rdm.MultiplyRoundedDoublingAndAddSaturateHigh(op1, op2, op3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, op3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleTernaryOpTest__MultiplyRoundedDoublingAndAddSaturateHigh_Vector128_Int32(); var result = Rdm.MultiplyRoundedDoublingAndAddSaturateHigh(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleTernaryOpTest__MultiplyRoundedDoublingAndAddSaturateHigh_Vector128_Int32(); fixed (Vector128<Int32>* pFld1 = &test._fld1) fixed (Vector128<Int32>* pFld2 = &test._fld2) fixed (Vector128<Int32>* pFld3 = &test._fld3) { var result = Rdm.MultiplyRoundedDoublingAndAddSaturateHigh( AdvSimd.LoadVector128((Int32*)(pFld1)), AdvSimd.LoadVector128((Int32*)(pFld2)), AdvSimd.LoadVector128((Int32*)(pFld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Rdm.MultiplyRoundedDoublingAndAddSaturateHigh(_fld1, _fld2, _fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Int32>* pFld1 = &_fld1) fixed (Vector128<Int32>* pFld2 = &_fld2) fixed (Vector128<Int32>* pFld3 = &_fld3) { var result = Rdm.MultiplyRoundedDoublingAndAddSaturateHigh( AdvSimd.LoadVector128((Int32*)(pFld1)), AdvSimd.LoadVector128((Int32*)(pFld2)), AdvSimd.LoadVector128((Int32*)(pFld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Rdm.MultiplyRoundedDoublingAndAddSaturateHigh(test._fld1, test._fld2, test._fld3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Rdm.MultiplyRoundedDoublingAndAddSaturateHigh( AdvSimd.LoadVector128((Int32*)(&test._fld1)), AdvSimd.LoadVector128((Int32*)(&test._fld2)), AdvSimd.LoadVector128((Int32*)(&test._fld3)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Int32> op1, Vector128<Int32> op2, Vector128<Int32> op3, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] inArray3 = new Int32[Op3ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray3[0]), op3); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(void* op1, void* op2, void* op3, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] inArray3 = new Int32[Op3ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(op3), (uint)Unsafe.SizeOf<Vector128<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>()); ValidateResult(inArray1, inArray2, inArray3, outArray, method); } private void ValidateResult(Int32[] firstOp, Int32[] secondOp, Int32[] thirdOp, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.MultiplyRoundedDoublingAndAddSaturateHigh(firstOp[i], secondOp[i], thirdOp[i]) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Rdm)}.{nameof(Rdm.MultiplyRoundedDoublingAndAddSaturateHigh)}<Int32>(Vector128<Int32>, Vector128<Int32>, Vector128<Int32>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($"secondOp: ({string.Join(", ", secondOp)})"); TestLibrary.TestFramework.LogInformation($" thirdOp: ({string.Join(", ", thirdOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/tests/BuildWasmApps/Wasm.Build.Tests/NativeRebuildTests/SimpleSourceChangeRebuildTest.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.IO; using System.Linq; using Wasm.Build.Tests; using Xunit; using Xunit.Abstractions; #nullable enable namespace Wasm.Build.NativeRebuild.Tests { public class SimpleSourceChangeRebuildTest : NativeRebuildTestsBase { public SimpleSourceChangeRebuildTest(ITestOutputHelper output, SharedBuildPerTestClassFixture buildContext) : base(output, buildContext) { } [Theory] [MemberData(nameof(NativeBuildData))] public void SimpleStringChangeInSource(BuildArgs buildArgs, bool nativeRelink, bool invariant, RunHost host, string id) { buildArgs = buildArgs with { ProjectName = $"rebuild_simple_{buildArgs.Config}" }; (buildArgs, BuildPaths paths) = FirstNativeBuild(s_mainReturns42, nativeRelink, invariant: invariant, buildArgs, id); string mainAssembly = $"{buildArgs.ProjectName}.dll"; var pathsDict = GetFilesTable(buildArgs, paths, unchanged: true); pathsDict.UpdateTo(unchanged: false, mainAssembly); pathsDict.UpdateTo(unchanged: !buildArgs.AOT, "dotnet.wasm", "dotnet.js"); if (buildArgs.AOT) pathsDict.UpdateTo(unchanged: false, $"{mainAssembly}.bc", $"{mainAssembly}.o"); var originalStat = StatFiles(pathsDict.Select(kvp => kvp.Value.fullPath)); // Changes string mainResults55 = @" public class TestClass { public static int Main() { return 55; } }"; File.WriteAllText(Path.Combine(_projectDir!, "Program.cs"), mainResults55); // Rebuild Rebuild(nativeRelink, invariant, buildArgs, id); var newStat = StatFiles(pathsDict.Select(kvp => kvp.Value.fullPath)); CompareStat(originalStat, newStat, pathsDict.Values); RunAndTestWasmApp(buildArgs, buildDir: _projectDir, expectedExitCode: 55, host: host, id: id); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.IO; using System.Linq; using Wasm.Build.Tests; using Xunit; using Xunit.Abstractions; #nullable enable namespace Wasm.Build.NativeRebuild.Tests { public class SimpleSourceChangeRebuildTest : NativeRebuildTestsBase { public SimpleSourceChangeRebuildTest(ITestOutputHelper output, SharedBuildPerTestClassFixture buildContext) : base(output, buildContext) { } [Theory] [MemberData(nameof(NativeBuildData))] public void SimpleStringChangeInSource(BuildArgs buildArgs, bool nativeRelink, bool invariant, RunHost host, string id) { buildArgs = buildArgs with { ProjectName = $"rebuild_simple_{buildArgs.Config}" }; (buildArgs, BuildPaths paths) = FirstNativeBuild(s_mainReturns42, nativeRelink, invariant: invariant, buildArgs, id); string mainAssembly = $"{buildArgs.ProjectName}.dll"; var pathsDict = GetFilesTable(buildArgs, paths, unchanged: true); pathsDict.UpdateTo(unchanged: false, mainAssembly); pathsDict.UpdateTo(unchanged: !buildArgs.AOT, "dotnet.wasm", "dotnet.js"); if (buildArgs.AOT) pathsDict.UpdateTo(unchanged: false, $"{mainAssembly}.bc", $"{mainAssembly}.o"); var originalStat = StatFiles(pathsDict.Select(kvp => kvp.Value.fullPath)); // Changes string mainResults55 = @" public class TestClass { public static int Main() { return 55; } }"; File.WriteAllText(Path.Combine(_projectDir!, "Program.cs"), mainResults55); // Rebuild Rebuild(nativeRelink, invariant, buildArgs, id); var newStat = StatFiles(pathsDict.Select(kvp => kvp.Value.fullPath)); CompareStat(originalStat, newStat, pathsDict.Values); RunAndTestWasmApp(buildArgs, buildDir: _projectDir, expectedExitCode: 55, host: host, id: id); } } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/coreclr/tools/Common/Compiler/DependencyAnalysis/SortableDependencyNode.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; using System.Runtime.CompilerServices; using ILCompiler.DependencyAnalysisFramework; using Internal.TypeSystem; namespace ILCompiler.DependencyAnalysis { public abstract partial class SortableDependencyNode : DependencyNodeCore<NodeFactory>, ISortableNode { #if !SUPPORT_JIT /// <summary> /// Allows grouping of <see cref="ObjectNode"/> instances such that all nodes in a lower phase /// will be ordered before nodes in a later phase. /// </summary> protected internal virtual int Phase => (int)ObjectNodePhase.Unordered; /// <summary> /// Gets an identifier that is the same for all instances of this <see cref="ObjectNode"/> /// descendant, but different from the <see cref="ClassCode"/> of any other descendant. /// </summary> /// <remarks> /// This is really just a number, ideally produced by "new Random().Next(int.MinValue, int.MaxValue)". /// If two manage to conflict (which is pretty unlikely), just make a new one... /// </remarks> public abstract int ClassCode { get; } // Note to implementers: the type of `other` is actually the same as the type of `this`. public virtual int CompareToImpl(ISortableNode other, CompilerComparer comparer) { throw new NotImplementedException("Multiple nodes of this type are not supported"); } protected enum ObjectNodePhase { /// <summary> /// Nodes should only be placed in this phase if they have strict output ordering requirements that /// affect compiler correctness. Today that includes native layout tables. /// </summary> Ordered, Unordered } protected enum ObjectNodeOrder { // // The ordering of this sequence of nodes is deliberate and currently required for // compiler correctness. // // // ReadyToRun Nodes // Win32ResourcesNode, CorHeaderNode, ReadyToRunHeaderNode, ReadyToRunAssemblyHeaderNode, ImportSectionsTableNode, ImportSectionNode, MethodEntrypointTableNode, // // CoreRT Nodes // MetadataNode, ResourceDataNode, ResourceIndexNode, TypeMetadataMapNode, ClassConstructorContextMap, DynamicInvokeTemplateDataNode, ReflectionInvokeMapNode, DelegateMarshallingStubMapNode, StructMarshallingStubMapNode, ArrayMapNode, ReflectionFieldMapNode, NativeLayoutInfoNode, ExactMethodInstantiationsNode, GenericTypesHashtableNode, GenericMethodsHashtableNode, GenericVirtualMethodTableNode, InterfaceGenericVirtualMethodTableNode, GenericMethodsTemplateMap, GenericTypesTemplateMap, BlockReflectionTypeMapNode, StaticsInfoHashtableNode, ReflectionVirtualInvokeMapNode, ArrayOfEmbeddedPointersNode, DefaultConstructorMapNode, ExternalReferencesTableNode, StackTraceEmbeddedMetadataNode, StackTraceMethodMappingNode, ArrayOfEmbeddedDataNode, } public class EmbeddedObjectNodeComparer : IComparer<EmbeddedObjectNode> { private CompilerComparer _comparer; public EmbeddedObjectNodeComparer(CompilerComparer comparer) { _comparer = comparer; } public int Compare(EmbeddedObjectNode x, EmbeddedObjectNode y) { return CompareImpl(x, y, _comparer); } } /// <summary> /// This comparer is used to sort the marked node list. We only care about ordering ObjectNodes /// for emission into the binary, so any EmbeddedObjectNode or DependencyNodeCore objects are /// skipped for efficiency. /// </summary> public class ObjectNodeComparer : IComparer<DependencyNodeCore<NodeFactory>> { private CompilerComparer _comparer; public ObjectNodeComparer(CompilerComparer comparer) { _comparer = comparer; } public int Compare(DependencyNodeCore<NodeFactory> x1, DependencyNodeCore<NodeFactory> y1) { ObjectNode x = x1 as ObjectNode; ObjectNode y = y1 as ObjectNode; if (x == y) { return 0; } // Sort non-object nodes after ObjectNodes if (x == null) return 1; if (y == null) return -1; return CompareImpl(x, y, _comparer); } } static partial void ApplyCustomSort(SortableDependencyNode x, SortableDependencyNode y, ref int result); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int CompareImpl(SortableDependencyNode x, SortableDependencyNode y, CompilerComparer comparer) { int phaseX = x.Phase; int phaseY = y.Phase; if (phaseX == phaseY) { int customSort = 0; ApplyCustomSort(x, y, ref customSort); if (customSort != 0) return customSort; int codeX = x.ClassCode; int codeY = y.ClassCode; if (codeX == codeY) { Debug.Assert(x.GetType() == y.GetType() || (x.GetType().IsConstructedGenericType && y.GetType().IsConstructedGenericType && x.GetType().GetGenericTypeDefinition() == y.GetType().GetGenericTypeDefinition())); int result = x.CompareToImpl(y, comparer); // We did a reference equality check above so an "Equal" result is not expected Debug.Assert(result != 0 || x == y); return result; } else { Debug.Assert(x.GetType() != y.GetType()); return codeY > codeX ? -1 : 1; } } else { return phaseX - phaseY; } } #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; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; using ILCompiler.DependencyAnalysisFramework; using Internal.TypeSystem; namespace ILCompiler.DependencyAnalysis { public abstract partial class SortableDependencyNode : DependencyNodeCore<NodeFactory>, ISortableNode { #if !SUPPORT_JIT /// <summary> /// Allows grouping of <see cref="ObjectNode"/> instances such that all nodes in a lower phase /// will be ordered before nodes in a later phase. /// </summary> protected internal virtual int Phase => (int)ObjectNodePhase.Unordered; /// <summary> /// Gets an identifier that is the same for all instances of this <see cref="ObjectNode"/> /// descendant, but different from the <see cref="ClassCode"/> of any other descendant. /// </summary> /// <remarks> /// This is really just a number, ideally produced by "new Random().Next(int.MinValue, int.MaxValue)". /// If two manage to conflict (which is pretty unlikely), just make a new one... /// </remarks> public abstract int ClassCode { get; } // Note to implementers: the type of `other` is actually the same as the type of `this`. public virtual int CompareToImpl(ISortableNode other, CompilerComparer comparer) { throw new NotImplementedException("Multiple nodes of this type are not supported"); } protected enum ObjectNodePhase { /// <summary> /// Nodes should only be placed in this phase if they have strict output ordering requirements that /// affect compiler correctness. Today that includes native layout tables. /// </summary> Ordered, Unordered } protected enum ObjectNodeOrder { // // The ordering of this sequence of nodes is deliberate and currently required for // compiler correctness. // // // ReadyToRun Nodes // Win32ResourcesNode, CorHeaderNode, ReadyToRunHeaderNode, ReadyToRunAssemblyHeaderNode, ImportSectionsTableNode, ImportSectionNode, MethodEntrypointTableNode, // // CoreRT Nodes // MetadataNode, ResourceDataNode, ResourceIndexNode, TypeMetadataMapNode, ClassConstructorContextMap, DynamicInvokeTemplateDataNode, ReflectionInvokeMapNode, DelegateMarshallingStubMapNode, StructMarshallingStubMapNode, ArrayMapNode, ReflectionFieldMapNode, NativeLayoutInfoNode, ExactMethodInstantiationsNode, GenericTypesHashtableNode, GenericMethodsHashtableNode, GenericVirtualMethodTableNode, InterfaceGenericVirtualMethodTableNode, GenericMethodsTemplateMap, GenericTypesTemplateMap, BlockReflectionTypeMapNode, StaticsInfoHashtableNode, ReflectionVirtualInvokeMapNode, ArrayOfEmbeddedPointersNode, DefaultConstructorMapNode, ExternalReferencesTableNode, StackTraceEmbeddedMetadataNode, StackTraceMethodMappingNode, ArrayOfEmbeddedDataNode, } public class EmbeddedObjectNodeComparer : IComparer<EmbeddedObjectNode> { private CompilerComparer _comparer; public EmbeddedObjectNodeComparer(CompilerComparer comparer) { _comparer = comparer; } public int Compare(EmbeddedObjectNode x, EmbeddedObjectNode y) { return CompareImpl(x, y, _comparer); } } /// <summary> /// This comparer is used to sort the marked node list. We only care about ordering ObjectNodes /// for emission into the binary, so any EmbeddedObjectNode or DependencyNodeCore objects are /// skipped for efficiency. /// </summary> public class ObjectNodeComparer : IComparer<DependencyNodeCore<NodeFactory>> { private CompilerComparer _comparer; public ObjectNodeComparer(CompilerComparer comparer) { _comparer = comparer; } public int Compare(DependencyNodeCore<NodeFactory> x1, DependencyNodeCore<NodeFactory> y1) { ObjectNode x = x1 as ObjectNode; ObjectNode y = y1 as ObjectNode; if (x == y) { return 0; } // Sort non-object nodes after ObjectNodes if (x == null) return 1; if (y == null) return -1; return CompareImpl(x, y, _comparer); } } static partial void ApplyCustomSort(SortableDependencyNode x, SortableDependencyNode y, ref int result); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int CompareImpl(SortableDependencyNode x, SortableDependencyNode y, CompilerComparer comparer) { int phaseX = x.Phase; int phaseY = y.Phase; if (phaseX == phaseY) { int customSort = 0; ApplyCustomSort(x, y, ref customSort); if (customSort != 0) return customSort; int codeX = x.ClassCode; int codeY = y.ClassCode; if (codeX == codeY) { Debug.Assert(x.GetType() == y.GetType() || (x.GetType().IsConstructedGenericType && y.GetType().IsConstructedGenericType && x.GetType().GetGenericTypeDefinition() == y.GetType().GetGenericTypeDefinition())); int result = x.CompareToImpl(y, comparer); // We did a reference equality check above so an "Equal" result is not expected Debug.Assert(result != 0 || x == y); return result; } else { Debug.Assert(x.GetType() != y.GetType()); return codeY > codeX ? -1 : 1; } } else { return phaseX - phaseY; } } #endif } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElementCollectionType.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.Configuration { public enum ConfigurationElementCollectionType { /********************************************************************** This enum type specifies the behavior of the ConfigurationElementCollection. Some of the behavior is changeable via other properties (i.e. throwing on duplicate entries). - BasicMap and BasicMapAlternate This collection doesn't do any "clear" or "remove". Whatever the set of entries is in the config file is given back to the user. An example would be like Authentication Users, where each entry specifies a user. The Alternate version of this collection simply changes the index location of the items from the parent collection. For example, suppose you had entries in machine and app level specified like this: machine.config => A, B, C web.config => D, E, F For BasicMap, the collection at the app level would be: A, B, C, D, E, F With BasicMapAlternate, it'd be: D, E, F, A, B, C That means that the Alternate allows the "nearest" config file entries to take precedence over the "parent" config file entries. - AddRemoveClearMap and AddRemoveClearMapAlternate This collection honors the "add, remove, clear" commands. Internally it keeps track of each of them so that it knows whether it has to write out an add/remove/clear at the appropriate levels, so it uses a concept of "virtual index" and "real index" to keep track of stuff. The "virtual index" is what the end user would see and use. The "real index" is just for us. Any access via indexes have to go through some transformation step. The Alternate version changes the inheritance stuff like the BasicMapAlternate, where the "nearest" config file entries take precedence over the "parent" config file entries (see example above). **********************************************************************/ BasicMap, AddRemoveClearMap, BasicMapAlternate, AddRemoveClearMapAlternate, } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Configuration { public enum ConfigurationElementCollectionType { /********************************************************************** This enum type specifies the behavior of the ConfigurationElementCollection. Some of the behavior is changeable via other properties (i.e. throwing on duplicate entries). - BasicMap and BasicMapAlternate This collection doesn't do any "clear" or "remove". Whatever the set of entries is in the config file is given back to the user. An example would be like Authentication Users, where each entry specifies a user. The Alternate version of this collection simply changes the index location of the items from the parent collection. For example, suppose you had entries in machine and app level specified like this: machine.config => A, B, C web.config => D, E, F For BasicMap, the collection at the app level would be: A, B, C, D, E, F With BasicMapAlternate, it'd be: D, E, F, A, B, C That means that the Alternate allows the "nearest" config file entries to take precedence over the "parent" config file entries. - AddRemoveClearMap and AddRemoveClearMapAlternate This collection honors the "add, remove, clear" commands. Internally it keeps track of each of them so that it knows whether it has to write out an add/remove/clear at the appropriate levels, so it uses a concept of "virtual index" and "real index" to keep track of stuff. The "virtual index" is what the end user would see and use. The "real index" is just for us. Any access via indexes have to go through some transformation step. The Alternate version changes the inheritance stuff like the BasicMapAlternate, where the "nearest" config file entries take precedence over the "parent" config file entries (see example above). **********************************************************************/ BasicMap, AddRemoveClearMap, BasicMapAlternate, AddRemoveClearMapAlternate, } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/tests/GC/Scenarios/Affinity/affinitizer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Threading; using System.Diagnostics; public class Affinitizer { public static void Usage() { Console.WriteLine("Usage:"); Console.WriteLine("affinitizer.exe <num procs (0 for random)> <\"assembly.exe arg list\"> [random seed]"); } public static int Main(string[] args) { if ((args.Length < 2) || (args.Length > 3)) { Usage(); return 0; } int numProcessors = Environment.ProcessorCount; // get affinity IntPtr affinity = IntPtr.Zero; int a = 0; if ( (!int.TryParse(args[0], out a)) || (a < 0) ) { Usage(); return 0; } // cap the number of procs to the max on the machine affinity = new IntPtr(Math.Min(a, numProcessors)); // get process name and args string processName = null; string processArgs = null; int firstSpaceIndex = args[1].Trim().IndexOf(' '); if (firstSpaceIndex < 0) { // no args processName = args[1]; } else { processName = args[1].Substring(0, firstSpaceIndex); processArgs = args[1].Substring(firstSpaceIndex + 1); } // get random seed int seed = 0; if (args.Length == 3) { if (!int.TryParse(args[2], out seed)) { Usage(); return 0; } } else { seed = (int)DateTime.Now.Ticks; } Console.WriteLine("Running on a {0}-processor machine", numProcessors); return RunTest(affinity, processName, processArgs, seed); } public static int RunTest(IntPtr affinity, string processName, string processArgs, int seed) { // run the test Random rand = null; Process p = Process.Start(processName, processArgs); // cannot set the affinity before the process starts in managed code // This code executes so quickly that the GC heaps have not yet been initialized, // so it works. if (affinity != IntPtr.Zero) { // set affinity to (2^n)-1, where n=affinity int newAffinity = (int)Math.Pow(2, affinity.ToInt32())-1; p.ProcessorAffinity = new IntPtr(newAffinity); Console.WriteLine("Affinitizing to {0}", newAffinity); } else { rand = new Random(seed); Console.WriteLine("Using random seed: {0}", seed); } while (!p.HasExited) { // change affinity randomly every 5 seconds Thread.Sleep(5000); if (affinity == IntPtr.Zero) { try { // randomly change the affinity between 1 and (2^n)-1, where n=numProcessors int newAffinity = rand.Next(1, (int)Math.Pow(2, Environment.ProcessorCount)-1); p.ProcessorAffinity = new IntPtr(newAffinity); Console.WriteLine("Affinitizing to {0}", newAffinity); } // we couldn't set the affinity, so just exit catch (InvalidOperationException) { break; } catch (System.ComponentModel.Win32Exception) { break; } } } Console.WriteLine("Exiting with exit code {0}", p.ExitCode); return p.ExitCode; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Threading; using System.Diagnostics; public class Affinitizer { public static void Usage() { Console.WriteLine("Usage:"); Console.WriteLine("affinitizer.exe <num procs (0 for random)> <\"assembly.exe arg list\"> [random seed]"); } public static int Main(string[] args) { if ((args.Length < 2) || (args.Length > 3)) { Usage(); return 0; } int numProcessors = Environment.ProcessorCount; // get affinity IntPtr affinity = IntPtr.Zero; int a = 0; if ( (!int.TryParse(args[0], out a)) || (a < 0) ) { Usage(); return 0; } // cap the number of procs to the max on the machine affinity = new IntPtr(Math.Min(a, numProcessors)); // get process name and args string processName = null; string processArgs = null; int firstSpaceIndex = args[1].Trim().IndexOf(' '); if (firstSpaceIndex < 0) { // no args processName = args[1]; } else { processName = args[1].Substring(0, firstSpaceIndex); processArgs = args[1].Substring(firstSpaceIndex + 1); } // get random seed int seed = 0; if (args.Length == 3) { if (!int.TryParse(args[2], out seed)) { Usage(); return 0; } } else { seed = (int)DateTime.Now.Ticks; } Console.WriteLine("Running on a {0}-processor machine", numProcessors); return RunTest(affinity, processName, processArgs, seed); } public static int RunTest(IntPtr affinity, string processName, string processArgs, int seed) { // run the test Random rand = null; Process p = Process.Start(processName, processArgs); // cannot set the affinity before the process starts in managed code // This code executes so quickly that the GC heaps have not yet been initialized, // so it works. if (affinity != IntPtr.Zero) { // set affinity to (2^n)-1, where n=affinity int newAffinity = (int)Math.Pow(2, affinity.ToInt32())-1; p.ProcessorAffinity = new IntPtr(newAffinity); Console.WriteLine("Affinitizing to {0}", newAffinity); } else { rand = new Random(seed); Console.WriteLine("Using random seed: {0}", seed); } while (!p.HasExited) { // change affinity randomly every 5 seconds Thread.Sleep(5000); if (affinity == IntPtr.Zero) { try { // randomly change the affinity between 1 and (2^n)-1, where n=numProcessors int newAffinity = rand.Next(1, (int)Math.Pow(2, Environment.ProcessorCount)-1); p.ProcessorAffinity = new IntPtr(newAffinity); Console.WriteLine("Affinitizing to {0}", newAffinity); } // we couldn't set the affinity, so just exit catch (InvalidOperationException) { break; } catch (System.ComponentModel.Win32Exception) { break; } } } Console.WriteLine("Exiting with exit code {0}", p.ExitCode); return p.ExitCode; } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/libraries/System.Security.Claims/src/System/Security/Claims/ClaimsIdentity.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.Runtime.Serialization; using System.Security.Principal; namespace System.Security.Claims { /// <summary> /// An Identity that is represented by a set of claims. /// </summary> public class ClaimsIdentity : IIdentity { private enum SerializationMask { None = 0, AuthenticationType = 1, BootstrapConext = 2, NameClaimType = 4, RoleClaimType = 8, HasClaims = 16, HasLabel = 32, Actor = 64, UserData = 128, } private byte[]? _userSerializationData; private ClaimsIdentity? _actor; private string? _authenticationType; private object? _bootstrapContext; private List<List<Claim>>? _externalClaims; private string? _label; private readonly List<Claim> _instanceClaims = new List<Claim>(); private string _nameClaimType = DefaultNameClaimType; private string _roleClaimType = DefaultRoleClaimType; public const string DefaultIssuer = @"LOCAL AUTHORITY"; public const string DefaultNameClaimType = ClaimTypes.Name; public const string DefaultRoleClaimType = ClaimTypes.Role; // NOTE about _externalClaims. // GenericPrincpal and RolePrincipal set role claims here so that .IsInRole will be consistent with a 'role' claim found by querying the identity or principal. // _externalClaims are external to the identity and assumed to be dynamic, they not serialized or copied through Clone(). // Access through public method: ClaimProviders. /// <summary> /// Initializes an instance of <see cref="ClaimsIdentity"/>. /// </summary> public ClaimsIdentity() : this((IIdentity?)null, (IEnumerable<Claim>?)null, (string?)null, (string?)null, (string?)null) { } /// <summary> /// Initializes an instance of <see cref="ClaimsIdentity"/>. /// </summary> /// <param name="identity"><see cref="IIdentity"/> supplies the <see cref="Name"/> and <see cref="AuthenticationType"/>.</param> /// <remarks><seealso cref="ClaimsIdentity(IIdentity, IEnumerable{Claim}, string, string, string)"/> for details on how internal values are set.</remarks> public ClaimsIdentity(IIdentity? identity) : this(identity, (IEnumerable<Claim>?)null, (string?)null, (string?)null, (string?)null) { } /// <summary> /// Initializes an instance of <see cref="ClaimsIdentity"/>. /// </summary> /// <param name="claims"><see cref="IEnumerable{Claim}"/> associated with this instance.</param> /// <remarks> /// <remarks><seealso cref="ClaimsIdentity(IIdentity, IEnumerable{Claim}, string, string, string)"/> for details on how internal values are set.</remarks> /// </remarks> public ClaimsIdentity(IEnumerable<Claim>? claims) : this((IIdentity?)null, claims, (string?)null, (string?)null, (string?)null) { } /// <summary> /// Initializes an instance of <see cref="ClaimsIdentity"/>. /// </summary> /// <param name="authenticationType">The authentication method used to establish this identity.</param> public ClaimsIdentity(string? authenticationType) : this((IIdentity?)null, (IEnumerable<Claim>?)null, authenticationType, (string?)null, (string?)null) { } /// <summary> /// Initializes an instance of <see cref="ClaimsIdentity"/>. /// </summary> /// <param name="claims"><see cref="IEnumerable{Claim}"/> associated with this instance.</param> /// <param name="authenticationType">The authentication method used to establish this identity.</param> /// <remarks><seealso cref="ClaimsIdentity(IIdentity, IEnumerable{Claim}, string, string, string)"/> for details on how internal values are set.</remarks> public ClaimsIdentity(IEnumerable<Claim>? claims, string? authenticationType) : this((IIdentity?)null, claims, authenticationType, (string?)null, (string?)null) { } /// <summary> /// Initializes an instance of <see cref="ClaimsIdentity"/>. /// </summary> /// <param name="identity"><see cref="IIdentity"/> supplies the <see cref="Name"/> and <see cref="AuthenticationType"/>.</param> /// <param name="claims"><see cref="IEnumerable{Claim}"/> associated with this instance.</param> /// <remarks><seealso cref="ClaimsIdentity(IIdentity, IEnumerable{Claim}, string, string, string)"/> for details on how internal values are set.</remarks> public ClaimsIdentity(IIdentity? identity, IEnumerable<Claim>? claims) : this(identity, claims, (string?)null, (string?)null, (string?)null) { } /// <summary> /// Initializes an instance of <see cref="ClaimsIdentity"/>. /// </summary> /// <param name="authenticationType">The type of authentication used.</param> /// <param name="nameType">The <see cref="Claim.Type"/> used when obtaining the value of <see cref="ClaimsIdentity.Name"/>.</param> /// <param name="roleType">The <see cref="Claim.Type"/> used when performing logic for <see cref="ClaimsPrincipal.IsInRole"/>.</param> /// <remarks><seealso cref="ClaimsIdentity(IIdentity, IEnumerable{Claim}, string, string, string)"/> for details on how internal values are set.</remarks> public ClaimsIdentity(string? authenticationType, string? nameType, string? roleType) : this((IIdentity?)null, (IEnumerable<Claim>?)null, authenticationType, nameType, roleType) { } /// <summary> /// Initializes an instance of <see cref="ClaimsIdentity"/>. /// </summary> /// <param name="claims"><see cref="IEnumerable{Claim}"/> associated with this instance.</param> /// <param name="authenticationType">The type of authentication used.</param> /// <param name="nameType">The <see cref="Claim.Type"/> used when obtaining the value of <see cref="ClaimsIdentity.Name"/>.</param> /// <param name="roleType">The <see cref="Claim.Type"/> used when performing logic for <see cref="ClaimsPrincipal.IsInRole"/>.</param> /// <remarks><seealso cref="ClaimsIdentity(IIdentity, IEnumerable{Claim}, string, string, string)"/> for details on how internal values are set.</remarks> public ClaimsIdentity(IEnumerable<Claim>? claims, string? authenticationType, string? nameType, string? roleType) : this((IIdentity?)null, claims, authenticationType, nameType, roleType) { } /// <summary> /// Initializes an instance of <see cref="ClaimsIdentity"/>. /// </summary> /// <param name="identity"><see cref="IIdentity"/> supplies the <see cref="Name"/> and <see cref="AuthenticationType"/>.</param> /// <param name="claims"><see cref="IEnumerable{Claim}"/> associated with this instance.</param> /// <param name="authenticationType">The type of authentication used.</param> /// <param name="nameType">The <see cref="Claim.Type"/> used when obtaining the value of <see cref="ClaimsIdentity.Name"/>.</param> /// <param name="roleType">The <see cref="Claim.Type"/> used when performing logic for <see cref="ClaimsPrincipal.IsInRole"/>.</param> /// <remarks>If 'identity' is a <see cref="ClaimsIdentity"/>, then there are potentially multiple sources for AuthenticationType, NameClaimType, RoleClaimType. /// <para>Priority is given to the parameters: authenticationType, nameClaimType, roleClaimType.</para> /// <para>All <see cref="Claim"/>s are copied into this instance in a <see cref="List{Claim}"/>. Each Claim is examined and if Claim.Subject != this, then Claim.Clone(this) is called before the claim is added.</para> /// <para>Any 'External' claims are ignored.</para> /// </remarks> /// <exception cref="InvalidOperationException">if 'identity' is a <see cref="ClaimsIdentity"/> and <see cref="ClaimsIdentity.Actor"/> results in a circular reference back to 'this'.</exception> public ClaimsIdentity(IIdentity? identity, IEnumerable<Claim>? claims, string? authenticationType, string? nameType, string? roleType) { ClaimsIdentity? claimsIdentity = identity as ClaimsIdentity; _authenticationType = (identity != null && string.IsNullOrEmpty(authenticationType)) ? identity.AuthenticationType : authenticationType; _nameClaimType = !string.IsNullOrEmpty(nameType) ? nameType : (claimsIdentity != null ? claimsIdentity._nameClaimType : DefaultNameClaimType); _roleClaimType = !string.IsNullOrEmpty(roleType) ? roleType : (claimsIdentity != null ? claimsIdentity._roleClaimType : DefaultRoleClaimType); if (claimsIdentity != null) { _label = claimsIdentity._label; _bootstrapContext = claimsIdentity._bootstrapContext; if (claimsIdentity.Actor != null) { // // Check if the Actor is circular before copying. That check is done while setting // the Actor property and so not really needed here. But checking just for sanity sake // if (!IsCircular(claimsIdentity.Actor)) { _actor = claimsIdentity.Actor; } else { throw new InvalidOperationException(SR.InvalidOperationException_ActorGraphCircular); } } SafeAddClaims(claimsIdentity._instanceClaims); } else { if (identity != null && !string.IsNullOrEmpty(identity.Name)) { SafeAddClaim(new Claim(_nameClaimType, identity.Name, ClaimValueTypes.String, DefaultIssuer, DefaultIssuer, this)); } } if (claims != null) { SafeAddClaims(claims); } } /// <summary> /// Initializes an instance of <see cref="ClaimsIdentity"/> using a <see cref="BinaryReader"/>. /// Normally the <see cref="BinaryReader"/> is constructed using the bytes from <see cref="WriteTo(BinaryWriter)"/> and initialized in the same way as the <see cref="BinaryWriter"/>. /// </summary> /// <param name="reader">a <see cref="BinaryReader"/> pointing to a <see cref="ClaimsIdentity"/>.</param> /// <exception cref="ArgumentNullException">if 'reader' is null.</exception> public ClaimsIdentity(BinaryReader reader!!) { Initialize(reader); } /// <summary> /// Copy constructor. /// </summary> /// <param name="other"><see cref="ClaimsIdentity"/> to copy.</param> /// <exception cref="ArgumentNullException">if 'other' is null.</exception> protected ClaimsIdentity(ClaimsIdentity other!!) { if (other._actor != null) { _actor = other._actor.Clone(); } _authenticationType = other._authenticationType; _bootstrapContext = other._bootstrapContext; _label = other._label; _nameClaimType = other._nameClaimType; _roleClaimType = other._roleClaimType; if (other._userSerializationData != null) { _userSerializationData = other._userSerializationData.Clone() as byte[]; } SafeAddClaims(other._instanceClaims); } protected ClaimsIdentity(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(); } /// <summary> /// Initializes an instance of <see cref="ClaimsIdentity"/> from a serialized stream created via /// <see cref="ISerializable"/>. /// </summary> /// <param name="info"> /// The <see cref="SerializationInfo"/> to read from. /// </param> /// <exception cref="ArgumentNullException">Thrown is the <paramref name="info"/> is null.</exception> protected ClaimsIdentity(SerializationInfo info) { throw new PlatformNotSupportedException(); } /// <summary> /// Gets the authentication type that can be used to determine how this <see cref="ClaimsIdentity"/> authenticated to an authority. /// </summary> public virtual string? AuthenticationType { get { return _authenticationType; } } /// <summary> /// Gets a value that indicates if the user has been authenticated. /// </summary> public virtual bool IsAuthenticated { get { return !string.IsNullOrEmpty(_authenticationType); } } /// <summary> /// Gets or sets a <see cref="ClaimsIdentity"/> that was granted delegation rights. /// </summary> /// <exception cref="InvalidOperationException">if 'value' results in a circular reference back to 'this'.</exception> public ClaimsIdentity? Actor { get { return _actor; } set { if (value != null) { if (IsCircular(value)) { throw new InvalidOperationException(SR.InvalidOperationException_ActorGraphCircular); } } _actor = value; } } /// <summary> /// Gets or sets a context that was used to create this <see cref="ClaimsIdentity"/>. /// </summary> public object? BootstrapContext { get { return _bootstrapContext; } set { _bootstrapContext = value; } } /// <summary> /// Gets the claims as <see cref="IEnumerable{Claim}"/>, associated with this <see cref="ClaimsIdentity"/>. /// </summary> /// <remarks>May contain nulls.</remarks> public virtual IEnumerable<Claim> Claims { get { if (_externalClaims == null) { return _instanceClaims; } return CombinedClaimsIterator(); } } private IEnumerable<Claim> CombinedClaimsIterator() { for (int i = 0; i < _instanceClaims.Count; i++) { yield return _instanceClaims[i]; } for (int j = 0; j < _externalClaims!.Count; j++) { if (_externalClaims[j] != null) { foreach (Claim claim in _externalClaims[j]) { yield return claim; } } } } /// <summary> /// Contains any additional data provided by a derived type, typically set when calling <see cref="WriteTo(BinaryWriter, byte[])"/>. /// </summary> protected virtual byte[]? CustomSerializationData { get { return _userSerializationData; } } /// <summary> /// Allow the association of claims with this instance of <see cref="ClaimsIdentity"/>. /// The claims will not be serialized or added in Clone(). They will be included in searches, finds and returned from the call to <see cref="ClaimsIdentity.Claims"/>. /// </summary> internal List<List<Claim>> ExternalClaims { get { if (_externalClaims == null) { _externalClaims = new List<List<Claim>>(); } return _externalClaims; } } /// <summary> /// Gets or sets the label for this <see cref="ClaimsIdentity"/> /// </summary> public string? Label { get { return _label; } set { _label = value; } } /// <summary> /// Gets the Name of this <see cref="ClaimsIdentity"/>. /// </summary> /// <remarks>Calls <see cref="FindFirst(string)"/> where string == NameClaimType, if found, returns <see cref="Claim.Value"/> otherwise null.</remarks> public virtual string? Name { // just an accessor for getting the name claim get { Claim? claim = FindFirst(_nameClaimType); if (claim != null) { return claim.Value; } return null; } } /// <summary> /// Gets the value that identifies 'Name' claims. This is used when returning the property <see cref="ClaimsIdentity.Name"/>. /// </summary> public string NameClaimType { get { return _nameClaimType; } } /// <summary> /// Gets the value that identifies 'Role' claims. This is used when calling <see cref="ClaimsPrincipal.IsInRole"/>. /// </summary> public string RoleClaimType { get { return _roleClaimType; } } /// <summary> /// Creates a new instance of <see cref="ClaimsIdentity"/> with values copied from this object. /// </summary> public virtual ClaimsIdentity Clone() { return new ClaimsIdentity(this); } /// <summary> /// Adds a single <see cref="Claim"/> to an internal list. /// </summary> /// <param name="claim">the <see cref="Claim"/>add.</param> /// <remarks>If <see cref="Claim.Subject"/> != this, then Claim.Clone(this) is called before the claim is added.</remarks> /// <exception cref="ArgumentNullException">if 'claim' is null.</exception> public virtual void AddClaim(Claim claim!!) { if (object.ReferenceEquals(claim.Subject, this)) { _instanceClaims.Add(claim); } else { _instanceClaims.Add(claim.Clone(this)); } } /// <summary> /// Adds a <see cref="IEnumerable{Claim}"/> to the internal list. /// </summary> /// <param name="claims">Enumeration of claims to add.</param> /// <remarks>Each claim is examined and if <see cref="Claim.Subject"/> != this, then Claim.Clone(this) is called before the claim is added.</remarks> /// <exception cref="ArgumentNullException">if 'claims' is null.</exception> public virtual void AddClaims(IEnumerable<Claim?> claims!!) { foreach (Claim? claim in claims) { if (claim == null) { continue; } if (object.ReferenceEquals(claim.Subject, this)) { _instanceClaims.Add(claim); } else { _instanceClaims.Add(claim.Clone(this)); } } } /// <summary> /// Attempts to remove a <see cref="Claim"/> the internal list. /// </summary> /// <param name="claim">the <see cref="Claim"/> to match.</param> /// <remarks> It is possible that a <see cref="Claim"/> returned from <see cref="Claims"/> cannot be removed. This would be the case for 'External' claims that are provided by reference. /// <para>object.ReferenceEquals is used to 'match'.</para> /// </remarks> public virtual bool TryRemoveClaim(Claim? claim) { if (claim == null) { return false; } bool removed = false; for (int i = 0; i < _instanceClaims.Count; i++) { if (object.ReferenceEquals(_instanceClaims[i], claim)) { _instanceClaims.RemoveAt(i); removed = true; break; } } return removed; } /// <summary> /// Removes a <see cref="Claim"/> from the internal list. /// </summary> /// <param name="claim">the <see cref="Claim"/> to match.</param> /// <remarks> It is possible that a <see cref="Claim"/> returned from <see cref="Claims"/> cannot be removed. This would be the case for 'External' claims that are provided by reference. /// <para>object.ReferenceEquals is used to 'match'.</para> /// </remarks> /// <exception cref="InvalidOperationException">if 'claim' cannot be removed.</exception> public virtual void RemoveClaim(Claim? claim) { if (!TryRemoveClaim(claim)) { throw new InvalidOperationException(SR.Format(SR.InvalidOperation_ClaimCannotBeRemoved, claim)); } } /// <summary> /// Adds claims to internal list. Calling Claim.Clone if Claim.Subject != this. /// </summary> /// <param name="claims">a <see cref="IEnumerable{Claim}"/> to add to </param> /// <remarks>private only call from constructor, adds to internal list.</remarks> private void SafeAddClaims(IEnumerable<Claim?> claims) { foreach (Claim? claim in claims) { if (claim == null) continue; if (object.ReferenceEquals(claim.Subject, this)) { _instanceClaims.Add(claim); } else { _instanceClaims.Add(claim.Clone(this)); } } } /// <summary> /// Adds claim to internal list. Calling Claim.Clone if Claim.Subject != this. /// </summary> /// <remarks>private only call from constructor, adds to internal list.</remarks> private void SafeAddClaim(Claim? claim) { if (claim == null) return; if (object.ReferenceEquals(claim.Subject, this)) { _instanceClaims.Add(claim); } else { _instanceClaims.Add(claim.Clone(this)); } } /// <summary> /// Retrieves a <see cref="IEnumerable{Claim}"/> where each claim is matched by <paramref name="match"/>. /// </summary> /// <param name="match">The function that performs the matching logic.</param> /// <returns>A <see cref="IEnumerable{Claim}"/> of matched claims.</returns> /// <exception cref="ArgumentNullException">if 'match' is null.</exception> public virtual IEnumerable<Claim> FindAll(Predicate<Claim> match!!) { foreach (Claim claim in Claims) { if (match(claim)) { yield return claim; } } } /// <summary> /// Retrieves a <see cref="IEnumerable{Claim}"/> where each Claim.Type equals <paramref name="type"/>. /// </summary> /// <param name="type">The type of the claim to match.</param> /// <returns>A <see cref="IEnumerable{Claim}"/> of matched claims.</returns> /// <remarks>Comparison is: StringComparison.OrdinalIgnoreCase.</remarks> /// <exception cref="ArgumentNullException">if 'type' is null.</exception> public virtual IEnumerable<Claim> FindAll(string type!!) { foreach (Claim claim in Claims) { if (claim != null) { if (string.Equals(claim.Type, type, StringComparison.OrdinalIgnoreCase)) { yield return claim; } } } } /// <summary> /// Retrieves the first <see cref="Claim"/> that is matched by <paramref name="match"/>. /// </summary> /// <param name="match">The function that performs the matching logic.</param> /// <returns>A <see cref="Claim"/>, null if nothing matches.</returns> /// <exception cref="ArgumentNullException">if 'match' is null.</exception> public virtual Claim? FindFirst(Predicate<Claim> match!!) { foreach (Claim claim in Claims) { if (match(claim)) { return claim; } } return null; } /// <summary> /// Retrieves the first <see cref="Claim"/> where Claim.Type equals <paramref name="type"/>. /// </summary> /// <param name="type">The type of the claim to match.</param> /// <returns>A <see cref="Claim"/>, null if nothing matches.</returns> /// <remarks>Comparison is: StringComparison.OrdinalIgnoreCase.</remarks> /// <exception cref="ArgumentNullException">if 'type' is null.</exception> public virtual Claim? FindFirst(string type!!) { foreach (Claim claim in Claims) { if (claim != null) { if (string.Equals(claim.Type, type, StringComparison.OrdinalIgnoreCase)) { return claim; } } } return null; } /// <summary> /// Determines if a claim is contained within this ClaimsIdentity. /// </summary> /// <param name="match">The function that performs the matching logic.</param> /// <returns>true if a claim is found, false otherwise.</returns> /// <exception cref="ArgumentNullException">if 'match' is null.</exception> public virtual bool HasClaim(Predicate<Claim> match!!) { foreach (Claim claim in Claims) { if (match(claim)) { return true; } } return false; } /// <summary> /// Determines if a claim with type AND value is contained within this ClaimsIdentity. /// </summary> /// <param name="type">the type of the claim to match.</param> /// <param name="value">the value of the claim to match.</param> /// <returns>true if a claim is matched, false otherwise.</returns> /// <remarks>Comparison is: StringComparison.OrdinalIgnoreCase for Claim.Type, StringComparison.Ordinal for Claim.Value.</remarks> /// <exception cref="ArgumentNullException">if 'type' is null.</exception> /// <exception cref="ArgumentNullException">if 'value' is null.</exception> public virtual bool HasClaim(string type!!, string value!!) { foreach (Claim claim in Claims) { if (claim != null && string.Equals(claim.Type, type, StringComparison.OrdinalIgnoreCase) && string.Equals(claim.Value, value, StringComparison.Ordinal)) { return true; } } return false; } /// <summary> /// Initializes from a <see cref="BinaryReader"/>. Normally the reader is initialized with the results from <see cref="WriteTo(BinaryWriter)"/> /// Normally the <see cref="BinaryReader"/> is initialized in the same way as the <see cref="BinaryWriter"/> passed to <see cref="WriteTo(BinaryWriter)"/>. /// </summary> /// <param name="reader">a <see cref="BinaryReader"/> pointing to a <see cref="ClaimsIdentity"/>.</param> /// <exception cref="ArgumentNullException">if 'reader' is null.</exception> private void Initialize(BinaryReader reader!!) { SerializationMask mask = (SerializationMask)reader.ReadInt32(); int numPropertiesRead = 0; int numPropertiesToRead = reader.ReadInt32(); if ((mask & SerializationMask.AuthenticationType) == SerializationMask.AuthenticationType) { _authenticationType = reader.ReadString(); numPropertiesRead++; } if ((mask & SerializationMask.BootstrapConext) == SerializationMask.BootstrapConext) { _bootstrapContext = reader.ReadString(); numPropertiesRead++; } if ((mask & SerializationMask.NameClaimType) == SerializationMask.NameClaimType) { _nameClaimType = reader.ReadString(); numPropertiesRead++; } else { _nameClaimType = ClaimsIdentity.DefaultNameClaimType; } if ((mask & SerializationMask.RoleClaimType) == SerializationMask.RoleClaimType) { _roleClaimType = reader.ReadString(); numPropertiesRead++; } else { _roleClaimType = ClaimsIdentity.DefaultRoleClaimType; } if ((mask & SerializationMask.HasLabel) == SerializationMask.HasLabel) { _label = reader.ReadString(); numPropertiesRead++; } if ((mask & SerializationMask.HasClaims) == SerializationMask.HasClaims) { int numberOfClaims = reader.ReadInt32(); for (int index = 0; index < numberOfClaims; index++) { _instanceClaims.Add(CreateClaim(reader)); } numPropertiesRead++; } if ((mask & SerializationMask.Actor) == SerializationMask.Actor) { _actor = new ClaimsIdentity(reader); numPropertiesRead++; } if ((mask & SerializationMask.UserData) == SerializationMask.UserData) { int cb = reader.ReadInt32(); _userSerializationData = reader.ReadBytes(cb); numPropertiesRead++; } for (int i = numPropertiesRead; i < numPropertiesToRead; i++) { reader.ReadString(); } } /// <summary> /// Provides an extensibility point for derived types to create a custom <see cref="Claim"/>. /// </summary> /// <param name="reader">the <see cref="BinaryReader"/>that points at the claim.</param> /// <returns>a new <see cref="Claim"/>.</returns> protected virtual Claim CreateClaim(BinaryReader reader!!) { return new Claim(reader, this); } /// <summary> /// Serializes using a <see cref="BinaryWriter"/> /// </summary> /// <param name="writer">the <see cref="BinaryWriter"/> to use for data storage.</param> /// <exception cref="ArgumentNullException">if 'writer' is null.</exception> public virtual void WriteTo(BinaryWriter writer) { WriteTo(writer, null); } /// <summary> /// Serializes using a <see cref="BinaryWriter"/> /// </summary> /// <param name="writer">the <see cref="BinaryWriter"/> to use for data storage.</param> /// <param name="userData">additional data provided by derived type.</param> /// <exception cref="ArgumentNullException">if 'writer' is null.</exception> protected virtual void WriteTo(BinaryWriter writer!!, byte[]? userData) { int numberOfPropertiesWritten = 0; var mask = SerializationMask.None; if (_authenticationType != null) { mask |= SerializationMask.AuthenticationType; numberOfPropertiesWritten++; } if (_bootstrapContext != null) { if (_bootstrapContext is string) { mask |= SerializationMask.BootstrapConext; numberOfPropertiesWritten++; } } if (!string.Equals(_nameClaimType, ClaimsIdentity.DefaultNameClaimType, StringComparison.Ordinal)) { mask |= SerializationMask.NameClaimType; numberOfPropertiesWritten++; } if (!string.Equals(_roleClaimType, ClaimsIdentity.DefaultRoleClaimType, StringComparison.Ordinal)) { mask |= SerializationMask.RoleClaimType; numberOfPropertiesWritten++; } if (!string.IsNullOrWhiteSpace(_label)) { mask |= SerializationMask.HasLabel; numberOfPropertiesWritten++; } if (_instanceClaims.Count > 0) { mask |= SerializationMask.HasClaims; numberOfPropertiesWritten++; } if (_actor != null) { mask |= SerializationMask.Actor; numberOfPropertiesWritten++; } if (userData != null && userData.Length > 0) { numberOfPropertiesWritten++; mask |= SerializationMask.UserData; } writer.Write((int)mask); writer.Write(numberOfPropertiesWritten); if ((mask & SerializationMask.AuthenticationType) == SerializationMask.AuthenticationType) { writer.Write(_authenticationType!); } if ((mask & SerializationMask.BootstrapConext) == SerializationMask.BootstrapConext) { writer.Write((string)_bootstrapContext!); } if ((mask & SerializationMask.NameClaimType) == SerializationMask.NameClaimType) { writer.Write(_nameClaimType); } if ((mask & SerializationMask.RoleClaimType) == SerializationMask.RoleClaimType) { writer.Write(_roleClaimType); } if ((mask & SerializationMask.HasLabel) == SerializationMask.HasLabel) { writer.Write(_label!); } if ((mask & SerializationMask.HasClaims) == SerializationMask.HasClaims) { writer.Write(_instanceClaims.Count); foreach (var claim in _instanceClaims) { claim.WriteTo(writer); } } if ((mask & SerializationMask.Actor) == SerializationMask.Actor) { _actor!.WriteTo(writer); } if ((mask & SerializationMask.UserData) == SerializationMask.UserData) { writer.Write(userData!.Length); writer.Write(userData); } writer.Flush(); } /// <summary> /// Checks if a circular reference exists to 'this' /// </summary> /// <param name="subject"></param> /// <returns></returns> private bool IsCircular(ClaimsIdentity subject) { if (ReferenceEquals(this, subject)) { return true; } ClaimsIdentity currSubject = subject; while (currSubject.Actor != null) { if (ReferenceEquals(this, currSubject.Actor)) { return true; } currSubject = currSubject.Actor; } return false; } /// <summary> /// Populates the specified <see cref="SerializationInfo"/> with the serialization data for the ClaimsIdentity /// </summary> /// <param name="info">The serialization information stream to write to. Satisfies ISerializable contract.</param> /// <param name="context">Context for serialization. Can be null.</param> /// <exception cref="ArgumentNullException">Thrown if the info parameter is null.</exception> protected virtual void GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(); } } }
// 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.Runtime.Serialization; using System.Security.Principal; namespace System.Security.Claims { /// <summary> /// An Identity that is represented by a set of claims. /// </summary> public class ClaimsIdentity : IIdentity { private enum SerializationMask { None = 0, AuthenticationType = 1, BootstrapConext = 2, NameClaimType = 4, RoleClaimType = 8, HasClaims = 16, HasLabel = 32, Actor = 64, UserData = 128, } private byte[]? _userSerializationData; private ClaimsIdentity? _actor; private string? _authenticationType; private object? _bootstrapContext; private List<List<Claim>>? _externalClaims; private string? _label; private readonly List<Claim> _instanceClaims = new List<Claim>(); private string _nameClaimType = DefaultNameClaimType; private string _roleClaimType = DefaultRoleClaimType; public const string DefaultIssuer = @"LOCAL AUTHORITY"; public const string DefaultNameClaimType = ClaimTypes.Name; public const string DefaultRoleClaimType = ClaimTypes.Role; // NOTE about _externalClaims. // GenericPrincpal and RolePrincipal set role claims here so that .IsInRole will be consistent with a 'role' claim found by querying the identity or principal. // _externalClaims are external to the identity and assumed to be dynamic, they not serialized or copied through Clone(). // Access through public method: ClaimProviders. /// <summary> /// Initializes an instance of <see cref="ClaimsIdentity"/>. /// </summary> public ClaimsIdentity() : this((IIdentity?)null, (IEnumerable<Claim>?)null, (string?)null, (string?)null, (string?)null) { } /// <summary> /// Initializes an instance of <see cref="ClaimsIdentity"/>. /// </summary> /// <param name="identity"><see cref="IIdentity"/> supplies the <see cref="Name"/> and <see cref="AuthenticationType"/>.</param> /// <remarks><seealso cref="ClaimsIdentity(IIdentity, IEnumerable{Claim}, string, string, string)"/> for details on how internal values are set.</remarks> public ClaimsIdentity(IIdentity? identity) : this(identity, (IEnumerable<Claim>?)null, (string?)null, (string?)null, (string?)null) { } /// <summary> /// Initializes an instance of <see cref="ClaimsIdentity"/>. /// </summary> /// <param name="claims"><see cref="IEnumerable{Claim}"/> associated with this instance.</param> /// <remarks> /// <remarks><seealso cref="ClaimsIdentity(IIdentity, IEnumerable{Claim}, string, string, string)"/> for details on how internal values are set.</remarks> /// </remarks> public ClaimsIdentity(IEnumerable<Claim>? claims) : this((IIdentity?)null, claims, (string?)null, (string?)null, (string?)null) { } /// <summary> /// Initializes an instance of <see cref="ClaimsIdentity"/>. /// </summary> /// <param name="authenticationType">The authentication method used to establish this identity.</param> public ClaimsIdentity(string? authenticationType) : this((IIdentity?)null, (IEnumerable<Claim>?)null, authenticationType, (string?)null, (string?)null) { } /// <summary> /// Initializes an instance of <see cref="ClaimsIdentity"/>. /// </summary> /// <param name="claims"><see cref="IEnumerable{Claim}"/> associated with this instance.</param> /// <param name="authenticationType">The authentication method used to establish this identity.</param> /// <remarks><seealso cref="ClaimsIdentity(IIdentity, IEnumerable{Claim}, string, string, string)"/> for details on how internal values are set.</remarks> public ClaimsIdentity(IEnumerable<Claim>? claims, string? authenticationType) : this((IIdentity?)null, claims, authenticationType, (string?)null, (string?)null) { } /// <summary> /// Initializes an instance of <see cref="ClaimsIdentity"/>. /// </summary> /// <param name="identity"><see cref="IIdentity"/> supplies the <see cref="Name"/> and <see cref="AuthenticationType"/>.</param> /// <param name="claims"><see cref="IEnumerable{Claim}"/> associated with this instance.</param> /// <remarks><seealso cref="ClaimsIdentity(IIdentity, IEnumerable{Claim}, string, string, string)"/> for details on how internal values are set.</remarks> public ClaimsIdentity(IIdentity? identity, IEnumerable<Claim>? claims) : this(identity, claims, (string?)null, (string?)null, (string?)null) { } /// <summary> /// Initializes an instance of <see cref="ClaimsIdentity"/>. /// </summary> /// <param name="authenticationType">The type of authentication used.</param> /// <param name="nameType">The <see cref="Claim.Type"/> used when obtaining the value of <see cref="ClaimsIdentity.Name"/>.</param> /// <param name="roleType">The <see cref="Claim.Type"/> used when performing logic for <see cref="ClaimsPrincipal.IsInRole"/>.</param> /// <remarks><seealso cref="ClaimsIdentity(IIdentity, IEnumerable{Claim}, string, string, string)"/> for details on how internal values are set.</remarks> public ClaimsIdentity(string? authenticationType, string? nameType, string? roleType) : this((IIdentity?)null, (IEnumerable<Claim>?)null, authenticationType, nameType, roleType) { } /// <summary> /// Initializes an instance of <see cref="ClaimsIdentity"/>. /// </summary> /// <param name="claims"><see cref="IEnumerable{Claim}"/> associated with this instance.</param> /// <param name="authenticationType">The type of authentication used.</param> /// <param name="nameType">The <see cref="Claim.Type"/> used when obtaining the value of <see cref="ClaimsIdentity.Name"/>.</param> /// <param name="roleType">The <see cref="Claim.Type"/> used when performing logic for <see cref="ClaimsPrincipal.IsInRole"/>.</param> /// <remarks><seealso cref="ClaimsIdentity(IIdentity, IEnumerable{Claim}, string, string, string)"/> for details on how internal values are set.</remarks> public ClaimsIdentity(IEnumerable<Claim>? claims, string? authenticationType, string? nameType, string? roleType) : this((IIdentity?)null, claims, authenticationType, nameType, roleType) { } /// <summary> /// Initializes an instance of <see cref="ClaimsIdentity"/>. /// </summary> /// <param name="identity"><see cref="IIdentity"/> supplies the <see cref="Name"/> and <see cref="AuthenticationType"/>.</param> /// <param name="claims"><see cref="IEnumerable{Claim}"/> associated with this instance.</param> /// <param name="authenticationType">The type of authentication used.</param> /// <param name="nameType">The <see cref="Claim.Type"/> used when obtaining the value of <see cref="ClaimsIdentity.Name"/>.</param> /// <param name="roleType">The <see cref="Claim.Type"/> used when performing logic for <see cref="ClaimsPrincipal.IsInRole"/>.</param> /// <remarks>If 'identity' is a <see cref="ClaimsIdentity"/>, then there are potentially multiple sources for AuthenticationType, NameClaimType, RoleClaimType. /// <para>Priority is given to the parameters: authenticationType, nameClaimType, roleClaimType.</para> /// <para>All <see cref="Claim"/>s are copied into this instance in a <see cref="List{Claim}"/>. Each Claim is examined and if Claim.Subject != this, then Claim.Clone(this) is called before the claim is added.</para> /// <para>Any 'External' claims are ignored.</para> /// </remarks> /// <exception cref="InvalidOperationException">if 'identity' is a <see cref="ClaimsIdentity"/> and <see cref="ClaimsIdentity.Actor"/> results in a circular reference back to 'this'.</exception> public ClaimsIdentity(IIdentity? identity, IEnumerable<Claim>? claims, string? authenticationType, string? nameType, string? roleType) { ClaimsIdentity? claimsIdentity = identity as ClaimsIdentity; _authenticationType = (identity != null && string.IsNullOrEmpty(authenticationType)) ? identity.AuthenticationType : authenticationType; _nameClaimType = !string.IsNullOrEmpty(nameType) ? nameType : (claimsIdentity != null ? claimsIdentity._nameClaimType : DefaultNameClaimType); _roleClaimType = !string.IsNullOrEmpty(roleType) ? roleType : (claimsIdentity != null ? claimsIdentity._roleClaimType : DefaultRoleClaimType); if (claimsIdentity != null) { _label = claimsIdentity._label; _bootstrapContext = claimsIdentity._bootstrapContext; if (claimsIdentity.Actor != null) { // // Check if the Actor is circular before copying. That check is done while setting // the Actor property and so not really needed here. But checking just for sanity sake // if (!IsCircular(claimsIdentity.Actor)) { _actor = claimsIdentity.Actor; } else { throw new InvalidOperationException(SR.InvalidOperationException_ActorGraphCircular); } } SafeAddClaims(claimsIdentity._instanceClaims); } else { if (identity != null && !string.IsNullOrEmpty(identity.Name)) { SafeAddClaim(new Claim(_nameClaimType, identity.Name, ClaimValueTypes.String, DefaultIssuer, DefaultIssuer, this)); } } if (claims != null) { SafeAddClaims(claims); } } /// <summary> /// Initializes an instance of <see cref="ClaimsIdentity"/> using a <see cref="BinaryReader"/>. /// Normally the <see cref="BinaryReader"/> is constructed using the bytes from <see cref="WriteTo(BinaryWriter)"/> and initialized in the same way as the <see cref="BinaryWriter"/>. /// </summary> /// <param name="reader">a <see cref="BinaryReader"/> pointing to a <see cref="ClaimsIdentity"/>.</param> /// <exception cref="ArgumentNullException">if 'reader' is null.</exception> public ClaimsIdentity(BinaryReader reader!!) { Initialize(reader); } /// <summary> /// Copy constructor. /// </summary> /// <param name="other"><see cref="ClaimsIdentity"/> to copy.</param> /// <exception cref="ArgumentNullException">if 'other' is null.</exception> protected ClaimsIdentity(ClaimsIdentity other!!) { if (other._actor != null) { _actor = other._actor.Clone(); } _authenticationType = other._authenticationType; _bootstrapContext = other._bootstrapContext; _label = other._label; _nameClaimType = other._nameClaimType; _roleClaimType = other._roleClaimType; if (other._userSerializationData != null) { _userSerializationData = other._userSerializationData.Clone() as byte[]; } SafeAddClaims(other._instanceClaims); } protected ClaimsIdentity(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(); } /// <summary> /// Initializes an instance of <see cref="ClaimsIdentity"/> from a serialized stream created via /// <see cref="ISerializable"/>. /// </summary> /// <param name="info"> /// The <see cref="SerializationInfo"/> to read from. /// </param> /// <exception cref="ArgumentNullException">Thrown is the <paramref name="info"/> is null.</exception> protected ClaimsIdentity(SerializationInfo info) { throw new PlatformNotSupportedException(); } /// <summary> /// Gets the authentication type that can be used to determine how this <see cref="ClaimsIdentity"/> authenticated to an authority. /// </summary> public virtual string? AuthenticationType { get { return _authenticationType; } } /// <summary> /// Gets a value that indicates if the user has been authenticated. /// </summary> public virtual bool IsAuthenticated { get { return !string.IsNullOrEmpty(_authenticationType); } } /// <summary> /// Gets or sets a <see cref="ClaimsIdentity"/> that was granted delegation rights. /// </summary> /// <exception cref="InvalidOperationException">if 'value' results in a circular reference back to 'this'.</exception> public ClaimsIdentity? Actor { get { return _actor; } set { if (value != null) { if (IsCircular(value)) { throw new InvalidOperationException(SR.InvalidOperationException_ActorGraphCircular); } } _actor = value; } } /// <summary> /// Gets or sets a context that was used to create this <see cref="ClaimsIdentity"/>. /// </summary> public object? BootstrapContext { get { return _bootstrapContext; } set { _bootstrapContext = value; } } /// <summary> /// Gets the claims as <see cref="IEnumerable{Claim}"/>, associated with this <see cref="ClaimsIdentity"/>. /// </summary> /// <remarks>May contain nulls.</remarks> public virtual IEnumerable<Claim> Claims { get { if (_externalClaims == null) { return _instanceClaims; } return CombinedClaimsIterator(); } } private IEnumerable<Claim> CombinedClaimsIterator() { for (int i = 0; i < _instanceClaims.Count; i++) { yield return _instanceClaims[i]; } for (int j = 0; j < _externalClaims!.Count; j++) { if (_externalClaims[j] != null) { foreach (Claim claim in _externalClaims[j]) { yield return claim; } } } } /// <summary> /// Contains any additional data provided by a derived type, typically set when calling <see cref="WriteTo(BinaryWriter, byte[])"/>. /// </summary> protected virtual byte[]? CustomSerializationData { get { return _userSerializationData; } } /// <summary> /// Allow the association of claims with this instance of <see cref="ClaimsIdentity"/>. /// The claims will not be serialized or added in Clone(). They will be included in searches, finds and returned from the call to <see cref="ClaimsIdentity.Claims"/>. /// </summary> internal List<List<Claim>> ExternalClaims { get { if (_externalClaims == null) { _externalClaims = new List<List<Claim>>(); } return _externalClaims; } } /// <summary> /// Gets or sets the label for this <see cref="ClaimsIdentity"/> /// </summary> public string? Label { get { return _label; } set { _label = value; } } /// <summary> /// Gets the Name of this <see cref="ClaimsIdentity"/>. /// </summary> /// <remarks>Calls <see cref="FindFirst(string)"/> where string == NameClaimType, if found, returns <see cref="Claim.Value"/> otherwise null.</remarks> public virtual string? Name { // just an accessor for getting the name claim get { Claim? claim = FindFirst(_nameClaimType); if (claim != null) { return claim.Value; } return null; } } /// <summary> /// Gets the value that identifies 'Name' claims. This is used when returning the property <see cref="ClaimsIdentity.Name"/>. /// </summary> public string NameClaimType { get { return _nameClaimType; } } /// <summary> /// Gets the value that identifies 'Role' claims. This is used when calling <see cref="ClaimsPrincipal.IsInRole"/>. /// </summary> public string RoleClaimType { get { return _roleClaimType; } } /// <summary> /// Creates a new instance of <see cref="ClaimsIdentity"/> with values copied from this object. /// </summary> public virtual ClaimsIdentity Clone() { return new ClaimsIdentity(this); } /// <summary> /// Adds a single <see cref="Claim"/> to an internal list. /// </summary> /// <param name="claim">the <see cref="Claim"/>add.</param> /// <remarks>If <see cref="Claim.Subject"/> != this, then Claim.Clone(this) is called before the claim is added.</remarks> /// <exception cref="ArgumentNullException">if 'claim' is null.</exception> public virtual void AddClaim(Claim claim!!) { if (object.ReferenceEquals(claim.Subject, this)) { _instanceClaims.Add(claim); } else { _instanceClaims.Add(claim.Clone(this)); } } /// <summary> /// Adds a <see cref="IEnumerable{Claim}"/> to the internal list. /// </summary> /// <param name="claims">Enumeration of claims to add.</param> /// <remarks>Each claim is examined and if <see cref="Claim.Subject"/> != this, then Claim.Clone(this) is called before the claim is added.</remarks> /// <exception cref="ArgumentNullException">if 'claims' is null.</exception> public virtual void AddClaims(IEnumerable<Claim?> claims!!) { foreach (Claim? claim in claims) { if (claim == null) { continue; } if (object.ReferenceEquals(claim.Subject, this)) { _instanceClaims.Add(claim); } else { _instanceClaims.Add(claim.Clone(this)); } } } /// <summary> /// Attempts to remove a <see cref="Claim"/> the internal list. /// </summary> /// <param name="claim">the <see cref="Claim"/> to match.</param> /// <remarks> It is possible that a <see cref="Claim"/> returned from <see cref="Claims"/> cannot be removed. This would be the case for 'External' claims that are provided by reference. /// <para>object.ReferenceEquals is used to 'match'.</para> /// </remarks> public virtual bool TryRemoveClaim(Claim? claim) { if (claim == null) { return false; } bool removed = false; for (int i = 0; i < _instanceClaims.Count; i++) { if (object.ReferenceEquals(_instanceClaims[i], claim)) { _instanceClaims.RemoveAt(i); removed = true; break; } } return removed; } /// <summary> /// Removes a <see cref="Claim"/> from the internal list. /// </summary> /// <param name="claim">the <see cref="Claim"/> to match.</param> /// <remarks> It is possible that a <see cref="Claim"/> returned from <see cref="Claims"/> cannot be removed. This would be the case for 'External' claims that are provided by reference. /// <para>object.ReferenceEquals is used to 'match'.</para> /// </remarks> /// <exception cref="InvalidOperationException">if 'claim' cannot be removed.</exception> public virtual void RemoveClaim(Claim? claim) { if (!TryRemoveClaim(claim)) { throw new InvalidOperationException(SR.Format(SR.InvalidOperation_ClaimCannotBeRemoved, claim)); } } /// <summary> /// Adds claims to internal list. Calling Claim.Clone if Claim.Subject != this. /// </summary> /// <param name="claims">a <see cref="IEnumerable{Claim}"/> to add to </param> /// <remarks>private only call from constructor, adds to internal list.</remarks> private void SafeAddClaims(IEnumerable<Claim?> claims) { foreach (Claim? claim in claims) { if (claim == null) continue; if (object.ReferenceEquals(claim.Subject, this)) { _instanceClaims.Add(claim); } else { _instanceClaims.Add(claim.Clone(this)); } } } /// <summary> /// Adds claim to internal list. Calling Claim.Clone if Claim.Subject != this. /// </summary> /// <remarks>private only call from constructor, adds to internal list.</remarks> private void SafeAddClaim(Claim? claim) { if (claim == null) return; if (object.ReferenceEquals(claim.Subject, this)) { _instanceClaims.Add(claim); } else { _instanceClaims.Add(claim.Clone(this)); } } /// <summary> /// Retrieves a <see cref="IEnumerable{Claim}"/> where each claim is matched by <paramref name="match"/>. /// </summary> /// <param name="match">The function that performs the matching logic.</param> /// <returns>A <see cref="IEnumerable{Claim}"/> of matched claims.</returns> /// <exception cref="ArgumentNullException">if 'match' is null.</exception> public virtual IEnumerable<Claim> FindAll(Predicate<Claim> match!!) { foreach (Claim claim in Claims) { if (match(claim)) { yield return claim; } } } /// <summary> /// Retrieves a <see cref="IEnumerable{Claim}"/> where each Claim.Type equals <paramref name="type"/>. /// </summary> /// <param name="type">The type of the claim to match.</param> /// <returns>A <see cref="IEnumerable{Claim}"/> of matched claims.</returns> /// <remarks>Comparison is: StringComparison.OrdinalIgnoreCase.</remarks> /// <exception cref="ArgumentNullException">if 'type' is null.</exception> public virtual IEnumerable<Claim> FindAll(string type!!) { foreach (Claim claim in Claims) { if (claim != null) { if (string.Equals(claim.Type, type, StringComparison.OrdinalIgnoreCase)) { yield return claim; } } } } /// <summary> /// Retrieves the first <see cref="Claim"/> that is matched by <paramref name="match"/>. /// </summary> /// <param name="match">The function that performs the matching logic.</param> /// <returns>A <see cref="Claim"/>, null if nothing matches.</returns> /// <exception cref="ArgumentNullException">if 'match' is null.</exception> public virtual Claim? FindFirst(Predicate<Claim> match!!) { foreach (Claim claim in Claims) { if (match(claim)) { return claim; } } return null; } /// <summary> /// Retrieves the first <see cref="Claim"/> where Claim.Type equals <paramref name="type"/>. /// </summary> /// <param name="type">The type of the claim to match.</param> /// <returns>A <see cref="Claim"/>, null if nothing matches.</returns> /// <remarks>Comparison is: StringComparison.OrdinalIgnoreCase.</remarks> /// <exception cref="ArgumentNullException">if 'type' is null.</exception> public virtual Claim? FindFirst(string type!!) { foreach (Claim claim in Claims) { if (claim != null) { if (string.Equals(claim.Type, type, StringComparison.OrdinalIgnoreCase)) { return claim; } } } return null; } /// <summary> /// Determines if a claim is contained within this ClaimsIdentity. /// </summary> /// <param name="match">The function that performs the matching logic.</param> /// <returns>true if a claim is found, false otherwise.</returns> /// <exception cref="ArgumentNullException">if 'match' is null.</exception> public virtual bool HasClaim(Predicate<Claim> match!!) { foreach (Claim claim in Claims) { if (match(claim)) { return true; } } return false; } /// <summary> /// Determines if a claim with type AND value is contained within this ClaimsIdentity. /// </summary> /// <param name="type">the type of the claim to match.</param> /// <param name="value">the value of the claim to match.</param> /// <returns>true if a claim is matched, false otherwise.</returns> /// <remarks>Comparison is: StringComparison.OrdinalIgnoreCase for Claim.Type, StringComparison.Ordinal for Claim.Value.</remarks> /// <exception cref="ArgumentNullException">if 'type' is null.</exception> /// <exception cref="ArgumentNullException">if 'value' is null.</exception> public virtual bool HasClaim(string type!!, string value!!) { foreach (Claim claim in Claims) { if (claim != null && string.Equals(claim.Type, type, StringComparison.OrdinalIgnoreCase) && string.Equals(claim.Value, value, StringComparison.Ordinal)) { return true; } } return false; } /// <summary> /// Initializes from a <see cref="BinaryReader"/>. Normally the reader is initialized with the results from <see cref="WriteTo(BinaryWriter)"/> /// Normally the <see cref="BinaryReader"/> is initialized in the same way as the <see cref="BinaryWriter"/> passed to <see cref="WriteTo(BinaryWriter)"/>. /// </summary> /// <param name="reader">a <see cref="BinaryReader"/> pointing to a <see cref="ClaimsIdentity"/>.</param> /// <exception cref="ArgumentNullException">if 'reader' is null.</exception> private void Initialize(BinaryReader reader!!) { SerializationMask mask = (SerializationMask)reader.ReadInt32(); int numPropertiesRead = 0; int numPropertiesToRead = reader.ReadInt32(); if ((mask & SerializationMask.AuthenticationType) == SerializationMask.AuthenticationType) { _authenticationType = reader.ReadString(); numPropertiesRead++; } if ((mask & SerializationMask.BootstrapConext) == SerializationMask.BootstrapConext) { _bootstrapContext = reader.ReadString(); numPropertiesRead++; } if ((mask & SerializationMask.NameClaimType) == SerializationMask.NameClaimType) { _nameClaimType = reader.ReadString(); numPropertiesRead++; } else { _nameClaimType = ClaimsIdentity.DefaultNameClaimType; } if ((mask & SerializationMask.RoleClaimType) == SerializationMask.RoleClaimType) { _roleClaimType = reader.ReadString(); numPropertiesRead++; } else { _roleClaimType = ClaimsIdentity.DefaultRoleClaimType; } if ((mask & SerializationMask.HasLabel) == SerializationMask.HasLabel) { _label = reader.ReadString(); numPropertiesRead++; } if ((mask & SerializationMask.HasClaims) == SerializationMask.HasClaims) { int numberOfClaims = reader.ReadInt32(); for (int index = 0; index < numberOfClaims; index++) { _instanceClaims.Add(CreateClaim(reader)); } numPropertiesRead++; } if ((mask & SerializationMask.Actor) == SerializationMask.Actor) { _actor = new ClaimsIdentity(reader); numPropertiesRead++; } if ((mask & SerializationMask.UserData) == SerializationMask.UserData) { int cb = reader.ReadInt32(); _userSerializationData = reader.ReadBytes(cb); numPropertiesRead++; } for (int i = numPropertiesRead; i < numPropertiesToRead; i++) { reader.ReadString(); } } /// <summary> /// Provides an extensibility point for derived types to create a custom <see cref="Claim"/>. /// </summary> /// <param name="reader">the <see cref="BinaryReader"/>that points at the claim.</param> /// <returns>a new <see cref="Claim"/>.</returns> protected virtual Claim CreateClaim(BinaryReader reader!!) { return new Claim(reader, this); } /// <summary> /// Serializes using a <see cref="BinaryWriter"/> /// </summary> /// <param name="writer">the <see cref="BinaryWriter"/> to use for data storage.</param> /// <exception cref="ArgumentNullException">if 'writer' is null.</exception> public virtual void WriteTo(BinaryWriter writer) { WriteTo(writer, null); } /// <summary> /// Serializes using a <see cref="BinaryWriter"/> /// </summary> /// <param name="writer">the <see cref="BinaryWriter"/> to use for data storage.</param> /// <param name="userData">additional data provided by derived type.</param> /// <exception cref="ArgumentNullException">if 'writer' is null.</exception> protected virtual void WriteTo(BinaryWriter writer!!, byte[]? userData) { int numberOfPropertiesWritten = 0; var mask = SerializationMask.None; if (_authenticationType != null) { mask |= SerializationMask.AuthenticationType; numberOfPropertiesWritten++; } if (_bootstrapContext != null) { if (_bootstrapContext is string) { mask |= SerializationMask.BootstrapConext; numberOfPropertiesWritten++; } } if (!string.Equals(_nameClaimType, ClaimsIdentity.DefaultNameClaimType, StringComparison.Ordinal)) { mask |= SerializationMask.NameClaimType; numberOfPropertiesWritten++; } if (!string.Equals(_roleClaimType, ClaimsIdentity.DefaultRoleClaimType, StringComparison.Ordinal)) { mask |= SerializationMask.RoleClaimType; numberOfPropertiesWritten++; } if (!string.IsNullOrWhiteSpace(_label)) { mask |= SerializationMask.HasLabel; numberOfPropertiesWritten++; } if (_instanceClaims.Count > 0) { mask |= SerializationMask.HasClaims; numberOfPropertiesWritten++; } if (_actor != null) { mask |= SerializationMask.Actor; numberOfPropertiesWritten++; } if (userData != null && userData.Length > 0) { numberOfPropertiesWritten++; mask |= SerializationMask.UserData; } writer.Write((int)mask); writer.Write(numberOfPropertiesWritten); if ((mask & SerializationMask.AuthenticationType) == SerializationMask.AuthenticationType) { writer.Write(_authenticationType!); } if ((mask & SerializationMask.BootstrapConext) == SerializationMask.BootstrapConext) { writer.Write((string)_bootstrapContext!); } if ((mask & SerializationMask.NameClaimType) == SerializationMask.NameClaimType) { writer.Write(_nameClaimType); } if ((mask & SerializationMask.RoleClaimType) == SerializationMask.RoleClaimType) { writer.Write(_roleClaimType); } if ((mask & SerializationMask.HasLabel) == SerializationMask.HasLabel) { writer.Write(_label!); } if ((mask & SerializationMask.HasClaims) == SerializationMask.HasClaims) { writer.Write(_instanceClaims.Count); foreach (var claim in _instanceClaims) { claim.WriteTo(writer); } } if ((mask & SerializationMask.Actor) == SerializationMask.Actor) { _actor!.WriteTo(writer); } if ((mask & SerializationMask.UserData) == SerializationMask.UserData) { writer.Write(userData!.Length); writer.Write(userData); } writer.Flush(); } /// <summary> /// Checks if a circular reference exists to 'this' /// </summary> /// <param name="subject"></param> /// <returns></returns> private bool IsCircular(ClaimsIdentity subject) { if (ReferenceEquals(this, subject)) { return true; } ClaimsIdentity currSubject = subject; while (currSubject.Actor != null) { if (ReferenceEquals(this, currSubject.Actor)) { return true; } currSubject = currSubject.Actor; } return false; } /// <summary> /// Populates the specified <see cref="SerializationInfo"/> with the serialization data for the ClaimsIdentity /// </summary> /// <param name="info">The serialization information stream to write to. Satisfies ISerializable contract.</param> /// <param name="context">Context for serialization. Can be null.</param> /// <exception cref="ArgumentNullException">Thrown if the info parameter is null.</exception> protected virtual void GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(); } } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/tests/JIT/HardwareIntrinsics/X86/Sse41.X64/Extract.Int64.1.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void ExtractInt641() { var test = new ExtractScalarTest__ExtractInt641(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class ExtractScalarTest__ExtractInt641 { private struct TestStruct { public Vector128<Int64> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref testStruct._fld), ref Unsafe.As<Int64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); return testStruct; } public void RunStructFldScenario(ExtractScalarTest__ExtractInt641 testClass) { var result = Sse41.X64.Extract(_fld, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64); private static Int64[] _data = new Int64[Op1ElementCount]; private static Vector128<Int64> _clsVar; private Vector128<Int64> _fld; private SimpleUnaryOpTest__DataTable<Int64, Int64> _dataTable; static ExtractScalarTest__ExtractInt641() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar), ref Unsafe.As<Int64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); } public ExtractScalarTest__ExtractInt641() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld), ref Unsafe.As<Int64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); } _dataTable = new SimpleUnaryOpTest__DataTable<Int64, Int64>(_data, new Int64[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse41.X64.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse41.X64.Extract( Unsafe.Read<Vector128<Int64>>(_dataTable.inArrayPtr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse41.X64.Extract( Sse2.LoadVector128((Int64*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse41.X64.Extract( Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse41.X64).GetMethod(nameof(Sse41.X64.Extract), new Type[] { typeof(Vector128<Int64>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int64>>(_dataTable.inArrayPtr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Int64)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse41.X64).GetMethod(nameof(Sse41.X64.Extract), new Type[] { typeof(Vector128<Int64>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadVector128((Int64*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Int64)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse41.X64).GetMethod(nameof(Sse41.X64.Extract), new Type[] { typeof(Vector128<Int64>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Int64)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse41.X64.Extract( _clsVar, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector128<Int64>>(_dataTable.inArrayPtr); var result = Sse41.X64.Extract(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = Sse2.LoadVector128((Int64*)(_dataTable.inArrayPtr)); var result = Sse41.X64.Extract(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var firstOp = Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArrayPtr)); var result = Sse41.X64.Extract(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ExtractScalarTest__ExtractInt641(); var result = Sse41.X64.Extract(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse41.X64.Extract(_fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse41.X64.Extract(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Int64> firstOp, void* result, [CallerMemberName] string method = "") { Int64[] inArray = new Int64[Op1ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int64>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Int64[] inArray = new Int64[Op1ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (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(inArray, outArray, method); } private void ValidateResult(Int64[] firstOp, Int64[] result, [CallerMemberName] string method = "") { bool succeeded = true; if ((result[0] != firstOp[1])) { succeeded = false; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse41.X64)}.{nameof(Sse41.X64.Extract)}<Int64>(Vector128<Int64><9>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void ExtractInt641() { var test = new ExtractScalarTest__ExtractInt641(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class ExtractScalarTest__ExtractInt641 { private struct TestStruct { public Vector128<Int64> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref testStruct._fld), ref Unsafe.As<Int64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); return testStruct; } public void RunStructFldScenario(ExtractScalarTest__ExtractInt641 testClass) { var result = Sse41.X64.Extract(_fld, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64); private static Int64[] _data = new Int64[Op1ElementCount]; private static Vector128<Int64> _clsVar; private Vector128<Int64> _fld; private SimpleUnaryOpTest__DataTable<Int64, Int64> _dataTable; static ExtractScalarTest__ExtractInt641() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar), ref Unsafe.As<Int64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); } public ExtractScalarTest__ExtractInt641() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld), ref Unsafe.As<Int64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); } _dataTable = new SimpleUnaryOpTest__DataTable<Int64, Int64>(_data, new Int64[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse41.X64.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse41.X64.Extract( Unsafe.Read<Vector128<Int64>>(_dataTable.inArrayPtr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse41.X64.Extract( Sse2.LoadVector128((Int64*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse41.X64.Extract( Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse41.X64).GetMethod(nameof(Sse41.X64.Extract), new Type[] { typeof(Vector128<Int64>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int64>>(_dataTable.inArrayPtr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Int64)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse41.X64).GetMethod(nameof(Sse41.X64.Extract), new Type[] { typeof(Vector128<Int64>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadVector128((Int64*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Int64)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse41.X64).GetMethod(nameof(Sse41.X64.Extract), new Type[] { typeof(Vector128<Int64>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Int64)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse41.X64.Extract( _clsVar, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector128<Int64>>(_dataTable.inArrayPtr); var result = Sse41.X64.Extract(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = Sse2.LoadVector128((Int64*)(_dataTable.inArrayPtr)); var result = Sse41.X64.Extract(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var firstOp = Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArrayPtr)); var result = Sse41.X64.Extract(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ExtractScalarTest__ExtractInt641(); var result = Sse41.X64.Extract(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse41.X64.Extract(_fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse41.X64.Extract(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Int64> firstOp, void* result, [CallerMemberName] string method = "") { Int64[] inArray = new Int64[Op1ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int64>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Int64[] inArray = new Int64[Op1ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (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(inArray, outArray, method); } private void ValidateResult(Int64[] firstOp, Int64[] result, [CallerMemberName] string method = "") { bool succeeded = true; if ((result[0] != firstOp[1])) { succeeded = false; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse41.X64)}.{nameof(Sse41.X64.Extract)}<Int64>(Vector128<Int64><9>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/libraries/System.Speech/src/Recognition/RecognizerStateChangedEventArgs.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.Speech.Recognition { // EventArgs used in the SpeechRecognizer.StateChanged event. public class StateChangedEventArgs : EventArgs { #region Constructors internal StateChangedEventArgs(RecognizerState recognizerState) { _recognizerState = recognizerState; } #endregion #region public Properties public RecognizerState RecognizerState { get { return _recognizerState; } } #endregion #region Private Fields private RecognizerState _recognizerState; #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Speech.Recognition { // EventArgs used in the SpeechRecognizer.StateChanged event. public class StateChangedEventArgs : EventArgs { #region Constructors internal StateChangedEventArgs(RecognizerState recognizerState) { _recognizerState = recognizerState; } #endregion #region public Properties public RecognizerState RecognizerState { get { return _recognizerState; } } #endregion #region Private Fields private RecognizerState _recognizerState; #endregion } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RandomNumberGeneratorImplementation.Browser.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.Security.Cryptography { internal sealed partial class RandomNumberGeneratorImplementation { private static unsafe void GetBytes(byte* pbBuffer, int count) { Debug.Assert(count > 0); Interop.GetCryptographicallySecureRandomBytes(pbBuffer, count); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; namespace System.Security.Cryptography { internal sealed partial class RandomNumberGeneratorImplementation { private static unsafe void GetBytes(byte* pbBuffer, int count) { Debug.Assert(count > 0); Interop.GetCryptographicallySecureRandomBytes(pbBuffer, count); } } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/libraries/System.Net.Sockets/ref/System.Net.Sockets.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.Net.Sockets { public enum IOControlCode : long { [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] EnableCircularQueuing = (long)671088642, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] Flush = (long)671088644, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] AddressListChange = (long)671088663, DataToRead = (long)1074030207, OobDataRead = (long)1074033415, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] GetBroadcastAddress = (long)1207959557, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] AddressListQuery = (long)1207959574, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] QueryTargetPnpHandle = (long)1207959576, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] AsyncIO = (long)2147772029, NonBlockingIO = (long)2147772030, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] AssociateHandle = (long)2281701377, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] MultipointLoopback = (long)2281701385, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] MulticastScope = (long)2281701386, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] SetQos = (long)2281701387, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] SetGroupQos = (long)2281701388, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] RoutingInterfaceChange = (long)2281701397, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] NamespaceChange = (long)2281701401, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] ReceiveAll = (long)2550136833, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] ReceiveAllMulticast = (long)2550136834, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] ReceiveAllIgmpMulticast = (long)2550136835, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] KeepAliveValues = (long)2550136836, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] AbsorbRouterAlert = (long)2550136837, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] UnicastInterface = (long)2550136838, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] LimitBroadcasts = (long)2550136839, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] BindToInterface = (long)2550136840, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] MulticastInterface = (long)2550136841, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] AddMulticastGroupOnInterface = (long)2550136842, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] DeleteMulticastGroupFromInterface = (long)2550136843, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] GetExtensionFunctionPointer = (long)3355443206, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] GetQos = (long)3355443207, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] GetGroupQos = (long)3355443208, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] TranslateHandle = (long)3355443213, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] RoutingInterfaceQuery = (long)3355443220, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] AddressListSort = (long)3355443225, } public partial struct IPPacketInformation : System.IEquatable<System.Net.Sockets.IPPacketInformation> { private object _dummy; private int _dummyPrimitive; public System.Net.IPAddress Address { get { throw null; } } public int Interface { get { throw null; } } public override bool Equals([System.Diagnostics.CodeAnalysis.NotNullWhen(true)] object? comparand) { throw null; } public bool Equals(System.Net.Sockets.IPPacketInformation other) { throw null; } public override int GetHashCode() { throw null; } public static bool operator ==(System.Net.Sockets.IPPacketInformation packetInformation1, System.Net.Sockets.IPPacketInformation packetInformation2) { throw null; } public static bool operator !=(System.Net.Sockets.IPPacketInformation packetInformation1, System.Net.Sockets.IPPacketInformation packetInformation2) { throw null; } } public enum IPProtectionLevel { Unspecified = -1, Unrestricted = 10, EdgeRestricted = 20, Restricted = 30, } public partial class IPv6MulticastOption { public IPv6MulticastOption(System.Net.IPAddress group) { } public IPv6MulticastOption(System.Net.IPAddress group, long ifindex) { } public System.Net.IPAddress Group { get { throw null; } set { } } public long InterfaceIndex { get { throw null; } set { } } } public partial class LingerOption { public LingerOption(bool enable, int seconds) { } public bool Enabled { get { throw null; } set { } } public int LingerTime { get { throw null; } set { } } } public partial class MulticastOption { public MulticastOption(System.Net.IPAddress group) { } public MulticastOption(System.Net.IPAddress group, int interfaceIndex) { } public MulticastOption(System.Net.IPAddress group, System.Net.IPAddress mcint) { } public System.Net.IPAddress Group { get { throw null; } set { } } public int InterfaceIndex { get { throw null; } set { } } public System.Net.IPAddress? LocalAddress { get { throw null; } set { } } } public partial class NetworkStream : System.IO.Stream { public NetworkStream(System.Net.Sockets.Socket socket) { } public NetworkStream(System.Net.Sockets.Socket socket, bool ownsSocket) { } public NetworkStream(System.Net.Sockets.Socket socket, System.IO.FileAccess access) { } public NetworkStream(System.Net.Sockets.Socket socket, System.IO.FileAccess access, bool ownsSocket) { } public override bool CanRead { get { throw null; } } public override bool CanSeek { get { throw null; } } public override bool CanTimeout { get { throw null; } } public override bool CanWrite { get { throw null; } } public virtual bool DataAvailable { get { throw null; } } public override long Length { get { throw null; } } public override long Position { get { throw null; } set { } } protected bool Readable { get { throw null; } set { } } public override int ReadTimeout { get { throw null; } set { } } public System.Net.Sockets.Socket Socket { get { throw null; } } protected bool Writeable { get { throw null; } set { } } public override int WriteTimeout { get { throw null; } set { } } public override System.IAsyncResult BeginRead(byte[] buffer, int offset, int count, System.AsyncCallback? callback, object? state) { throw null; } public override System.IAsyncResult BeginWrite(byte[] buffer, int offset, int count, System.AsyncCallback? callback, object? state) { throw null; } public void Close(int timeout) { } protected override void Dispose(bool disposing) { } public override int EndRead(System.IAsyncResult asyncResult) { throw null; } public override void EndWrite(System.IAsyncResult asyncResult) { } ~NetworkStream() { } public override void Flush() { } public override System.Threading.Tasks.Task FlushAsync(System.Threading.CancellationToken cancellationToken) { throw null; } public override int Read(byte[] buffer, int offset, int count) { throw null; } public override int Read(System.Span<byte> buffer) { throw null; } public override System.Threading.Tasks.Task<int> ReadAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { throw null; } public override System.Threading.Tasks.ValueTask<int> ReadAsync(System.Memory<byte> buffer, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override int ReadByte() { throw null; } public override long Seek(long offset, System.IO.SeekOrigin origin) { throw null; } public override void SetLength(long value) { } public override void Write(byte[] buffer, int offset, int count) { } public override void Write(System.ReadOnlySpan<byte> buffer) { } public override System.Threading.Tasks.Task WriteAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { throw null; } public override System.Threading.Tasks.ValueTask WriteAsync(System.ReadOnlyMemory<byte> buffer, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override void WriteByte(byte value) { } } public enum ProtocolFamily { Unknown = -1, Unspecified = 0, Unix = 1, InterNetwork = 2, ImpLink = 3, Pup = 4, Chaos = 5, Ipx = 6, NS = 6, Iso = 7, Osi = 7, Ecma = 8, DataKit = 9, Ccitt = 10, Sna = 11, DecNet = 12, DataLink = 13, Lat = 14, HyperChannel = 15, AppleTalk = 16, NetBios = 17, VoiceView = 18, FireFox = 19, Banyan = 21, Atm = 22, InterNetworkV6 = 23, Cluster = 24, Ieee12844 = 25, Irda = 26, NetworkDesigners = 28, Max = 29, Packet = 65536, ControllerAreaNetwork = 65537, } public enum ProtocolType { Unknown = -1, IP = 0, IPv6HopByHopOptions = 0, Unspecified = 0, Icmp = 1, Igmp = 2, Ggp = 3, IPv4 = 4, Tcp = 6, Pup = 12, Udp = 17, Idp = 22, IPv6 = 41, IPv6RoutingHeader = 43, IPv6FragmentHeader = 44, IPSecEncapsulatingSecurityPayload = 50, IPSecAuthenticationHeader = 51, IcmpV6 = 58, IPv6NoNextHeader = 59, IPv6DestinationOptions = 60, ND = 77, Raw = 255, Ipx = 1000, Spx = 1256, SpxII = 1257, } public sealed partial class SafeSocketHandle : Microsoft.Win32.SafeHandles.SafeHandleMinusOneIsInvalid { public SafeSocketHandle() : base (default(bool)) { } public SafeSocketHandle(System.IntPtr preexistingHandle, bool ownsHandle) : base (default(bool)) { } protected override bool ReleaseHandle() { throw null; } } public enum SelectMode { SelectRead = 0, SelectWrite = 1, SelectError = 2, } public partial class SendPacketsElement { public SendPacketsElement(byte[] buffer) { } public SendPacketsElement(byte[] buffer, int offset, int count) { } public SendPacketsElement(byte[] buffer, int offset, int count, bool endOfPacket) { } public SendPacketsElement(ReadOnlyMemory<byte> buffer) { } public SendPacketsElement(ReadOnlyMemory<byte> buffer, bool endOfPacket) { } public SendPacketsElement(System.IO.FileStream fileStream) { } public SendPacketsElement(System.IO.FileStream fileStream, long offset, int count) { } public SendPacketsElement(System.IO.FileStream fileStream, long offset, int count, bool endOfPacket) { } public SendPacketsElement(string filepath) { } public SendPacketsElement(string filepath, int offset, int count) { } public SendPacketsElement(string filepath, int offset, int count, bool endOfPacket) { } public SendPacketsElement(string filepath, long offset, int count) { } public SendPacketsElement(string filepath, long offset, int count, bool endOfPacket) { } public byte[]? Buffer { get { throw null; } } public int Count { get { throw null; } } public bool EndOfPacket { get { throw null; } } public string? FilePath { get { throw null; } } public System.IO.FileStream? FileStream { get { throw null; } } public ReadOnlyMemory<byte>? MemoryBuffer { get { throw null; } } public int Offset { get { throw null; } } public long OffsetLong { get { throw null; } } } public partial class Socket : System.IDisposable { public Socket(System.Net.Sockets.SafeSocketHandle handle) { } public Socket(System.Net.Sockets.AddressFamily addressFamily, System.Net.Sockets.SocketType socketType, System.Net.Sockets.ProtocolType protocolType) { } [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] public Socket(System.Net.Sockets.SocketInformation socketInformation) { } public Socket(System.Net.Sockets.SocketType socketType, System.Net.Sockets.ProtocolType protocolType) { } public System.Net.Sockets.AddressFamily AddressFamily { get { throw null; } } public int Available { get { throw null; } } public bool Blocking { get { throw null; } set { } } public bool Connected { get { throw null; } } public bool DontFragment { get { throw null; } set { } } public bool DualMode { get { throw null; } set { } } public bool EnableBroadcast { get { throw null; } set { } } public bool ExclusiveAddressUse { get { throw null; } set { } } public System.IntPtr Handle { get { throw null; } } public bool IsBound { get { throw null; } } [System.Diagnostics.CodeAnalysis.DisallowNullAttribute] public System.Net.Sockets.LingerOption? LingerState { get { throw null; } set { } } public System.Net.EndPoint? LocalEndPoint { get { throw null; } } public bool MulticastLoopback { get { throw null; } set { } } public bool NoDelay { get { throw null; } set { } } public static bool OSSupportsIPv4 { get { throw null; } } public static bool OSSupportsIPv6 { get { throw null; } } public static bool OSSupportsUnixDomainSockets { get { throw null; } } public System.Net.Sockets.ProtocolType ProtocolType { get { throw null; } } public int ReceiveBufferSize { get { throw null; } set { } } public int ReceiveTimeout { get { throw null; } set { } } public System.Net.EndPoint? RemoteEndPoint { get { throw null; } } public System.Net.Sockets.SafeSocketHandle SafeHandle { get { throw null; } } public int SendBufferSize { get { throw null; } set { } } public int SendTimeout { get { throw null; } set { } } public System.Net.Sockets.SocketType SocketType { get { throw null; } } [System.ObsoleteAttribute("SupportsIPv4 has been deprecated. Use OSSupportsIPv4 instead.")] public static bool SupportsIPv4 { get { throw null; } } [System.ObsoleteAttribute("SupportsIPv6 has been deprecated. Use OSSupportsIPv6 instead.")] public static bool SupportsIPv6 { get { throw null; } } public short Ttl { get { throw null; } set { } } [System.ObsoleteAttribute("UseOnlyOverlappedIO has been deprecated and is not supported.")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public bool UseOnlyOverlappedIO { get { throw null; } set { } } public System.Net.Sockets.Socket Accept() { throw null; } public System.Threading.Tasks.Task<System.Net.Sockets.Socket> AcceptAsync() { throw null; } public System.Threading.Tasks.ValueTask<System.Net.Sockets.Socket> AcceptAsync(System.Threading.CancellationToken cancellationToken) { throw null; } public System.Threading.Tasks.Task<System.Net.Sockets.Socket> AcceptAsync(System.Net.Sockets.Socket? acceptSocket) { throw null; } public System.Threading.Tasks.ValueTask<System.Net.Sockets.Socket> AcceptAsync(System.Net.Sockets.Socket? acceptSocket, System.Threading.CancellationToken cancellationToken) { throw null; } public bool AcceptAsync(System.Net.Sockets.SocketAsyncEventArgs e) { throw null; } public System.IAsyncResult BeginAccept(System.AsyncCallback? callback, object? state) { throw null; } public System.IAsyncResult BeginAccept(int receiveSize, System.AsyncCallback? callback, object? state) { throw null; } public System.IAsyncResult BeginAccept(System.Net.Sockets.Socket? acceptSocket, int receiveSize, System.AsyncCallback? callback, object? state) { throw null; } public System.IAsyncResult BeginConnect(System.Net.EndPoint remoteEP, System.AsyncCallback? callback, object? state) { throw null; } public System.IAsyncResult BeginConnect(System.Net.IPAddress address, int port, System.AsyncCallback? requestCallback, object? state) { throw null; } public System.IAsyncResult BeginConnect(System.Net.IPAddress[] addresses, int port, System.AsyncCallback? requestCallback, object? state) { throw null; } public System.IAsyncResult BeginConnect(string host, int port, System.AsyncCallback? requestCallback, object? state) { throw null; } public System.IAsyncResult BeginDisconnect(bool reuseSocket, System.AsyncCallback? callback, object? state) { throw null; } public System.IAsyncResult BeginReceive(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, System.AsyncCallback? callback, object? state) { throw null; } public System.IAsyncResult? BeginReceive(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode, System.AsyncCallback? callback, object? state) { throw null; } public System.IAsyncResult BeginReceive(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags, System.AsyncCallback? callback, object? state) { throw null; } public System.IAsyncResult? BeginReceive(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode, System.AsyncCallback? callback, object? state) { throw null; } public System.IAsyncResult BeginReceiveFrom(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, ref System.Net.EndPoint remoteEP, System.AsyncCallback? callback, object? state) { throw null; } public System.IAsyncResult BeginReceiveMessageFrom(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, ref System.Net.EndPoint remoteEP, System.AsyncCallback? callback, object? state) { throw null; } public System.IAsyncResult BeginSend(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, System.AsyncCallback? callback, object? state) { throw null; } public System.IAsyncResult? BeginSend(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode, System.AsyncCallback? callback, object? state) { throw null; } public System.IAsyncResult BeginSend(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags, System.AsyncCallback? callback, object? state) { throw null; } public System.IAsyncResult? BeginSend(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode, System.AsyncCallback? callback, object? state) { throw null; } public System.IAsyncResult BeginSendFile(string? fileName, System.AsyncCallback? callback, object? state) { throw null; } public System.IAsyncResult BeginSendFile(string? fileName, byte[]? preBuffer, byte[]? postBuffer, System.Net.Sockets.TransmitFileOptions flags, System.AsyncCallback? callback, object? state) { throw null; } public System.IAsyncResult BeginSendTo(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEP, System.AsyncCallback? callback, object? state) { throw null; } public void Bind(System.Net.EndPoint localEP) { } public static void CancelConnectAsync(System.Net.Sockets.SocketAsyncEventArgs e) { } public void Close() { } public void Close(int timeout) { } public void Connect(System.Net.EndPoint remoteEP) { } public void Connect(System.Net.IPAddress address, int port) { } public void Connect(System.Net.IPAddress[] addresses, int port) { } public void Connect(string host, int port) { } public System.Threading.Tasks.Task ConnectAsync(System.Net.EndPoint remoteEP) { throw null; } public System.Threading.Tasks.ValueTask ConnectAsync(System.Net.EndPoint remoteEP, System.Threading.CancellationToken cancellationToken) { throw null; } public System.Threading.Tasks.Task ConnectAsync(System.Net.IPAddress address, int port) { throw null; } public System.Threading.Tasks.ValueTask ConnectAsync(System.Net.IPAddress address, int port, System.Threading.CancellationToken cancellationToken) { throw null; } public System.Threading.Tasks.Task ConnectAsync(System.Net.IPAddress[] addresses, int port) { throw null; } public System.Threading.Tasks.ValueTask ConnectAsync(System.Net.IPAddress[] addresses, int port, System.Threading.CancellationToken cancellationToken) { throw null; } public System.Threading.Tasks.Task ConnectAsync(string host, int port) { throw null; } public System.Threading.Tasks.ValueTask ConnectAsync(string host, int port, System.Threading.CancellationToken cancellationToken) { throw null; } public bool ConnectAsync(System.Net.Sockets.SocketAsyncEventArgs e) { throw null; } public static bool ConnectAsync(System.Net.Sockets.SocketType socketType, System.Net.Sockets.ProtocolType protocolType, System.Net.Sockets.SocketAsyncEventArgs e) { throw null; } public void Disconnect(bool reuseSocket) { } public bool DisconnectAsync(System.Net.Sockets.SocketAsyncEventArgs e) { throw null; } public System.Threading.Tasks.ValueTask DisconnectAsync(bool reuseSocket, System.Threading.CancellationToken cancellationToken = default) { throw null; } public void Dispose() { } protected virtual void Dispose(bool disposing) { } [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] public System.Net.Sockets.SocketInformation DuplicateAndClose(int targetProcessId) { throw null; } public System.Net.Sockets.Socket EndAccept(out byte[] buffer, System.IAsyncResult asyncResult) { throw null; } public System.Net.Sockets.Socket EndAccept(out byte[] buffer, out int bytesTransferred, System.IAsyncResult asyncResult) { throw null; } public System.Net.Sockets.Socket EndAccept(System.IAsyncResult asyncResult) { throw null; } public void EndConnect(System.IAsyncResult asyncResult) { } public void EndDisconnect(System.IAsyncResult asyncResult) { } public int EndReceive(System.IAsyncResult asyncResult) { throw null; } public int EndReceive(System.IAsyncResult asyncResult, out System.Net.Sockets.SocketError errorCode) { throw null; } public int EndReceiveFrom(System.IAsyncResult asyncResult, ref System.Net.EndPoint endPoint) { throw null; } public int EndReceiveMessageFrom(System.IAsyncResult asyncResult, ref System.Net.Sockets.SocketFlags socketFlags, ref System.Net.EndPoint endPoint, out System.Net.Sockets.IPPacketInformation ipPacketInformation) { throw null; } public int EndSend(System.IAsyncResult asyncResult) { throw null; } public int EndSend(System.IAsyncResult asyncResult, out System.Net.Sockets.SocketError errorCode) { throw null; } public void EndSendFile(System.IAsyncResult asyncResult) { } public int EndSendTo(System.IAsyncResult asyncResult) { throw null; } ~Socket() { } public int GetRawSocketOption(int optionLevel, int optionName, System.Span<byte> optionValue) { throw null; } public object? GetSocketOption(System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName) { throw null; } public void GetSocketOption(System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName, byte[] optionValue) { } public byte[] GetSocketOption(System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName, int optionLength) { throw null; } public int IOControl(int ioControlCode, byte[]? optionInValue, byte[]? optionOutValue) { throw null; } public int IOControl(System.Net.Sockets.IOControlCode ioControlCode, byte[]? optionInValue, byte[]? optionOutValue) { throw null; } public void Listen() { } public void Listen(int backlog) { } public bool Poll(int microSeconds, System.Net.Sockets.SelectMode mode) { throw null; } public int Receive(byte[] buffer) { throw null; } public int Receive(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags) { throw null; } public int Receive(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode) { throw null; } public int Receive(byte[] buffer, int size, System.Net.Sockets.SocketFlags socketFlags) { throw null; } public int Receive(byte[] buffer, System.Net.Sockets.SocketFlags socketFlags) { throw null; } public int Receive(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers) { throw null; } public int Receive(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags) { throw null; } public int Receive(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode) { throw null; } public int Receive(System.Span<byte> buffer) { throw null; } public int Receive(System.Span<byte> buffer, System.Net.Sockets.SocketFlags socketFlags) { throw null; } public int Receive(System.Span<byte> buffer, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode) { throw null; } public System.Threading.Tasks.Task<int> ReceiveAsync(System.ArraySegment<byte> buffer) { throw null; } public System.Threading.Tasks.Task<int> ReceiveAsync(System.ArraySegment<byte> buffer, System.Net.Sockets.SocketFlags socketFlags) { throw null; } public System.Threading.Tasks.Task<int> ReceiveAsync(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers) { throw null; } public System.Threading.Tasks.Task<int> ReceiveAsync(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags) { throw null; } public System.Threading.Tasks.ValueTask<int> ReceiveAsync(System.Memory<byte> buffer, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public System.Threading.Tasks.ValueTask<int> ReceiveAsync(System.Memory<byte> buffer, System.Net.Sockets.SocketFlags socketFlags, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public bool ReceiveAsync(System.Net.Sockets.SocketAsyncEventArgs e) { throw null; } public int ReceiveFrom(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, ref System.Net.EndPoint remoteEP) { throw null; } public int ReceiveFrom(byte[] buffer, int size, System.Net.Sockets.SocketFlags socketFlags, ref System.Net.EndPoint remoteEP) { throw null; } public int ReceiveFrom(byte[] buffer, ref System.Net.EndPoint remoteEP) { throw null; } public int ReceiveFrom(byte[] buffer, System.Net.Sockets.SocketFlags socketFlags, ref System.Net.EndPoint remoteEP) { throw null; } public int ReceiveFrom(System.Span<byte> buffer, ref System.Net.EndPoint remoteEP) { throw null; } public int ReceiveFrom(System.Span<byte> buffer, System.Net.Sockets.SocketFlags socketFlags, ref System.Net.EndPoint remoteEP) { throw null; } public System.Threading.Tasks.Task<System.Net.Sockets.SocketReceiveFromResult> ReceiveFromAsync(System.ArraySegment<byte> buffer, System.Net.EndPoint remoteEndPoint) { throw null; } public System.Threading.Tasks.Task<System.Net.Sockets.SocketReceiveFromResult> ReceiveFromAsync(System.ArraySegment<byte> buffer, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEndPoint) { throw null; } public System.Threading.Tasks.ValueTask<System.Net.Sockets.SocketReceiveFromResult> ReceiveFromAsync(System.Memory<byte> buffer, System.Net.EndPoint remoteEndPoint, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public System.Threading.Tasks.ValueTask<System.Net.Sockets.SocketReceiveFromResult> ReceiveFromAsync(System.Memory<byte> buffer, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEndPoint, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public bool ReceiveFromAsync(System.Net.Sockets.SocketAsyncEventArgs e) { throw null; } public int ReceiveMessageFrom(byte[] buffer, int offset, int size, ref System.Net.Sockets.SocketFlags socketFlags, ref System.Net.EndPoint remoteEP, out System.Net.Sockets.IPPacketInformation ipPacketInformation) { throw null; } public int ReceiveMessageFrom(System.Span<byte> buffer, ref System.Net.Sockets.SocketFlags socketFlags, ref System.Net.EndPoint remoteEP, out System.Net.Sockets.IPPacketInformation ipPacketInformation) { throw null; } public System.Threading.Tasks.Task<System.Net.Sockets.SocketReceiveMessageFromResult> ReceiveMessageFromAsync(System.ArraySegment<byte> buffer, System.Net.EndPoint remoteEndPoint) { throw null; } public System.Threading.Tasks.Task<System.Net.Sockets.SocketReceiveMessageFromResult> ReceiveMessageFromAsync(System.ArraySegment<byte> buffer, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEndPoint) { throw null; } public System.Threading.Tasks.ValueTask<System.Net.Sockets.SocketReceiveMessageFromResult> ReceiveMessageFromAsync(System.Memory<byte> buffer, System.Net.EndPoint remoteEndPoint, System.Threading.CancellationToken cancellationToken = default) { throw null; } public System.Threading.Tasks.ValueTask<System.Net.Sockets.SocketReceiveMessageFromResult> ReceiveMessageFromAsync(System.Memory<byte> buffer, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEndPoint, System.Threading.CancellationToken cancellationToken = default) { throw null; } public bool ReceiveMessageFromAsync(System.Net.Sockets.SocketAsyncEventArgs e) { throw null; } public static void Select(System.Collections.IList? checkRead, System.Collections.IList? checkWrite, System.Collections.IList? checkError, int microSeconds) { } public int Send(byte[] buffer) { throw null; } public int Send(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags) { throw null; } public int Send(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode) { throw null; } public int Send(byte[] buffer, int size, System.Net.Sockets.SocketFlags socketFlags) { throw null; } public int Send(byte[] buffer, System.Net.Sockets.SocketFlags socketFlags) { throw null; } public int Send(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers) { throw null; } public int Send(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags) { throw null; } public int Send(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode) { throw null; } public int Send(System.ReadOnlySpan<byte> buffer) { throw null; } public int Send(System.ReadOnlySpan<byte> buffer, System.Net.Sockets.SocketFlags socketFlags) { throw null; } public int Send(System.ReadOnlySpan<byte> buffer, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode) { throw null; } public System.Threading.Tasks.Task<int> SendAsync(System.ArraySegment<byte> buffer) { throw null; } public System.Threading.Tasks.Task<int> SendAsync(System.ArraySegment<byte> buffer, System.Net.Sockets.SocketFlags socketFlags) { throw null; } public System.Threading.Tasks.Task<int> SendAsync(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers) { throw null; } public System.Threading.Tasks.Task<int> SendAsync(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags) { throw null; } public System.Threading.Tasks.ValueTask<int> SendAsync(System.ReadOnlyMemory<byte> buffer, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public System.Threading.Tasks.ValueTask<int> SendAsync(System.ReadOnlyMemory<byte> buffer, System.Net.Sockets.SocketFlags socketFlags, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public bool SendAsync(System.Net.Sockets.SocketAsyncEventArgs e) { throw null; } public void SendFile(string? fileName) { } public void SendFile(string? fileName, byte[]? preBuffer, byte[]? postBuffer, System.Net.Sockets.TransmitFileOptions flags) { } public void SendFile(string? fileName, System.ReadOnlySpan<byte> preBuffer, System.ReadOnlySpan<byte> postBuffer, System.Net.Sockets.TransmitFileOptions flags) { } public System.Threading.Tasks.ValueTask SendFileAsync(string? fileName, System.ReadOnlyMemory<byte> preBuffer, System.ReadOnlyMemory<byte> postBuffer, System.Net.Sockets.TransmitFileOptions flags, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public System.Threading.Tasks.ValueTask SendFileAsync(string? fileName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public bool SendPacketsAsync(System.Net.Sockets.SocketAsyncEventArgs e) { throw null; } public int SendTo(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEP) { throw null; } public int SendTo(byte[] buffer, int size, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEP) { throw null; } public int SendTo(byte[] buffer, System.Net.EndPoint remoteEP) { throw null; } public int SendTo(byte[] buffer, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEP) { throw null; } public int SendTo(System.ReadOnlySpan<byte> buffer, System.Net.EndPoint remoteEP) { throw null; } public int SendTo(System.ReadOnlySpan<byte> buffer, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEP) { throw null; } public System.Threading.Tasks.Task<int> SendToAsync(System.ArraySegment<byte> buffer, System.Net.EndPoint remoteEP) { throw null; } public System.Threading.Tasks.Task<int> SendToAsync(System.ArraySegment<byte> buffer, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEP) { throw null; } public System.Threading.Tasks.ValueTask<int> SendToAsync(System.ReadOnlyMemory<byte> buffer, System.Net.EndPoint remoteEP, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public System.Threading.Tasks.ValueTask<int> SendToAsync(System.ReadOnlyMemory<byte> buffer, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEP, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public bool SendToAsync(System.Net.Sockets.SocketAsyncEventArgs e) { throw null; } [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] public void SetIPProtectionLevel(System.Net.Sockets.IPProtectionLevel level) { } public void SetRawSocketOption(int optionLevel, int optionName, System.ReadOnlySpan<byte> optionValue) { } public void SetSocketOption(System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName, bool optionValue) { } public void SetSocketOption(System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName, byte[] optionValue) { } public void SetSocketOption(System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName, int optionValue) { } public void SetSocketOption(System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName, object optionValue) { } public void Shutdown(System.Net.Sockets.SocketShutdown how) { } } public partial class SocketAsyncEventArgs : System.EventArgs, System.IDisposable { public SocketAsyncEventArgs() { } public SocketAsyncEventArgs(bool unsafeSuppressExecutionContextFlow) { } public System.Net.Sockets.Socket? AcceptSocket { get { throw null; } set { } } public byte[]? Buffer { get { throw null; } } public System.Collections.Generic.IList<System.ArraySegment<byte>>? BufferList { get { throw null; } set { } } public int BytesTransferred { get { throw null; } } public System.Exception? ConnectByNameError { get { throw null; } } public System.Net.Sockets.Socket? ConnectSocket { get { throw null; } } public int Count { get { throw null; } } public bool DisconnectReuseSocket { get { throw null; } set { } } public System.Net.Sockets.SocketAsyncOperation LastOperation { get { throw null; } } public System.Memory<byte> MemoryBuffer { get { throw null; } } public int Offset { get { throw null; } } public System.Net.Sockets.IPPacketInformation ReceiveMessageFromPacketInfo { get { throw null; } } public System.Net.EndPoint? RemoteEndPoint { get { throw null; } set { } } public System.Net.Sockets.SendPacketsElement[]? SendPacketsElements { get { throw null; } set { } } public System.Net.Sockets.TransmitFileOptions SendPacketsFlags { get { throw null; } set { } } public int SendPacketsSendSize { get { throw null; } set { } } public System.Net.Sockets.SocketError SocketError { get { throw null; } set { } } public System.Net.Sockets.SocketFlags SocketFlags { get { throw null; } set { } } public object? UserToken { get { throw null; } set { } } public event System.EventHandler<System.Net.Sockets.SocketAsyncEventArgs>? Completed { add { } remove { } } public void Dispose() { } ~SocketAsyncEventArgs() { } protected virtual void OnCompleted(System.Net.Sockets.SocketAsyncEventArgs e) { } public void SetBuffer(byte[]? buffer, int offset, int count) { } public void SetBuffer(int offset, int count) { } public void SetBuffer(System.Memory<byte> buffer) { } } public enum SocketAsyncOperation { None = 0, Accept = 1, Connect = 2, Disconnect = 3, Receive = 4, ReceiveFrom = 5, ReceiveMessageFrom = 6, Send = 7, SendPackets = 8, SendTo = 9, } [System.FlagsAttribute] public enum SocketFlags { None = 0, OutOfBand = 1, Peek = 2, DontRoute = 4, Truncated = 256, ControlDataTruncated = 512, Broadcast = 1024, Multicast = 2048, Partial = 32768, } public partial struct SocketInformation { private object _dummy; private int _dummyPrimitive; public System.Net.Sockets.SocketInformationOptions Options { readonly get { throw null; } set { } } public byte[] ProtocolInformation { readonly get { throw null; } set { } } } [System.FlagsAttribute] public enum SocketInformationOptions { NonBlocking = 1, Connected = 2, Listening = 4, [System.ObsoleteAttribute("SocketInformationOptions.UseOnlyOverlappedIO has been deprecated and is not supported.")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] UseOnlyOverlappedIO = 8, } public enum SocketOptionLevel { IP = 0, Tcp = 6, Udp = 17, IPv6 = 41, Socket = 65535, } public enum SocketOptionName { DontLinger = -129, ExclusiveAddressUse = -5, Debug = 1, IPOptions = 1, NoChecksum = 1, NoDelay = 1, AcceptConnection = 2, BsdUrgent = 2, Expedited = 2, HeaderIncluded = 2, TcpKeepAliveTime = 3, TypeOfService = 3, IpTimeToLive = 4, ReuseAddress = 4, KeepAlive = 8, MulticastInterface = 9, MulticastTimeToLive = 10, MulticastLoopback = 11, AddMembership = 12, DropMembership = 13, DontFragment = 14, AddSourceMembership = 15, DontRoute = 16, DropSourceMembership = 16, TcpKeepAliveRetryCount = 16, BlockSource = 17, TcpKeepAliveInterval = 17, UnblockSource = 18, PacketInformation = 19, ChecksumCoverage = 20, HopLimit = 21, IPProtectionLevel = 23, IPv6Only = 27, Broadcast = 32, UseLoopback = 64, Linger = 128, OutOfBandInline = 256, SendBuffer = 4097, ReceiveBuffer = 4098, SendLowWater = 4099, ReceiveLowWater = 4100, SendTimeout = 4101, ReceiveTimeout = 4102, Error = 4103, Type = 4104, ReuseUnicastPort = 12295, UpdateAcceptContext = 28683, UpdateConnectContext = 28688, MaxConnections = 2147483647, } public partial struct SocketReceiveFromResult { public int ReceivedBytes; public System.Net.EndPoint RemoteEndPoint; } public partial struct SocketReceiveMessageFromResult { public System.Net.Sockets.IPPacketInformation PacketInformation; public int ReceivedBytes; public System.Net.EndPoint RemoteEndPoint; public System.Net.Sockets.SocketFlags SocketFlags; } public enum SocketShutdown { Receive = 0, Send = 1, Both = 2, } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static partial class SocketTaskExtensions { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static System.Threading.Tasks.Task<System.Net.Sockets.Socket> AcceptAsync(this System.Net.Sockets.Socket socket) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static System.Threading.Tasks.Task<System.Net.Sockets.Socket> AcceptAsync(this System.Net.Sockets.Socket socket, System.Net.Sockets.Socket? acceptSocket) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static System.Threading.Tasks.Task ConnectAsync(this System.Net.Sockets.Socket socket, System.Net.EndPoint remoteEP) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static System.Threading.Tasks.ValueTask ConnectAsync(this System.Net.Sockets.Socket socket, System.Net.EndPoint remoteEP, System.Threading.CancellationToken cancellationToken) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static System.Threading.Tasks.Task ConnectAsync(this System.Net.Sockets.Socket socket, System.Net.IPAddress address, int port) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static System.Threading.Tasks.ValueTask ConnectAsync(this System.Net.Sockets.Socket socket, System.Net.IPAddress address, int port, System.Threading.CancellationToken cancellationToken) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static System.Threading.Tasks.Task ConnectAsync(this System.Net.Sockets.Socket socket, System.Net.IPAddress[] addresses, int port) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static System.Threading.Tasks.ValueTask ConnectAsync(this System.Net.Sockets.Socket socket, System.Net.IPAddress[] addresses, int port, System.Threading.CancellationToken cancellationToken) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static System.Threading.Tasks.Task ConnectAsync(this System.Net.Sockets.Socket socket, string host, int port) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static System.Threading.Tasks.ValueTask ConnectAsync(this System.Net.Sockets.Socket socket, string host, int port, System.Threading.CancellationToken cancellationToken) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static System.Threading.Tasks.Task<int> ReceiveAsync(this System.Net.Sockets.Socket socket, System.ArraySegment<byte> buffer, System.Net.Sockets.SocketFlags socketFlags) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static System.Threading.Tasks.Task<int> ReceiveAsync(this System.Net.Sockets.Socket socket, System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static System.Threading.Tasks.ValueTask<int> ReceiveAsync(this System.Net.Sockets.Socket socket, System.Memory<byte> buffer, System.Net.Sockets.SocketFlags socketFlags, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static System.Threading.Tasks.Task<System.Net.Sockets.SocketReceiveFromResult> ReceiveFromAsync(this System.Net.Sockets.Socket socket, System.ArraySegment<byte> buffer, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEndPoint) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static System.Threading.Tasks.Task<System.Net.Sockets.SocketReceiveMessageFromResult> ReceiveMessageFromAsync(this System.Net.Sockets.Socket socket, System.ArraySegment<byte> buffer, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEndPoint) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static System.Threading.Tasks.Task<int> SendAsync(this System.Net.Sockets.Socket socket, System.ArraySegment<byte> buffer, System.Net.Sockets.SocketFlags socketFlags) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static System.Threading.Tasks.Task<int> SendAsync(this System.Net.Sockets.Socket socket, System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static System.Threading.Tasks.ValueTask<int> SendAsync(this System.Net.Sockets.Socket socket, System.ReadOnlyMemory<byte> buffer, System.Net.Sockets.SocketFlags socketFlags, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static System.Threading.Tasks.Task<int> SendToAsync(this System.Net.Sockets.Socket socket, System.ArraySegment<byte> buffer, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEP) { throw null; } } public enum SocketType { Unknown = -1, Stream = 1, Dgram = 2, Raw = 3, Rdm = 4, Seqpacket = 5, } public partial class TcpClient : System.IDisposable { public TcpClient() { } public TcpClient(System.Net.IPEndPoint localEP) { } public TcpClient(System.Net.Sockets.AddressFamily family) { } public TcpClient(string hostname, int port) { } protected bool Active { get { throw null; } set { } } public int Available { get { throw null; } } public System.Net.Sockets.Socket Client { get { throw null; } set { } } public bool Connected { get { throw null; } } public bool ExclusiveAddressUse { get { throw null; } set { } } [System.Diagnostics.CodeAnalysis.DisallowNullAttribute] public System.Net.Sockets.LingerOption? LingerState { get { throw null; } set { } } public bool NoDelay { get { throw null; } set { } } public int ReceiveBufferSize { get { throw null; } set { } } public int ReceiveTimeout { get { throw null; } set { } } public int SendBufferSize { get { throw null; } set { } } public int SendTimeout { get { throw null; } set { } } public System.IAsyncResult BeginConnect(System.Net.IPAddress address, int port, System.AsyncCallback? requestCallback, object? state) { throw null; } public System.IAsyncResult BeginConnect(System.Net.IPAddress[] addresses, int port, System.AsyncCallback? requestCallback, object? state) { throw null; } public System.IAsyncResult BeginConnect(string host, int port, System.AsyncCallback? requestCallback, object? state) { throw null; } public void Close() { } public void Connect(System.Net.IPAddress address, int port) { } public void Connect(System.Net.IPAddress[] ipAddresses, int port) { } public void Connect(System.Net.IPEndPoint remoteEP) { } public void Connect(string hostname, int port) { } public System.Threading.Tasks.Task ConnectAsync(System.Net.IPAddress address, int port) { throw null; } public System.Threading.Tasks.Task ConnectAsync(System.Net.IPAddress[] addresses, int port) { throw null; } public System.Threading.Tasks.Task ConnectAsync(string host, int port) { throw null; } public System.Threading.Tasks.Task ConnectAsync(System.Net.IPEndPoint remoteEP) { throw null; } public System.Threading.Tasks.ValueTask ConnectAsync(System.Net.IPAddress address, int port, System.Threading.CancellationToken cancellationToken) { throw null; } public System.Threading.Tasks.ValueTask ConnectAsync(System.Net.IPAddress[] addresses, int port, System.Threading.CancellationToken cancellationToken) { throw null; } public System.Threading.Tasks.ValueTask ConnectAsync(string host, int port, System.Threading.CancellationToken cancellationToken) { throw null; } public System.Threading.Tasks.ValueTask ConnectAsync(System.Net.IPEndPoint remoteEP, System.Threading.CancellationToken cancellationToken) { throw null; } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public void EndConnect(System.IAsyncResult asyncResult) { } ~TcpClient() { } public System.Net.Sockets.NetworkStream GetStream() { throw null; } } public partial class TcpListener { [System.ObsoleteAttribute("This constructor has been deprecated. Use TcpListener(IPAddress localaddr, int port) instead.")] public TcpListener(int port) { } public TcpListener(System.Net.IPAddress localaddr, int port) { } public TcpListener(System.Net.IPEndPoint localEP) { } protected bool Active { get { throw null; } } public bool ExclusiveAddressUse { get { throw null; } set { } } public System.Net.EndPoint LocalEndpoint { get { throw null; } } public System.Net.Sockets.Socket Server { get { throw null; } } public System.Net.Sockets.Socket AcceptSocket() { throw null; } public System.Threading.Tasks.Task<System.Net.Sockets.Socket> AcceptSocketAsync() { throw null; } public System.Threading.Tasks.ValueTask<System.Net.Sockets.Socket> AcceptSocketAsync(System.Threading.CancellationToken cancellationToken) { throw null; } public System.Net.Sockets.TcpClient AcceptTcpClient() { throw null; } public System.Threading.Tasks.Task<System.Net.Sockets.TcpClient> AcceptTcpClientAsync() { throw null; } public System.Threading.Tasks.ValueTask<System.Net.Sockets.TcpClient> AcceptTcpClientAsync(System.Threading.CancellationToken cancellationToken) { throw null; } [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] public void AllowNatTraversal(bool allowed) { } public System.IAsyncResult BeginAcceptSocket(System.AsyncCallback? callback, object? state) { throw null; } public System.IAsyncResult BeginAcceptTcpClient(System.AsyncCallback? callback, object? state) { throw null; } public static System.Net.Sockets.TcpListener Create(int port) { throw null; } public System.Net.Sockets.Socket EndAcceptSocket(System.IAsyncResult asyncResult) { throw null; } public System.Net.Sockets.TcpClient EndAcceptTcpClient(System.IAsyncResult asyncResult) { throw null; } public bool Pending() { throw null; } public void Start() { } public void Start(int backlog) { } public void Stop() { } } [System.FlagsAttribute] public enum TransmitFileOptions { UseDefaultWorkerThread = 0, Disconnect = 1, ReuseSocket = 2, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] WriteBehind = 4, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] UseSystemThread = 16, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] UseKernelApc = 32, } public partial class UdpClient : System.IDisposable { public UdpClient() { } public UdpClient(int port) { } public UdpClient(int port, System.Net.Sockets.AddressFamily family) { } public UdpClient(System.Net.IPEndPoint localEP) { } public UdpClient(System.Net.Sockets.AddressFamily family) { } public UdpClient(string hostname, int port) { } protected bool Active { get { throw null; } set { } } public int Available { get { throw null; } } public System.Net.Sockets.Socket Client { get { throw null; } set { } } public bool DontFragment { get { throw null; } set { } } public bool EnableBroadcast { get { throw null; } set { } } public bool ExclusiveAddressUse { get { throw null; } set { } } public bool MulticastLoopback { get { throw null; } set { } } public short Ttl { get { throw null; } set { } } [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] public void AllowNatTraversal(bool allowed) { } public System.IAsyncResult BeginReceive(System.AsyncCallback? requestCallback, object? state) { throw null; } public System.IAsyncResult BeginSend(byte[] datagram, int bytes, System.AsyncCallback? requestCallback, object? state) { throw null; } public System.IAsyncResult BeginSend(byte[] datagram, int bytes, System.Net.IPEndPoint? endPoint, System.AsyncCallback? requestCallback, object? state) { throw null; } public System.IAsyncResult BeginSend(byte[] datagram, int bytes, string? hostname, int port, System.AsyncCallback? requestCallback, object? state) { throw null; } public void Close() { } public void Connect(System.Net.IPAddress addr, int port) { } public void Connect(System.Net.IPEndPoint endPoint) { } public void Connect(string hostname, int port) { } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public void DropMulticastGroup(System.Net.IPAddress multicastAddr) { } public void DropMulticastGroup(System.Net.IPAddress multicastAddr, int ifindex) { } public byte[] EndReceive(System.IAsyncResult asyncResult, ref System.Net.IPEndPoint? remoteEP) { throw null; } public int EndSend(System.IAsyncResult asyncResult) { throw null; } public void JoinMulticastGroup(int ifindex, System.Net.IPAddress multicastAddr) { } public void JoinMulticastGroup(System.Net.IPAddress multicastAddr) { } public void JoinMulticastGroup(System.Net.IPAddress multicastAddr, int timeToLive) { } public void JoinMulticastGroup(System.Net.IPAddress multicastAddr, System.Net.IPAddress localAddress) { } public byte[] Receive([System.Diagnostics.CodeAnalysis.NotNullAttribute] ref System.Net.IPEndPoint? remoteEP) { throw null; } public System.Threading.Tasks.Task<System.Net.Sockets.UdpReceiveResult> ReceiveAsync() { throw null; } public System.Threading.Tasks.ValueTask<System.Net.Sockets.UdpReceiveResult> ReceiveAsync(System.Threading.CancellationToken cancellationToken) { throw null; } public int Send(byte[] dgram, int bytes) { throw null; } public int Send(System.ReadOnlySpan<byte> datagram) {throw null; } public int Send(byte[] dgram, int bytes, System.Net.IPEndPoint? endPoint) { throw null; } public int Send(System.ReadOnlySpan<byte> datagram, System.Net.IPEndPoint? endPoint) { throw null; } public int Send(byte[] dgram, int bytes, string? hostname, int port) { throw null; } public int Send(System.ReadOnlySpan<byte> datagram, string? hostname, int port) { throw null; } public System.Threading.Tasks.Task<int> SendAsync(byte[] datagram, int bytes) { throw null; } public System.Threading.Tasks.ValueTask<int> SendAsync(System.ReadOnlyMemory<byte> datagram, System.Threading.CancellationToken cancellationToken = default) { throw null; } public System.Threading.Tasks.Task<int> SendAsync(byte[] datagram, int bytes, System.Net.IPEndPoint? endPoint) { throw null; } public System.Threading.Tasks.ValueTask<int> SendAsync(System.ReadOnlyMemory<byte> datagram, System.Net.IPEndPoint? endPoint, System.Threading.CancellationToken cancellationToken = default) { throw null; } public System.Threading.Tasks.Task<int> SendAsync(byte[] datagram, int bytes, string? hostname, int port) { throw null; } public System.Threading.Tasks.ValueTask<int> SendAsync(System.ReadOnlyMemory<byte> datagram, string? hostname, int port, System.Threading.CancellationToken cancellationToken = default) { throw null; } } public partial struct UdpReceiveResult : System.IEquatable<System.Net.Sockets.UdpReceiveResult> { private object _dummy; private int _dummyPrimitive; public UdpReceiveResult(byte[] buffer, System.Net.IPEndPoint remoteEndPoint) { throw null; } public byte[] Buffer { get { throw null; } } public System.Net.IPEndPoint RemoteEndPoint { get { throw null; } } public bool Equals(System.Net.Sockets.UdpReceiveResult other) { throw null; } public override bool Equals([System.Diagnostics.CodeAnalysis.NotNullWhen(true)] object? obj) { throw null; } public override int GetHashCode() { throw null; } public static bool operator ==(System.Net.Sockets.UdpReceiveResult left, System.Net.Sockets.UdpReceiveResult right) { throw null; } public static bool operator !=(System.Net.Sockets.UdpReceiveResult left, System.Net.Sockets.UdpReceiveResult right) { throw null; } } public sealed partial class UnixDomainSocketEndPoint : System.Net.EndPoint { public UnixDomainSocketEndPoint(string path) { } } }
// 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.Net.Sockets { public enum IOControlCode : long { [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] EnableCircularQueuing = (long)671088642, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] Flush = (long)671088644, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] AddressListChange = (long)671088663, DataToRead = (long)1074030207, OobDataRead = (long)1074033415, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] GetBroadcastAddress = (long)1207959557, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] AddressListQuery = (long)1207959574, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] QueryTargetPnpHandle = (long)1207959576, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] AsyncIO = (long)2147772029, NonBlockingIO = (long)2147772030, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] AssociateHandle = (long)2281701377, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] MultipointLoopback = (long)2281701385, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] MulticastScope = (long)2281701386, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] SetQos = (long)2281701387, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] SetGroupQos = (long)2281701388, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] RoutingInterfaceChange = (long)2281701397, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] NamespaceChange = (long)2281701401, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] ReceiveAll = (long)2550136833, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] ReceiveAllMulticast = (long)2550136834, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] ReceiveAllIgmpMulticast = (long)2550136835, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] KeepAliveValues = (long)2550136836, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] AbsorbRouterAlert = (long)2550136837, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] UnicastInterface = (long)2550136838, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] LimitBroadcasts = (long)2550136839, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] BindToInterface = (long)2550136840, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] MulticastInterface = (long)2550136841, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] AddMulticastGroupOnInterface = (long)2550136842, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] DeleteMulticastGroupFromInterface = (long)2550136843, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] GetExtensionFunctionPointer = (long)3355443206, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] GetQos = (long)3355443207, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] GetGroupQos = (long)3355443208, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] TranslateHandle = (long)3355443213, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] RoutingInterfaceQuery = (long)3355443220, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] AddressListSort = (long)3355443225, } public partial struct IPPacketInformation : System.IEquatable<System.Net.Sockets.IPPacketInformation> { private object _dummy; private int _dummyPrimitive; public System.Net.IPAddress Address { get { throw null; } } public int Interface { get { throw null; } } public override bool Equals([System.Diagnostics.CodeAnalysis.NotNullWhen(true)] object? comparand) { throw null; } public bool Equals(System.Net.Sockets.IPPacketInformation other) { throw null; } public override int GetHashCode() { throw null; } public static bool operator ==(System.Net.Sockets.IPPacketInformation packetInformation1, System.Net.Sockets.IPPacketInformation packetInformation2) { throw null; } public static bool operator !=(System.Net.Sockets.IPPacketInformation packetInformation1, System.Net.Sockets.IPPacketInformation packetInformation2) { throw null; } } public enum IPProtectionLevel { Unspecified = -1, Unrestricted = 10, EdgeRestricted = 20, Restricted = 30, } public partial class IPv6MulticastOption { public IPv6MulticastOption(System.Net.IPAddress group) { } public IPv6MulticastOption(System.Net.IPAddress group, long ifindex) { } public System.Net.IPAddress Group { get { throw null; } set { } } public long InterfaceIndex { get { throw null; } set { } } } public partial class LingerOption { public LingerOption(bool enable, int seconds) { } public bool Enabled { get { throw null; } set { } } public int LingerTime { get { throw null; } set { } } } public partial class MulticastOption { public MulticastOption(System.Net.IPAddress group) { } public MulticastOption(System.Net.IPAddress group, int interfaceIndex) { } public MulticastOption(System.Net.IPAddress group, System.Net.IPAddress mcint) { } public System.Net.IPAddress Group { get { throw null; } set { } } public int InterfaceIndex { get { throw null; } set { } } public System.Net.IPAddress? LocalAddress { get { throw null; } set { } } } public partial class NetworkStream : System.IO.Stream { public NetworkStream(System.Net.Sockets.Socket socket) { } public NetworkStream(System.Net.Sockets.Socket socket, bool ownsSocket) { } public NetworkStream(System.Net.Sockets.Socket socket, System.IO.FileAccess access) { } public NetworkStream(System.Net.Sockets.Socket socket, System.IO.FileAccess access, bool ownsSocket) { } public override bool CanRead { get { throw null; } } public override bool CanSeek { get { throw null; } } public override bool CanTimeout { get { throw null; } } public override bool CanWrite { get { throw null; } } public virtual bool DataAvailable { get { throw null; } } public override long Length { get { throw null; } } public override long Position { get { throw null; } set { } } protected bool Readable { get { throw null; } set { } } public override int ReadTimeout { get { throw null; } set { } } public System.Net.Sockets.Socket Socket { get { throw null; } } protected bool Writeable { get { throw null; } set { } } public override int WriteTimeout { get { throw null; } set { } } public override System.IAsyncResult BeginRead(byte[] buffer, int offset, int count, System.AsyncCallback? callback, object? state) { throw null; } public override System.IAsyncResult BeginWrite(byte[] buffer, int offset, int count, System.AsyncCallback? callback, object? state) { throw null; } public void Close(int timeout) { } protected override void Dispose(bool disposing) { } public override int EndRead(System.IAsyncResult asyncResult) { throw null; } public override void EndWrite(System.IAsyncResult asyncResult) { } ~NetworkStream() { } public override void Flush() { } public override System.Threading.Tasks.Task FlushAsync(System.Threading.CancellationToken cancellationToken) { throw null; } public override int Read(byte[] buffer, int offset, int count) { throw null; } public override int Read(System.Span<byte> buffer) { throw null; } public override System.Threading.Tasks.Task<int> ReadAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { throw null; } public override System.Threading.Tasks.ValueTask<int> ReadAsync(System.Memory<byte> buffer, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override int ReadByte() { throw null; } public override long Seek(long offset, System.IO.SeekOrigin origin) { throw null; } public override void SetLength(long value) { } public override void Write(byte[] buffer, int offset, int count) { } public override void Write(System.ReadOnlySpan<byte> buffer) { } public override System.Threading.Tasks.Task WriteAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { throw null; } public override System.Threading.Tasks.ValueTask WriteAsync(System.ReadOnlyMemory<byte> buffer, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override void WriteByte(byte value) { } } public enum ProtocolFamily { Unknown = -1, Unspecified = 0, Unix = 1, InterNetwork = 2, ImpLink = 3, Pup = 4, Chaos = 5, Ipx = 6, NS = 6, Iso = 7, Osi = 7, Ecma = 8, DataKit = 9, Ccitt = 10, Sna = 11, DecNet = 12, DataLink = 13, Lat = 14, HyperChannel = 15, AppleTalk = 16, NetBios = 17, VoiceView = 18, FireFox = 19, Banyan = 21, Atm = 22, InterNetworkV6 = 23, Cluster = 24, Ieee12844 = 25, Irda = 26, NetworkDesigners = 28, Max = 29, Packet = 65536, ControllerAreaNetwork = 65537, } public enum ProtocolType { Unknown = -1, IP = 0, IPv6HopByHopOptions = 0, Unspecified = 0, Icmp = 1, Igmp = 2, Ggp = 3, IPv4 = 4, Tcp = 6, Pup = 12, Udp = 17, Idp = 22, IPv6 = 41, IPv6RoutingHeader = 43, IPv6FragmentHeader = 44, IPSecEncapsulatingSecurityPayload = 50, IPSecAuthenticationHeader = 51, IcmpV6 = 58, IPv6NoNextHeader = 59, IPv6DestinationOptions = 60, ND = 77, Raw = 255, Ipx = 1000, Spx = 1256, SpxII = 1257, } public sealed partial class SafeSocketHandle : Microsoft.Win32.SafeHandles.SafeHandleMinusOneIsInvalid { public SafeSocketHandle() : base (default(bool)) { } public SafeSocketHandle(System.IntPtr preexistingHandle, bool ownsHandle) : base (default(bool)) { } protected override bool ReleaseHandle() { throw null; } } public enum SelectMode { SelectRead = 0, SelectWrite = 1, SelectError = 2, } public partial class SendPacketsElement { public SendPacketsElement(byte[] buffer) { } public SendPacketsElement(byte[] buffer, int offset, int count) { } public SendPacketsElement(byte[] buffer, int offset, int count, bool endOfPacket) { } public SendPacketsElement(ReadOnlyMemory<byte> buffer) { } public SendPacketsElement(ReadOnlyMemory<byte> buffer, bool endOfPacket) { } public SendPacketsElement(System.IO.FileStream fileStream) { } public SendPacketsElement(System.IO.FileStream fileStream, long offset, int count) { } public SendPacketsElement(System.IO.FileStream fileStream, long offset, int count, bool endOfPacket) { } public SendPacketsElement(string filepath) { } public SendPacketsElement(string filepath, int offset, int count) { } public SendPacketsElement(string filepath, int offset, int count, bool endOfPacket) { } public SendPacketsElement(string filepath, long offset, int count) { } public SendPacketsElement(string filepath, long offset, int count, bool endOfPacket) { } public byte[]? Buffer { get { throw null; } } public int Count { get { throw null; } } public bool EndOfPacket { get { throw null; } } public string? FilePath { get { throw null; } } public System.IO.FileStream? FileStream { get { throw null; } } public ReadOnlyMemory<byte>? MemoryBuffer { get { throw null; } } public int Offset { get { throw null; } } public long OffsetLong { get { throw null; } } } public partial class Socket : System.IDisposable { public Socket(System.Net.Sockets.SafeSocketHandle handle) { } public Socket(System.Net.Sockets.AddressFamily addressFamily, System.Net.Sockets.SocketType socketType, System.Net.Sockets.ProtocolType protocolType) { } [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] public Socket(System.Net.Sockets.SocketInformation socketInformation) { } public Socket(System.Net.Sockets.SocketType socketType, System.Net.Sockets.ProtocolType protocolType) { } public System.Net.Sockets.AddressFamily AddressFamily { get { throw null; } } public int Available { get { throw null; } } public bool Blocking { get { throw null; } set { } } public bool Connected { get { throw null; } } public bool DontFragment { get { throw null; } set { } } public bool DualMode { get { throw null; } set { } } public bool EnableBroadcast { get { throw null; } set { } } public bool ExclusiveAddressUse { get { throw null; } set { } } public System.IntPtr Handle { get { throw null; } } public bool IsBound { get { throw null; } } [System.Diagnostics.CodeAnalysis.DisallowNullAttribute] public System.Net.Sockets.LingerOption? LingerState { get { throw null; } set { } } public System.Net.EndPoint? LocalEndPoint { get { throw null; } } public bool MulticastLoopback { get { throw null; } set { } } public bool NoDelay { get { throw null; } set { } } public static bool OSSupportsIPv4 { get { throw null; } } public static bool OSSupportsIPv6 { get { throw null; } } public static bool OSSupportsUnixDomainSockets { get { throw null; } } public System.Net.Sockets.ProtocolType ProtocolType { get { throw null; } } public int ReceiveBufferSize { get { throw null; } set { } } public int ReceiveTimeout { get { throw null; } set { } } public System.Net.EndPoint? RemoteEndPoint { get { throw null; } } public System.Net.Sockets.SafeSocketHandle SafeHandle { get { throw null; } } public int SendBufferSize { get { throw null; } set { } } public int SendTimeout { get { throw null; } set { } } public System.Net.Sockets.SocketType SocketType { get { throw null; } } [System.ObsoleteAttribute("SupportsIPv4 has been deprecated. Use OSSupportsIPv4 instead.")] public static bool SupportsIPv4 { get { throw null; } } [System.ObsoleteAttribute("SupportsIPv6 has been deprecated. Use OSSupportsIPv6 instead.")] public static bool SupportsIPv6 { get { throw null; } } public short Ttl { get { throw null; } set { } } [System.ObsoleteAttribute("UseOnlyOverlappedIO has been deprecated and is not supported.")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public bool UseOnlyOverlappedIO { get { throw null; } set { } } public System.Net.Sockets.Socket Accept() { throw null; } public System.Threading.Tasks.Task<System.Net.Sockets.Socket> AcceptAsync() { throw null; } public System.Threading.Tasks.ValueTask<System.Net.Sockets.Socket> AcceptAsync(System.Threading.CancellationToken cancellationToken) { throw null; } public System.Threading.Tasks.Task<System.Net.Sockets.Socket> AcceptAsync(System.Net.Sockets.Socket? acceptSocket) { throw null; } public System.Threading.Tasks.ValueTask<System.Net.Sockets.Socket> AcceptAsync(System.Net.Sockets.Socket? acceptSocket, System.Threading.CancellationToken cancellationToken) { throw null; } public bool AcceptAsync(System.Net.Sockets.SocketAsyncEventArgs e) { throw null; } public System.IAsyncResult BeginAccept(System.AsyncCallback? callback, object? state) { throw null; } public System.IAsyncResult BeginAccept(int receiveSize, System.AsyncCallback? callback, object? state) { throw null; } public System.IAsyncResult BeginAccept(System.Net.Sockets.Socket? acceptSocket, int receiveSize, System.AsyncCallback? callback, object? state) { throw null; } public System.IAsyncResult BeginConnect(System.Net.EndPoint remoteEP, System.AsyncCallback? callback, object? state) { throw null; } public System.IAsyncResult BeginConnect(System.Net.IPAddress address, int port, System.AsyncCallback? requestCallback, object? state) { throw null; } public System.IAsyncResult BeginConnect(System.Net.IPAddress[] addresses, int port, System.AsyncCallback? requestCallback, object? state) { throw null; } public System.IAsyncResult BeginConnect(string host, int port, System.AsyncCallback? requestCallback, object? state) { throw null; } public System.IAsyncResult BeginDisconnect(bool reuseSocket, System.AsyncCallback? callback, object? state) { throw null; } public System.IAsyncResult BeginReceive(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, System.AsyncCallback? callback, object? state) { throw null; } public System.IAsyncResult? BeginReceive(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode, System.AsyncCallback? callback, object? state) { throw null; } public System.IAsyncResult BeginReceive(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags, System.AsyncCallback? callback, object? state) { throw null; } public System.IAsyncResult? BeginReceive(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode, System.AsyncCallback? callback, object? state) { throw null; } public System.IAsyncResult BeginReceiveFrom(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, ref System.Net.EndPoint remoteEP, System.AsyncCallback? callback, object? state) { throw null; } public System.IAsyncResult BeginReceiveMessageFrom(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, ref System.Net.EndPoint remoteEP, System.AsyncCallback? callback, object? state) { throw null; } public System.IAsyncResult BeginSend(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, System.AsyncCallback? callback, object? state) { throw null; } public System.IAsyncResult? BeginSend(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode, System.AsyncCallback? callback, object? state) { throw null; } public System.IAsyncResult BeginSend(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags, System.AsyncCallback? callback, object? state) { throw null; } public System.IAsyncResult? BeginSend(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode, System.AsyncCallback? callback, object? state) { throw null; } public System.IAsyncResult BeginSendFile(string? fileName, System.AsyncCallback? callback, object? state) { throw null; } public System.IAsyncResult BeginSendFile(string? fileName, byte[]? preBuffer, byte[]? postBuffer, System.Net.Sockets.TransmitFileOptions flags, System.AsyncCallback? callback, object? state) { throw null; } public System.IAsyncResult BeginSendTo(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEP, System.AsyncCallback? callback, object? state) { throw null; } public void Bind(System.Net.EndPoint localEP) { } public static void CancelConnectAsync(System.Net.Sockets.SocketAsyncEventArgs e) { } public void Close() { } public void Close(int timeout) { } public void Connect(System.Net.EndPoint remoteEP) { } public void Connect(System.Net.IPAddress address, int port) { } public void Connect(System.Net.IPAddress[] addresses, int port) { } public void Connect(string host, int port) { } public System.Threading.Tasks.Task ConnectAsync(System.Net.EndPoint remoteEP) { throw null; } public System.Threading.Tasks.ValueTask ConnectAsync(System.Net.EndPoint remoteEP, System.Threading.CancellationToken cancellationToken) { throw null; } public System.Threading.Tasks.Task ConnectAsync(System.Net.IPAddress address, int port) { throw null; } public System.Threading.Tasks.ValueTask ConnectAsync(System.Net.IPAddress address, int port, System.Threading.CancellationToken cancellationToken) { throw null; } public System.Threading.Tasks.Task ConnectAsync(System.Net.IPAddress[] addresses, int port) { throw null; } public System.Threading.Tasks.ValueTask ConnectAsync(System.Net.IPAddress[] addresses, int port, System.Threading.CancellationToken cancellationToken) { throw null; } public System.Threading.Tasks.Task ConnectAsync(string host, int port) { throw null; } public System.Threading.Tasks.ValueTask ConnectAsync(string host, int port, System.Threading.CancellationToken cancellationToken) { throw null; } public bool ConnectAsync(System.Net.Sockets.SocketAsyncEventArgs e) { throw null; } public static bool ConnectAsync(System.Net.Sockets.SocketType socketType, System.Net.Sockets.ProtocolType protocolType, System.Net.Sockets.SocketAsyncEventArgs e) { throw null; } public void Disconnect(bool reuseSocket) { } public bool DisconnectAsync(System.Net.Sockets.SocketAsyncEventArgs e) { throw null; } public System.Threading.Tasks.ValueTask DisconnectAsync(bool reuseSocket, System.Threading.CancellationToken cancellationToken = default) { throw null; } public void Dispose() { } protected virtual void Dispose(bool disposing) { } [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] public System.Net.Sockets.SocketInformation DuplicateAndClose(int targetProcessId) { throw null; } public System.Net.Sockets.Socket EndAccept(out byte[] buffer, System.IAsyncResult asyncResult) { throw null; } public System.Net.Sockets.Socket EndAccept(out byte[] buffer, out int bytesTransferred, System.IAsyncResult asyncResult) { throw null; } public System.Net.Sockets.Socket EndAccept(System.IAsyncResult asyncResult) { throw null; } public void EndConnect(System.IAsyncResult asyncResult) { } public void EndDisconnect(System.IAsyncResult asyncResult) { } public int EndReceive(System.IAsyncResult asyncResult) { throw null; } public int EndReceive(System.IAsyncResult asyncResult, out System.Net.Sockets.SocketError errorCode) { throw null; } public int EndReceiveFrom(System.IAsyncResult asyncResult, ref System.Net.EndPoint endPoint) { throw null; } public int EndReceiveMessageFrom(System.IAsyncResult asyncResult, ref System.Net.Sockets.SocketFlags socketFlags, ref System.Net.EndPoint endPoint, out System.Net.Sockets.IPPacketInformation ipPacketInformation) { throw null; } public int EndSend(System.IAsyncResult asyncResult) { throw null; } public int EndSend(System.IAsyncResult asyncResult, out System.Net.Sockets.SocketError errorCode) { throw null; } public void EndSendFile(System.IAsyncResult asyncResult) { } public int EndSendTo(System.IAsyncResult asyncResult) { throw null; } ~Socket() { } public int GetRawSocketOption(int optionLevel, int optionName, System.Span<byte> optionValue) { throw null; } public object? GetSocketOption(System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName) { throw null; } public void GetSocketOption(System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName, byte[] optionValue) { } public byte[] GetSocketOption(System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName, int optionLength) { throw null; } public int IOControl(int ioControlCode, byte[]? optionInValue, byte[]? optionOutValue) { throw null; } public int IOControl(System.Net.Sockets.IOControlCode ioControlCode, byte[]? optionInValue, byte[]? optionOutValue) { throw null; } public void Listen() { } public void Listen(int backlog) { } public bool Poll(int microSeconds, System.Net.Sockets.SelectMode mode) { throw null; } public int Receive(byte[] buffer) { throw null; } public int Receive(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags) { throw null; } public int Receive(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode) { throw null; } public int Receive(byte[] buffer, int size, System.Net.Sockets.SocketFlags socketFlags) { throw null; } public int Receive(byte[] buffer, System.Net.Sockets.SocketFlags socketFlags) { throw null; } public int Receive(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers) { throw null; } public int Receive(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags) { throw null; } public int Receive(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode) { throw null; } public int Receive(System.Span<byte> buffer) { throw null; } public int Receive(System.Span<byte> buffer, System.Net.Sockets.SocketFlags socketFlags) { throw null; } public int Receive(System.Span<byte> buffer, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode) { throw null; } public System.Threading.Tasks.Task<int> ReceiveAsync(System.ArraySegment<byte> buffer) { throw null; } public System.Threading.Tasks.Task<int> ReceiveAsync(System.ArraySegment<byte> buffer, System.Net.Sockets.SocketFlags socketFlags) { throw null; } public System.Threading.Tasks.Task<int> ReceiveAsync(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers) { throw null; } public System.Threading.Tasks.Task<int> ReceiveAsync(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags) { throw null; } public System.Threading.Tasks.ValueTask<int> ReceiveAsync(System.Memory<byte> buffer, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public System.Threading.Tasks.ValueTask<int> ReceiveAsync(System.Memory<byte> buffer, System.Net.Sockets.SocketFlags socketFlags, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public bool ReceiveAsync(System.Net.Sockets.SocketAsyncEventArgs e) { throw null; } public int ReceiveFrom(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, ref System.Net.EndPoint remoteEP) { throw null; } public int ReceiveFrom(byte[] buffer, int size, System.Net.Sockets.SocketFlags socketFlags, ref System.Net.EndPoint remoteEP) { throw null; } public int ReceiveFrom(byte[] buffer, ref System.Net.EndPoint remoteEP) { throw null; } public int ReceiveFrom(byte[] buffer, System.Net.Sockets.SocketFlags socketFlags, ref System.Net.EndPoint remoteEP) { throw null; } public int ReceiveFrom(System.Span<byte> buffer, ref System.Net.EndPoint remoteEP) { throw null; } public int ReceiveFrom(System.Span<byte> buffer, System.Net.Sockets.SocketFlags socketFlags, ref System.Net.EndPoint remoteEP) { throw null; } public System.Threading.Tasks.Task<System.Net.Sockets.SocketReceiveFromResult> ReceiveFromAsync(System.ArraySegment<byte> buffer, System.Net.EndPoint remoteEndPoint) { throw null; } public System.Threading.Tasks.Task<System.Net.Sockets.SocketReceiveFromResult> ReceiveFromAsync(System.ArraySegment<byte> buffer, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEndPoint) { throw null; } public System.Threading.Tasks.ValueTask<System.Net.Sockets.SocketReceiveFromResult> ReceiveFromAsync(System.Memory<byte> buffer, System.Net.EndPoint remoteEndPoint, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public System.Threading.Tasks.ValueTask<System.Net.Sockets.SocketReceiveFromResult> ReceiveFromAsync(System.Memory<byte> buffer, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEndPoint, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public bool ReceiveFromAsync(System.Net.Sockets.SocketAsyncEventArgs e) { throw null; } public int ReceiveMessageFrom(byte[] buffer, int offset, int size, ref System.Net.Sockets.SocketFlags socketFlags, ref System.Net.EndPoint remoteEP, out System.Net.Sockets.IPPacketInformation ipPacketInformation) { throw null; } public int ReceiveMessageFrom(System.Span<byte> buffer, ref System.Net.Sockets.SocketFlags socketFlags, ref System.Net.EndPoint remoteEP, out System.Net.Sockets.IPPacketInformation ipPacketInformation) { throw null; } public System.Threading.Tasks.Task<System.Net.Sockets.SocketReceiveMessageFromResult> ReceiveMessageFromAsync(System.ArraySegment<byte> buffer, System.Net.EndPoint remoteEndPoint) { throw null; } public System.Threading.Tasks.Task<System.Net.Sockets.SocketReceiveMessageFromResult> ReceiveMessageFromAsync(System.ArraySegment<byte> buffer, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEndPoint) { throw null; } public System.Threading.Tasks.ValueTask<System.Net.Sockets.SocketReceiveMessageFromResult> ReceiveMessageFromAsync(System.Memory<byte> buffer, System.Net.EndPoint remoteEndPoint, System.Threading.CancellationToken cancellationToken = default) { throw null; } public System.Threading.Tasks.ValueTask<System.Net.Sockets.SocketReceiveMessageFromResult> ReceiveMessageFromAsync(System.Memory<byte> buffer, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEndPoint, System.Threading.CancellationToken cancellationToken = default) { throw null; } public bool ReceiveMessageFromAsync(System.Net.Sockets.SocketAsyncEventArgs e) { throw null; } public static void Select(System.Collections.IList? checkRead, System.Collections.IList? checkWrite, System.Collections.IList? checkError, int microSeconds) { } public int Send(byte[] buffer) { throw null; } public int Send(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags) { throw null; } public int Send(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode) { throw null; } public int Send(byte[] buffer, int size, System.Net.Sockets.SocketFlags socketFlags) { throw null; } public int Send(byte[] buffer, System.Net.Sockets.SocketFlags socketFlags) { throw null; } public int Send(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers) { throw null; } public int Send(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags) { throw null; } public int Send(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode) { throw null; } public int Send(System.ReadOnlySpan<byte> buffer) { throw null; } public int Send(System.ReadOnlySpan<byte> buffer, System.Net.Sockets.SocketFlags socketFlags) { throw null; } public int Send(System.ReadOnlySpan<byte> buffer, System.Net.Sockets.SocketFlags socketFlags, out System.Net.Sockets.SocketError errorCode) { throw null; } public System.Threading.Tasks.Task<int> SendAsync(System.ArraySegment<byte> buffer) { throw null; } public System.Threading.Tasks.Task<int> SendAsync(System.ArraySegment<byte> buffer, System.Net.Sockets.SocketFlags socketFlags) { throw null; } public System.Threading.Tasks.Task<int> SendAsync(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers) { throw null; } public System.Threading.Tasks.Task<int> SendAsync(System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags) { throw null; } public System.Threading.Tasks.ValueTask<int> SendAsync(System.ReadOnlyMemory<byte> buffer, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public System.Threading.Tasks.ValueTask<int> SendAsync(System.ReadOnlyMemory<byte> buffer, System.Net.Sockets.SocketFlags socketFlags, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public bool SendAsync(System.Net.Sockets.SocketAsyncEventArgs e) { throw null; } public void SendFile(string? fileName) { } public void SendFile(string? fileName, byte[]? preBuffer, byte[]? postBuffer, System.Net.Sockets.TransmitFileOptions flags) { } public void SendFile(string? fileName, System.ReadOnlySpan<byte> preBuffer, System.ReadOnlySpan<byte> postBuffer, System.Net.Sockets.TransmitFileOptions flags) { } public System.Threading.Tasks.ValueTask SendFileAsync(string? fileName, System.ReadOnlyMemory<byte> preBuffer, System.ReadOnlyMemory<byte> postBuffer, System.Net.Sockets.TransmitFileOptions flags, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public System.Threading.Tasks.ValueTask SendFileAsync(string? fileName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public bool SendPacketsAsync(System.Net.Sockets.SocketAsyncEventArgs e) { throw null; } public int SendTo(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEP) { throw null; } public int SendTo(byte[] buffer, int size, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEP) { throw null; } public int SendTo(byte[] buffer, System.Net.EndPoint remoteEP) { throw null; } public int SendTo(byte[] buffer, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEP) { throw null; } public int SendTo(System.ReadOnlySpan<byte> buffer, System.Net.EndPoint remoteEP) { throw null; } public int SendTo(System.ReadOnlySpan<byte> buffer, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEP) { throw null; } public System.Threading.Tasks.Task<int> SendToAsync(System.ArraySegment<byte> buffer, System.Net.EndPoint remoteEP) { throw null; } public System.Threading.Tasks.Task<int> SendToAsync(System.ArraySegment<byte> buffer, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEP) { throw null; } public System.Threading.Tasks.ValueTask<int> SendToAsync(System.ReadOnlyMemory<byte> buffer, System.Net.EndPoint remoteEP, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public System.Threading.Tasks.ValueTask<int> SendToAsync(System.ReadOnlyMemory<byte> buffer, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEP, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public bool SendToAsync(System.Net.Sockets.SocketAsyncEventArgs e) { throw null; } [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] public void SetIPProtectionLevel(System.Net.Sockets.IPProtectionLevel level) { } public void SetRawSocketOption(int optionLevel, int optionName, System.ReadOnlySpan<byte> optionValue) { } public void SetSocketOption(System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName, bool optionValue) { } public void SetSocketOption(System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName, byte[] optionValue) { } public void SetSocketOption(System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName, int optionValue) { } public void SetSocketOption(System.Net.Sockets.SocketOptionLevel optionLevel, System.Net.Sockets.SocketOptionName optionName, object optionValue) { } public void Shutdown(System.Net.Sockets.SocketShutdown how) { } } public partial class SocketAsyncEventArgs : System.EventArgs, System.IDisposable { public SocketAsyncEventArgs() { } public SocketAsyncEventArgs(bool unsafeSuppressExecutionContextFlow) { } public System.Net.Sockets.Socket? AcceptSocket { get { throw null; } set { } } public byte[]? Buffer { get { throw null; } } public System.Collections.Generic.IList<System.ArraySegment<byte>>? BufferList { get { throw null; } set { } } public int BytesTransferred { get { throw null; } } public System.Exception? ConnectByNameError { get { throw null; } } public System.Net.Sockets.Socket? ConnectSocket { get { throw null; } } public int Count { get { throw null; } } public bool DisconnectReuseSocket { get { throw null; } set { } } public System.Net.Sockets.SocketAsyncOperation LastOperation { get { throw null; } } public System.Memory<byte> MemoryBuffer { get { throw null; } } public int Offset { get { throw null; } } public System.Net.Sockets.IPPacketInformation ReceiveMessageFromPacketInfo { get { throw null; } } public System.Net.EndPoint? RemoteEndPoint { get { throw null; } set { } } public System.Net.Sockets.SendPacketsElement[]? SendPacketsElements { get { throw null; } set { } } public System.Net.Sockets.TransmitFileOptions SendPacketsFlags { get { throw null; } set { } } public int SendPacketsSendSize { get { throw null; } set { } } public System.Net.Sockets.SocketError SocketError { get { throw null; } set { } } public System.Net.Sockets.SocketFlags SocketFlags { get { throw null; } set { } } public object? UserToken { get { throw null; } set { } } public event System.EventHandler<System.Net.Sockets.SocketAsyncEventArgs>? Completed { add { } remove { } } public void Dispose() { } ~SocketAsyncEventArgs() { } protected virtual void OnCompleted(System.Net.Sockets.SocketAsyncEventArgs e) { } public void SetBuffer(byte[]? buffer, int offset, int count) { } public void SetBuffer(int offset, int count) { } public void SetBuffer(System.Memory<byte> buffer) { } } public enum SocketAsyncOperation { None = 0, Accept = 1, Connect = 2, Disconnect = 3, Receive = 4, ReceiveFrom = 5, ReceiveMessageFrom = 6, Send = 7, SendPackets = 8, SendTo = 9, } [System.FlagsAttribute] public enum SocketFlags { None = 0, OutOfBand = 1, Peek = 2, DontRoute = 4, Truncated = 256, ControlDataTruncated = 512, Broadcast = 1024, Multicast = 2048, Partial = 32768, } public partial struct SocketInformation { private object _dummy; private int _dummyPrimitive; public System.Net.Sockets.SocketInformationOptions Options { readonly get { throw null; } set { } } public byte[] ProtocolInformation { readonly get { throw null; } set { } } } [System.FlagsAttribute] public enum SocketInformationOptions { NonBlocking = 1, Connected = 2, Listening = 4, [System.ObsoleteAttribute("SocketInformationOptions.UseOnlyOverlappedIO has been deprecated and is not supported.")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] UseOnlyOverlappedIO = 8, } public enum SocketOptionLevel { IP = 0, Tcp = 6, Udp = 17, IPv6 = 41, Socket = 65535, } public enum SocketOptionName { DontLinger = -129, ExclusiveAddressUse = -5, Debug = 1, IPOptions = 1, NoChecksum = 1, NoDelay = 1, AcceptConnection = 2, BsdUrgent = 2, Expedited = 2, HeaderIncluded = 2, TcpKeepAliveTime = 3, TypeOfService = 3, IpTimeToLive = 4, ReuseAddress = 4, KeepAlive = 8, MulticastInterface = 9, MulticastTimeToLive = 10, MulticastLoopback = 11, AddMembership = 12, DropMembership = 13, DontFragment = 14, AddSourceMembership = 15, DontRoute = 16, DropSourceMembership = 16, TcpKeepAliveRetryCount = 16, BlockSource = 17, TcpKeepAliveInterval = 17, UnblockSource = 18, PacketInformation = 19, ChecksumCoverage = 20, HopLimit = 21, IPProtectionLevel = 23, IPv6Only = 27, Broadcast = 32, UseLoopback = 64, Linger = 128, OutOfBandInline = 256, SendBuffer = 4097, ReceiveBuffer = 4098, SendLowWater = 4099, ReceiveLowWater = 4100, SendTimeout = 4101, ReceiveTimeout = 4102, Error = 4103, Type = 4104, ReuseUnicastPort = 12295, UpdateAcceptContext = 28683, UpdateConnectContext = 28688, MaxConnections = 2147483647, } public partial struct SocketReceiveFromResult { public int ReceivedBytes; public System.Net.EndPoint RemoteEndPoint; } public partial struct SocketReceiveMessageFromResult { public System.Net.Sockets.IPPacketInformation PacketInformation; public int ReceivedBytes; public System.Net.EndPoint RemoteEndPoint; public System.Net.Sockets.SocketFlags SocketFlags; } public enum SocketShutdown { Receive = 0, Send = 1, Both = 2, } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static partial class SocketTaskExtensions { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static System.Threading.Tasks.Task<System.Net.Sockets.Socket> AcceptAsync(this System.Net.Sockets.Socket socket) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static System.Threading.Tasks.Task<System.Net.Sockets.Socket> AcceptAsync(this System.Net.Sockets.Socket socket, System.Net.Sockets.Socket? acceptSocket) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static System.Threading.Tasks.Task ConnectAsync(this System.Net.Sockets.Socket socket, System.Net.EndPoint remoteEP) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static System.Threading.Tasks.ValueTask ConnectAsync(this System.Net.Sockets.Socket socket, System.Net.EndPoint remoteEP, System.Threading.CancellationToken cancellationToken) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static System.Threading.Tasks.Task ConnectAsync(this System.Net.Sockets.Socket socket, System.Net.IPAddress address, int port) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static System.Threading.Tasks.ValueTask ConnectAsync(this System.Net.Sockets.Socket socket, System.Net.IPAddress address, int port, System.Threading.CancellationToken cancellationToken) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static System.Threading.Tasks.Task ConnectAsync(this System.Net.Sockets.Socket socket, System.Net.IPAddress[] addresses, int port) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static System.Threading.Tasks.ValueTask ConnectAsync(this System.Net.Sockets.Socket socket, System.Net.IPAddress[] addresses, int port, System.Threading.CancellationToken cancellationToken) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static System.Threading.Tasks.Task ConnectAsync(this System.Net.Sockets.Socket socket, string host, int port) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static System.Threading.Tasks.ValueTask ConnectAsync(this System.Net.Sockets.Socket socket, string host, int port, System.Threading.CancellationToken cancellationToken) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static System.Threading.Tasks.Task<int> ReceiveAsync(this System.Net.Sockets.Socket socket, System.ArraySegment<byte> buffer, System.Net.Sockets.SocketFlags socketFlags) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static System.Threading.Tasks.Task<int> ReceiveAsync(this System.Net.Sockets.Socket socket, System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static System.Threading.Tasks.ValueTask<int> ReceiveAsync(this System.Net.Sockets.Socket socket, System.Memory<byte> buffer, System.Net.Sockets.SocketFlags socketFlags, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static System.Threading.Tasks.Task<System.Net.Sockets.SocketReceiveFromResult> ReceiveFromAsync(this System.Net.Sockets.Socket socket, System.ArraySegment<byte> buffer, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEndPoint) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static System.Threading.Tasks.Task<System.Net.Sockets.SocketReceiveMessageFromResult> ReceiveMessageFromAsync(this System.Net.Sockets.Socket socket, System.ArraySegment<byte> buffer, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEndPoint) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static System.Threading.Tasks.Task<int> SendAsync(this System.Net.Sockets.Socket socket, System.ArraySegment<byte> buffer, System.Net.Sockets.SocketFlags socketFlags) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static System.Threading.Tasks.Task<int> SendAsync(this System.Net.Sockets.Socket socket, System.Collections.Generic.IList<System.ArraySegment<byte>> buffers, System.Net.Sockets.SocketFlags socketFlags) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static System.Threading.Tasks.ValueTask<int> SendAsync(this System.Net.Sockets.Socket socket, System.ReadOnlyMemory<byte> buffer, System.Net.Sockets.SocketFlags socketFlags, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static System.Threading.Tasks.Task<int> SendToAsync(this System.Net.Sockets.Socket socket, System.ArraySegment<byte> buffer, System.Net.Sockets.SocketFlags socketFlags, System.Net.EndPoint remoteEP) { throw null; } } public enum SocketType { Unknown = -1, Stream = 1, Dgram = 2, Raw = 3, Rdm = 4, Seqpacket = 5, } public partial class TcpClient : System.IDisposable { public TcpClient() { } public TcpClient(System.Net.IPEndPoint localEP) { } public TcpClient(System.Net.Sockets.AddressFamily family) { } public TcpClient(string hostname, int port) { } protected bool Active { get { throw null; } set { } } public int Available { get { throw null; } } public System.Net.Sockets.Socket Client { get { throw null; } set { } } public bool Connected { get { throw null; } } public bool ExclusiveAddressUse { get { throw null; } set { } } [System.Diagnostics.CodeAnalysis.DisallowNullAttribute] public System.Net.Sockets.LingerOption? LingerState { get { throw null; } set { } } public bool NoDelay { get { throw null; } set { } } public int ReceiveBufferSize { get { throw null; } set { } } public int ReceiveTimeout { get { throw null; } set { } } public int SendBufferSize { get { throw null; } set { } } public int SendTimeout { get { throw null; } set { } } public System.IAsyncResult BeginConnect(System.Net.IPAddress address, int port, System.AsyncCallback? requestCallback, object? state) { throw null; } public System.IAsyncResult BeginConnect(System.Net.IPAddress[] addresses, int port, System.AsyncCallback? requestCallback, object? state) { throw null; } public System.IAsyncResult BeginConnect(string host, int port, System.AsyncCallback? requestCallback, object? state) { throw null; } public void Close() { } public void Connect(System.Net.IPAddress address, int port) { } public void Connect(System.Net.IPAddress[] ipAddresses, int port) { } public void Connect(System.Net.IPEndPoint remoteEP) { } public void Connect(string hostname, int port) { } public System.Threading.Tasks.Task ConnectAsync(System.Net.IPAddress address, int port) { throw null; } public System.Threading.Tasks.Task ConnectAsync(System.Net.IPAddress[] addresses, int port) { throw null; } public System.Threading.Tasks.Task ConnectAsync(string host, int port) { throw null; } public System.Threading.Tasks.Task ConnectAsync(System.Net.IPEndPoint remoteEP) { throw null; } public System.Threading.Tasks.ValueTask ConnectAsync(System.Net.IPAddress address, int port, System.Threading.CancellationToken cancellationToken) { throw null; } public System.Threading.Tasks.ValueTask ConnectAsync(System.Net.IPAddress[] addresses, int port, System.Threading.CancellationToken cancellationToken) { throw null; } public System.Threading.Tasks.ValueTask ConnectAsync(string host, int port, System.Threading.CancellationToken cancellationToken) { throw null; } public System.Threading.Tasks.ValueTask ConnectAsync(System.Net.IPEndPoint remoteEP, System.Threading.CancellationToken cancellationToken) { throw null; } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public void EndConnect(System.IAsyncResult asyncResult) { } ~TcpClient() { } public System.Net.Sockets.NetworkStream GetStream() { throw null; } } public partial class TcpListener { [System.ObsoleteAttribute("This constructor has been deprecated. Use TcpListener(IPAddress localaddr, int port) instead.")] public TcpListener(int port) { } public TcpListener(System.Net.IPAddress localaddr, int port) { } public TcpListener(System.Net.IPEndPoint localEP) { } protected bool Active { get { throw null; } } public bool ExclusiveAddressUse { get { throw null; } set { } } public System.Net.EndPoint LocalEndpoint { get { throw null; } } public System.Net.Sockets.Socket Server { get { throw null; } } public System.Net.Sockets.Socket AcceptSocket() { throw null; } public System.Threading.Tasks.Task<System.Net.Sockets.Socket> AcceptSocketAsync() { throw null; } public System.Threading.Tasks.ValueTask<System.Net.Sockets.Socket> AcceptSocketAsync(System.Threading.CancellationToken cancellationToken) { throw null; } public System.Net.Sockets.TcpClient AcceptTcpClient() { throw null; } public System.Threading.Tasks.Task<System.Net.Sockets.TcpClient> AcceptTcpClientAsync() { throw null; } public System.Threading.Tasks.ValueTask<System.Net.Sockets.TcpClient> AcceptTcpClientAsync(System.Threading.CancellationToken cancellationToken) { throw null; } [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] public void AllowNatTraversal(bool allowed) { } public System.IAsyncResult BeginAcceptSocket(System.AsyncCallback? callback, object? state) { throw null; } public System.IAsyncResult BeginAcceptTcpClient(System.AsyncCallback? callback, object? state) { throw null; } public static System.Net.Sockets.TcpListener Create(int port) { throw null; } public System.Net.Sockets.Socket EndAcceptSocket(System.IAsyncResult asyncResult) { throw null; } public System.Net.Sockets.TcpClient EndAcceptTcpClient(System.IAsyncResult asyncResult) { throw null; } public bool Pending() { throw null; } public void Start() { } public void Start(int backlog) { } public void Stop() { } } [System.FlagsAttribute] public enum TransmitFileOptions { UseDefaultWorkerThread = 0, Disconnect = 1, ReuseSocket = 2, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] WriteBehind = 4, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] UseSystemThread = 16, [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] UseKernelApc = 32, } public partial class UdpClient : System.IDisposable { public UdpClient() { } public UdpClient(int port) { } public UdpClient(int port, System.Net.Sockets.AddressFamily family) { } public UdpClient(System.Net.IPEndPoint localEP) { } public UdpClient(System.Net.Sockets.AddressFamily family) { } public UdpClient(string hostname, int port) { } protected bool Active { get { throw null; } set { } } public int Available { get { throw null; } } public System.Net.Sockets.Socket Client { get { throw null; } set { } } public bool DontFragment { get { throw null; } set { } } public bool EnableBroadcast { get { throw null; } set { } } public bool ExclusiveAddressUse { get { throw null; } set { } } public bool MulticastLoopback { get { throw null; } set { } } public short Ttl { get { throw null; } set { } } [System.Runtime.Versioning.SupportedOSPlatformAttribute("windows")] public void AllowNatTraversal(bool allowed) { } public System.IAsyncResult BeginReceive(System.AsyncCallback? requestCallback, object? state) { throw null; } public System.IAsyncResult BeginSend(byte[] datagram, int bytes, System.AsyncCallback? requestCallback, object? state) { throw null; } public System.IAsyncResult BeginSend(byte[] datagram, int bytes, System.Net.IPEndPoint? endPoint, System.AsyncCallback? requestCallback, object? state) { throw null; } public System.IAsyncResult BeginSend(byte[] datagram, int bytes, string? hostname, int port, System.AsyncCallback? requestCallback, object? state) { throw null; } public void Close() { } public void Connect(System.Net.IPAddress addr, int port) { } public void Connect(System.Net.IPEndPoint endPoint) { } public void Connect(string hostname, int port) { } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public void DropMulticastGroup(System.Net.IPAddress multicastAddr) { } public void DropMulticastGroup(System.Net.IPAddress multicastAddr, int ifindex) { } public byte[] EndReceive(System.IAsyncResult asyncResult, ref System.Net.IPEndPoint? remoteEP) { throw null; } public int EndSend(System.IAsyncResult asyncResult) { throw null; } public void JoinMulticastGroup(int ifindex, System.Net.IPAddress multicastAddr) { } public void JoinMulticastGroup(System.Net.IPAddress multicastAddr) { } public void JoinMulticastGroup(System.Net.IPAddress multicastAddr, int timeToLive) { } public void JoinMulticastGroup(System.Net.IPAddress multicastAddr, System.Net.IPAddress localAddress) { } public byte[] Receive([System.Diagnostics.CodeAnalysis.NotNullAttribute] ref System.Net.IPEndPoint? remoteEP) { throw null; } public System.Threading.Tasks.Task<System.Net.Sockets.UdpReceiveResult> ReceiveAsync() { throw null; } public System.Threading.Tasks.ValueTask<System.Net.Sockets.UdpReceiveResult> ReceiveAsync(System.Threading.CancellationToken cancellationToken) { throw null; } public int Send(byte[] dgram, int bytes) { throw null; } public int Send(System.ReadOnlySpan<byte> datagram) {throw null; } public int Send(byte[] dgram, int bytes, System.Net.IPEndPoint? endPoint) { throw null; } public int Send(System.ReadOnlySpan<byte> datagram, System.Net.IPEndPoint? endPoint) { throw null; } public int Send(byte[] dgram, int bytes, string? hostname, int port) { throw null; } public int Send(System.ReadOnlySpan<byte> datagram, string? hostname, int port) { throw null; } public System.Threading.Tasks.Task<int> SendAsync(byte[] datagram, int bytes) { throw null; } public System.Threading.Tasks.ValueTask<int> SendAsync(System.ReadOnlyMemory<byte> datagram, System.Threading.CancellationToken cancellationToken = default) { throw null; } public System.Threading.Tasks.Task<int> SendAsync(byte[] datagram, int bytes, System.Net.IPEndPoint? endPoint) { throw null; } public System.Threading.Tasks.ValueTask<int> SendAsync(System.ReadOnlyMemory<byte> datagram, System.Net.IPEndPoint? endPoint, System.Threading.CancellationToken cancellationToken = default) { throw null; } public System.Threading.Tasks.Task<int> SendAsync(byte[] datagram, int bytes, string? hostname, int port) { throw null; } public System.Threading.Tasks.ValueTask<int> SendAsync(System.ReadOnlyMemory<byte> datagram, string? hostname, int port, System.Threading.CancellationToken cancellationToken = default) { throw null; } } public partial struct UdpReceiveResult : System.IEquatable<System.Net.Sockets.UdpReceiveResult> { private object _dummy; private int _dummyPrimitive; public UdpReceiveResult(byte[] buffer, System.Net.IPEndPoint remoteEndPoint) { throw null; } public byte[] Buffer { get { throw null; } } public System.Net.IPEndPoint RemoteEndPoint { get { throw null; } } public bool Equals(System.Net.Sockets.UdpReceiveResult other) { throw null; } public override bool Equals([System.Diagnostics.CodeAnalysis.NotNullWhen(true)] object? obj) { throw null; } public override int GetHashCode() { throw null; } public static bool operator ==(System.Net.Sockets.UdpReceiveResult left, System.Net.Sockets.UdpReceiveResult right) { throw null; } public static bool operator !=(System.Net.Sockets.UdpReceiveResult left, System.Net.Sockets.UdpReceiveResult right) { throw null; } } public sealed partial class UnixDomainSocketEndPoint : System.Net.EndPoint { public UnixDomainSocketEndPoint(string path) { } } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonCollectionInfoValuesOfTCollection.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.Text.Json.Serialization.Metadata { /// <summary> /// Provides serialization metadata about a collection type. /// </summary> /// <typeparam name="TCollection">The collection type.</typeparam> /// <remarks>This API is for use by the output of the System.Text.Json source generator and should not be called directly.</remarks> [EditorBrowsable(EditorBrowsableState.Never)] public sealed class JsonCollectionInfoValues<TCollection> { /// <summary> /// A <see cref="Func{TResult}"/> to create an instance of the collection when deserializing. /// </summary> /// <remarks>This API is for use by the output of the System.Text.Json source generator and should not be called directly.</remarks> public Func<TCollection>? ObjectCreator { get; init; } /// <summary> /// If a dictionary type, the <see cref="JsonTypeInfo"/> instance representing the key type. /// </summary> /// <remarks>This API is for use by the output of the System.Text.Json source generator and should not be called directly.</remarks> public JsonTypeInfo? KeyInfo { get; init; } /// <summary> /// A <see cref="JsonTypeInfo"/> instance representing the element type. /// </summary> /// <remarks>This API is for use by the output of the System.Text.Json source generator and should not be called directly.</remarks> public JsonTypeInfo ElementInfo { get; init; } = null!; /// <summary> /// The <see cref="JsonNumberHandling"/> option to apply to number collection elements. /// </summary> /// <remarks>This API is for use by the output of the System.Text.Json source generator and should not be called directly.</remarks> public JsonNumberHandling NumberHandling { get; init; } /// <summary> /// An optimized serialization implementation assuming pre-determined <see cref="JsonSourceGenerationOptionsAttribute"/> defaults. /// </summary> /// <remarks>This API is for use by the output of the System.Text.Json source generator and should not be called directly.</remarks> public Action<Utf8JsonWriter, TCollection>? SerializeHandler { get; init; } } }
// 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.Text.Json.Serialization.Metadata { /// <summary> /// Provides serialization metadata about a collection type. /// </summary> /// <typeparam name="TCollection">The collection type.</typeparam> /// <remarks>This API is for use by the output of the System.Text.Json source generator and should not be called directly.</remarks> [EditorBrowsable(EditorBrowsableState.Never)] public sealed class JsonCollectionInfoValues<TCollection> { /// <summary> /// A <see cref="Func{TResult}"/> to create an instance of the collection when deserializing. /// </summary> /// <remarks>This API is for use by the output of the System.Text.Json source generator and should not be called directly.</remarks> public Func<TCollection>? ObjectCreator { get; init; } /// <summary> /// If a dictionary type, the <see cref="JsonTypeInfo"/> instance representing the key type. /// </summary> /// <remarks>This API is for use by the output of the System.Text.Json source generator and should not be called directly.</remarks> public JsonTypeInfo? KeyInfo { get; init; } /// <summary> /// A <see cref="JsonTypeInfo"/> instance representing the element type. /// </summary> /// <remarks>This API is for use by the output of the System.Text.Json source generator and should not be called directly.</remarks> public JsonTypeInfo ElementInfo { get; init; } = null!; /// <summary> /// The <see cref="JsonNumberHandling"/> option to apply to number collection elements. /// </summary> /// <remarks>This API is for use by the output of the System.Text.Json source generator and should not be called directly.</remarks> public JsonNumberHandling NumberHandling { get; init; } /// <summary> /// An optimized serialization implementation assuming pre-determined <see cref="JsonSourceGenerationOptionsAttribute"/> defaults. /// </summary> /// <remarks>This API is for use by the output of the System.Text.Json source generator and should not be called directly.</remarks> public Action<Utf8JsonWriter, TCollection>? SerializeHandler { get; init; } } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/mono/mono/tests/array-subtype-attr.cs
using System; using System.Reflection; namespace MonoBug { public class Program { static private int Main(string[] args) { Assembly assembly = Assembly.GetExecutingAssembly (); Type type = assembly.GetType("MonoBug.Program", true); MethodInfo info = type.GetMethod("Foo"); object[] attributes = info.GetCustomAttributes (false); int found = 0; foreach (object obj in attributes) { Console.WriteLine("Attribute of type {0} found", obj.GetType().ToString()); found ++; } return found == 1? 0: 1; } [My("blah", new string[] { "crash" }, "additional parameter")] public void Foo() { } } [AttributeUsage(AttributeTargets.Method)] class MyAttribute : Attribute { public MyAttribute(params object[] arguments) { } } }
using System; using System.Reflection; namespace MonoBug { public class Program { static private int Main(string[] args) { Assembly assembly = Assembly.GetExecutingAssembly (); Type type = assembly.GetType("MonoBug.Program", true); MethodInfo info = type.GetMethod("Foo"); object[] attributes = info.GetCustomAttributes (false); int found = 0; foreach (object obj in attributes) { Console.WriteLine("Attribute of type {0} found", obj.GetType().ToString()); found ++; } return found == 1? 0: 1; } [My("blah", new string[] { "crash" }, "additional parameter")] public void Foo() { } } [AttributeUsage(AttributeTargets.Method)] class MyAttribute : Attribute { public MyAttribute(params object[] arguments) { } } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/libraries/Microsoft.Extensions.Logging.EventLog/src/EventLogLogger.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; using System.Text; namespace Microsoft.Extensions.Logging.EventLog { /// <summary> /// A logger that writes messages to Windows Event Log. /// </summary> internal sealed class EventLogLogger : ILogger { private readonly string _name; private readonly EventLogSettings _settings; private readonly IExternalScopeProvider _externalScopeProvider; private const string ContinuationString = "..."; private readonly int _beginOrEndMessageSegmentSize; private readonly int _intermediateMessageSegmentSize; /// <summary> /// Initializes a new instance of the <see cref="EventLogLogger"/> class. /// </summary> /// <param name="name">The name of the logger.</param> /// <param name="settings">The <see cref="EventLogSettings"/>.</param> /// <param name="externalScopeProvider">The <see cref="IExternalScopeProvider"/>.</param> public EventLogLogger(string name!!, EventLogSettings settings!!, IExternalScopeProvider externalScopeProvider) { _name = name; _settings = settings; _externalScopeProvider = externalScopeProvider; EventLog = settings.EventLog; // Examples: // 1. An error occu... // 2. ...esponse stream _beginOrEndMessageSegmentSize = EventLog.MaxMessageSize - ContinuationString.Length; // Example: // ...rred while writ... _intermediateMessageSegmentSize = EventLog.MaxMessageSize - 2 * ContinuationString.Length; } public IEventLog EventLog { get; } /// <inheritdoc /> public IDisposable BeginScope<TState>(TState state) { return _externalScopeProvider?.Push(state); } /// <inheritdoc /> public bool IsEnabled(LogLevel logLevel) { return logLevel != LogLevel.None && (_settings.Filter == null || _settings.Filter(_name, logLevel)); } /// <inheritdoc /> public void Log<TState>( LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) { if (!IsEnabled(logLevel)) { return; } if (formatter == null) { throw new ArgumentNullException(nameof(formatter)); } string message = formatter(state, exception); if (string.IsNullOrEmpty(message)) { return; } StringBuilder builder = new StringBuilder() .Append("Category: ") .AppendLine(_name) .Append("EventId: ") .Append(eventId.Id) .AppendLine(); _externalScopeProvider?.ForEachScope((scope, sb) => { if (scope is IEnumerable<KeyValuePair<string, object>> properties) { foreach (KeyValuePair<string, object> pair in properties) { sb.Append(pair.Key).Append(": ").AppendLine(pair.Value?.ToString()); } } else if (scope != null) { sb.AppendLine(scope.ToString()); } }, builder); builder.AppendLine() .AppendLine(message); if (exception != null) { builder.AppendLine().AppendLine("Exception: ").Append(exception).AppendLine(); } WriteMessage(builder.ToString(), GetEventLogEntryType(logLevel), EventLog.DefaultEventId ?? eventId.Id); } // category '0' translates to 'None' in event log private void WriteMessage(string message, EventLogEntryType eventLogEntryType, int eventId) { if (message.Length <= EventLog.MaxMessageSize) { EventLog.WriteEntry(message, eventLogEntryType, eventId, category: 0); return; } int startIndex = 0; string messageSegment = null; while (true) { // Begin segment // Example: An error occu... if (startIndex == 0) { #if NET messageSegment = string.Concat(message.AsSpan(startIndex, _beginOrEndMessageSegmentSize), ContinuationString); #else messageSegment = message.Substring(startIndex, _beginOrEndMessageSegmentSize) + ContinuationString; #endif startIndex += _beginOrEndMessageSegmentSize; } else { // Check if rest of the message can fit within the maximum message size // Example: ...esponse stream if ((message.Length - (startIndex + 1)) <= _beginOrEndMessageSegmentSize) { #if NET messageSegment = string.Concat(ContinuationString, message.AsSpan(startIndex)); #else messageSegment = ContinuationString + message.Substring(startIndex); #endif EventLog.WriteEntry(messageSegment, eventLogEntryType, eventId, category: 0); break; } else { // Example: ...rred while writ... messageSegment = #if NET string.Concat( ContinuationString, message.AsSpan(startIndex, _intermediateMessageSegmentSize), ContinuationString); #else ContinuationString + message.Substring(startIndex, _intermediateMessageSegmentSize) + ContinuationString; #endif startIndex += _intermediateMessageSegmentSize; } } EventLog.WriteEntry(messageSegment, eventLogEntryType, eventId, category: 0); } } private EventLogEntryType GetEventLogEntryType(LogLevel level) { switch (level) { case LogLevel.Information: case LogLevel.Debug: case LogLevel.Trace: return EventLogEntryType.Information; case LogLevel.Warning: return EventLogEntryType.Warning; case LogLevel.Critical: case LogLevel.Error: return EventLogEntryType.Error; default: return EventLogEntryType.Information; } } } }
// 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; using System.Text; namespace Microsoft.Extensions.Logging.EventLog { /// <summary> /// A logger that writes messages to Windows Event Log. /// </summary> internal sealed class EventLogLogger : ILogger { private readonly string _name; private readonly EventLogSettings _settings; private readonly IExternalScopeProvider _externalScopeProvider; private const string ContinuationString = "..."; private readonly int _beginOrEndMessageSegmentSize; private readonly int _intermediateMessageSegmentSize; /// <summary> /// Initializes a new instance of the <see cref="EventLogLogger"/> class. /// </summary> /// <param name="name">The name of the logger.</param> /// <param name="settings">The <see cref="EventLogSettings"/>.</param> /// <param name="externalScopeProvider">The <see cref="IExternalScopeProvider"/>.</param> public EventLogLogger(string name!!, EventLogSettings settings!!, IExternalScopeProvider externalScopeProvider) { _name = name; _settings = settings; _externalScopeProvider = externalScopeProvider; EventLog = settings.EventLog; // Examples: // 1. An error occu... // 2. ...esponse stream _beginOrEndMessageSegmentSize = EventLog.MaxMessageSize - ContinuationString.Length; // Example: // ...rred while writ... _intermediateMessageSegmentSize = EventLog.MaxMessageSize - 2 * ContinuationString.Length; } public IEventLog EventLog { get; } /// <inheritdoc /> public IDisposable BeginScope<TState>(TState state) { return _externalScopeProvider?.Push(state); } /// <inheritdoc /> public bool IsEnabled(LogLevel logLevel) { return logLevel != LogLevel.None && (_settings.Filter == null || _settings.Filter(_name, logLevel)); } /// <inheritdoc /> public void Log<TState>( LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) { if (!IsEnabled(logLevel)) { return; } if (formatter == null) { throw new ArgumentNullException(nameof(formatter)); } string message = formatter(state, exception); if (string.IsNullOrEmpty(message)) { return; } StringBuilder builder = new StringBuilder() .Append("Category: ") .AppendLine(_name) .Append("EventId: ") .Append(eventId.Id) .AppendLine(); _externalScopeProvider?.ForEachScope((scope, sb) => { if (scope is IEnumerable<KeyValuePair<string, object>> properties) { foreach (KeyValuePair<string, object> pair in properties) { sb.Append(pair.Key).Append(": ").AppendLine(pair.Value?.ToString()); } } else if (scope != null) { sb.AppendLine(scope.ToString()); } }, builder); builder.AppendLine() .AppendLine(message); if (exception != null) { builder.AppendLine().AppendLine("Exception: ").Append(exception).AppendLine(); } WriteMessage(builder.ToString(), GetEventLogEntryType(logLevel), EventLog.DefaultEventId ?? eventId.Id); } // category '0' translates to 'None' in event log private void WriteMessage(string message, EventLogEntryType eventLogEntryType, int eventId) { if (message.Length <= EventLog.MaxMessageSize) { EventLog.WriteEntry(message, eventLogEntryType, eventId, category: 0); return; } int startIndex = 0; string messageSegment = null; while (true) { // Begin segment // Example: An error occu... if (startIndex == 0) { #if NET messageSegment = string.Concat(message.AsSpan(startIndex, _beginOrEndMessageSegmentSize), ContinuationString); #else messageSegment = message.Substring(startIndex, _beginOrEndMessageSegmentSize) + ContinuationString; #endif startIndex += _beginOrEndMessageSegmentSize; } else { // Check if rest of the message can fit within the maximum message size // Example: ...esponse stream if ((message.Length - (startIndex + 1)) <= _beginOrEndMessageSegmentSize) { #if NET messageSegment = string.Concat(ContinuationString, message.AsSpan(startIndex)); #else messageSegment = ContinuationString + message.Substring(startIndex); #endif EventLog.WriteEntry(messageSegment, eventLogEntryType, eventId, category: 0); break; } else { // Example: ...rred while writ... messageSegment = #if NET string.Concat( ContinuationString, message.AsSpan(startIndex, _intermediateMessageSegmentSize), ContinuationString); #else ContinuationString + message.Substring(startIndex, _intermediateMessageSegmentSize) + ContinuationString; #endif startIndex += _intermediateMessageSegmentSize; } } EventLog.WriteEntry(messageSegment, eventLogEntryType, eventId, category: 0); } } private EventLogEntryType GetEventLogEntryType(LogLevel level) { switch (level) { case LogLevel.Information: case LogLevel.Debug: case LogLevel.Trace: return EventLogEntryType.Information; case LogLevel.Warning: return EventLogEntryType.Warning; case LogLevel.Critical: case LogLevel.Error: return EventLogEntryType.Error; default: return EventLogEntryType.Information; } } } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd.Arm64/ShiftRightLogicalRoundedNarrowingSaturateScalar.Vector64.Byte.1.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void ShiftRightLogicalRoundedNarrowingSaturateScalar_Vector64_Byte_1() { var test = new ImmUnaryOpTest__ShiftRightLogicalRoundedNarrowingSaturateScalar_Vector64_Byte_1(); 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 ImmUnaryOpTest__ShiftRightLogicalRoundedNarrowingSaturateScalar_Vector64_Byte_1 { private struct DataTable { private byte[] inArray; private byte[] outArray; private GCHandle inHandle; private GCHandle outHandle; private ulong alignment; public DataTable(UInt16[] inArray, Byte[] outArray, int alignment) { int sizeOfinArray = inArray.Length * Unsafe.SizeOf<UInt16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle = GCHandle.Alloc(this.inArray, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArrayPtr), ref Unsafe.As<UInt16, byte>(ref inArray[0]), (uint)sizeOfinArray); } public void* inArrayPtr => Align((byte*)(inHandle.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle.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<UInt16> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref testStruct._fld), ref Unsafe.As<UInt16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); return testStruct; } public void RunStructFldScenario(ImmUnaryOpTest__ShiftRightLogicalRoundedNarrowingSaturateScalar_Vector64_Byte_1 testClass) { var result = AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar(_fld, 3); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(ImmUnaryOpTest__ShiftRightLogicalRoundedNarrowingSaturateScalar_Vector64_Byte_1 testClass) { fixed (Vector64<UInt16>* pFld = &_fld) { var result = AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar( AdvSimd.LoadVector64((UInt16*)(pFld)), 3 ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<UInt16>>() / sizeof(UInt16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Byte>>() / sizeof(Byte); private static readonly byte Imm = 3; private static UInt16[] _data = new UInt16[Op1ElementCount]; private static Vector64<UInt16> _clsVar; private Vector64<UInt16> _fld; private DataTable _dataTable; static ImmUnaryOpTest__ShiftRightLogicalRoundedNarrowingSaturateScalar_Vector64_Byte_1() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _clsVar), ref Unsafe.As<UInt16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); } public ImmUnaryOpTest__ShiftRightLogicalRoundedNarrowingSaturateScalar_Vector64_Byte_1() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _fld), ref Unsafe.As<UInt16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt16(); } _dataTable = new DataTable(_data, new Byte[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.ShiftRightLogicalRoundedNarrowingSaturateScalar( Unsafe.Read<Vector64<UInt16>>(_dataTable.inArrayPtr), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar( AdvSimd.LoadVector64((UInt16*)(_dataTable.inArrayPtr)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar), new Type[] { typeof(Vector64<UInt16>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<UInt16>>(_dataTable.inArrayPtr), (byte)3 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Byte>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar), new Type[] { typeof(Vector64<UInt16>), typeof(byte) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((UInt16*)(_dataTable.inArrayPtr)), (byte)3 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Byte>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar( _clsVar, 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<UInt16>* pClsVar = &_clsVar) { var result = AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar( AdvSimd.LoadVector64((UInt16*)(pClsVar)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector64<UInt16>>(_dataTable.inArrayPtr); var result = AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar(firstOp, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = AdvSimd.LoadVector64((UInt16*)(_dataTable.inArrayPtr)); var result = AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar(firstOp, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmUnaryOpTest__ShiftRightLogicalRoundedNarrowingSaturateScalar_Vector64_Byte_1(); var result = AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar(test._fld, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new ImmUnaryOpTest__ShiftRightLogicalRoundedNarrowingSaturateScalar_Vector64_Byte_1(); fixed (Vector64<UInt16>* pFld = &test._fld) { var result = AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar( AdvSimd.LoadVector64((UInt16*)(pFld)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar(_fld, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<UInt16>* pFld = &_fld) { var result = AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar( AdvSimd.LoadVector64((UInt16*)(pFld)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar(test._fld, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar( AdvSimd.LoadVector64((UInt16*)(&test._fld)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void 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<UInt16> firstOp, void* result, [CallerMemberName] string method = "") { UInt16[] inArray = new UInt16[Op1ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Byte>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { UInt16[] inArray = new UInt16[Op1ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Byte>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(UInt16[] firstOp, Byte[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (Helpers.ShiftRightLogicalRoundedNarrowingSaturate(firstOp[0], Imm) != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != 0) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar)}<Byte>(Vector64<UInt16>, 3): {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.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void ShiftRightLogicalRoundedNarrowingSaturateScalar_Vector64_Byte_1() { var test = new ImmUnaryOpTest__ShiftRightLogicalRoundedNarrowingSaturateScalar_Vector64_Byte_1(); 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 ImmUnaryOpTest__ShiftRightLogicalRoundedNarrowingSaturateScalar_Vector64_Byte_1 { private struct DataTable { private byte[] inArray; private byte[] outArray; private GCHandle inHandle; private GCHandle outHandle; private ulong alignment; public DataTable(UInt16[] inArray, Byte[] outArray, int alignment) { int sizeOfinArray = inArray.Length * Unsafe.SizeOf<UInt16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle = GCHandle.Alloc(this.inArray, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArrayPtr), ref Unsafe.As<UInt16, byte>(ref inArray[0]), (uint)sizeOfinArray); } public void* inArrayPtr => Align((byte*)(inHandle.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle.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<UInt16> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref testStruct._fld), ref Unsafe.As<UInt16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); return testStruct; } public void RunStructFldScenario(ImmUnaryOpTest__ShiftRightLogicalRoundedNarrowingSaturateScalar_Vector64_Byte_1 testClass) { var result = AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar(_fld, 3); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(ImmUnaryOpTest__ShiftRightLogicalRoundedNarrowingSaturateScalar_Vector64_Byte_1 testClass) { fixed (Vector64<UInt16>* pFld = &_fld) { var result = AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar( AdvSimd.LoadVector64((UInt16*)(pFld)), 3 ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<UInt16>>() / sizeof(UInt16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Byte>>() / sizeof(Byte); private static readonly byte Imm = 3; private static UInt16[] _data = new UInt16[Op1ElementCount]; private static Vector64<UInt16> _clsVar; private Vector64<UInt16> _fld; private DataTable _dataTable; static ImmUnaryOpTest__ShiftRightLogicalRoundedNarrowingSaturateScalar_Vector64_Byte_1() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _clsVar), ref Unsafe.As<UInt16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); } public ImmUnaryOpTest__ShiftRightLogicalRoundedNarrowingSaturateScalar_Vector64_Byte_1() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<UInt16>, byte>(ref _fld), ref Unsafe.As<UInt16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt16(); } _dataTable = new DataTable(_data, new Byte[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.ShiftRightLogicalRoundedNarrowingSaturateScalar( Unsafe.Read<Vector64<UInt16>>(_dataTable.inArrayPtr), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar( AdvSimd.LoadVector64((UInt16*)(_dataTable.inArrayPtr)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar), new Type[] { typeof(Vector64<UInt16>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<UInt16>>(_dataTable.inArrayPtr), (byte)3 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Byte>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd.Arm64).GetMethod(nameof(AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar), new Type[] { typeof(Vector64<UInt16>), typeof(byte) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((UInt16*)(_dataTable.inArrayPtr)), (byte)3 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Byte>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar( _clsVar, 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<UInt16>* pClsVar = &_clsVar) { var result = AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar( AdvSimd.LoadVector64((UInt16*)(pClsVar)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector64<UInt16>>(_dataTable.inArrayPtr); var result = AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar(firstOp, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = AdvSimd.LoadVector64((UInt16*)(_dataTable.inArrayPtr)); var result = AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar(firstOp, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmUnaryOpTest__ShiftRightLogicalRoundedNarrowingSaturateScalar_Vector64_Byte_1(); var result = AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar(test._fld, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new ImmUnaryOpTest__ShiftRightLogicalRoundedNarrowingSaturateScalar_Vector64_Byte_1(); fixed (Vector64<UInt16>* pFld = &test._fld) { var result = AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar( AdvSimd.LoadVector64((UInt16*)(pFld)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar(_fld, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<UInt16>* pFld = &_fld) { var result = AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar( AdvSimd.LoadVector64((UInt16*)(pFld)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar(test._fld, 3); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar( AdvSimd.LoadVector64((UInt16*)(&test._fld)), 3 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void 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<UInt16> firstOp, void* result, [CallerMemberName] string method = "") { UInt16[] inArray = new UInt16[Op1ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Byte>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { UInt16[] inArray = new UInt16[Op1ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector64<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Byte>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(UInt16[] firstOp, Byte[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (Helpers.ShiftRightLogicalRoundedNarrowingSaturate(firstOp[0], Imm) != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != 0) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd.Arm64)}.{nameof(AdvSimd.Arm64.ShiftRightLogicalRoundedNarrowingSaturateScalar)}<Byte>(Vector64<UInt16>, 3): {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,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/libraries/System.Text.Encoding.CodePages/src/System/Text/CodePagesEncodingProvider.Windows.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Text { public sealed partial class CodePagesEncodingProvider : EncodingProvider { /// <summary>Get the system default non-unicode code page, or 0 if not available.</summary> private static int SystemDefaultCodePage { get { int codePage; return Interop.Kernel32.TryGetACPCodePage(out codePage) ? codePage : 0; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Text { public sealed partial class CodePagesEncodingProvider : EncodingProvider { /// <summary>Get the system default non-unicode code page, or 0 if not available.</summary> private static int SystemDefaultCodePage { get { int codePage; return Interop.Kernel32.TryGetACPCodePage(out codePage) ? codePage : 0; } } } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/tests/reflection/DefaultInterfaceMethods/GetInterfaceMapConsumer.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.Reflection; class Program { static int Main() { bool failed = false; { var map = typeof(Fooer).GetInterfaceMap(typeof(IFoo<Fooer>)); int foundMatchMask = 0; MethodInfo ifooDefaultMethod = typeof(IFoo<Fooer>).GetMethod("DefaultMethod"); MethodInfo ifooOtherMethod = typeof(IFoo<Fooer>).GetMethod("OtherMethod"); MethodInfo ibarOtherMethod = typeof(IBar<Fooer>).GetMethod("OtherMethod"); for (int i = 0; i < map.InterfaceMethods.Length; i++) { MethodInfo declMethod = map.InterfaceMethods[i]; MethodInfo implMethod = map.TargetMethods[i]; Console.Write("{0} ({1}) - {2} ({3}) - ", declMethod, declMethod.DeclaringType, implMethod, implMethod.DeclaringType); if (declMethod.Equals(ifooDefaultMethod)) { foundMatchMask |= 1; CheckEqual(ref failed, implMethod, ifooDefaultMethod); } else if (declMethod.Equals(ifooOtherMethod)) { foundMatchMask |= 2; CheckEqual(ref failed, implMethod, ibarOtherMethod); } else { Console.WriteLine("UNEXPECTED"); failed = true; } } if (foundMatchMask != 3) return 10; } { var map = typeof(Fooer).GetInterfaceMap(typeof(IFoo)); int foundMatchMask = 0; MethodInfo ifooDefaultMethod = typeof(IFoo).GetMethod("DefaultMethod"); MethodInfo ifooOtherMethod = typeof(IFoo).GetMethod("OtherMethod"); MethodInfo ibarOtherMethod = typeof(IBar).GetMethod("OtherMethod"); for (int i = 0; i < map.InterfaceMethods.Length; i++) { MethodInfo declMethod = map.InterfaceMethods[i]; MethodInfo implMethod = map.TargetMethods[i]; Console.Write("{0} ({1}) - {2} ({3}) - ", declMethod, declMethod.DeclaringType, implMethod, implMethod.DeclaringType); if (declMethod.Equals(ifooDefaultMethod)) { foundMatchMask |= 1; CheckEqual(ref failed, implMethod, ifooDefaultMethod); } else if (declMethod.Equals(ifooOtherMethod)) { foundMatchMask |= 2; CheckEqual(ref failed, implMethod, ibarOtherMethod); } else { Console.WriteLine("UNEXPECTED"); failed = true; } } if (foundMatchMask != 3) return 10; } { var map = typeof(Reabstractor).GetInterfaceMap(typeof(IFoo)); int foundMatchMask = 0; MethodInfo ifooDefaultMethod = typeof(IFoo).GetMethod("DefaultMethod"); MethodInfo ifooOtherMethod = typeof(IFoo).GetMethod("OtherMethod"); for (int i = 0; i < map.InterfaceMethods.Length; i++) { MethodInfo declMethod = map.InterfaceMethods[i]; MethodInfo implMethod = map.TargetMethods[i]; Console.Write("{0} ({1}) - {2} ({3}) - ", declMethod, declMethod.DeclaringType, implMethod, implMethod?.DeclaringType); if (declMethod.Equals(ifooDefaultMethod)) { foundMatchMask |= 1; CheckEqual(ref failed, implMethod, null); } else if (declMethod.Equals(ifooOtherMethod)) { foundMatchMask |= 2; CheckEqual(ref failed, implMethod, null); } else { Console.WriteLine("UNEXPECTED"); failed = true; } } if (foundMatchMask != 3) return 10; } { var map = typeof(Diamond).GetInterfaceMap(typeof(IFoo)); int foundMatchMask = 0; MethodInfo ifooDefaultMethod = typeof(IFoo).GetMethod("DefaultMethod"); MethodInfo ifooOtherMethod = typeof(IFoo).GetMethod("OtherMethod"); for (int i = 0; i < map.InterfaceMethods.Length; i++) { MethodInfo declMethod = map.InterfaceMethods[i]; MethodInfo implMethod = map.TargetMethods[i]; Console.Write("{0} ({1}) - {2} ({3}) - ", declMethod, declMethod.DeclaringType, implMethod, implMethod?.DeclaringType); if (declMethod.Equals(ifooDefaultMethod)) { foundMatchMask |= 1; CheckEqual(ref failed, implMethod, ifooDefaultMethod); } else if (declMethod.Equals(ifooOtherMethod)) { foundMatchMask |= 2; CheckEqual(ref failed, implMethod, null); } else { Console.WriteLine("UNEXPECTED"); failed = true; } } if (foundMatchMask != 3) return 10; } return failed ? -1 : 100; } static void CheckEqual(ref bool failed, MethodInfo method1, MethodInfo method2) { if (Object.Equals(method1, method2)) Console.WriteLine("OK"); else { Console.WriteLine("FAIL"); failed = true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Reflection; class Program { static int Main() { bool failed = false; { var map = typeof(Fooer).GetInterfaceMap(typeof(IFoo<Fooer>)); int foundMatchMask = 0; MethodInfo ifooDefaultMethod = typeof(IFoo<Fooer>).GetMethod("DefaultMethod"); MethodInfo ifooOtherMethod = typeof(IFoo<Fooer>).GetMethod("OtherMethod"); MethodInfo ibarOtherMethod = typeof(IBar<Fooer>).GetMethod("OtherMethod"); for (int i = 0; i < map.InterfaceMethods.Length; i++) { MethodInfo declMethod = map.InterfaceMethods[i]; MethodInfo implMethod = map.TargetMethods[i]; Console.Write("{0} ({1}) - {2} ({3}) - ", declMethod, declMethod.DeclaringType, implMethod, implMethod.DeclaringType); if (declMethod.Equals(ifooDefaultMethod)) { foundMatchMask |= 1; CheckEqual(ref failed, implMethod, ifooDefaultMethod); } else if (declMethod.Equals(ifooOtherMethod)) { foundMatchMask |= 2; CheckEqual(ref failed, implMethod, ibarOtherMethod); } else { Console.WriteLine("UNEXPECTED"); failed = true; } } if (foundMatchMask != 3) return 10; } { var map = typeof(Fooer).GetInterfaceMap(typeof(IFoo)); int foundMatchMask = 0; MethodInfo ifooDefaultMethod = typeof(IFoo).GetMethod("DefaultMethod"); MethodInfo ifooOtherMethod = typeof(IFoo).GetMethod("OtherMethod"); MethodInfo ibarOtherMethod = typeof(IBar).GetMethod("OtherMethod"); for (int i = 0; i < map.InterfaceMethods.Length; i++) { MethodInfo declMethod = map.InterfaceMethods[i]; MethodInfo implMethod = map.TargetMethods[i]; Console.Write("{0} ({1}) - {2} ({3}) - ", declMethod, declMethod.DeclaringType, implMethod, implMethod.DeclaringType); if (declMethod.Equals(ifooDefaultMethod)) { foundMatchMask |= 1; CheckEqual(ref failed, implMethod, ifooDefaultMethod); } else if (declMethod.Equals(ifooOtherMethod)) { foundMatchMask |= 2; CheckEqual(ref failed, implMethod, ibarOtherMethod); } else { Console.WriteLine("UNEXPECTED"); failed = true; } } if (foundMatchMask != 3) return 10; } { var map = typeof(Reabstractor).GetInterfaceMap(typeof(IFoo)); int foundMatchMask = 0; MethodInfo ifooDefaultMethod = typeof(IFoo).GetMethod("DefaultMethod"); MethodInfo ifooOtherMethod = typeof(IFoo).GetMethod("OtherMethod"); for (int i = 0; i < map.InterfaceMethods.Length; i++) { MethodInfo declMethod = map.InterfaceMethods[i]; MethodInfo implMethod = map.TargetMethods[i]; Console.Write("{0} ({1}) - {2} ({3}) - ", declMethod, declMethod.DeclaringType, implMethod, implMethod?.DeclaringType); if (declMethod.Equals(ifooDefaultMethod)) { foundMatchMask |= 1; CheckEqual(ref failed, implMethod, null); } else if (declMethod.Equals(ifooOtherMethod)) { foundMatchMask |= 2; CheckEqual(ref failed, implMethod, null); } else { Console.WriteLine("UNEXPECTED"); failed = true; } } if (foundMatchMask != 3) return 10; } { var map = typeof(Diamond).GetInterfaceMap(typeof(IFoo)); int foundMatchMask = 0; MethodInfo ifooDefaultMethod = typeof(IFoo).GetMethod("DefaultMethod"); MethodInfo ifooOtherMethod = typeof(IFoo).GetMethod("OtherMethod"); for (int i = 0; i < map.InterfaceMethods.Length; i++) { MethodInfo declMethod = map.InterfaceMethods[i]; MethodInfo implMethod = map.TargetMethods[i]; Console.Write("{0} ({1}) - {2} ({3}) - ", declMethod, declMethod.DeclaringType, implMethod, implMethod?.DeclaringType); if (declMethod.Equals(ifooDefaultMethod)) { foundMatchMask |= 1; CheckEqual(ref failed, implMethod, ifooDefaultMethod); } else if (declMethod.Equals(ifooOtherMethod)) { foundMatchMask |= 2; CheckEqual(ref failed, implMethod, null); } else { Console.WriteLine("UNEXPECTED"); failed = true; } } if (foundMatchMask != 3) return 10; } return failed ? -1 : 100; } static void CheckEqual(ref bool failed, MethodInfo method1, MethodInfo method2) { if (Object.Equals(method1, method2)) Console.WriteLine("OK"); else { Console.WriteLine("FAIL"); failed = true; } } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/tests/JIT/Methodical/VT/callconv/vtret.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 MS { internal struct VT { private int _m_n; private VT[] _m_dummyGCRef; private VT(int n) { _m_n = n; _m_dummyGCRef = new VT[10]; } private static VT add(VT me, VT what) { me._m_n += what._m_n; return me; } private static VT sub(VT me, VT what) { me._m_n -= what._m_n; return me; } private static int Main() { VT vt = new VT(100); VT what = new VT(99); vt = VT.add(vt, what); vt = VT.sub(vt, what); return vt._m_n; } } }
// 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 MS { internal struct VT { private int _m_n; private VT[] _m_dummyGCRef; private VT(int n) { _m_n = n; _m_dummyGCRef = new VT[10]; } private static VT add(VT me, VT what) { me._m_n += what._m_n; return me; } private static VT sub(VT me, VT what) { me._m_n -= what._m_n; return me; } private static int Main() { VT vt = new VT(100); VT what = new VT(99); vt = VT.add(vt, what); vt = VT.sub(vt, what); return vt._m_n; } } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/ShiftRightLogicalRoundedAdd.Vector128.Byte.1.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void ShiftRightLogicalRoundedAdd_Vector128_Byte_1() { var test = new ImmBinaryOpTest__ShiftRightLogicalRoundedAdd_Vector128_Byte_1(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class ImmBinaryOpTest__ShiftRightLogicalRoundedAdd_Vector128_Byte_1 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Byte[] inArray1, Byte[] inArray2, Byte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Byte> _fld1; public Vector128<Byte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); return testStruct; } public void RunStructFldScenario(ImmBinaryOpTest__ShiftRightLogicalRoundedAdd_Vector128_Byte_1 testClass) { var result = AdvSimd.ShiftRightLogicalRoundedAdd(_fld1, _fld2, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(ImmBinaryOpTest__ShiftRightLogicalRoundedAdd_Vector128_Byte_1 testClass) { fixed (Vector128<Byte>* pFld1 = &_fld1) fixed (Vector128<Byte>* pFld2 = &_fld2) { var result = AdvSimd.ShiftRightLogicalRoundedAdd( AdvSimd.LoadVector128((Byte*)(pFld1)), AdvSimd.LoadVector128((Byte*)(pFld2)), 1 ); 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<Byte>>() / sizeof(Byte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static readonly byte Imm = 1; private static Byte[] _data1 = new Byte[Op1ElementCount]; private static Byte[] _data2 = new Byte[Op2ElementCount]; private static Vector128<Byte> _clsVar1; private static Vector128<Byte> _clsVar2; private Vector128<Byte> _fld1; private Vector128<Byte> _fld2; private DataTable _dataTable; static ImmBinaryOpTest__ShiftRightLogicalRoundedAdd_Vector128_Byte_1() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); } public ImmBinaryOpTest__ShiftRightLogicalRoundedAdd_Vector128_Byte_1() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } _dataTable = new DataTable(_data1, _data2, new Byte[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.ShiftRightLogicalRoundedAdd( Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr), 1 ); 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.ShiftRightLogicalRoundedAdd( AdvSimd.LoadVector128((Byte*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Byte*)(_dataTable.inArray2Ptr)), 1 ); 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.ShiftRightLogicalRoundedAdd), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(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.ShiftRightLogicalRoundedAdd), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>), typeof(byte) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Byte*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Byte*)(_dataTable.inArray2Ptr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.ShiftRightLogicalRoundedAdd( _clsVar1, _clsVar2, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Byte>* pClsVar1 = &_clsVar1) fixed (Vector128<Byte>* pClsVar2 = &_clsVar2) { var result = AdvSimd.ShiftRightLogicalRoundedAdd( AdvSimd.LoadVector128((Byte*)(pClsVar1)), AdvSimd.LoadVector128((Byte*)(pClsVar2)), 1 ); 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<Byte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr); var result = AdvSimd.ShiftRightLogicalRoundedAdd(op1, op2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((Byte*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((Byte*)(_dataTable.inArray2Ptr)); var result = AdvSimd.ShiftRightLogicalRoundedAdd(op1, op2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmBinaryOpTest__ShiftRightLogicalRoundedAdd_Vector128_Byte_1(); var result = AdvSimd.ShiftRightLogicalRoundedAdd(test._fld1, test._fld2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new ImmBinaryOpTest__ShiftRightLogicalRoundedAdd_Vector128_Byte_1(); fixed (Vector128<Byte>* pFld1 = &test._fld1) fixed (Vector128<Byte>* pFld2 = &test._fld2) { var result = AdvSimd.ShiftRightLogicalRoundedAdd( AdvSimd.LoadVector128((Byte*)(pFld1)), AdvSimd.LoadVector128((Byte*)(pFld2)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.ShiftRightLogicalRoundedAdd(_fld1, _fld2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Byte>* pFld1 = &_fld1) fixed (Vector128<Byte>* pFld2 = &_fld2) { var result = AdvSimd.ShiftRightLogicalRoundedAdd( AdvSimd.LoadVector128((Byte*)(pFld1)), AdvSimd.LoadVector128((Byte*)(pFld2)), 1 ); 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.ShiftRightLogicalRoundedAdd(test._fld1, test._fld2, 1); 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.ShiftRightLogicalRoundedAdd( AdvSimd.LoadVector128((Byte*)(&test._fld1)), AdvSimd.LoadVector128((Byte*)(&test._fld2)), 1 ); 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<Byte> firstOp, Vector128<Byte> secondOp, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), firstOp); Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), secondOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* firstOp, void* secondOp, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(secondOp), (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, inArray2, outArray, method); } private void ValidateResult(Byte[] firstOp, Byte[] secondOp, Byte[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.ShiftRightLogicalRoundedAdd(firstOp[i], secondOp[i], Imm) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ShiftRightLogicalRoundedAdd)}<Byte>(Vector128<Byte>, Vector128<Byte>, 1): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" secondOp: ({string.Join(", ", secondOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void ShiftRightLogicalRoundedAdd_Vector128_Byte_1() { var test = new ImmBinaryOpTest__ShiftRightLogicalRoundedAdd_Vector128_Byte_1(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class ImmBinaryOpTest__ShiftRightLogicalRoundedAdd_Vector128_Byte_1 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Byte[] inArray1, Byte[] inArray2, Byte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Byte> _fld1; public Vector128<Byte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); return testStruct; } public void RunStructFldScenario(ImmBinaryOpTest__ShiftRightLogicalRoundedAdd_Vector128_Byte_1 testClass) { var result = AdvSimd.ShiftRightLogicalRoundedAdd(_fld1, _fld2, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(ImmBinaryOpTest__ShiftRightLogicalRoundedAdd_Vector128_Byte_1 testClass) { fixed (Vector128<Byte>* pFld1 = &_fld1) fixed (Vector128<Byte>* pFld2 = &_fld2) { var result = AdvSimd.ShiftRightLogicalRoundedAdd( AdvSimd.LoadVector128((Byte*)(pFld1)), AdvSimd.LoadVector128((Byte*)(pFld2)), 1 ); 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<Byte>>() / sizeof(Byte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static readonly byte Imm = 1; private static Byte[] _data1 = new Byte[Op1ElementCount]; private static Byte[] _data2 = new Byte[Op2ElementCount]; private static Vector128<Byte> _clsVar1; private static Vector128<Byte> _clsVar2; private Vector128<Byte> _fld1; private Vector128<Byte> _fld2; private DataTable _dataTable; static ImmBinaryOpTest__ShiftRightLogicalRoundedAdd_Vector128_Byte_1() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); } public ImmBinaryOpTest__ShiftRightLogicalRoundedAdd_Vector128_Byte_1() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } _dataTable = new DataTable(_data1, _data2, new Byte[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.ShiftRightLogicalRoundedAdd( Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr), 1 ); 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.ShiftRightLogicalRoundedAdd( AdvSimd.LoadVector128((Byte*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Byte*)(_dataTable.inArray2Ptr)), 1 ); 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.ShiftRightLogicalRoundedAdd), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(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.ShiftRightLogicalRoundedAdd), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>), typeof(byte) }) .Invoke(null, new object[] { AdvSimd.LoadVector128((Byte*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector128((Byte*)(_dataTable.inArray2Ptr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.ShiftRightLogicalRoundedAdd( _clsVar1, _clsVar2, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Byte>* pClsVar1 = &_clsVar1) fixed (Vector128<Byte>* pClsVar2 = &_clsVar2) { var result = AdvSimd.ShiftRightLogicalRoundedAdd( AdvSimd.LoadVector128((Byte*)(pClsVar1)), AdvSimd.LoadVector128((Byte*)(pClsVar2)), 1 ); 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<Byte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr); var result = AdvSimd.ShiftRightLogicalRoundedAdd(op1, op2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector128((Byte*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector128((Byte*)(_dataTable.inArray2Ptr)); var result = AdvSimd.ShiftRightLogicalRoundedAdd(op1, op2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmBinaryOpTest__ShiftRightLogicalRoundedAdd_Vector128_Byte_1(); var result = AdvSimd.ShiftRightLogicalRoundedAdd(test._fld1, test._fld2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new ImmBinaryOpTest__ShiftRightLogicalRoundedAdd_Vector128_Byte_1(); fixed (Vector128<Byte>* pFld1 = &test._fld1) fixed (Vector128<Byte>* pFld2 = &test._fld2) { var result = AdvSimd.ShiftRightLogicalRoundedAdd( AdvSimd.LoadVector128((Byte*)(pFld1)), AdvSimd.LoadVector128((Byte*)(pFld2)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.ShiftRightLogicalRoundedAdd(_fld1, _fld2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Byte>* pFld1 = &_fld1) fixed (Vector128<Byte>* pFld2 = &_fld2) { var result = AdvSimd.ShiftRightLogicalRoundedAdd( AdvSimd.LoadVector128((Byte*)(pFld1)), AdvSimd.LoadVector128((Byte*)(pFld2)), 1 ); 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.ShiftRightLogicalRoundedAdd(test._fld1, test._fld2, 1); 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.ShiftRightLogicalRoundedAdd( AdvSimd.LoadVector128((Byte*)(&test._fld1)), AdvSimd.LoadVector128((Byte*)(&test._fld2)), 1 ); 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<Byte> firstOp, Vector128<Byte> secondOp, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), firstOp); Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), secondOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* firstOp, void* secondOp, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(secondOp), (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, inArray2, outArray, method); } private void ValidateResult(Byte[] firstOp, Byte[] secondOp, Byte[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.ShiftRightLogicalRoundedAdd(firstOp[i], secondOp[i], Imm) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ShiftRightLogicalRoundedAdd)}<Byte>(Vector128<Byte>, Vector128<Byte>, 1): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" secondOp: ({string.Join(", ", secondOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/libraries/System.Reflection.MetadataLoadContext/tests/src/Tests/MetadataLoadContext/GetAssemblies.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Linq; using Xunit; namespace System.Reflection.Tests { public static partial class MetadataLoadContextTests { [Fact] public static void GetAssemblies_EmptyMetadataLoadContext() { using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assembly[] loadedAssemblies = lc.GetAssemblies().ToArray(); Assert.Equal(1, loadedAssemblies.Length); } } [Fact] public static void GetAssemblies() { using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assembly[] loadedAssemblies = lc.GetAssemblies().ToArray(); Assert.Equal(1, loadedAssemblies.Length); // EmptyCoreMetadataAssemblyResolver already loaded s_SimpleNameOnlyImage Assembly a1 = lc.LoadFromByteArray(TestData.s_SimpleAssemblyImage); Assembly a2 = lc.LoadFromByteArray(TestData.s_SimpleNameOnlyImage); loadedAssemblies = lc.GetAssemblies().ToArray(); Assert.Equal(2, loadedAssemblies.Length); Assert.Contains<Assembly>(a1, loadedAssemblies); Assert.Contains<Assembly>(a2, loadedAssemblies); } } [Fact] public static void GetAssemblies_SnapshotIsAtomic() { Assembly a1 = null; var resolver = new FuncMetadataAssemblyResolver( delegate (MetadataLoadContext context, AssemblyName refName) { if (a1 == null) { // Initial request to load core assembly return a1 = context.LoadFromByteArray(TestData.s_SimpleAssemblyImage); } return null; }); using (MetadataLoadContext lc = new MetadataLoadContext(resolver)) { IEnumerable<Assembly> loadedAssembliesSnapshot = lc.GetAssemblies(); Assembly a2 = lc.LoadFromByteArray(TestData.s_SimpleNameOnlyImage); Assembly[] loadedAssemblies = loadedAssembliesSnapshot.ToArray(); Assert.Equal(1, loadedAssemblies.Length); Assert.Equal(a1, loadedAssemblies[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.Linq; using Xunit; namespace System.Reflection.Tests { public static partial class MetadataLoadContextTests { [Fact] public static void GetAssemblies_EmptyMetadataLoadContext() { using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assembly[] loadedAssemblies = lc.GetAssemblies().ToArray(); Assert.Equal(1, loadedAssemblies.Length); } } [Fact] public static void GetAssemblies() { using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assembly[] loadedAssemblies = lc.GetAssemblies().ToArray(); Assert.Equal(1, loadedAssemblies.Length); // EmptyCoreMetadataAssemblyResolver already loaded s_SimpleNameOnlyImage Assembly a1 = lc.LoadFromByteArray(TestData.s_SimpleAssemblyImage); Assembly a2 = lc.LoadFromByteArray(TestData.s_SimpleNameOnlyImage); loadedAssemblies = lc.GetAssemblies().ToArray(); Assert.Equal(2, loadedAssemblies.Length); Assert.Contains<Assembly>(a1, loadedAssemblies); Assert.Contains<Assembly>(a2, loadedAssemblies); } } [Fact] public static void GetAssemblies_SnapshotIsAtomic() { Assembly a1 = null; var resolver = new FuncMetadataAssemblyResolver( delegate (MetadataLoadContext context, AssemblyName refName) { if (a1 == null) { // Initial request to load core assembly return a1 = context.LoadFromByteArray(TestData.s_SimpleAssemblyImage); } return null; }); using (MetadataLoadContext lc = new MetadataLoadContext(resolver)) { IEnumerable<Assembly> loadedAssembliesSnapshot = lc.GetAssemblies(); Assembly a2 = lc.LoadFromByteArray(TestData.s_SimpleNameOnlyImage); Assembly[] loadedAssemblies = loadedAssembliesSnapshot.ToArray(); Assert.Equal(1, loadedAssemblies.Length); Assert.Equal(a1, loadedAssemblies[0]); } } } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/libraries/System.IO.Compression.ZipFile/src/System/IO/Compression/ZipFile.Create.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Buffers; using System.Collections.Generic; using System.Diagnostics; using System.Text; namespace System.IO.Compression { public static partial class ZipFile { /// <summary> /// Opens a <code>ZipArchive</code> on the specified path for reading. The specified file is opened with <code>FileMode.Open</code>. /// </summary> /// /// <exception cref="ArgumentException">archiveFileName is a zero-length string, contains only whitespace, or contains one /// or more invalid characters as defined by InvalidPathChars.</exception> /// <exception cref="ArgumentNullException">archiveFileName is null.</exception> /// <exception cref="PathTooLongException">The specified archiveFileName exceeds the system-defined maximum length. /// For example, on Windows-based platforms, paths must be less than 248 characters, /// and file names must be less than 260 characters.</exception> /// <exception cref="DirectoryNotFoundException">The specified archiveFileName is invalid, (for example, it is on an unmapped drive).</exception> /// <exception cref="IOException">An unspecified I/O error occurred while opening the file.</exception> /// <exception cref="UnauthorizedAccessException">archiveFileName specified a directory. /// -OR- The caller does not have the required permission.</exception> /// <exception cref="FileNotFoundException">The file specified in archiveFileName was not found.</exception> /// <exception cref="NotSupportedException">archiveFileName is in an invalid format. </exception> /// <exception cref="InvalidDataException">The specified file could not be interpreted as a Zip file.</exception> /// /// <param name="archiveFileName">A string specifying the path on the filesystem to open the archive on. The path is permitted /// to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory.</param> public static ZipArchive OpenRead(string archiveFileName) => Open(archiveFileName, ZipArchiveMode.Read); /// <summary> /// Opens a <code>ZipArchive</code> on the specified <code>archiveFileName</code> in the specified <code>ZipArchiveMode</code> mode. /// </summary> /// /// <exception cref="ArgumentException">archiveFileName is a zero-length string, contains only whitespace, /// or contains one or more invalid characters as defined by InvalidPathChars.</exception> /// <exception cref="ArgumentNullException">path is null.</exception> /// <exception cref="PathTooLongException">The specified archiveFileName exceeds the system-defined maximum length. /// For example, on Windows-based platforms, paths must be less than 248 characters, /// and file names must be less than 260 characters.</exception> /// <exception cref="DirectoryNotFoundException">The specified archiveFileName is invalid, (for example, it is on an unmapped drive).</exception> /// <exception cref="IOException">An unspecified I/O error occurred while opening the file.</exception> /// <exception cref="UnauthorizedAccessException">archiveFileName specified a directory. /// -OR- The caller does not have the required permission.</exception> /// <exception cref="ArgumentOutOfRangeException"><code>mode</code> specified an invalid value.</exception> /// <exception cref="FileNotFoundException">The file specified in <code>archiveFileName</code> was not found. </exception> /// <exception cref="NotSupportedException"><code>archiveFileName</code> is in an invalid format.</exception> /// <exception cref="InvalidDataException">The specified file could not be interpreted as a Zip file. /// -OR- <code>mode</code> is <code>Update</code> and an entry is missing from the archive or /// is corrupt and cannot be read. /// -OR- <code>mode</code> is <code>Update</code> and an entry is too large to fit into memory.</exception> /// /// <param name="archiveFileName">A string specifying the path on the filesystem to open the archive on. /// The path is permitted to specify relative or absolute path information. /// Relative path information is interpreted as relative to the current working directory.</param> /// <param name="mode">See the description of the <code>ZipArchiveMode</code> enum. /// If <code>Read</code> is specified, the file is opened with <code>System.IO.FileMode.Open</code>, and will throw /// a <code>FileNotFoundException</code> if the file does not exist. /// If <code>Create</code> is specified, the file is opened with <code>System.IO.FileMode.CreateNew</code>, and will throw /// a <code>System.IO.IOException</code> if the file already exists. /// If <code>Update</code> is specified, the file is opened with <code>System.IO.FileMode.OpenOrCreate</code>. /// If the file exists and is a Zip file, its entries will become accessible, and may be modified, and new entries may be created. /// If the file exists and is not a Zip file, a <code>ZipArchiveException</code> will be thrown. /// If the file exists and is empty or does not exist, a new Zip file will be created. /// Note that creating a Zip file with the <code>ZipArchiveMode.Create</code> mode is more efficient when creating a new Zip file.</param> public static ZipArchive Open(string archiveFileName, ZipArchiveMode mode) => Open(archiveFileName, mode, entryNameEncoding: null); /// <summary> /// Opens a <code>ZipArchive</code> on the specified <code>archiveFileName</code> in the specified <code>ZipArchiveMode</code> mode. /// </summary> /// /// <exception cref="ArgumentException">archiveFileName is a zero-length string, contains only whitespace, /// or contains one or more invalid characters as defined by InvalidPathChars.</exception> /// <exception cref="ArgumentNullException">path is null.</exception> /// <exception cref="PathTooLongException">The specified archiveFileName exceeds the system-defined maximum length. /// For example, on Windows-based platforms, paths must be less than 248 characters, /// and file names must be less than 260 characters.</exception> /// <exception cref="DirectoryNotFoundException">The specified archiveFileName is invalid, (for example, it is on an unmapped drive).</exception> /// <exception cref="IOException">An unspecified I/O error occurred while opening the file.</exception> /// <exception cref="UnauthorizedAccessException">archiveFileName specified a directory. /// -OR- The caller does not have the required permission.</exception> /// <exception cref="ArgumentOutOfRangeException"><code>mode</code> specified an invalid value.</exception> /// <exception cref="FileNotFoundException">The file specified in <code>archiveFileName</code> was not found. </exception> /// <exception cref="NotSupportedException"><code>archiveFileName</code> is in an invalid format.</exception> /// <exception cref="InvalidDataException">The specified file could not be interpreted as a Zip file. /// -OR- <code>mode</code> is <code>Update</code> and an entry is missing from the archive or /// is corrupt and cannot be read. /// -OR- <code>mode</code> is <code>Update</code> and an entry is too large to fit into memory.</exception> /// /// <param name="archiveFileName">A string specifying the path on the filesystem to open the archive on. /// The path is permitted to specify relative or absolute path information. /// Relative path information is interpreted as relative to the current working directory.</param> /// <param name="mode">See the description of the <code>ZipArchiveMode</code> enum. /// If <code>Read</code> is specified, the file is opened with <code>System.IO.FileMode.Open</code>, and will throw /// a <code>FileNotFoundException</code> if the file does not exist. /// If <code>Create</code> is specified, the file is opened with <code>System.IO.FileMode.CreateNew</code>, and will throw /// a <code>System.IO.IOException</code> if the file already exists. /// If <code>Update</code> is specified, the file is opened with <code>System.IO.FileMode.OpenOrCreate</code>. /// If the file exists and is a Zip file, its entries will become accessible, and may be modified, and new entries may be created. /// If the file exists and is not a Zip file, a <code>ZipArchiveException</code> will be thrown. /// If the file exists and is empty or does not exist, a new Zip file will be created. /// Note that creating a Zip file with the <code>ZipArchiveMode.Create</code> mode is more efficient when creating a new Zip file.</param> /// <param name="entryNameEncoding">The encoding to use when reading or writing entry names in this ZipArchive. /// /// <para>NOTE: Specifying this parameter to values other than <c>null</c> is discouraged. /// However, this may be necessary for interoperability with ZIP archive tools and libraries that do not correctly support /// UTF-8 encoding for entry names.<br /> /// This value is used as follows:</para> /// <para><strong>Reading (opening) ZIP archive files:</strong></para> /// <para>If <c>entryNameEncoding</c> is not specified (<c>== null</c>):</para> /// <list> /// <item>For entries where the language encoding flag (EFS) in the general purpose bit flag of the local file header is <em>not</em> set, /// use the current system default code page (<c>Encoding.Default</c>) in order to decode the entry name.</item> /// <item>For entries where the language encoding flag (EFS) in the general purpose bit flag of the local file header <em>is</em> set, /// use UTF-8 (<c>Encoding.UTF8</c>) in order to decode the entry name.</item> /// </list> /// <para>If <c>entryNameEncoding</c> is specified (<c>!= null</c>):</para> /// <list> /// <item>For entries where the language encoding flag (EFS) in the general purpose bit flag of the local file header is <em>not</em> set, /// use the specified <c>entryNameEncoding</c> in order to decode the entry name.</item> /// <item>For entries where the language encoding flag (EFS) in the general purpose bit flag of the local file header <em>is</em> set, /// use UTF-8 (<c>Encoding.UTF8</c>) in order to decode the entry name.</item> /// </list> /// <para><strong>Writing (saving) ZIP archive files:</strong></para> /// <para>If <c>entryNameEncoding</c> is not specified (<c>== null</c>):</para> /// <list> /// <item>For entry names that contain characters outside the ASCII range, /// the language encoding flag (EFS) will be set in the general purpose bit flag of the local file header, /// and UTF-8 (<c>Encoding.UTF8</c>) will be used in order to encode the entry name into bytes.</item> /// <item>For entry names that do not contain characters outside the ASCII range, /// the language encoding flag (EFS) will not be set in the general purpose bit flag of the local file header, /// and the current system default code page (<c>Encoding.Default</c>) will be used to encode the entry names into bytes.</item> /// </list> /// <para>If <c>entryNameEncoding</c> is specified (<c>!= null</c>):</para> /// <list> /// <item>The specified <c>entryNameEncoding</c> will always be used to encode the entry names into bytes. /// The language encoding flag (EFS) in the general purpose bit flag of the local file header will be set if and only /// if the specified <c>entryNameEncoding</c> is a UTF-8 encoding.</item> /// </list> /// <para>Note that Unicode encodings other than UTF-8 may not be currently used for the <c>entryNameEncoding</c>, /// otherwise an <see cref="ArgumentException"/> is thrown.</para> /// </param> public static ZipArchive Open(string archiveFileName, ZipArchiveMode mode, Encoding? entryNameEncoding) { // Relies on FileStream's ctor for checking of archiveFileName FileMode fileMode; FileAccess access; FileShare fileShare; switch (mode) { case ZipArchiveMode.Read: fileMode = FileMode.Open; access = FileAccess.Read; fileShare = FileShare.Read; break; case ZipArchiveMode.Create: fileMode = FileMode.CreateNew; access = FileAccess.Write; fileShare = FileShare.None; break; case ZipArchiveMode.Update: fileMode = FileMode.OpenOrCreate; access = FileAccess.ReadWrite; fileShare = FileShare.None; break; default: throw new ArgumentOutOfRangeException(nameof(mode)); } // Suppress CA2000: fs gets passed to the new ZipArchive, which stores it internally. // The stream will then be owned by the archive and be disposed when the archive is disposed. // If the ctor completes without throwing, we know fs has been successfully stores in the archive; // If the ctor throws, we need to close it here. FileStream fs = new FileStream(archiveFileName, fileMode, access, fileShare, bufferSize: 0x1000, useAsync: false); try { return new ZipArchive(fs, mode, leaveOpen: false, entryNameEncoding: entryNameEncoding); } catch { fs.Dispose(); throw; } } /// <summary> /// <p>Creates a Zip archive at the path <code>destinationArchiveFileName</code> that contains the files and directories from /// the directory specified by <code>sourceDirectoryName</code>. The directory structure is preserved in the archive, and a /// recursive search is done for files to be archived. The archive must not exist. If the directory is empty, an empty /// archive will be created. If a file in the directory cannot be added to the archive, the archive will be left incomplete /// and invalid and the method will throw an exception. This method does not include the base directory into the archive. /// If an error is encountered while adding files to the archive, this method will stop adding files and leave the archive /// in an invalid state. The paths are permitted to specify relative or absolute path information. Relative path information /// is interpreted as relative to the current working directory. If a file in the archive has data in the last write time /// field that is not a valid Zip timestamp, an indicator value of 1980 January 1 at midnight will be used for the file's /// last modified time.</p> /// /// <p>If an entry with the specified name already exists in the archive, a second entry will be created that has an identical name.</p> /// /// <p>Since no <code>CompressionLevel</code> is specified, the default provided by the implementation of the underlying compression /// algorithm will be used; the <code>ZipArchive</code> will not impose its own default. /// (Currently, the underlying compression algorithm is provided by the <code>System.IO.Compression.DeflateStream</code> class.)</p> /// </summary> /// /// <exception cref="ArgumentException"><code>sourceDirectoryName</code> or <code>destinationArchiveFileName</code> is a zero-length /// string, contains only whitespace, or contains one or more invalid characters as defined by /// <code>InvalidPathChars</code>.</exception> /// <exception cref="ArgumentNullException"><code>sourceDirectoryName</code> or <code>destinationArchiveFileName</code> is null.</exception> /// <exception cref="PathTooLongException">In <code>sourceDirectoryName</code> or <code>destinationArchiveFileName</code>, the specified /// path, file name, or both exceed the system-defined maximum length. /// For example, on Windows-based platforms, paths must be less than 248 characters, and file /// names must be less than 260 characters.</exception> /// <exception cref="DirectoryNotFoundException">The path specified in <code>sourceDirectoryName</code> or <code>destinationArchiveFileName</code> /// is invalid, (for example, it is on an unmapped drive). /// -OR- The directory specified by <code>sourceDirectoryName</code> does not exist.</exception> /// <exception cref="IOException"><code>destinationArchiveFileName</code> already exists. /// -OR- An I/O error occurred while opening a file to be archived.</exception> /// <exception cref="UnauthorizedAccessException"><code>destinationArchiveFileName</code> specified a directory. /// -OR- The caller does not have the required permission.</exception> /// <exception cref="NotSupportedException"><code>sourceDirectoryName</code> or <code>destinationArchiveFileName</code> is /// in an invalid format.</exception> /// /// <param name="sourceDirectoryName">The path to the directory on the file system to be archived. </param> /// <param name="destinationArchiveFileName">The name of the archive to be created.</param> public static void CreateFromDirectory(string sourceDirectoryName, string destinationArchiveFileName) => DoCreateFromDirectory(sourceDirectoryName, destinationArchiveFileName, compressionLevel: null, includeBaseDirectory: false, entryNameEncoding: null); /// <summary> /// <p>Creates a Zip archive at the path <code>destinationArchiveFileName</code> that contains the files and directories in the directory /// specified by <code>sourceDirectoryName</code>. The directory structure is preserved in the archive, and a recursive search is /// done for files to be archived. The archive must not exist. If the directory is empty, an empty archive will be created. /// If a file in the directory cannot be added to the archive, the archive will be left incomplete and invalid and the /// method will throw an exception. This method optionally includes the base directory in the archive. /// If an error is encountered while adding files to the archive, this method will stop adding files and leave the archive /// in an invalid state. The paths are permitted to specify relative or absolute path information. Relative path information /// is interpreted as relative to the current working directory. If a file in the archive has data in the last write time /// field that is not a valid Zip timestamp, an indicator value of 1980 January 1 at midnight will be used for the file's /// last modified time.</p> /// /// <p>If an entry with the specified name already exists in the archive, a second entry will be created that has an identical name.</p> /// /// <p>Since no <code>CompressionLevel</code> is specified, the default provided by the implementation of the underlying compression /// algorithm will be used; the <code>ZipArchive</code> will not impose its own default. /// (Currently, the underlying compression algorithm is provided by the <code>System.IO.Compression.DeflateStream</code> class.)</p> /// </summary> /// /// <exception cref="ArgumentException"><code>sourceDirectoryName</code> or <code>destinationArchiveFileName</code> is a zero-length /// string, contains only whitespace, or contains one or more invalid characters as defined by /// <code>InvalidPathChars</code>.</exception> /// <exception cref="ArgumentNullException"><code>sourceDirectoryName</code> or <code>destinationArchiveFileName</code> is null.</exception> /// <exception cref="PathTooLongException">In <code>sourceDirectoryName</code> or <code>destinationArchiveFileName</code>, the /// specified path, file name, or both exceed the system-defined maximum length. /// For example, on Windows-based platforms, paths must be less than 248 characters, /// and file names must be less than 260 characters.</exception> /// <exception cref="DirectoryNotFoundException">The path specified in <code>sourceDirectoryName</code> or /// <code>destinationArchiveFileName</code> is invalid, (for example, it is on an unmapped drive). /// -OR- The directory specified by <code>sourceDirectoryName</code> does not exist.</exception> /// <exception cref="IOException"><code>destinationArchiveFileName</code> already exists. /// -OR- An I/O error occurred while opening a file to be archived.</exception> /// <exception cref="UnauthorizedAccessException"><code>destinationArchiveFileName</code> specified a directory. /// -OR- The caller does not have the required permission.</exception> /// <exception cref="NotSupportedException"><code>sourceDirectoryName</code> or <code>destinationArchiveFileName</code> /// is in an invalid format.</exception> /// /// <param name="sourceDirectoryName">The path to the directory on the file system to be archived.</param> /// <param name="destinationArchiveFileName">The name of the archive to be created.</param> /// <param name="compressionLevel">The level of the compression (speed/memory vs. compressed size trade-off).</param> /// <param name="includeBaseDirectory"><code>true</code> to indicate that a directory named <code>sourceDirectoryName</code> should /// be included at the root of the archive. <code>false</code> to indicate that the files and directories in <code>sourceDirectoryName</code> /// should be included directly in the archive.</param> public static void CreateFromDirectory(string sourceDirectoryName, string destinationArchiveFileName, CompressionLevel compressionLevel, bool includeBaseDirectory) => DoCreateFromDirectory(sourceDirectoryName, destinationArchiveFileName, compressionLevel, includeBaseDirectory, entryNameEncoding: null); /// <summary> /// <p>Creates a Zip archive at the path <code>destinationArchiveFileName</code> that contains the files and directories in the directory /// specified by <code>sourceDirectoryName</code>. The directory structure is preserved in the archive, and a recursive search is /// done for files to be archived. The archive must not exist. If the directory is empty, an empty archive will be created. /// If a file in the directory cannot be added to the archive, the archive will be left incomplete and invalid and the /// method will throw an exception. This method optionally includes the base directory in the archive. /// If an error is encountered while adding files to the archive, this method will stop adding files and leave the archive /// in an invalid state. The paths are permitted to specify relative or absolute path information. Relative path information /// is interpreted as relative to the current working directory. If a file in the archive has data in the last write time /// field that is not a valid Zip timestamp, an indicator value of 1980 January 1 at midnight will be used for the file's /// last modified time.</p> /// /// <p>If an entry with the specified name already exists in the archive, a second entry will be created that has an identical name.</p> /// /// <p>Since no <code>CompressionLevel</code> is specified, the default provided by the implementation of the underlying compression /// algorithm will be used; the <code>ZipArchive</code> will not impose its own default. /// (Currently, the underlying compression algorithm is provided by the <code>System.IO.Compression.DeflateStream</code> class.)</p> /// </summary> /// /// <exception cref="ArgumentException"><code>sourceDirectoryName</code> or <code>destinationArchiveFileName</code> is a zero-length /// string, contains only whitespace, or contains one or more invalid characters as defined by /// <code>InvalidPathChars</code>.</exception> /// <exception cref="ArgumentNullException"><code>sourceDirectoryName</code> or <code>destinationArchiveFileName</code> is null.</exception> /// <exception cref="PathTooLongException">In <code>sourceDirectoryName</code> or <code>destinationArchiveFileName</code>, the /// specified path, file name, or both exceed the system-defined maximum length. /// For example, on Windows-based platforms, paths must be less than 248 characters, /// and file names must be less than 260 characters.</exception> /// <exception cref="DirectoryNotFoundException">The path specified in <code>sourceDirectoryName</code> or /// <code>destinationArchiveFileName</code> is invalid, (for example, it is on an unmapped drive). /// -OR- The directory specified by <code>sourceDirectoryName</code> does not exist.</exception> /// <exception cref="IOException"><code>destinationArchiveFileName</code> already exists. /// -OR- An I/O error occurred while opening a file to be archived.</exception> /// <exception cref="UnauthorizedAccessException"><code>destinationArchiveFileName</code> specified a directory. /// -OR- The caller does not have the required permission.</exception> /// <exception cref="NotSupportedException"><code>sourceDirectoryName</code> or <code>destinationArchiveFileName</code> /// is in an invalid format.</exception> /// /// <param name="sourceDirectoryName">The path to the directory on the file system to be archived.</param> /// <param name="destinationArchiveFileName">The name of the archive to be created.</param> /// <param name="compressionLevel">The level of the compression (speed/memory vs. compressed size trade-off).</param> /// <param name="includeBaseDirectory"><code>true</code> to indicate that a directory named <code>sourceDirectoryName</code> should /// be included at the root of the archive. <code>false</code> to indicate that the files and directories in <code>sourceDirectoryName</code> /// should be included directly in the archive.</param> /// <param name="entryNameEncoding">The encoding to use when reading or writing entry names in this ZipArchive. /// /// <para>NOTE: Specifying this parameter to values other than <c>null</c> is discouraged. /// However, this may be necessary for interoperability with ZIP archive tools and libraries that do not correctly support /// UTF-8 encoding for entry names.<br /> /// This value is used as follows while creating the archive:</para> /// <para>If <c>entryNameEncoding</c> is not specified (<c>== null</c>):</para> /// <list> /// <item>For file names that contain characters outside the ASCII range:<br /> /// The language encoding flag (EFS) will be set in the general purpose bit flag of the local file header of the corresponding entry, /// and UTF-8 (<c>Encoding.UTF8</c>) will be used in order to encode the entry name into bytes.</item> /// <item>For file names that do not contain characters outside the ASCII range:<br /> /// the language encoding flag (EFS) will not be set in the general purpose bit flag of the local file header of the corresponding entry, /// and the current system default code page (<c>Encoding.Default</c>) will be used to encode the entry names into bytes.</item> /// </list> /// <para>If <c>entryNameEncoding</c> is specified (<c>!= null</c>):</para> /// <list> /// <item>The specified <c>entryNameEncoding</c> will always be used to encode the entry names into bytes. /// The language encoding flag (EFS) in the general purpose bit flag of the local file header for each entry will be set if and only /// if the specified <c>entryNameEncoding</c> is a UTF-8 encoding.</item> /// </list> /// <para>Note that Unicode encodings other than UTF-8 may not be currently used for the <c>entryNameEncoding</c>, /// otherwise an <see cref="ArgumentException"/> is thrown.</para> /// </param> public static void CreateFromDirectory(string sourceDirectoryName, string destinationArchiveFileName, CompressionLevel compressionLevel, bool includeBaseDirectory, Encoding? entryNameEncoding) => DoCreateFromDirectory(sourceDirectoryName, destinationArchiveFileName, compressionLevel, includeBaseDirectory, entryNameEncoding); private static void DoCreateFromDirectory(string sourceDirectoryName, string destinationArchiveFileName, CompressionLevel? compressionLevel, bool includeBaseDirectory, Encoding? entryNameEncoding) { // Rely on Path.GetFullPath for validation of sourceDirectoryName and destinationArchive // Checking of compressionLevel is passed down to DeflateStream and the IDeflater implementation // as it is a pluggable component that completely encapsulates the meaning of compressionLevel. sourceDirectoryName = Path.GetFullPath(sourceDirectoryName); destinationArchiveFileName = Path.GetFullPath(destinationArchiveFileName); using (ZipArchive archive = Open(destinationArchiveFileName, ZipArchiveMode.Create, entryNameEncoding)) { bool directoryIsEmpty = true; //add files and directories DirectoryInfo di = new DirectoryInfo(sourceDirectoryName); string basePath = di.FullName; if (includeBaseDirectory && di.Parent != null) basePath = di.Parent.FullName; // Windows' MaxPath (260) is used as an arbitrary default capacity, as it is likely // to be greater than the length of typical entry names from the file system, even // on non-Windows platforms. The capacity will be increased, if needed. const int DefaultCapacity = 260; char[] entryNameBuffer = ArrayPool<char>.Shared.Rent(DefaultCapacity); try { foreach (FileSystemInfo file in di.EnumerateFileSystemInfos("*", SearchOption.AllDirectories)) { directoryIsEmpty = false; int entryNameLength = file.FullName.Length - basePath.Length; Debug.Assert(entryNameLength > 0); if (file is FileInfo) { // Create entry for file: string entryName = ZipFileUtils.EntryFromPath(file.FullName, basePath.Length, entryNameLength, ref entryNameBuffer); ZipFileExtensions.DoCreateEntryFromFile(archive, file.FullName, entryName, compressionLevel); } else { // Entry marking an empty dir: if (file is DirectoryInfo possiblyEmpty && ZipFileUtils.IsDirEmpty(possiblyEmpty)) { // FullName never returns a directory separator character on the end, // but Zip archives require it to specify an explicit directory: string entryName = ZipFileUtils.EntryFromPath(file.FullName, basePath.Length, entryNameLength, ref entryNameBuffer, appendPathSeparator: true); archive.CreateEntry(entryName); } } } // foreach // If no entries create an empty root directory entry: if (includeBaseDirectory && directoryIsEmpty) archive.CreateEntry(ZipFileUtils.EntryFromPath(di.Name, 0, di.Name.Length, ref entryNameBuffer, appendPathSeparator: true)); } finally { ArrayPool<char>.Shared.Return(entryNameBuffer); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Buffers; using System.Collections.Generic; using System.Diagnostics; using System.Text; namespace System.IO.Compression { public static partial class ZipFile { /// <summary> /// Opens a <code>ZipArchive</code> on the specified path for reading. The specified file is opened with <code>FileMode.Open</code>. /// </summary> /// /// <exception cref="ArgumentException">archiveFileName is a zero-length string, contains only whitespace, or contains one /// or more invalid characters as defined by InvalidPathChars.</exception> /// <exception cref="ArgumentNullException">archiveFileName is null.</exception> /// <exception cref="PathTooLongException">The specified archiveFileName exceeds the system-defined maximum length. /// For example, on Windows-based platforms, paths must be less than 248 characters, /// and file names must be less than 260 characters.</exception> /// <exception cref="DirectoryNotFoundException">The specified archiveFileName is invalid, (for example, it is on an unmapped drive).</exception> /// <exception cref="IOException">An unspecified I/O error occurred while opening the file.</exception> /// <exception cref="UnauthorizedAccessException">archiveFileName specified a directory. /// -OR- The caller does not have the required permission.</exception> /// <exception cref="FileNotFoundException">The file specified in archiveFileName was not found.</exception> /// <exception cref="NotSupportedException">archiveFileName is in an invalid format. </exception> /// <exception cref="InvalidDataException">The specified file could not be interpreted as a Zip file.</exception> /// /// <param name="archiveFileName">A string specifying the path on the filesystem to open the archive on. The path is permitted /// to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory.</param> public static ZipArchive OpenRead(string archiveFileName) => Open(archiveFileName, ZipArchiveMode.Read); /// <summary> /// Opens a <code>ZipArchive</code> on the specified <code>archiveFileName</code> in the specified <code>ZipArchiveMode</code> mode. /// </summary> /// /// <exception cref="ArgumentException">archiveFileName is a zero-length string, contains only whitespace, /// or contains one or more invalid characters as defined by InvalidPathChars.</exception> /// <exception cref="ArgumentNullException">path is null.</exception> /// <exception cref="PathTooLongException">The specified archiveFileName exceeds the system-defined maximum length. /// For example, on Windows-based platforms, paths must be less than 248 characters, /// and file names must be less than 260 characters.</exception> /// <exception cref="DirectoryNotFoundException">The specified archiveFileName is invalid, (for example, it is on an unmapped drive).</exception> /// <exception cref="IOException">An unspecified I/O error occurred while opening the file.</exception> /// <exception cref="UnauthorizedAccessException">archiveFileName specified a directory. /// -OR- The caller does not have the required permission.</exception> /// <exception cref="ArgumentOutOfRangeException"><code>mode</code> specified an invalid value.</exception> /// <exception cref="FileNotFoundException">The file specified in <code>archiveFileName</code> was not found. </exception> /// <exception cref="NotSupportedException"><code>archiveFileName</code> is in an invalid format.</exception> /// <exception cref="InvalidDataException">The specified file could not be interpreted as a Zip file. /// -OR- <code>mode</code> is <code>Update</code> and an entry is missing from the archive or /// is corrupt and cannot be read. /// -OR- <code>mode</code> is <code>Update</code> and an entry is too large to fit into memory.</exception> /// /// <param name="archiveFileName">A string specifying the path on the filesystem to open the archive on. /// The path is permitted to specify relative or absolute path information. /// Relative path information is interpreted as relative to the current working directory.</param> /// <param name="mode">See the description of the <code>ZipArchiveMode</code> enum. /// If <code>Read</code> is specified, the file is opened with <code>System.IO.FileMode.Open</code>, and will throw /// a <code>FileNotFoundException</code> if the file does not exist. /// If <code>Create</code> is specified, the file is opened with <code>System.IO.FileMode.CreateNew</code>, and will throw /// a <code>System.IO.IOException</code> if the file already exists. /// If <code>Update</code> is specified, the file is opened with <code>System.IO.FileMode.OpenOrCreate</code>. /// If the file exists and is a Zip file, its entries will become accessible, and may be modified, and new entries may be created. /// If the file exists and is not a Zip file, a <code>ZipArchiveException</code> will be thrown. /// If the file exists and is empty or does not exist, a new Zip file will be created. /// Note that creating a Zip file with the <code>ZipArchiveMode.Create</code> mode is more efficient when creating a new Zip file.</param> public static ZipArchive Open(string archiveFileName, ZipArchiveMode mode) => Open(archiveFileName, mode, entryNameEncoding: null); /// <summary> /// Opens a <code>ZipArchive</code> on the specified <code>archiveFileName</code> in the specified <code>ZipArchiveMode</code> mode. /// </summary> /// /// <exception cref="ArgumentException">archiveFileName is a zero-length string, contains only whitespace, /// or contains one or more invalid characters as defined by InvalidPathChars.</exception> /// <exception cref="ArgumentNullException">path is null.</exception> /// <exception cref="PathTooLongException">The specified archiveFileName exceeds the system-defined maximum length. /// For example, on Windows-based platforms, paths must be less than 248 characters, /// and file names must be less than 260 characters.</exception> /// <exception cref="DirectoryNotFoundException">The specified archiveFileName is invalid, (for example, it is on an unmapped drive).</exception> /// <exception cref="IOException">An unspecified I/O error occurred while opening the file.</exception> /// <exception cref="UnauthorizedAccessException">archiveFileName specified a directory. /// -OR- The caller does not have the required permission.</exception> /// <exception cref="ArgumentOutOfRangeException"><code>mode</code> specified an invalid value.</exception> /// <exception cref="FileNotFoundException">The file specified in <code>archiveFileName</code> was not found. </exception> /// <exception cref="NotSupportedException"><code>archiveFileName</code> is in an invalid format.</exception> /// <exception cref="InvalidDataException">The specified file could not be interpreted as a Zip file. /// -OR- <code>mode</code> is <code>Update</code> and an entry is missing from the archive or /// is corrupt and cannot be read. /// -OR- <code>mode</code> is <code>Update</code> and an entry is too large to fit into memory.</exception> /// /// <param name="archiveFileName">A string specifying the path on the filesystem to open the archive on. /// The path is permitted to specify relative or absolute path information. /// Relative path information is interpreted as relative to the current working directory.</param> /// <param name="mode">See the description of the <code>ZipArchiveMode</code> enum. /// If <code>Read</code> is specified, the file is opened with <code>System.IO.FileMode.Open</code>, and will throw /// a <code>FileNotFoundException</code> if the file does not exist. /// If <code>Create</code> is specified, the file is opened with <code>System.IO.FileMode.CreateNew</code>, and will throw /// a <code>System.IO.IOException</code> if the file already exists. /// If <code>Update</code> is specified, the file is opened with <code>System.IO.FileMode.OpenOrCreate</code>. /// If the file exists and is a Zip file, its entries will become accessible, and may be modified, and new entries may be created. /// If the file exists and is not a Zip file, a <code>ZipArchiveException</code> will be thrown. /// If the file exists and is empty or does not exist, a new Zip file will be created. /// Note that creating a Zip file with the <code>ZipArchiveMode.Create</code> mode is more efficient when creating a new Zip file.</param> /// <param name="entryNameEncoding">The encoding to use when reading or writing entry names in this ZipArchive. /// /// <para>NOTE: Specifying this parameter to values other than <c>null</c> is discouraged. /// However, this may be necessary for interoperability with ZIP archive tools and libraries that do not correctly support /// UTF-8 encoding for entry names.<br /> /// This value is used as follows:</para> /// <para><strong>Reading (opening) ZIP archive files:</strong></para> /// <para>If <c>entryNameEncoding</c> is not specified (<c>== null</c>):</para> /// <list> /// <item>For entries where the language encoding flag (EFS) in the general purpose bit flag of the local file header is <em>not</em> set, /// use the current system default code page (<c>Encoding.Default</c>) in order to decode the entry name.</item> /// <item>For entries where the language encoding flag (EFS) in the general purpose bit flag of the local file header <em>is</em> set, /// use UTF-8 (<c>Encoding.UTF8</c>) in order to decode the entry name.</item> /// </list> /// <para>If <c>entryNameEncoding</c> is specified (<c>!= null</c>):</para> /// <list> /// <item>For entries where the language encoding flag (EFS) in the general purpose bit flag of the local file header is <em>not</em> set, /// use the specified <c>entryNameEncoding</c> in order to decode the entry name.</item> /// <item>For entries where the language encoding flag (EFS) in the general purpose bit flag of the local file header <em>is</em> set, /// use UTF-8 (<c>Encoding.UTF8</c>) in order to decode the entry name.</item> /// </list> /// <para><strong>Writing (saving) ZIP archive files:</strong></para> /// <para>If <c>entryNameEncoding</c> is not specified (<c>== null</c>):</para> /// <list> /// <item>For entry names that contain characters outside the ASCII range, /// the language encoding flag (EFS) will be set in the general purpose bit flag of the local file header, /// and UTF-8 (<c>Encoding.UTF8</c>) will be used in order to encode the entry name into bytes.</item> /// <item>For entry names that do not contain characters outside the ASCII range, /// the language encoding flag (EFS) will not be set in the general purpose bit flag of the local file header, /// and the current system default code page (<c>Encoding.Default</c>) will be used to encode the entry names into bytes.</item> /// </list> /// <para>If <c>entryNameEncoding</c> is specified (<c>!= null</c>):</para> /// <list> /// <item>The specified <c>entryNameEncoding</c> will always be used to encode the entry names into bytes. /// The language encoding flag (EFS) in the general purpose bit flag of the local file header will be set if and only /// if the specified <c>entryNameEncoding</c> is a UTF-8 encoding.</item> /// </list> /// <para>Note that Unicode encodings other than UTF-8 may not be currently used for the <c>entryNameEncoding</c>, /// otherwise an <see cref="ArgumentException"/> is thrown.</para> /// </param> public static ZipArchive Open(string archiveFileName, ZipArchiveMode mode, Encoding? entryNameEncoding) { // Relies on FileStream's ctor for checking of archiveFileName FileMode fileMode; FileAccess access; FileShare fileShare; switch (mode) { case ZipArchiveMode.Read: fileMode = FileMode.Open; access = FileAccess.Read; fileShare = FileShare.Read; break; case ZipArchiveMode.Create: fileMode = FileMode.CreateNew; access = FileAccess.Write; fileShare = FileShare.None; break; case ZipArchiveMode.Update: fileMode = FileMode.OpenOrCreate; access = FileAccess.ReadWrite; fileShare = FileShare.None; break; default: throw new ArgumentOutOfRangeException(nameof(mode)); } // Suppress CA2000: fs gets passed to the new ZipArchive, which stores it internally. // The stream will then be owned by the archive and be disposed when the archive is disposed. // If the ctor completes without throwing, we know fs has been successfully stores in the archive; // If the ctor throws, we need to close it here. FileStream fs = new FileStream(archiveFileName, fileMode, access, fileShare, bufferSize: 0x1000, useAsync: false); try { return new ZipArchive(fs, mode, leaveOpen: false, entryNameEncoding: entryNameEncoding); } catch { fs.Dispose(); throw; } } /// <summary> /// <p>Creates a Zip archive at the path <code>destinationArchiveFileName</code> that contains the files and directories from /// the directory specified by <code>sourceDirectoryName</code>. The directory structure is preserved in the archive, and a /// recursive search is done for files to be archived. The archive must not exist. If the directory is empty, an empty /// archive will be created. If a file in the directory cannot be added to the archive, the archive will be left incomplete /// and invalid and the method will throw an exception. This method does not include the base directory into the archive. /// If an error is encountered while adding files to the archive, this method will stop adding files and leave the archive /// in an invalid state. The paths are permitted to specify relative or absolute path information. Relative path information /// is interpreted as relative to the current working directory. If a file in the archive has data in the last write time /// field that is not a valid Zip timestamp, an indicator value of 1980 January 1 at midnight will be used for the file's /// last modified time.</p> /// /// <p>If an entry with the specified name already exists in the archive, a second entry will be created that has an identical name.</p> /// /// <p>Since no <code>CompressionLevel</code> is specified, the default provided by the implementation of the underlying compression /// algorithm will be used; the <code>ZipArchive</code> will not impose its own default. /// (Currently, the underlying compression algorithm is provided by the <code>System.IO.Compression.DeflateStream</code> class.)</p> /// </summary> /// /// <exception cref="ArgumentException"><code>sourceDirectoryName</code> or <code>destinationArchiveFileName</code> is a zero-length /// string, contains only whitespace, or contains one or more invalid characters as defined by /// <code>InvalidPathChars</code>.</exception> /// <exception cref="ArgumentNullException"><code>sourceDirectoryName</code> or <code>destinationArchiveFileName</code> is null.</exception> /// <exception cref="PathTooLongException">In <code>sourceDirectoryName</code> or <code>destinationArchiveFileName</code>, the specified /// path, file name, or both exceed the system-defined maximum length. /// For example, on Windows-based platforms, paths must be less than 248 characters, and file /// names must be less than 260 characters.</exception> /// <exception cref="DirectoryNotFoundException">The path specified in <code>sourceDirectoryName</code> or <code>destinationArchiveFileName</code> /// is invalid, (for example, it is on an unmapped drive). /// -OR- The directory specified by <code>sourceDirectoryName</code> does not exist.</exception> /// <exception cref="IOException"><code>destinationArchiveFileName</code> already exists. /// -OR- An I/O error occurred while opening a file to be archived.</exception> /// <exception cref="UnauthorizedAccessException"><code>destinationArchiveFileName</code> specified a directory. /// -OR- The caller does not have the required permission.</exception> /// <exception cref="NotSupportedException"><code>sourceDirectoryName</code> or <code>destinationArchiveFileName</code> is /// in an invalid format.</exception> /// /// <param name="sourceDirectoryName">The path to the directory on the file system to be archived. </param> /// <param name="destinationArchiveFileName">The name of the archive to be created.</param> public static void CreateFromDirectory(string sourceDirectoryName, string destinationArchiveFileName) => DoCreateFromDirectory(sourceDirectoryName, destinationArchiveFileName, compressionLevel: null, includeBaseDirectory: false, entryNameEncoding: null); /// <summary> /// <p>Creates a Zip archive at the path <code>destinationArchiveFileName</code> that contains the files and directories in the directory /// specified by <code>sourceDirectoryName</code>. The directory structure is preserved in the archive, and a recursive search is /// done for files to be archived. The archive must not exist. If the directory is empty, an empty archive will be created. /// If a file in the directory cannot be added to the archive, the archive will be left incomplete and invalid and the /// method will throw an exception. This method optionally includes the base directory in the archive. /// If an error is encountered while adding files to the archive, this method will stop adding files and leave the archive /// in an invalid state. The paths are permitted to specify relative or absolute path information. Relative path information /// is interpreted as relative to the current working directory. If a file in the archive has data in the last write time /// field that is not a valid Zip timestamp, an indicator value of 1980 January 1 at midnight will be used for the file's /// last modified time.</p> /// /// <p>If an entry with the specified name already exists in the archive, a second entry will be created that has an identical name.</p> /// /// <p>Since no <code>CompressionLevel</code> is specified, the default provided by the implementation of the underlying compression /// algorithm will be used; the <code>ZipArchive</code> will not impose its own default. /// (Currently, the underlying compression algorithm is provided by the <code>System.IO.Compression.DeflateStream</code> class.)</p> /// </summary> /// /// <exception cref="ArgumentException"><code>sourceDirectoryName</code> or <code>destinationArchiveFileName</code> is a zero-length /// string, contains only whitespace, or contains one or more invalid characters as defined by /// <code>InvalidPathChars</code>.</exception> /// <exception cref="ArgumentNullException"><code>sourceDirectoryName</code> or <code>destinationArchiveFileName</code> is null.</exception> /// <exception cref="PathTooLongException">In <code>sourceDirectoryName</code> or <code>destinationArchiveFileName</code>, the /// specified path, file name, or both exceed the system-defined maximum length. /// For example, on Windows-based platforms, paths must be less than 248 characters, /// and file names must be less than 260 characters.</exception> /// <exception cref="DirectoryNotFoundException">The path specified in <code>sourceDirectoryName</code> or /// <code>destinationArchiveFileName</code> is invalid, (for example, it is on an unmapped drive). /// -OR- The directory specified by <code>sourceDirectoryName</code> does not exist.</exception> /// <exception cref="IOException"><code>destinationArchiveFileName</code> already exists. /// -OR- An I/O error occurred while opening a file to be archived.</exception> /// <exception cref="UnauthorizedAccessException"><code>destinationArchiveFileName</code> specified a directory. /// -OR- The caller does not have the required permission.</exception> /// <exception cref="NotSupportedException"><code>sourceDirectoryName</code> or <code>destinationArchiveFileName</code> /// is in an invalid format.</exception> /// /// <param name="sourceDirectoryName">The path to the directory on the file system to be archived.</param> /// <param name="destinationArchiveFileName">The name of the archive to be created.</param> /// <param name="compressionLevel">The level of the compression (speed/memory vs. compressed size trade-off).</param> /// <param name="includeBaseDirectory"><code>true</code> to indicate that a directory named <code>sourceDirectoryName</code> should /// be included at the root of the archive. <code>false</code> to indicate that the files and directories in <code>sourceDirectoryName</code> /// should be included directly in the archive.</param> public static void CreateFromDirectory(string sourceDirectoryName, string destinationArchiveFileName, CompressionLevel compressionLevel, bool includeBaseDirectory) => DoCreateFromDirectory(sourceDirectoryName, destinationArchiveFileName, compressionLevel, includeBaseDirectory, entryNameEncoding: null); /// <summary> /// <p>Creates a Zip archive at the path <code>destinationArchiveFileName</code> that contains the files and directories in the directory /// specified by <code>sourceDirectoryName</code>. The directory structure is preserved in the archive, and a recursive search is /// done for files to be archived. The archive must not exist. If the directory is empty, an empty archive will be created. /// If a file in the directory cannot be added to the archive, the archive will be left incomplete and invalid and the /// method will throw an exception. This method optionally includes the base directory in the archive. /// If an error is encountered while adding files to the archive, this method will stop adding files and leave the archive /// in an invalid state. The paths are permitted to specify relative or absolute path information. Relative path information /// is interpreted as relative to the current working directory. If a file in the archive has data in the last write time /// field that is not a valid Zip timestamp, an indicator value of 1980 January 1 at midnight will be used for the file's /// last modified time.</p> /// /// <p>If an entry with the specified name already exists in the archive, a second entry will be created that has an identical name.</p> /// /// <p>Since no <code>CompressionLevel</code> is specified, the default provided by the implementation of the underlying compression /// algorithm will be used; the <code>ZipArchive</code> will not impose its own default. /// (Currently, the underlying compression algorithm is provided by the <code>System.IO.Compression.DeflateStream</code> class.)</p> /// </summary> /// /// <exception cref="ArgumentException"><code>sourceDirectoryName</code> or <code>destinationArchiveFileName</code> is a zero-length /// string, contains only whitespace, or contains one or more invalid characters as defined by /// <code>InvalidPathChars</code>.</exception> /// <exception cref="ArgumentNullException"><code>sourceDirectoryName</code> or <code>destinationArchiveFileName</code> is null.</exception> /// <exception cref="PathTooLongException">In <code>sourceDirectoryName</code> or <code>destinationArchiveFileName</code>, the /// specified path, file name, or both exceed the system-defined maximum length. /// For example, on Windows-based platforms, paths must be less than 248 characters, /// and file names must be less than 260 characters.</exception> /// <exception cref="DirectoryNotFoundException">The path specified in <code>sourceDirectoryName</code> or /// <code>destinationArchiveFileName</code> is invalid, (for example, it is on an unmapped drive). /// -OR- The directory specified by <code>sourceDirectoryName</code> does not exist.</exception> /// <exception cref="IOException"><code>destinationArchiveFileName</code> already exists. /// -OR- An I/O error occurred while opening a file to be archived.</exception> /// <exception cref="UnauthorizedAccessException"><code>destinationArchiveFileName</code> specified a directory. /// -OR- The caller does not have the required permission.</exception> /// <exception cref="NotSupportedException"><code>sourceDirectoryName</code> or <code>destinationArchiveFileName</code> /// is in an invalid format.</exception> /// /// <param name="sourceDirectoryName">The path to the directory on the file system to be archived.</param> /// <param name="destinationArchiveFileName">The name of the archive to be created.</param> /// <param name="compressionLevel">The level of the compression (speed/memory vs. compressed size trade-off).</param> /// <param name="includeBaseDirectory"><code>true</code> to indicate that a directory named <code>sourceDirectoryName</code> should /// be included at the root of the archive. <code>false</code> to indicate that the files and directories in <code>sourceDirectoryName</code> /// should be included directly in the archive.</param> /// <param name="entryNameEncoding">The encoding to use when reading or writing entry names in this ZipArchive. /// /// <para>NOTE: Specifying this parameter to values other than <c>null</c> is discouraged. /// However, this may be necessary for interoperability with ZIP archive tools and libraries that do not correctly support /// UTF-8 encoding for entry names.<br /> /// This value is used as follows while creating the archive:</para> /// <para>If <c>entryNameEncoding</c> is not specified (<c>== null</c>):</para> /// <list> /// <item>For file names that contain characters outside the ASCII range:<br /> /// The language encoding flag (EFS) will be set in the general purpose bit flag of the local file header of the corresponding entry, /// and UTF-8 (<c>Encoding.UTF8</c>) will be used in order to encode the entry name into bytes.</item> /// <item>For file names that do not contain characters outside the ASCII range:<br /> /// the language encoding flag (EFS) will not be set in the general purpose bit flag of the local file header of the corresponding entry, /// and the current system default code page (<c>Encoding.Default</c>) will be used to encode the entry names into bytes.</item> /// </list> /// <para>If <c>entryNameEncoding</c> is specified (<c>!= null</c>):</para> /// <list> /// <item>The specified <c>entryNameEncoding</c> will always be used to encode the entry names into bytes. /// The language encoding flag (EFS) in the general purpose bit flag of the local file header for each entry will be set if and only /// if the specified <c>entryNameEncoding</c> is a UTF-8 encoding.</item> /// </list> /// <para>Note that Unicode encodings other than UTF-8 may not be currently used for the <c>entryNameEncoding</c>, /// otherwise an <see cref="ArgumentException"/> is thrown.</para> /// </param> public static void CreateFromDirectory(string sourceDirectoryName, string destinationArchiveFileName, CompressionLevel compressionLevel, bool includeBaseDirectory, Encoding? entryNameEncoding) => DoCreateFromDirectory(sourceDirectoryName, destinationArchiveFileName, compressionLevel, includeBaseDirectory, entryNameEncoding); private static void DoCreateFromDirectory(string sourceDirectoryName, string destinationArchiveFileName, CompressionLevel? compressionLevel, bool includeBaseDirectory, Encoding? entryNameEncoding) { // Rely on Path.GetFullPath for validation of sourceDirectoryName and destinationArchive // Checking of compressionLevel is passed down to DeflateStream and the IDeflater implementation // as it is a pluggable component that completely encapsulates the meaning of compressionLevel. sourceDirectoryName = Path.GetFullPath(sourceDirectoryName); destinationArchiveFileName = Path.GetFullPath(destinationArchiveFileName); using (ZipArchive archive = Open(destinationArchiveFileName, ZipArchiveMode.Create, entryNameEncoding)) { bool directoryIsEmpty = true; //add files and directories DirectoryInfo di = new DirectoryInfo(sourceDirectoryName); string basePath = di.FullName; if (includeBaseDirectory && di.Parent != null) basePath = di.Parent.FullName; // Windows' MaxPath (260) is used as an arbitrary default capacity, as it is likely // to be greater than the length of typical entry names from the file system, even // on non-Windows platforms. The capacity will be increased, if needed. const int DefaultCapacity = 260; char[] entryNameBuffer = ArrayPool<char>.Shared.Rent(DefaultCapacity); try { foreach (FileSystemInfo file in di.EnumerateFileSystemInfos("*", SearchOption.AllDirectories)) { directoryIsEmpty = false; int entryNameLength = file.FullName.Length - basePath.Length; Debug.Assert(entryNameLength > 0); if (file is FileInfo) { // Create entry for file: string entryName = ZipFileUtils.EntryFromPath(file.FullName, basePath.Length, entryNameLength, ref entryNameBuffer); ZipFileExtensions.DoCreateEntryFromFile(archive, file.FullName, entryName, compressionLevel); } else { // Entry marking an empty dir: if (file is DirectoryInfo possiblyEmpty && ZipFileUtils.IsDirEmpty(possiblyEmpty)) { // FullName never returns a directory separator character on the end, // but Zip archives require it to specify an explicit directory: string entryName = ZipFileUtils.EntryFromPath(file.FullName, basePath.Length, entryNameLength, ref entryNameBuffer, appendPathSeparator: true); archive.CreateEntry(entryName); } } } // foreach // If no entries create an empty root directory entry: if (includeBaseDirectory && directoryIsEmpty) archive.CreateEntry(ZipFileUtils.EntryFromPath(di.Name, 0, di.Name.Length, ref entryNameBuffer, appendPathSeparator: true)); } finally { ArrayPool<char>.Shared.Return(entryNameBuffer); } } } } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/tests/GC/Features/Finalizer/finalizeother/finalizeinherit.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // Tests Finalize() with Inheritance using System; using System.Runtime.CompilerServices; namespace One { abstract class A { } class B: A { ~B() { Console.WriteLine("In Finalize of B"); } } class C: B { public static int count=0; ~C() { Console.WriteLine("In Finalize of C"); count++; } } } namespace Two { using One; class D: C { } } namespace Three { using One; using Two; class CreateObj { // disabling unused variable warning #pragma warning disable 0414 B b; D d; #pragma warning restore 0414 C c; // No inline to ensure no stray refs to the B, C, D objects. [MethodImplAttribute(MethodImplOptions.NoInlining)] public CreateObj() { b = new B(); c = new C(); d = new D(); } [MethodImplAttribute(MethodImplOptions.NoInlining)] public bool RunTest() { A a = c; d=null; b=null; a=null; c=null; GC.Collect(); GC.WaitForPendingFinalizers(); return (C.count == 2); } } class Test { static int Main() { CreateObj temp = new CreateObj(); temp.RunTest(); GC.Collect(); GC.WaitForPendingFinalizers(); if (C.count == 2) { Console.WriteLine("Test Passed"); return 100; } 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. // Tests Finalize() with Inheritance using System; using System.Runtime.CompilerServices; namespace One { abstract class A { } class B: A { ~B() { Console.WriteLine("In Finalize of B"); } } class C: B { public static int count=0; ~C() { Console.WriteLine("In Finalize of C"); count++; } } } namespace Two { using One; class D: C { } } namespace Three { using One; using Two; class CreateObj { // disabling unused variable warning #pragma warning disable 0414 B b; D d; #pragma warning restore 0414 C c; // No inline to ensure no stray refs to the B, C, D objects. [MethodImplAttribute(MethodImplOptions.NoInlining)] public CreateObj() { b = new B(); c = new C(); d = new D(); } [MethodImplAttribute(MethodImplOptions.NoInlining)] public bool RunTest() { A a = c; d=null; b=null; a=null; c=null; GC.Collect(); GC.WaitForPendingFinalizers(); return (C.count == 2); } } class Test { static int Main() { CreateObj temp = new CreateObj(); temp.RunTest(); GC.Collect(); GC.WaitForPendingFinalizers(); if (C.count == 2) { Console.WriteLine("Test Passed"); return 100; } Console.WriteLine("Test Failed"); return 1; } } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/tests/JIT/HardwareIntrinsics/X86/Avx2/ShiftLeftLogical128BitLane.UInt32.1.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void ShiftLeftLogical128BitLaneUInt321() { var test = new ImmUnaryOpTest__ShiftLeftLogical128BitLaneUInt321(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class ImmUnaryOpTest__ShiftLeftLogical128BitLaneUInt321 { private struct TestStruct { public Vector256<UInt32> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (uint)8; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref testStruct._fld), ref Unsafe.As<UInt32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); return testStruct; } public void RunStructFldScenario(ImmUnaryOpTest__ShiftLeftLogical128BitLaneUInt321 testClass) { var result = Avx2.ShiftLeftLogical128BitLane(_fld, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } 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 static Vector256<UInt32> _clsVar; private Vector256<UInt32> _fld; private SimpleUnaryOpTest__DataTable<UInt32, UInt32> _dataTable; static ImmUnaryOpTest__ShiftLeftLogical128BitLaneUInt321() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (uint)8; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _clsVar), ref Unsafe.As<UInt32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); } public ImmUnaryOpTest__ShiftLeftLogical128BitLaneUInt321() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (uint)8; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _fld), ref Unsafe.As<UInt32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (uint)8; } _dataTable = new SimpleUnaryOpTest__DataTable<UInt32, UInt32>(_data, new UInt32[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx2.ShiftLeftLogical128BitLane( Unsafe.Read<Vector256<UInt32>>(_dataTable.inArrayPtr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx2.ShiftLeftLogical128BitLane( Avx.LoadVector256((UInt32*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx2.ShiftLeftLogical128BitLane( Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftLeftLogical128BitLane), new Type[] { typeof(Vector256<UInt32>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<UInt32>>(_dataTable.inArrayPtr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftLeftLogical128BitLane), new Type[] { typeof(Vector256<UInt32>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadVector256((UInt32*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftLeftLogical128BitLane), new Type[] { typeof(Vector256<UInt32>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.ShiftLeftLogical128BitLane( _clsVar, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector256<UInt32>>(_dataTable.inArrayPtr); var result = Avx2.ShiftLeftLogical128BitLane(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = Avx.LoadVector256((UInt32*)(_dataTable.inArrayPtr)); var result = Avx2.ShiftLeftLogical128BitLane(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var firstOp = Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArrayPtr)); var result = Avx2.ShiftLeftLogical128BitLane(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmUnaryOpTest__ShiftLeftLogical128BitLaneUInt321(); var result = Avx2.ShiftLeftLogical128BitLane(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx2.ShiftLeftLogical128BitLane(_fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx2.ShiftLeftLogical128BitLane(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(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 (result[0] != 2048) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != 2048) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.ShiftLeftLogical128BitLane)}<UInt32>(Vector256<UInt32><9>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void ShiftLeftLogical128BitLaneUInt321() { var test = new ImmUnaryOpTest__ShiftLeftLogical128BitLaneUInt321(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class ImmUnaryOpTest__ShiftLeftLogical128BitLaneUInt321 { private struct TestStruct { public Vector256<UInt32> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (uint)8; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref testStruct._fld), ref Unsafe.As<UInt32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); return testStruct; } public void RunStructFldScenario(ImmUnaryOpTest__ShiftLeftLogical128BitLaneUInt321 testClass) { var result = Avx2.ShiftLeftLogical128BitLane(_fld, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } 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 static Vector256<UInt32> _clsVar; private Vector256<UInt32> _fld; private SimpleUnaryOpTest__DataTable<UInt32, UInt32> _dataTable; static ImmUnaryOpTest__ShiftLeftLogical128BitLaneUInt321() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (uint)8; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _clsVar), ref Unsafe.As<UInt32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); } public ImmUnaryOpTest__ShiftLeftLogical128BitLaneUInt321() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (uint)8; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _fld), ref Unsafe.As<UInt32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (uint)8; } _dataTable = new SimpleUnaryOpTest__DataTable<UInt32, UInt32>(_data, new UInt32[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx2.ShiftLeftLogical128BitLane( Unsafe.Read<Vector256<UInt32>>(_dataTable.inArrayPtr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx2.ShiftLeftLogical128BitLane( Avx.LoadVector256((UInt32*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx2.ShiftLeftLogical128BitLane( Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftLeftLogical128BitLane), new Type[] { typeof(Vector256<UInt32>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<UInt32>>(_dataTable.inArrayPtr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftLeftLogical128BitLane), new Type[] { typeof(Vector256<UInt32>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadVector256((UInt32*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftLeftLogical128BitLane), new Type[] { typeof(Vector256<UInt32>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.ShiftLeftLogical128BitLane( _clsVar, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector256<UInt32>>(_dataTable.inArrayPtr); var result = Avx2.ShiftLeftLogical128BitLane(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = Avx.LoadVector256((UInt32*)(_dataTable.inArrayPtr)); var result = Avx2.ShiftLeftLogical128BitLane(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var firstOp = Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArrayPtr)); var result = Avx2.ShiftLeftLogical128BitLane(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmUnaryOpTest__ShiftLeftLogical128BitLaneUInt321(); var result = Avx2.ShiftLeftLogical128BitLane(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx2.ShiftLeftLogical128BitLane(_fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx2.ShiftLeftLogical128BitLane(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(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 (result[0] != 2048) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != 2048) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.ShiftLeftLogical128BitLane)}<UInt32>(Vector256<UInt32><9>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/libraries/Common/src/Interop/Windows/WebSocket/Interop.WebSocketReceive.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Runtime.InteropServices; using System.Security; internal static partial class Interop { internal static partial class WebSocket { [GeneratedDllImport(Libraries.WebSocket)] internal static partial int WebSocketReceive( SafeHandle webSocketHandle, IntPtr buffers, IntPtr applicationContext); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Runtime.InteropServices; using System.Security; internal static partial class Interop { internal static partial class WebSocket { [GeneratedDllImport(Libraries.WebSocket)] internal static partial int WebSocketReceive( SafeHandle webSocketHandle, IntPtr buffers, IntPtr applicationContext); } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/coreclr/tools/Common/Compiler/DependencyAnalysis/Target_X86/X86Emitter.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 ILCompiler.DependencyAnalysis.X86 { public struct X86Emitter { public X86Emitter(NodeFactory factory, bool relocsOnly) { Builder = new ObjectDataBuilder(factory, relocsOnly); TargetRegister = new TargetRegisterMap(factory.Target.OperatingSystem); } public ObjectDataBuilder Builder; public TargetRegisterMap TargetRegister; public void EmitCMP(ref AddrMode addrMode, sbyte immediate) { if (addrMode.Size == AddrModeSize.Int16) Builder.EmitByte(0x66); EmitIndirInstruction((byte)((addrMode.Size != AddrModeSize.Int8) ? 0x83 : 0x80), 0x7, ref addrMode); Builder.EmitByte((byte)immediate); } public void EmitADD(ref AddrMode addrMode, sbyte immediate) { if (addrMode.Size == AddrModeSize.Int16) Builder.EmitByte(0x66); EmitIndirInstruction((byte)((addrMode.Size != AddrModeSize.Int8) ? 0x83 : 0x80), (byte)0, ref addrMode); Builder.EmitByte((byte)immediate); } public void EmitJMP(ISymbolNode symbol) { if (symbol.RepresentsIndirectionCell) { Builder.EmitByte(0xff); Builder.EmitByte(0x25); Builder.EmitReloc(symbol, RelocType.IMAGE_REL_BASED_HIGHLOW); } else { Builder.EmitByte(0xE9); Builder.EmitReloc(symbol, RelocType.IMAGE_REL_BASED_REL32); } } public void EmitXOR(Register register1, Register register2) { Builder.EmitByte(0x33); Builder.EmitByte((byte)(0xC0 | ((byte)register1 << 3) | (byte)register2)); } public void EmitPUSH(sbyte imm8) { Builder.EmitByte(0x6A); Builder.EmitByte(unchecked((byte)imm8)); } public void EmitPUSH(ISymbolNode node) { if (node.RepresentsIndirectionCell) { // push [node address] Builder.EmitByte(0xFF); Builder.EmitByte(0x35); } else { // push <node address> Builder.EmitByte(0x68); } Builder.EmitReloc(node, RelocType.IMAGE_REL_BASED_HIGHLOW); } public void EmitMOV(Register regDst, Register regSrc) { Builder.EmitByte(0x8B); Builder.EmitByte((byte)(0xC0 | (((int)regDst & 0x07) << 3) | (((int)regSrc & 0x07)))); } public void EmitMOV(Register register, ISymbolNode node, int delta = 0) { if (node.RepresentsIndirectionCell) { // mov register, [node address] Builder.EmitByte(0x8B); Builder.EmitByte((byte)(0x00 | ((byte)register << 3) | 0x5)); } else { // mov register, immediate Builder.EmitByte((byte)(0xB8 + (byte)register)); } Builder.EmitReloc(node, RelocType.IMAGE_REL_BASED_HIGHLOW, delta); } public void EmitINT3() { Builder.EmitByte(0xCC); } public void EmitRET() { Builder.EmitByte(0xC3); } public void EmitRETIfEqual() { // jne @+1 Builder.EmitByte(0x75); Builder.EmitByte(0x01); // ret Builder.EmitByte(0xC3); } private bool InSignedByteRange(int i) { return i == (int)(sbyte)i; } private void EmitImmediate(int immediate, int size) { switch (size) { case 0: break; case 1: Builder.EmitByte((byte)immediate); break; case 2: Builder.EmitShort((short)immediate); break; case 4: Builder.EmitInt(immediate); break; default: throw new NotImplementedException(); } } private void EmitModRM(byte subOpcode, ref AddrMode addrMode) { byte modRM = (byte)((subOpcode & 0x07) << 3); if (addrMode.BaseReg > Register.None) { Debug.Assert(addrMode.BaseReg >= Register.RegDirect); Register reg = (Register)(addrMode.BaseReg - Register.RegDirect); Builder.EmitByte((byte)(0xC0 | modRM | ((int)reg & 0x07))); } else { byte lowOrderBitsOfBaseReg = (byte)((int)addrMode.BaseReg & 0x07); modRM |= lowOrderBitsOfBaseReg; int offsetSize = 0; if (addrMode.Offset == 0 && (lowOrderBitsOfBaseReg != (byte)Register.EBP)) { offsetSize = 0; } else if (InSignedByteRange(addrMode.Offset)) { offsetSize = 1; modRM |= 0x40; } else { offsetSize = 4; modRM |= 0x80; } bool emitSibByte = false; Register sibByteBaseRegister = addrMode.BaseReg; if (addrMode.BaseReg == Register.None) { emitSibByte = (addrMode.IndexReg != Register.NoIndex); modRM &= 0x38; // set Mod bits to 00 and clear out base reg offsetSize = 4; // this forces 32-bit displacement if (emitSibByte) { // EBP in SIB byte means no base // ModRM base register forced to ESP in SIB code below sibByteBaseRegister = Register.EBP; } else { // EBP in ModRM means no base modRM |= (byte)(Register.EBP); } } else if (lowOrderBitsOfBaseReg == (byte)Register.ESP || addrMode.IndexReg.HasValue) { emitSibByte = true; } if (!emitSibByte) { Builder.EmitByte(modRM); } else { modRM = (byte)((modRM & 0xF8) | (int)Register.ESP); Builder.EmitByte(modRM); int indexRegAsInt = (int)(addrMode.IndexReg.HasValue ? addrMode.IndexReg.Value : Register.ESP); Builder.EmitByte((byte)((addrMode.Scale << 6) + ((indexRegAsInt & 0x07) << 3) + ((int)sibByteBaseRegister & 0x07))); } EmitImmediate(addrMode.Offset, offsetSize); } } private void EmitExtendedOpcode(int opcode) { if ((opcode >> 16) != 0) { if ((opcode >> 24) != 0) { Builder.EmitByte((byte)(opcode >> 24)); } Builder.EmitByte((byte)(opcode >> 16)); } Builder.EmitByte((byte)(opcode >> 8)); } private void EmitIndirInstruction(int opcode, byte subOpcode, ref AddrMode addrMode) { if ((opcode >> 8) != 0) { EmitExtendedOpcode(opcode); } Builder.EmitByte((byte)opcode); EmitModRM(subOpcode, ref addrMode); } } }
// 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 ILCompiler.DependencyAnalysis.X86 { public struct X86Emitter { public X86Emitter(NodeFactory factory, bool relocsOnly) { Builder = new ObjectDataBuilder(factory, relocsOnly); TargetRegister = new TargetRegisterMap(factory.Target.OperatingSystem); } public ObjectDataBuilder Builder; public TargetRegisterMap TargetRegister; public void EmitCMP(ref AddrMode addrMode, sbyte immediate) { if (addrMode.Size == AddrModeSize.Int16) Builder.EmitByte(0x66); EmitIndirInstruction((byte)((addrMode.Size != AddrModeSize.Int8) ? 0x83 : 0x80), 0x7, ref addrMode); Builder.EmitByte((byte)immediate); } public void EmitADD(ref AddrMode addrMode, sbyte immediate) { if (addrMode.Size == AddrModeSize.Int16) Builder.EmitByte(0x66); EmitIndirInstruction((byte)((addrMode.Size != AddrModeSize.Int8) ? 0x83 : 0x80), (byte)0, ref addrMode); Builder.EmitByte((byte)immediate); } public void EmitJMP(ISymbolNode symbol) { if (symbol.RepresentsIndirectionCell) { Builder.EmitByte(0xff); Builder.EmitByte(0x25); Builder.EmitReloc(symbol, RelocType.IMAGE_REL_BASED_HIGHLOW); } else { Builder.EmitByte(0xE9); Builder.EmitReloc(symbol, RelocType.IMAGE_REL_BASED_REL32); } } public void EmitXOR(Register register1, Register register2) { Builder.EmitByte(0x33); Builder.EmitByte((byte)(0xC0 | ((byte)register1 << 3) | (byte)register2)); } public void EmitPUSH(sbyte imm8) { Builder.EmitByte(0x6A); Builder.EmitByte(unchecked((byte)imm8)); } public void EmitPUSH(ISymbolNode node) { if (node.RepresentsIndirectionCell) { // push [node address] Builder.EmitByte(0xFF); Builder.EmitByte(0x35); } else { // push <node address> Builder.EmitByte(0x68); } Builder.EmitReloc(node, RelocType.IMAGE_REL_BASED_HIGHLOW); } public void EmitMOV(Register regDst, Register regSrc) { Builder.EmitByte(0x8B); Builder.EmitByte((byte)(0xC0 | (((int)regDst & 0x07) << 3) | (((int)regSrc & 0x07)))); } public void EmitMOV(Register register, ISymbolNode node, int delta = 0) { if (node.RepresentsIndirectionCell) { // mov register, [node address] Builder.EmitByte(0x8B); Builder.EmitByte((byte)(0x00 | ((byte)register << 3) | 0x5)); } else { // mov register, immediate Builder.EmitByte((byte)(0xB8 + (byte)register)); } Builder.EmitReloc(node, RelocType.IMAGE_REL_BASED_HIGHLOW, delta); } public void EmitINT3() { Builder.EmitByte(0xCC); } public void EmitRET() { Builder.EmitByte(0xC3); } public void EmitRETIfEqual() { // jne @+1 Builder.EmitByte(0x75); Builder.EmitByte(0x01); // ret Builder.EmitByte(0xC3); } private bool InSignedByteRange(int i) { return i == (int)(sbyte)i; } private void EmitImmediate(int immediate, int size) { switch (size) { case 0: break; case 1: Builder.EmitByte((byte)immediate); break; case 2: Builder.EmitShort((short)immediate); break; case 4: Builder.EmitInt(immediate); break; default: throw new NotImplementedException(); } } private void EmitModRM(byte subOpcode, ref AddrMode addrMode) { byte modRM = (byte)((subOpcode & 0x07) << 3); if (addrMode.BaseReg > Register.None) { Debug.Assert(addrMode.BaseReg >= Register.RegDirect); Register reg = (Register)(addrMode.BaseReg - Register.RegDirect); Builder.EmitByte((byte)(0xC0 | modRM | ((int)reg & 0x07))); } else { byte lowOrderBitsOfBaseReg = (byte)((int)addrMode.BaseReg & 0x07); modRM |= lowOrderBitsOfBaseReg; int offsetSize = 0; if (addrMode.Offset == 0 && (lowOrderBitsOfBaseReg != (byte)Register.EBP)) { offsetSize = 0; } else if (InSignedByteRange(addrMode.Offset)) { offsetSize = 1; modRM |= 0x40; } else { offsetSize = 4; modRM |= 0x80; } bool emitSibByte = false; Register sibByteBaseRegister = addrMode.BaseReg; if (addrMode.BaseReg == Register.None) { emitSibByte = (addrMode.IndexReg != Register.NoIndex); modRM &= 0x38; // set Mod bits to 00 and clear out base reg offsetSize = 4; // this forces 32-bit displacement if (emitSibByte) { // EBP in SIB byte means no base // ModRM base register forced to ESP in SIB code below sibByteBaseRegister = Register.EBP; } else { // EBP in ModRM means no base modRM |= (byte)(Register.EBP); } } else if (lowOrderBitsOfBaseReg == (byte)Register.ESP || addrMode.IndexReg.HasValue) { emitSibByte = true; } if (!emitSibByte) { Builder.EmitByte(modRM); } else { modRM = (byte)((modRM & 0xF8) | (int)Register.ESP); Builder.EmitByte(modRM); int indexRegAsInt = (int)(addrMode.IndexReg.HasValue ? addrMode.IndexReg.Value : Register.ESP); Builder.EmitByte((byte)((addrMode.Scale << 6) + ((indexRegAsInt & 0x07) << 3) + ((int)sibByteBaseRegister & 0x07))); } EmitImmediate(addrMode.Offset, offsetSize); } } private void EmitExtendedOpcode(int opcode) { if ((opcode >> 16) != 0) { if ((opcode >> 24) != 0) { Builder.EmitByte((byte)(opcode >> 24)); } Builder.EmitByte((byte)(opcode >> 16)); } Builder.EmitByte((byte)(opcode >> 8)); } private void EmitIndirInstruction(int opcode, byte subOpcode, ref AddrMode addrMode) { if ((opcode >> 8) != 0) { EmitExtendedOpcode(opcode); } Builder.EmitByte((byte)opcode); EmitModRM(subOpcode, ref addrMode); } } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/libraries/Common/tests/System/Xml/XPath/Common/XPathResultToken.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Xml.XPath; namespace XPathTests.Common { public class XPathResultToken { public XPathNodeType NodeType { get; set; } public string BaseURI { get; set; } public bool HasChildren { get; set; } public bool HasAttributes { get; set; } public bool IsEmptyElement { get; set; } public string LocalName { get; set; } public string Name { get; set; } public string NamespaceURI { get; set; } public bool HasNameTable { get; set; } public string Prefix { get; set; } public string Value { get; set; } public string XmlLang { get; set; } public XPathResultToken() { BaseURI = string.Empty; LocalName = string.Empty; Name = string.Empty; NamespaceURI = string.Empty; Prefix = string.Empty; Value = string.Empty; XmlLang = string.Empty; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Xml.XPath; namespace XPathTests.Common { public class XPathResultToken { public XPathNodeType NodeType { get; set; } public string BaseURI { get; set; } public bool HasChildren { get; set; } public bool HasAttributes { get; set; } public bool IsEmptyElement { get; set; } public string LocalName { get; set; } public string Name { get; set; } public string NamespaceURI { get; set; } public bool HasNameTable { get; set; } public string Prefix { get; set; } public string Value { get; set; } public string XmlLang { get; set; } public XPathResultToken() { BaseURI = string.Empty; LocalName = string.Empty; Name = string.Empty; NamespaceURI = string.Empty; Prefix = string.Empty; Value = string.Empty; XmlLang = string.Empty; } } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/tests/GC/Stress/Tests/PlugGaps.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Collections.Generic; public class GCUtil { public static List<GCHandle> list = new List<GCHandle>(); public static List<byte[]> blist = new List<byte[]>(); public static List<GCHandle> list2 = new List<GCHandle>(); public static List<byte[]> blist2 = new List<byte[]>(); public static void Alloc(int numNodes, int percentPinned) { for (int i = 0; i < numNodes; i++) { byte[] b = new byte[10]; b[0] = 0xC; if (i % ((int)(numNodes * (100 / percentPinned))) == 0) { list.Add(GCHandle.Alloc(b, GCHandleType.Pinned)); } blist.Add(b); } } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void FreePins() { foreach (GCHandle gch in list) { gch.Free(); } list.Clear(); blist.Clear(); } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void FreeNonPins() { blist.Clear(); } public static void Alloc2(int numNodes, int percentPinned) { for (int i = 0; i < numNodes; i++) { byte[] b = new byte[10]; b[0] = 0xC; if (i % ((int)(numNodes * (100 / percentPinned))) == 0) { list2.Add(GCHandle.Alloc(b, GCHandleType.Pinned)); } blist2.Add(b); } } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void FreePins2() { foreach (GCHandle gch in list2) { gch.Free(); } list2.Clear(); blist2.Clear(); } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void FreeNonPins2() { blist2.Clear(); } public static void AllocWithGaps() { for (int i = 0; i < 1024 * 1024; i++) { byte[] unpinned = new byte[50]; byte[] pinned = new byte[10]; blist.Add(unpinned); list.Add(GCHandle.Alloc(pinned, GCHandleType.Pinned)); } } } public class Test { public static List<GCHandle> gchList = new List<GCHandle>(); public static List<byte[]> bList = new List<byte[]>(); public static int Main(string[] args) { Console.WriteLine("Beginning phase 1"); GCUtil.AllocWithGaps(); Console.WriteLine("phase 1 complete"); // losing all live references to the unpinned byte arrays // this will fragment the heap with ~50 byte holes GCUtil.FreeNonPins(); GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); Console.WriteLine("Beginning phase 2"); bList = new List<byte[]>(); for (int i = 0; i < 1024 * 1024; i++) { byte[] unpinned = new byte[50]; bList.Add(unpinned); } Console.WriteLine("phase 2 complete"); GC.KeepAlive(gchList); GC.KeepAlive(bList); return 100; } } /* 00 0012df98 5e0f6282 ntdll!KiFastSystemCallRet 01 0012dfe8 5e0f580d mscorwks!CLREventWaitHelper+0x92 [f:\pd7\ndp\clr\src\vm\synch.cpp @ 647] 02 0012e168 5e0f53d7 mscorwks!CLREvent::WaitEx+0x42d [f:\pd7\ndp\clr\src\vm\synch.cpp @ 717] 03 0012e180 5de6eb3f mscorwks!CLREvent::Wait+0x27 [f:\pd7\ndp\clr\src\vm\synch.cpp @ 663] 04 0012e1a0 5de6a7a5 mscorwks!SVR::gc_heap::user_thread_wait+0x5f [f:\pd7\ndp\clr\src\vm\gcee.cpp @ 1876] 05 0012e1b0 5e031909 mscorwks!WKS::gc_heap::concurrent_gc_wait+0xa5 [f:\pd7\ndp\clr\src\vm\gcee.cpp @ 1890] 06 0012e1e8 5e03663d mscorwks!WKS::gc_heap::c_adjust_limits+0x119 [f:\pd7\ndp\clr\src\vm\gc.cpp @ 5834] 07 0012e200 5e04af14 mscorwks!WKS::gc_heap::garbage_collect+0xad [f:\pd7\ndp\clr\src\vm\gc.cpp @ 8357] 08 0012e230 5e032fa7 mscorwks!WKS::GCHeap::GarbageCollectGeneration+0x1e4 [f:\pd7\ndp\clr\src\vm\gc.cpp @ 18941] 09 0012e300 5e04a17b mscorwks!WKS::gc_heap::allocate_more_space+0x97 [f:\pd7\ndp\clr\src\vm\gc.cpp @ 6827] 0a 0012e320 5e04a9e8 mscorwks!WKS::gc_heap::allocate+0x8b [f:\pd7\ndp\clr\src\vm\gc.cpp @ 7185] 0b 0012e3d0 5de64ff6 mscorwks!WKS::GCHeap::Alloc+0x1f8 [f:\pd7\ndp\clr\src\vm\gc.cpp @ 18557] 0c 0012e4dc 5de65ab8 mscorwks!Alloc+0x256 [f:\pd7\ndp\clr\src\vm\gcscan.cpp @ 121] 0d 0012e5d4 5de39ead mscorwks!FastAllocatePrimitiveArray+0x3f8 [f:\pd7\ndp\clr\src\vm\gcscan.cpp @ 999] 0e 0012e798 02c80239 mscorwks!JIT_NewArr1+0x4dd [f:\pd7\ndp\clr\src\vm\jitinterface.cpp @ 15211] 0f 0012e7b0 5db8b98d 445488!Test.Main()+0xe1 10 0012ebe4 5db8b74e mscorwks!CallDescrWorker+0x10d [f:\pd7\ndp\clr\src\vm\class.cpp @ 13371] 11 0012ed44 5de59887 mscorwks!CallDescrWorkerWithHandler+0x22e [f:\pd7\ndp\clr\src\vm\class.cpp @ 13278] 12 0012f13c 5de58ba7 mscorwks!MethodDesc::CallDescr+0xc97 [f:\pd7\ndp\clr\src\vm\method.cpp @ 2046] 13 0012f268 5d993abd mscorwks!MethodDesc::CallTargetWorker+0x297 [f:\pd7\ndp\clr\src\vm\method.cpp @ 1717] 0:000> dt WKS::gc_heap::settings +0x000 condemned_generation : 2 +0x004 promotion : 1 +0x008 compaction : 1 +0x00c heap_expansion : 0 +0x010 concurrent : 1 +0x014 concurrent_compaction : 1 +0x018 demotion : 0 +0x01c card_bundles : 1 +0x020 gen0_reduction_count : 0 +0x024 segment_allocation_failed_count : 0 +0x028 elevation : 3 ( el_locked ) +0x02c reason : 0 ( reason_alloc ) +0x030 pause_mode : 1 ( pause_interactive ) */
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Collections.Generic; public class GCUtil { public static List<GCHandle> list = new List<GCHandle>(); public static List<byte[]> blist = new List<byte[]>(); public static List<GCHandle> list2 = new List<GCHandle>(); public static List<byte[]> blist2 = new List<byte[]>(); public static void Alloc(int numNodes, int percentPinned) { for (int i = 0; i < numNodes; i++) { byte[] b = new byte[10]; b[0] = 0xC; if (i % ((int)(numNodes * (100 / percentPinned))) == 0) { list.Add(GCHandle.Alloc(b, GCHandleType.Pinned)); } blist.Add(b); } } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void FreePins() { foreach (GCHandle gch in list) { gch.Free(); } list.Clear(); blist.Clear(); } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void FreeNonPins() { blist.Clear(); } public static void Alloc2(int numNodes, int percentPinned) { for (int i = 0; i < numNodes; i++) { byte[] b = new byte[10]; b[0] = 0xC; if (i % ((int)(numNodes * (100 / percentPinned))) == 0) { list2.Add(GCHandle.Alloc(b, GCHandleType.Pinned)); } blist2.Add(b); } } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void FreePins2() { foreach (GCHandle gch in list2) { gch.Free(); } list2.Clear(); blist2.Clear(); } [MethodImplAttribute(MethodImplOptions.NoInlining)] public static void FreeNonPins2() { blist2.Clear(); } public static void AllocWithGaps() { for (int i = 0; i < 1024 * 1024; i++) { byte[] unpinned = new byte[50]; byte[] pinned = new byte[10]; blist.Add(unpinned); list.Add(GCHandle.Alloc(pinned, GCHandleType.Pinned)); } } } public class Test { public static List<GCHandle> gchList = new List<GCHandle>(); public static List<byte[]> bList = new List<byte[]>(); public static int Main(string[] args) { Console.WriteLine("Beginning phase 1"); GCUtil.AllocWithGaps(); Console.WriteLine("phase 1 complete"); // losing all live references to the unpinned byte arrays // this will fragment the heap with ~50 byte holes GCUtil.FreeNonPins(); GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); Console.WriteLine("Beginning phase 2"); bList = new List<byte[]>(); for (int i = 0; i < 1024 * 1024; i++) { byte[] unpinned = new byte[50]; bList.Add(unpinned); } Console.WriteLine("phase 2 complete"); GC.KeepAlive(gchList); GC.KeepAlive(bList); return 100; } } /* 00 0012df98 5e0f6282 ntdll!KiFastSystemCallRet 01 0012dfe8 5e0f580d mscorwks!CLREventWaitHelper+0x92 [f:\pd7\ndp\clr\src\vm\synch.cpp @ 647] 02 0012e168 5e0f53d7 mscorwks!CLREvent::WaitEx+0x42d [f:\pd7\ndp\clr\src\vm\synch.cpp @ 717] 03 0012e180 5de6eb3f mscorwks!CLREvent::Wait+0x27 [f:\pd7\ndp\clr\src\vm\synch.cpp @ 663] 04 0012e1a0 5de6a7a5 mscorwks!SVR::gc_heap::user_thread_wait+0x5f [f:\pd7\ndp\clr\src\vm\gcee.cpp @ 1876] 05 0012e1b0 5e031909 mscorwks!WKS::gc_heap::concurrent_gc_wait+0xa5 [f:\pd7\ndp\clr\src\vm\gcee.cpp @ 1890] 06 0012e1e8 5e03663d mscorwks!WKS::gc_heap::c_adjust_limits+0x119 [f:\pd7\ndp\clr\src\vm\gc.cpp @ 5834] 07 0012e200 5e04af14 mscorwks!WKS::gc_heap::garbage_collect+0xad [f:\pd7\ndp\clr\src\vm\gc.cpp @ 8357] 08 0012e230 5e032fa7 mscorwks!WKS::GCHeap::GarbageCollectGeneration+0x1e4 [f:\pd7\ndp\clr\src\vm\gc.cpp @ 18941] 09 0012e300 5e04a17b mscorwks!WKS::gc_heap::allocate_more_space+0x97 [f:\pd7\ndp\clr\src\vm\gc.cpp @ 6827] 0a 0012e320 5e04a9e8 mscorwks!WKS::gc_heap::allocate+0x8b [f:\pd7\ndp\clr\src\vm\gc.cpp @ 7185] 0b 0012e3d0 5de64ff6 mscorwks!WKS::GCHeap::Alloc+0x1f8 [f:\pd7\ndp\clr\src\vm\gc.cpp @ 18557] 0c 0012e4dc 5de65ab8 mscorwks!Alloc+0x256 [f:\pd7\ndp\clr\src\vm\gcscan.cpp @ 121] 0d 0012e5d4 5de39ead mscorwks!FastAllocatePrimitiveArray+0x3f8 [f:\pd7\ndp\clr\src\vm\gcscan.cpp @ 999] 0e 0012e798 02c80239 mscorwks!JIT_NewArr1+0x4dd [f:\pd7\ndp\clr\src\vm\jitinterface.cpp @ 15211] 0f 0012e7b0 5db8b98d 445488!Test.Main()+0xe1 10 0012ebe4 5db8b74e mscorwks!CallDescrWorker+0x10d [f:\pd7\ndp\clr\src\vm\class.cpp @ 13371] 11 0012ed44 5de59887 mscorwks!CallDescrWorkerWithHandler+0x22e [f:\pd7\ndp\clr\src\vm\class.cpp @ 13278] 12 0012f13c 5de58ba7 mscorwks!MethodDesc::CallDescr+0xc97 [f:\pd7\ndp\clr\src\vm\method.cpp @ 2046] 13 0012f268 5d993abd mscorwks!MethodDesc::CallTargetWorker+0x297 [f:\pd7\ndp\clr\src\vm\method.cpp @ 1717] 0:000> dt WKS::gc_heap::settings +0x000 condemned_generation : 2 +0x004 promotion : 1 +0x008 compaction : 1 +0x00c heap_expansion : 0 +0x010 concurrent : 1 +0x014 concurrent_compaction : 1 +0x018 demotion : 0 +0x01c card_bundles : 1 +0x020 gen0_reduction_count : 0 +0x024 segment_allocation_failed_count : 0 +0x028 elevation : 3 ( el_locked ) +0x02c reason : 0 ( reason_alloc ) +0x030 pause_mode : 1 ( pause_interactive ) */
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/libraries/System.Private.DataContractSerialization/src/System/Text/BinHexEncoding.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.Runtime; namespace System.Text { internal sealed class BinHexEncoding : Encoding { public override int GetMaxByteCount(int charCount) { if (charCount < 0) throw new ArgumentOutOfRangeException(nameof(charCount), SR.ValueMustBeNonNegative); if ((charCount % 2) != 0) throw new FormatException(SR.Format(SR.XmlInvalidBinHexLength, charCount.ToString())); return charCount / 2; } public override int GetByteCount(char[] chars, int index, int count) { return GetMaxByteCount(count); } public unsafe override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { ArgumentNullException.ThrowIfNull(chars); if (charIndex < 0) throw new ArgumentOutOfRangeException(nameof(charIndex), SR.ValueMustBeNonNegative); if (charIndex > chars.Length) throw new ArgumentOutOfRangeException(nameof(charIndex), SR.Format(SR.OffsetExceedsBufferSize, chars.Length)); if (charCount < 0) throw new ArgumentOutOfRangeException(nameof(charCount), SR.ValueMustBeNonNegative); if (charCount > chars.Length - charIndex) throw new ArgumentOutOfRangeException(nameof(charCount), SR.Format(SR.SizeExceedsRemainingBufferSpace, chars.Length - charIndex)); ArgumentNullException.ThrowIfNull(bytes); if (byteIndex < 0) throw new ArgumentOutOfRangeException(nameof(byteIndex), SR.ValueMustBeNonNegative); if (byteIndex > bytes.Length) throw new ArgumentOutOfRangeException(nameof(byteIndex), SR.Format(SR.OffsetExceedsBufferSize, bytes.Length)); int byteCount = GetByteCount(chars, charIndex, charCount); if (byteCount < 0 || byteCount > bytes.Length - byteIndex) throw new ArgumentException(SR.XmlArrayTooSmall, nameof(bytes)); if (charCount > 0) { if (!HexConverter.TryDecodeFromUtf16(chars.AsSpan(charIndex, charCount), bytes.AsSpan(byteIndex, byteCount), out int charsProcessed)) { int error = charsProcessed + charIndex; throw new FormatException(SR.Format(SR.XmlInvalidBinHexSequence, new string(chars, error, 2), error)); } } return byteCount; } public override int GetMaxCharCount(int byteCount) { if (byteCount < 0 || byteCount > int.MaxValue / 2) throw new ArgumentOutOfRangeException(nameof(byteCount), SR.Format(SR.ValueMustBeInRange, 0, int.MaxValue / 2)); return byteCount * 2; } public override int GetCharCount(byte[] bytes, int index, int count) { return GetMaxCharCount(count); } public unsafe override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { ArgumentNullException.ThrowIfNull(bytes); if (byteIndex < 0) throw new ArgumentOutOfRangeException(nameof(byteIndex), SR.ValueMustBeNonNegative); if (byteIndex > bytes.Length) throw new ArgumentOutOfRangeException(nameof(byteIndex), SR.Format(SR.OffsetExceedsBufferSize, bytes.Length)); if (byteCount < 0) throw new ArgumentOutOfRangeException(nameof(byteCount), SR.ValueMustBeNonNegative); if (byteCount > bytes.Length - byteIndex) throw new ArgumentOutOfRangeException(nameof(byteCount), SR.Format(SR.SizeExceedsRemainingBufferSpace, bytes.Length - byteIndex)); int charCount = GetCharCount(bytes, byteIndex, byteCount); ArgumentNullException.ThrowIfNull(chars); if (charIndex < 0) throw new ArgumentOutOfRangeException(nameof(charIndex), SR.ValueMustBeNonNegative); if (charIndex > chars.Length) throw new ArgumentOutOfRangeException(nameof(charIndex), SR.Format(SR.OffsetExceedsBufferSize, chars.Length)); if (charCount < 0 || charCount > chars.Length - charIndex) throw new ArgumentException(SR.XmlArrayTooSmall, nameof(chars)); if (byteCount > 0) { HexConverter.EncodeToUtf16(bytes.AsSpan(byteIndex, byteCount), chars.AsSpan(charIndex)); } return charCount; } } }
// 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.Runtime; namespace System.Text { internal sealed class BinHexEncoding : Encoding { public override int GetMaxByteCount(int charCount) { if (charCount < 0) throw new ArgumentOutOfRangeException(nameof(charCount), SR.ValueMustBeNonNegative); if ((charCount % 2) != 0) throw new FormatException(SR.Format(SR.XmlInvalidBinHexLength, charCount.ToString())); return charCount / 2; } public override int GetByteCount(char[] chars, int index, int count) { return GetMaxByteCount(count); } public unsafe override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { ArgumentNullException.ThrowIfNull(chars); if (charIndex < 0) throw new ArgumentOutOfRangeException(nameof(charIndex), SR.ValueMustBeNonNegative); if (charIndex > chars.Length) throw new ArgumentOutOfRangeException(nameof(charIndex), SR.Format(SR.OffsetExceedsBufferSize, chars.Length)); if (charCount < 0) throw new ArgumentOutOfRangeException(nameof(charCount), SR.ValueMustBeNonNegative); if (charCount > chars.Length - charIndex) throw new ArgumentOutOfRangeException(nameof(charCount), SR.Format(SR.SizeExceedsRemainingBufferSpace, chars.Length - charIndex)); ArgumentNullException.ThrowIfNull(bytes); if (byteIndex < 0) throw new ArgumentOutOfRangeException(nameof(byteIndex), SR.ValueMustBeNonNegative); if (byteIndex > bytes.Length) throw new ArgumentOutOfRangeException(nameof(byteIndex), SR.Format(SR.OffsetExceedsBufferSize, bytes.Length)); int byteCount = GetByteCount(chars, charIndex, charCount); if (byteCount < 0 || byteCount > bytes.Length - byteIndex) throw new ArgumentException(SR.XmlArrayTooSmall, nameof(bytes)); if (charCount > 0) { if (!HexConverter.TryDecodeFromUtf16(chars.AsSpan(charIndex, charCount), bytes.AsSpan(byteIndex, byteCount), out int charsProcessed)) { int error = charsProcessed + charIndex; throw new FormatException(SR.Format(SR.XmlInvalidBinHexSequence, new string(chars, error, 2), error)); } } return byteCount; } public override int GetMaxCharCount(int byteCount) { if (byteCount < 0 || byteCount > int.MaxValue / 2) throw new ArgumentOutOfRangeException(nameof(byteCount), SR.Format(SR.ValueMustBeInRange, 0, int.MaxValue / 2)); return byteCount * 2; } public override int GetCharCount(byte[] bytes, int index, int count) { return GetMaxCharCount(count); } public unsafe override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { ArgumentNullException.ThrowIfNull(bytes); if (byteIndex < 0) throw new ArgumentOutOfRangeException(nameof(byteIndex), SR.ValueMustBeNonNegative); if (byteIndex > bytes.Length) throw new ArgumentOutOfRangeException(nameof(byteIndex), SR.Format(SR.OffsetExceedsBufferSize, bytes.Length)); if (byteCount < 0) throw new ArgumentOutOfRangeException(nameof(byteCount), SR.ValueMustBeNonNegative); if (byteCount > bytes.Length - byteIndex) throw new ArgumentOutOfRangeException(nameof(byteCount), SR.Format(SR.SizeExceedsRemainingBufferSpace, bytes.Length - byteIndex)); int charCount = GetCharCount(bytes, byteIndex, byteCount); ArgumentNullException.ThrowIfNull(chars); if (charIndex < 0) throw new ArgumentOutOfRangeException(nameof(charIndex), SR.ValueMustBeNonNegative); if (charIndex > chars.Length) throw new ArgumentOutOfRangeException(nameof(charIndex), SR.Format(SR.OffsetExceedsBufferSize, chars.Length)); if (charCount < 0 || charCount > chars.Length - charIndex) throw new ArgumentException(SR.XmlArrayTooSmall, nameof(chars)); if (byteCount > 0) { HexConverter.EncodeToUtf16(bytes.AsSpan(byteIndex, byteCount), chars.AsSpan(charIndex)); } return charCount; } } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/tests/JIT/HardwareIntrinsics/X86/Sse2/LoadVector128.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\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 LoadVector128Int64() { var test = new SimpleUnaryOpTest__LoadVector128Int64(); 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__LoadVector128Int64 { private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64); private static Int64[] _data = new Int64[Op1ElementCount]; private SimpleUnaryOpTest__DataTable<Int64, Int64> _dataTable; public SimpleUnaryOpTest__LoadVector128Int64() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); } _dataTable = new SimpleUnaryOpTest__DataTable<Int64, Int64>(_data, new Int64[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse2.LoadVector128( (Int64*)(_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(Sse2).GetMethod(nameof(Sse2.LoadVector128), new Type[] { typeof(Int64*) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.inArrayPtr, typeof(Int64*)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(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(Vector128<Int64> firstOp, void* result, [CallerMemberName] string method = "") { Int64[] inArray = new Int64[Op1ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int64>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Int64[] inArray = new Int64[Op1ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (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(inArray, outArray, method); } private void ValidateResult(Int64[] firstOp, Int64[] 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(Sse2)}.{nameof(Sse2.LoadVector128)}<Int64>(Vector128<Int64>): {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 LoadVector128Int64() { var test = new SimpleUnaryOpTest__LoadVector128Int64(); 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__LoadVector128Int64 { private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64); private static Int64[] _data = new Int64[Op1ElementCount]; private SimpleUnaryOpTest__DataTable<Int64, Int64> _dataTable; public SimpleUnaryOpTest__LoadVector128Int64() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); } _dataTable = new SimpleUnaryOpTest__DataTable<Int64, Int64>(_data, new Int64[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse2.LoadVector128( (Int64*)(_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(Sse2).GetMethod(nameof(Sse2.LoadVector128), new Type[] { typeof(Int64*) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.inArrayPtr, typeof(Int64*)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(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(Vector128<Int64> firstOp, void* result, [CallerMemberName] string method = "") { Int64[] inArray = new Int64[Op1ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int64>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Int64[] inArray = new Int64[Op1ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (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(inArray, outArray, method); } private void ValidateResult(Int64[] firstOp, Int64[] 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(Sse2)}.{nameof(Sse2.LoadVector128)}<Int64>(Vector128<Int64>): {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,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/libraries/Common/src/Interop/Windows/WinSock/Interop.WSARecv.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.Net.Sockets; using System.Runtime.InteropServices; using System.Threading; internal static partial class Interop { internal static partial class Winsock { [GeneratedDllImport(Libraries.Ws2_32, SetLastError = true)] internal static unsafe partial SocketError WSARecv( SafeHandle socketHandle, WSABuffer* buffer, int bufferCount, out int bytesTransferred, ref SocketFlags socketFlags, NativeOverlapped* overlapped, IntPtr completionRoutine); internal static unsafe SocketError WSARecv( SafeHandle socketHandle, Span<WSABuffer> buffers, int bufferCount, out int bytesTransferred, ref SocketFlags socketFlags, NativeOverlapped* overlapped, IntPtr completionRoutine) { Debug.Assert(!buffers.IsEmpty); fixed (WSABuffer* buffersPtr = &MemoryMarshal.GetReference(buffers)) { return WSARecv(socketHandle, buffersPtr, bufferCount, out bytesTransferred, ref socketFlags, overlapped, completionRoutine); } } } }
// 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.Net.Sockets; using System.Runtime.InteropServices; using System.Threading; internal static partial class Interop { internal static partial class Winsock { [GeneratedDllImport(Libraries.Ws2_32, SetLastError = true)] internal static unsafe partial SocketError WSARecv( SafeHandle socketHandle, WSABuffer* buffer, int bufferCount, out int bytesTransferred, ref SocketFlags socketFlags, NativeOverlapped* overlapped, IntPtr completionRoutine); internal static unsafe SocketError WSARecv( SafeHandle socketHandle, Span<WSABuffer> buffers, int bufferCount, out int bytesTransferred, ref SocketFlags socketFlags, NativeOverlapped* overlapped, IntPtr completionRoutine) { Debug.Assert(!buffers.IsEmpty); fixed (WSABuffer* buffersPtr = &MemoryMarshal.GetReference(buffers)) { return WSARecv(socketHandle, buffersPtr, bufferCount, out bytesTransferred, ref socketFlags, overlapped, completionRoutine); } } } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/ShiftRightLogical.Vector64.Int32.1.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void ShiftRightLogical_Vector64_Int32_1() { var test = new ImmUnaryOpTest__ShiftRightLogical_Vector64_Int32_1(); 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 ImmUnaryOpTest__ShiftRightLogical_Vector64_Int32_1 { private struct DataTable { private byte[] inArray; private byte[] outArray; private GCHandle inHandle; private GCHandle outHandle; private ulong alignment; public DataTable(Int32[] inArray, Int32[] outArray, int alignment) { int sizeOfinArray = inArray.Length * Unsafe.SizeOf<Int32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle = GCHandle.Alloc(this.inArray, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArrayPtr), ref Unsafe.As<Int32, byte>(ref inArray[0]), (uint)sizeOfinArray); } public void* inArrayPtr => Align((byte*)(inHandle.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<Int32> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref testStruct._fld), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); return testStruct; } public void RunStructFldScenario(ImmUnaryOpTest__ShiftRightLogical_Vector64_Int32_1 testClass) { var result = AdvSimd.ShiftRightLogical(_fld, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(ImmUnaryOpTest__ShiftRightLogical_Vector64_Int32_1 testClass) { fixed (Vector64<Int32>* pFld = &_fld) { var result = AdvSimd.ShiftRightLogical( AdvSimd.LoadVector64((Int32*)(pFld)), 1 ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32); private static readonly byte Imm = 1; private static Int32[] _data = new Int32[Op1ElementCount]; private static Vector64<Int32> _clsVar; private Vector64<Int32> _fld; private DataTable _dataTable; static ImmUnaryOpTest__ShiftRightLogical_Vector64_Int32_1() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _clsVar), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); } public ImmUnaryOpTest__ShiftRightLogical_Vector64_Int32_1() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _fld), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new DataTable(_data, new Int32[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.ShiftRightLogical( Unsafe.Read<Vector64<Int32>>(_dataTable.inArrayPtr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.ShiftRightLogical( AdvSimd.LoadVector64((Int32*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ShiftRightLogical), new Type[] { typeof(Vector64<Int32>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Int32>>(_dataTable.inArrayPtr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ShiftRightLogical), new Type[] { typeof(Vector64<Int32>), typeof(byte) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((Int32*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.ShiftRightLogical( _clsVar, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<Int32>* pClsVar = &_clsVar) { var result = AdvSimd.ShiftRightLogical( AdvSimd.LoadVector64((Int32*)(pClsVar)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector64<Int32>>(_dataTable.inArrayPtr); var result = AdvSimd.ShiftRightLogical(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = AdvSimd.LoadVector64((Int32*)(_dataTable.inArrayPtr)); var result = AdvSimd.ShiftRightLogical(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmUnaryOpTest__ShiftRightLogical_Vector64_Int32_1(); var result = AdvSimd.ShiftRightLogical(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new ImmUnaryOpTest__ShiftRightLogical_Vector64_Int32_1(); fixed (Vector64<Int32>* pFld = &test._fld) { var result = AdvSimd.ShiftRightLogical( AdvSimd.LoadVector64((Int32*)(pFld)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.ShiftRightLogical(_fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<Int32>* pFld = &_fld) { var result = AdvSimd.ShiftRightLogical( AdvSimd.LoadVector64((Int32*)(pFld)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.ShiftRightLogical(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.ShiftRightLogical( AdvSimd.LoadVector64((Int32*)(&test._fld)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector64<Int32> firstOp, void* result, [CallerMemberName] string method = "") { Int32[] inArray = new Int32[Op1ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int32>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Int32[] inArray = new Int32[Op1ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector64<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int32>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(Int32[] firstOp, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.ShiftRightLogical(firstOp[i], Imm) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ShiftRightLogical)}<Int32>(Vector64<Int32>, 1): {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.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void ShiftRightLogical_Vector64_Int32_1() { var test = new ImmUnaryOpTest__ShiftRightLogical_Vector64_Int32_1(); 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 ImmUnaryOpTest__ShiftRightLogical_Vector64_Int32_1 { private struct DataTable { private byte[] inArray; private byte[] outArray; private GCHandle inHandle; private GCHandle outHandle; private ulong alignment; public DataTable(Int32[] inArray, Int32[] outArray, int alignment) { int sizeOfinArray = inArray.Length * Unsafe.SizeOf<Int32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle = GCHandle.Alloc(this.inArray, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArrayPtr), ref Unsafe.As<Int32, byte>(ref inArray[0]), (uint)sizeOfinArray); } public void* inArrayPtr => Align((byte*)(inHandle.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<Int32> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref testStruct._fld), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); return testStruct; } public void RunStructFldScenario(ImmUnaryOpTest__ShiftRightLogical_Vector64_Int32_1 testClass) { var result = AdvSimd.ShiftRightLogical(_fld, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(ImmUnaryOpTest__ShiftRightLogical_Vector64_Int32_1 testClass) { fixed (Vector64<Int32>* pFld = &_fld) { var result = AdvSimd.ShiftRightLogical( AdvSimd.LoadVector64((Int32*)(pFld)), 1 ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32); private static readonly byte Imm = 1; private static Int32[] _data = new Int32[Op1ElementCount]; private static Vector64<Int32> _clsVar; private Vector64<Int32> _fld; private DataTable _dataTable; static ImmUnaryOpTest__ShiftRightLogical_Vector64_Int32_1() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _clsVar), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); } public ImmUnaryOpTest__ShiftRightLogical_Vector64_Int32_1() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _fld), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new DataTable(_data, new Int32[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.ShiftRightLogical( Unsafe.Read<Vector64<Int32>>(_dataTable.inArrayPtr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.ShiftRightLogical( AdvSimd.LoadVector64((Int32*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ShiftRightLogical), new Type[] { typeof(Vector64<Int32>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Int32>>(_dataTable.inArrayPtr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ShiftRightLogical), new Type[] { typeof(Vector64<Int32>), typeof(byte) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((Int32*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.ShiftRightLogical( _clsVar, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<Int32>* pClsVar = &_clsVar) { var result = AdvSimd.ShiftRightLogical( AdvSimd.LoadVector64((Int32*)(pClsVar)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector64<Int32>>(_dataTable.inArrayPtr); var result = AdvSimd.ShiftRightLogical(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = AdvSimd.LoadVector64((Int32*)(_dataTable.inArrayPtr)); var result = AdvSimd.ShiftRightLogical(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmUnaryOpTest__ShiftRightLogical_Vector64_Int32_1(); var result = AdvSimd.ShiftRightLogical(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new ImmUnaryOpTest__ShiftRightLogical_Vector64_Int32_1(); fixed (Vector64<Int32>* pFld = &test._fld) { var result = AdvSimd.ShiftRightLogical( AdvSimd.LoadVector64((Int32*)(pFld)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.ShiftRightLogical(_fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<Int32>* pFld = &_fld) { var result = AdvSimd.ShiftRightLogical( AdvSimd.LoadVector64((Int32*)(pFld)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.ShiftRightLogical(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.ShiftRightLogical( AdvSimd.LoadVector64((Int32*)(&test._fld)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector64<Int32> firstOp, void* result, [CallerMemberName] string method = "") { Int32[] inArray = new Int32[Op1ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int32>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Int32[] inArray = new Int32[Op1ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector64<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int32>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(Int32[] firstOp, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.ShiftRightLogical(firstOp[i], Imm) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ShiftRightLogical)}<Int32>(Vector64<Int32>, 1): {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,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/tests/JIT/CodeGenBringUpTests/DblSubConst.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_DblSubConst { const int Pass = 100; const int Fail = -1; [MethodImplAttribute(MethodImplOptions.NoInlining)] public static double DblSubConst(double x) { return x-1d; } public static int Main() { double y = DblSubConst(1d); Console.WriteLine(y); if (System.Math.Abs(y) <= Double.Epsilon) return Pass; else 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_DblSubConst { const int Pass = 100; const int Fail = -1; [MethodImplAttribute(MethodImplOptions.NoInlining)] public static double DblSubConst(double x) { return x-1d; } public static int Main() { double y = DblSubConst(1d); Console.WriteLine(y); if (System.Math.Abs(y) <= Double.Epsilon) return Pass; else return Fail; } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/FindPal.Android.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Security.Cryptography.X509Certificates { internal sealed partial class FindPal { private static partial IFindPal OpenPal(X509Certificate2Collection findFrom, X509Certificate2Collection copyTo, bool validOnly) { return new AndroidCertificateFinder(findFrom, copyTo, validOnly); } private sealed class AndroidCertificateFinder : ManagedCertificateFinder { public AndroidCertificateFinder(X509Certificate2Collection findFrom, X509Certificate2Collection copyTo, bool validOnly) : base(findFrom, copyTo, validOnly) { } protected override byte[] GetSubjectPublicKeyInfo(X509Certificate2 cert) { AndroidCertificatePal pal = (AndroidCertificatePal)cert.Pal; return pal.SubjectPublicKeyInfo; } protected override X509Certificate2 CloneCertificate(X509Certificate2 cert) { return new X509Certificate2(AndroidCertificatePal.FromOtherCert(cert)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Security.Cryptography.X509Certificates { internal sealed partial class FindPal { private static partial IFindPal OpenPal(X509Certificate2Collection findFrom, X509Certificate2Collection copyTo, bool validOnly) { return new AndroidCertificateFinder(findFrom, copyTo, validOnly); } private sealed class AndroidCertificateFinder : ManagedCertificateFinder { public AndroidCertificateFinder(X509Certificate2Collection findFrom, X509Certificate2Collection copyTo, bool validOnly) : base(findFrom, copyTo, validOnly) { } protected override byte[] GetSubjectPublicKeyInfo(X509Certificate2 cert) { AndroidCertificatePal pal = (AndroidCertificatePal)cert.Pal; return pal.SubjectPublicKeyInfo; } protected override X509Certificate2 CloneCertificate(X509Certificate2 cert) { return new X509Certificate2(AndroidCertificatePal.FromOtherCert(cert)); } } } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/tests/JIT/CodeGenBringUpTests/Array1.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_Array1 { const int Pass = 100; const int Fail = -1; [MethodImplAttribute(MethodImplOptions.NoInlining)] static void Array1(int[] a) { a[1] = 5; } static int Main() { int[] a = {1, 2, 3, 4}; Array1(a); if (a[1] != 5) return Fail; return Pass; } }
// 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_Array1 { const int Pass = 100; const int Fail = -1; [MethodImplAttribute(MethodImplOptions.NoInlining)] static void Array1(int[] a) { a[1] = 5; } static int Main() { int[] a = {1, 2, 3, 4}; Array1(a); if (a[1] != 5) return Fail; return Pass; } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/libraries/System.Private.CoreLib/src/System/IO/TextReader.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.Text; using System.Threading; using System.Threading.Tasks; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Buffers; namespace System.IO { // This abstract base class represents a reader that can read a sequential // stream of characters. This is not intended for reading bytes - // there are methods on the Stream class to read bytes. // A subclass must minimally implement the Peek() and Read() methods. // // This class is intended for character input, not bytes. // There are methods on the Stream class for reading bytes. public abstract partial class TextReader : MarshalByRefObject, IDisposable { // Create our own instance to avoid static field initialization order problems on Mono. public static readonly TextReader Null = new StreamReader.NullStreamReader(); protected TextReader() { } public virtual void Close() { Dispose(true); GC.SuppressFinalize(this); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { } // Returns the next available character without actually reading it from // the input stream. The current position of the TextReader is not changed by // this operation. The returned value is -1 if no further characters are // available. // // This default method simply returns -1. // public virtual int Peek() { return -1; } // Reads the next character from the input stream. The returned value is // -1 if no further characters are available. // // This default method simply returns -1. // public virtual int Read() { return -1; } // Reads a block of characters. This method will read up to // count characters from this TextReader into the // buffer character array starting at position // index. Returns the actual number of characters read. // public virtual int Read(char[] buffer!!, int index, int count) { if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } int n; for (n = 0; n < count; n++) { int ch = Read(); if (ch == -1) break; buffer[index + n] = (char)ch; } return n; } // Reads a span of characters. This method will read up to // count characters from this TextReader into the // span of characters Returns the actual number of characters read. // public virtual int Read(Span<char> buffer) { char[] array = ArrayPool<char>.Shared.Rent(buffer.Length); try { int numRead = Read(array, 0, buffer.Length); if ((uint)numRead > (uint)buffer.Length) { throw new IOException(SR.IO_InvalidReadLength); } new Span<char>(array, 0, numRead).CopyTo(buffer); return numRead; } finally { ArrayPool<char>.Shared.Return(array); } } // Reads all characters from the current position to the end of the // TextReader, and returns them as one string. public virtual string ReadToEnd() { char[] chars = new char[4096]; int len; StringBuilder sb = new StringBuilder(4096); while ((len = Read(chars, 0, chars.Length)) != 0) { sb.Append(chars, 0, len); } return sb.ToString(); } // Blocking version of read. Returns only when count // characters have been read or the end of the file was reached. // public virtual int ReadBlock(char[] buffer, int index, int count) { int i, n = 0; do { n += (i = Read(buffer, index + n, count - n)); } while (i > 0 && n < count); return n; } // Blocking version of read for span of characters. Returns only when count // characters have been read or the end of the file was reached. // public virtual int ReadBlock(Span<char> buffer) { char[] array = ArrayPool<char>.Shared.Rent(buffer.Length); try { int numRead = ReadBlock(array, 0, buffer.Length); if ((uint)numRead > (uint)buffer.Length) { throw new IOException(SR.IO_InvalidReadLength); } new Span<char>(array, 0, numRead).CopyTo(buffer); return numRead; } finally { ArrayPool<char>.Shared.Return(array); } } // Reads a line. A line is defined as a sequence of characters followed by // a carriage return ('\r'), a line feed ('\n'), or a carriage return // immediately followed by a line feed. The resulting string does not // contain the terminating carriage return and/or line feed. The returned // value is null if the end of the input stream has been reached. // public virtual string? ReadLine() { StringBuilder sb = new StringBuilder(); while (true) { int ch = Read(); if (ch == -1) break; if (ch == '\r' || ch == '\n') { if (ch == '\r' && Peek() == '\n') { Read(); } return sb.ToString(); } sb.Append((char)ch); } if (sb.Length > 0) { return sb.ToString(); } return null; } #region Task based Async APIs public virtual Task<string?> ReadLineAsync() => ReadLineCoreAsync(default); /// <summary> /// Reads a line of characters asynchronously and returns the data as a string. /// </summary> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A value task that represents the asynchronous read operation. The value of the <c>TResult</c> /// parameter contains the next line from the text reader, or is <see langword="null" /> if all of the characters have been read.</returns> /// <exception cref="ArgumentOutOfRangeException">The number of characters in the next line is larger than <see cref="int.MaxValue"/>.</exception> /// <exception cref="ObjectDisposedException">The text reader has been disposed.</exception> /// <exception cref="InvalidOperationException">The reader is currently in use by a previous read operation.</exception> /// <remarks> /// <para>The <see cref="TextReader"/> class is an abstract class. Therefore, you do not instantiate it in /// your code. For an example of using the <see cref="ReadLineAsync(CancellationToken)"/> method, see the /// <see cref="StreamReader.ReadLineAsync(CancellationToken)"/> method.</para> /// <para>If the current <see cref="TextReader"/> represents the standard input stream returned by /// the <c>Console.In</c> property, the <see cref="ReadLineAsync(CancellationToken)"/> method /// executes synchronously rather than asynchronously.</para> /// </remarks> public virtual ValueTask<string?> ReadLineAsync(CancellationToken cancellationToken) => new ValueTask<string?>(ReadLineCoreAsync(cancellationToken)); private Task<string?> ReadLineCoreAsync(CancellationToken cancellationToken) => Task<string?>.Factory.StartNew(static state => ((TextReader)state!).ReadLine(), this, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); public virtual Task<string> ReadToEndAsync() => ReadToEndAsync(default); /// <summary> /// Reads all characters from the current position to the end of the text reader asynchronously and returns them as one string. /// </summary> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task that represents the asynchronous read operation. The value of the <c>TResult</c> parameter contains /// a string with the characters from the current position to the end of the text reader.</returns> /// <exception cref="ArgumentOutOfRangeException">The number of characters is larger than <see cref="int.MaxValue"/>.</exception> /// <exception cref="ObjectDisposedException">The text reader has been disposed.</exception> /// <exception cref="InvalidOperationException">The reader is currently in use by a previous read operation.</exception> /// <remarks> /// <para>The <see cref="TextReader"/> class is an abstract class. Therefore, you do not instantiate it in /// your code. For an example of using the <see cref="ReadToEndAsync(CancellationToken)"/> method, see the /// <see cref="StreamReader.ReadToEndAsync(CancellationToken)"/> method.</para> /// </remarks> public virtual async Task<string> ReadToEndAsync(CancellationToken cancellationToken) { var sb = new StringBuilder(4096); char[] chars = ArrayPool<char>.Shared.Rent(4096); try { int len; while ((len = await ReadAsyncInternal(chars, cancellationToken).ConfigureAwait(false)) != 0) { sb.Append(chars, 0, len); } } finally { ArrayPool<char>.Shared.Return(chars); } return sb.ToString(); } public virtual Task<int> ReadAsync(char[] buffer!!, int index, int count) { if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } return ReadAsyncInternal(new Memory<char>(buffer, index, count), default).AsTask(); } public virtual ValueTask<int> ReadAsync(Memory<char> buffer, CancellationToken cancellationToken = default) => new ValueTask<int>(MemoryMarshal.TryGetArray(buffer, out ArraySegment<char> array) ? ReadAsync(array.Array!, array.Offset, array.Count) : Task<int>.Factory.StartNew(static state => { var t = (TupleSlim<TextReader, Memory<char>>)state!; return t.Item1.Read(t.Item2.Span); }, new TupleSlim<TextReader, Memory<char>>(this, buffer), cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default)); internal virtual ValueTask<int> ReadAsyncInternal(Memory<char> buffer, CancellationToken cancellationToken) => new ValueTask<int>(Task<int>.Factory.StartNew(static state => { var t = (TupleSlim<TextReader, Memory<char>>)state!; return t.Item1.Read(t.Item2.Span); }, new TupleSlim<TextReader, Memory<char>>(this, buffer), cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default)); public virtual Task<int> ReadBlockAsync(char[] buffer!!, int index, int count) { if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } return ReadBlockAsyncInternal(new Memory<char>(buffer, index, count), default).AsTask(); } public virtual ValueTask<int> ReadBlockAsync(Memory<char> buffer, CancellationToken cancellationToken = default) => new ValueTask<int>(MemoryMarshal.TryGetArray(buffer, out ArraySegment<char> array) ? ReadBlockAsync(array.Array!, array.Offset, array.Count) : Task<int>.Factory.StartNew(static state => { var t = (TupleSlim<TextReader, Memory<char>>)state!; return t.Item1.ReadBlock(t.Item2.Span); }, new TupleSlim<TextReader, Memory<char>>(this, buffer), cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default)); internal async ValueTask<int> ReadBlockAsyncInternal(Memory<char> buffer, CancellationToken cancellationToken) { int n = 0, i; do { i = await ReadAsyncInternal(buffer.Slice(n), cancellationToken).ConfigureAwait(false); n += i; } while (i > 0 && n < buffer.Length); return n; } #endregion public static TextReader Synchronized(TextReader reader!!) { return reader is SyncTextReader ? reader : new SyncTextReader(reader); } internal sealed class SyncTextReader : TextReader { internal readonly TextReader _in; internal SyncTextReader(TextReader t) { _in = t; } [MethodImpl(MethodImplOptions.Synchronized)] public override void Close() => _in.Close(); [MethodImpl(MethodImplOptions.Synchronized)] protected override void Dispose(bool disposing) { // Explicitly pick up a potentially methodimpl'ed Dispose if (disposing) ((IDisposable)_in).Dispose(); } [MethodImpl(MethodImplOptions.Synchronized)] public override int Peek() => _in.Peek(); [MethodImpl(MethodImplOptions.Synchronized)] public override int Read() => _in.Read(); [MethodImpl(MethodImplOptions.Synchronized)] public override int Read(char[] buffer, int index, int count) => _in.Read(buffer, index, count); [MethodImpl(MethodImplOptions.Synchronized)] public override int ReadBlock(char[] buffer, int index, int count) => _in.ReadBlock(buffer, index, count); [MethodImpl(MethodImplOptions.Synchronized)] public override string? ReadLine() => _in.ReadLine(); [MethodImpl(MethodImplOptions.Synchronized)] public override string ReadToEnd() => _in.ReadToEnd(); // // On SyncTextReader all APIs should run synchronously, even the async ones. // [MethodImpl(MethodImplOptions.Synchronized)] public override Task<string?> ReadLineAsync() => Task.FromResult(ReadLine()); [MethodImpl(MethodImplOptions.Synchronized)] public override ValueTask<string?> ReadLineAsync(CancellationToken cancellationToken) => cancellationToken.IsCancellationRequested ? ValueTask.FromCanceled<string?>(cancellationToken) : new ValueTask<string?>(ReadLine()); [MethodImpl(MethodImplOptions.Synchronized)] public override Task<string> ReadToEndAsync() => Task.FromResult(ReadToEnd()); [MethodImpl(MethodImplOptions.Synchronized)] public override Task<string> ReadToEndAsync(CancellationToken cancellationToken) => cancellationToken.IsCancellationRequested ? Task.FromCanceled<string>(cancellationToken) : Task.FromResult(ReadToEnd()); [MethodImpl(MethodImplOptions.Synchronized)] public override Task<int> ReadBlockAsync(char[] buffer!!, int index, int count) { if (index < 0 || count < 0) throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); return Task.FromResult(ReadBlock(buffer, index, count)); } [MethodImpl(MethodImplOptions.Synchronized)] public override Task<int> ReadAsync(char[] buffer!!, int index, int count) { if (index < 0 || count < 0) throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); return Task.FromResult(Read(buffer, index, count)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Text; using System.Threading; using System.Threading.Tasks; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Buffers; namespace System.IO { // This abstract base class represents a reader that can read a sequential // stream of characters. This is not intended for reading bytes - // there are methods on the Stream class to read bytes. // A subclass must minimally implement the Peek() and Read() methods. // // This class is intended for character input, not bytes. // There are methods on the Stream class for reading bytes. public abstract partial class TextReader : MarshalByRefObject, IDisposable { // Create our own instance to avoid static field initialization order problems on Mono. public static readonly TextReader Null = new StreamReader.NullStreamReader(); protected TextReader() { } public virtual void Close() { Dispose(true); GC.SuppressFinalize(this); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { } // Returns the next available character without actually reading it from // the input stream. The current position of the TextReader is not changed by // this operation. The returned value is -1 if no further characters are // available. // // This default method simply returns -1. // public virtual int Peek() { return -1; } // Reads the next character from the input stream. The returned value is // -1 if no further characters are available. // // This default method simply returns -1. // public virtual int Read() { return -1; } // Reads a block of characters. This method will read up to // count characters from this TextReader into the // buffer character array starting at position // index. Returns the actual number of characters read. // public virtual int Read(char[] buffer!!, int index, int count) { if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } int n; for (n = 0; n < count; n++) { int ch = Read(); if (ch == -1) break; buffer[index + n] = (char)ch; } return n; } // Reads a span of characters. This method will read up to // count characters from this TextReader into the // span of characters Returns the actual number of characters read. // public virtual int Read(Span<char> buffer) { char[] array = ArrayPool<char>.Shared.Rent(buffer.Length); try { int numRead = Read(array, 0, buffer.Length); if ((uint)numRead > (uint)buffer.Length) { throw new IOException(SR.IO_InvalidReadLength); } new Span<char>(array, 0, numRead).CopyTo(buffer); return numRead; } finally { ArrayPool<char>.Shared.Return(array); } } // Reads all characters from the current position to the end of the // TextReader, and returns them as one string. public virtual string ReadToEnd() { char[] chars = new char[4096]; int len; StringBuilder sb = new StringBuilder(4096); while ((len = Read(chars, 0, chars.Length)) != 0) { sb.Append(chars, 0, len); } return sb.ToString(); } // Blocking version of read. Returns only when count // characters have been read or the end of the file was reached. // public virtual int ReadBlock(char[] buffer, int index, int count) { int i, n = 0; do { n += (i = Read(buffer, index + n, count - n)); } while (i > 0 && n < count); return n; } // Blocking version of read for span of characters. Returns only when count // characters have been read or the end of the file was reached. // public virtual int ReadBlock(Span<char> buffer) { char[] array = ArrayPool<char>.Shared.Rent(buffer.Length); try { int numRead = ReadBlock(array, 0, buffer.Length); if ((uint)numRead > (uint)buffer.Length) { throw new IOException(SR.IO_InvalidReadLength); } new Span<char>(array, 0, numRead).CopyTo(buffer); return numRead; } finally { ArrayPool<char>.Shared.Return(array); } } // Reads a line. A line is defined as a sequence of characters followed by // a carriage return ('\r'), a line feed ('\n'), or a carriage return // immediately followed by a line feed. The resulting string does not // contain the terminating carriage return and/or line feed. The returned // value is null if the end of the input stream has been reached. // public virtual string? ReadLine() { StringBuilder sb = new StringBuilder(); while (true) { int ch = Read(); if (ch == -1) break; if (ch == '\r' || ch == '\n') { if (ch == '\r' && Peek() == '\n') { Read(); } return sb.ToString(); } sb.Append((char)ch); } if (sb.Length > 0) { return sb.ToString(); } return null; } #region Task based Async APIs public virtual Task<string?> ReadLineAsync() => ReadLineCoreAsync(default); /// <summary> /// Reads a line of characters asynchronously and returns the data as a string. /// </summary> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A value task that represents the asynchronous read operation. The value of the <c>TResult</c> /// parameter contains the next line from the text reader, or is <see langword="null" /> if all of the characters have been read.</returns> /// <exception cref="ArgumentOutOfRangeException">The number of characters in the next line is larger than <see cref="int.MaxValue"/>.</exception> /// <exception cref="ObjectDisposedException">The text reader has been disposed.</exception> /// <exception cref="InvalidOperationException">The reader is currently in use by a previous read operation.</exception> /// <remarks> /// <para>The <see cref="TextReader"/> class is an abstract class. Therefore, you do not instantiate it in /// your code. For an example of using the <see cref="ReadLineAsync(CancellationToken)"/> method, see the /// <see cref="StreamReader.ReadLineAsync(CancellationToken)"/> method.</para> /// <para>If the current <see cref="TextReader"/> represents the standard input stream returned by /// the <c>Console.In</c> property, the <see cref="ReadLineAsync(CancellationToken)"/> method /// executes synchronously rather than asynchronously.</para> /// </remarks> public virtual ValueTask<string?> ReadLineAsync(CancellationToken cancellationToken) => new ValueTask<string?>(ReadLineCoreAsync(cancellationToken)); private Task<string?> ReadLineCoreAsync(CancellationToken cancellationToken) => Task<string?>.Factory.StartNew(static state => ((TextReader)state!).ReadLine(), this, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); public virtual Task<string> ReadToEndAsync() => ReadToEndAsync(default); /// <summary> /// Reads all characters from the current position to the end of the text reader asynchronously and returns them as one string. /// </summary> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task that represents the asynchronous read operation. The value of the <c>TResult</c> parameter contains /// a string with the characters from the current position to the end of the text reader.</returns> /// <exception cref="ArgumentOutOfRangeException">The number of characters is larger than <see cref="int.MaxValue"/>.</exception> /// <exception cref="ObjectDisposedException">The text reader has been disposed.</exception> /// <exception cref="InvalidOperationException">The reader is currently in use by a previous read operation.</exception> /// <remarks> /// <para>The <see cref="TextReader"/> class is an abstract class. Therefore, you do not instantiate it in /// your code. For an example of using the <see cref="ReadToEndAsync(CancellationToken)"/> method, see the /// <see cref="StreamReader.ReadToEndAsync(CancellationToken)"/> method.</para> /// </remarks> public virtual async Task<string> ReadToEndAsync(CancellationToken cancellationToken) { var sb = new StringBuilder(4096); char[] chars = ArrayPool<char>.Shared.Rent(4096); try { int len; while ((len = await ReadAsyncInternal(chars, cancellationToken).ConfigureAwait(false)) != 0) { sb.Append(chars, 0, len); } } finally { ArrayPool<char>.Shared.Return(chars); } return sb.ToString(); } public virtual Task<int> ReadAsync(char[] buffer!!, int index, int count) { if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } return ReadAsyncInternal(new Memory<char>(buffer, index, count), default).AsTask(); } public virtual ValueTask<int> ReadAsync(Memory<char> buffer, CancellationToken cancellationToken = default) => new ValueTask<int>(MemoryMarshal.TryGetArray(buffer, out ArraySegment<char> array) ? ReadAsync(array.Array!, array.Offset, array.Count) : Task<int>.Factory.StartNew(static state => { var t = (TupleSlim<TextReader, Memory<char>>)state!; return t.Item1.Read(t.Item2.Span); }, new TupleSlim<TextReader, Memory<char>>(this, buffer), cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default)); internal virtual ValueTask<int> ReadAsyncInternal(Memory<char> buffer, CancellationToken cancellationToken) => new ValueTask<int>(Task<int>.Factory.StartNew(static state => { var t = (TupleSlim<TextReader, Memory<char>>)state!; return t.Item1.Read(t.Item2.Span); }, new TupleSlim<TextReader, Memory<char>>(this, buffer), cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default)); public virtual Task<int> ReadBlockAsync(char[] buffer!!, int index, int count) { if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } return ReadBlockAsyncInternal(new Memory<char>(buffer, index, count), default).AsTask(); } public virtual ValueTask<int> ReadBlockAsync(Memory<char> buffer, CancellationToken cancellationToken = default) => new ValueTask<int>(MemoryMarshal.TryGetArray(buffer, out ArraySegment<char> array) ? ReadBlockAsync(array.Array!, array.Offset, array.Count) : Task<int>.Factory.StartNew(static state => { var t = (TupleSlim<TextReader, Memory<char>>)state!; return t.Item1.ReadBlock(t.Item2.Span); }, new TupleSlim<TextReader, Memory<char>>(this, buffer), cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default)); internal async ValueTask<int> ReadBlockAsyncInternal(Memory<char> buffer, CancellationToken cancellationToken) { int n = 0, i; do { i = await ReadAsyncInternal(buffer.Slice(n), cancellationToken).ConfigureAwait(false); n += i; } while (i > 0 && n < buffer.Length); return n; } #endregion public static TextReader Synchronized(TextReader reader!!) { return reader is SyncTextReader ? reader : new SyncTextReader(reader); } internal sealed class SyncTextReader : TextReader { internal readonly TextReader _in; internal SyncTextReader(TextReader t) { _in = t; } [MethodImpl(MethodImplOptions.Synchronized)] public override void Close() => _in.Close(); [MethodImpl(MethodImplOptions.Synchronized)] protected override void Dispose(bool disposing) { // Explicitly pick up a potentially methodimpl'ed Dispose if (disposing) ((IDisposable)_in).Dispose(); } [MethodImpl(MethodImplOptions.Synchronized)] public override int Peek() => _in.Peek(); [MethodImpl(MethodImplOptions.Synchronized)] public override int Read() => _in.Read(); [MethodImpl(MethodImplOptions.Synchronized)] public override int Read(char[] buffer, int index, int count) => _in.Read(buffer, index, count); [MethodImpl(MethodImplOptions.Synchronized)] public override int ReadBlock(char[] buffer, int index, int count) => _in.ReadBlock(buffer, index, count); [MethodImpl(MethodImplOptions.Synchronized)] public override string? ReadLine() => _in.ReadLine(); [MethodImpl(MethodImplOptions.Synchronized)] public override string ReadToEnd() => _in.ReadToEnd(); // // On SyncTextReader all APIs should run synchronously, even the async ones. // [MethodImpl(MethodImplOptions.Synchronized)] public override Task<string?> ReadLineAsync() => Task.FromResult(ReadLine()); [MethodImpl(MethodImplOptions.Synchronized)] public override ValueTask<string?> ReadLineAsync(CancellationToken cancellationToken) => cancellationToken.IsCancellationRequested ? ValueTask.FromCanceled<string?>(cancellationToken) : new ValueTask<string?>(ReadLine()); [MethodImpl(MethodImplOptions.Synchronized)] public override Task<string> ReadToEndAsync() => Task.FromResult(ReadToEnd()); [MethodImpl(MethodImplOptions.Synchronized)] public override Task<string> ReadToEndAsync(CancellationToken cancellationToken) => cancellationToken.IsCancellationRequested ? Task.FromCanceled<string>(cancellationToken) : Task.FromResult(ReadToEnd()); [MethodImpl(MethodImplOptions.Synchronized)] public override Task<int> ReadBlockAsync(char[] buffer!!, int index, int count) { if (index < 0 || count < 0) throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); return Task.FromResult(ReadBlock(buffer, index, count)); } [MethodImpl(MethodImplOptions.Synchronized)] public override Task<int> ReadAsync(char[] buffer!!, int index, int count) { if (index < 0 || count < 0) throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - index < count) throw new ArgumentException(SR.Argument_InvalidOffLen); return Task.FromResult(Read(buffer, index, count)); } } } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/Windows/KeyAgreeRecipientInfoPalWindows.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.Security.Cryptography; using System.Security.Cryptography.Pkcs; using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; using static Interop.Crypt32; namespace Internal.Cryptography.Pal.Windows { internal sealed class KeyAgreeRecipientInfoPalWindows : KeyAgreeRecipientInfoPal { internal KeyAgreeRecipientInfoPalWindows(SafeHandle pCmsgCmsRecipientInfoMemory, int index, int subIndex) : base() { _pCmsgCmsRecipientInfoMemory = pCmsgCmsRecipientInfoMemory; Index = index; SubIndex = subIndex; } public sealed override int Version { get { unsafe { return WithCmsgCmsRecipientInfo<int>( delegate (CMSG_KEY_AGREE_RECIPIENT_INFO* recipient) { return recipient->dwVersion; }); } } } public sealed override SubjectIdentifier RecipientIdentifier { get { unsafe { return WithCmsgCmsRecipientInfo<SubjectIdentifier>( delegate (CMSG_KEY_AGREE_RECIPIENT_INFO* recipient) { CMSG_RECIPIENT_ENCRYPTED_KEY_INFO* pEncryptedKeyInfo = recipient->rgpRecipientEncryptedKeys[SubIndex]; return pEncryptedKeyInfo->RecipientId.ToSubjectIdentifier(); }); } } } public sealed override AlgorithmIdentifier KeyEncryptionAlgorithm { get { unsafe { return WithCmsgCmsRecipientInfo<AlgorithmIdentifier>( delegate (CMSG_KEY_AGREE_RECIPIENT_INFO* recipient) { return recipient->KeyEncryptionAlgorithm.ToAlgorithmIdentifier(); }); } } } public sealed override byte[] EncryptedKey { get { unsafe { return WithCmsgCmsRecipientInfo<byte[]>( delegate (CMSG_KEY_AGREE_RECIPIENT_INFO* recipient) { CMSG_RECIPIENT_ENCRYPTED_KEY_INFO* pEncryptedKeyInfo = recipient->rgpRecipientEncryptedKeys[SubIndex]; return pEncryptedKeyInfo->EncryptedKey.ToByteArray(); }); } } } public sealed override SubjectIdentifierOrKey OriginatorIdentifierOrKey { get { unsafe { return WithCmsgCmsRecipientInfo<SubjectIdentifierOrKey>( delegate (CMSG_KEY_AGREE_RECIPIENT_INFO* recipient) { CMsgKeyAgreeOriginatorChoice originatorChoice = recipient->dwOriginatorChoice; return originatorChoice switch { CMsgKeyAgreeOriginatorChoice.CMSG_KEY_AGREE_ORIGINATOR_CERT => recipient->OriginatorCertId.ToSubjectIdentifierOrKey(), CMsgKeyAgreeOriginatorChoice.CMSG_KEY_AGREE_ORIGINATOR_PUBLIC_KEY => recipient->OriginatorPublicKeyInfo.ToSubjectIdentifierOrKey(), _ => throw new CryptographicException(SR.Format(SR.Cryptography_Cms_Invalid_Originator_Identifier_Choice, originatorChoice)), }; }); } } } public sealed override DateTime Date { get { if (RecipientIdentifier.Type != SubjectIdentifierType.SubjectKeyIdentifier) throw new InvalidOperationException(SR.Cryptography_Cms_Key_Agree_Date_Not_Available); unsafe { return WithCmsgCmsRecipientInfo<DateTime>( delegate (CMSG_KEY_AGREE_RECIPIENT_INFO* recipient) { CMSG_RECIPIENT_ENCRYPTED_KEY_INFO* pEncryptedKeyInfo = recipient->rgpRecipientEncryptedKeys[SubIndex]; long date = (((long)pEncryptedKeyInfo->Date.ftTimeHigh) << 32) | ((long)pEncryptedKeyInfo->Date.ftTimeLow); DateTime dateTime = DateTime.FromFileTimeUtc(date); return dateTime; }); } } } public sealed override CryptographicAttributeObject? OtherKeyAttribute { get { if (RecipientIdentifier.Type != SubjectIdentifierType.SubjectKeyIdentifier) throw new InvalidOperationException(SR.Cryptography_Cms_Key_Agree_Date_Not_Available); unsafe { return WithCmsgCmsRecipientInfo<CryptographicAttributeObject?>( delegate (CMSG_KEY_AGREE_RECIPIENT_INFO* recipient) { CMSG_RECIPIENT_ENCRYPTED_KEY_INFO* pEncryptedKeyInfo = recipient->rgpRecipientEncryptedKeys[SubIndex]; CRYPT_ATTRIBUTE_TYPE_VALUE* pCryptAttributeTypeValue = pEncryptedKeyInfo->pOtherAttr; if (pCryptAttributeTypeValue == null) return null; string oidValue = pCryptAttributeTypeValue->pszObjId.ToStringAnsi(); Oid oid = Oid.FromOidValue(oidValue, OidGroup.All); byte[] rawData = pCryptAttributeTypeValue->Value.ToByteArray(); Pkcs9AttributeObject pkcs9AttributeObject = new Pkcs9AttributeObject(oid, rawData); AsnEncodedDataCollection values = new AsnEncodedDataCollection(pkcs9AttributeObject); return new CryptographicAttributeObject(oid, values); }); } } } internal int Index { get; } internal int SubIndex { get; } // Provides access to the native CMSG_KEY_TRANS_RECIPIENT_INFO* structure. This helper is structured as taking a delegate to // help avoid the easy trap of forgetting to prevent the underlying memory block from being GC'd early. internal T WithCmsgCmsRecipientInfo<T>(KeyAgreeReceiver<T> receiver) { unsafe { CMSG_CMS_RECIPIENT_INFO* pRecipientInfo = (CMSG_CMS_RECIPIENT_INFO*)(_pCmsgCmsRecipientInfoMemory.DangerousGetHandle()); CMSG_KEY_AGREE_RECIPIENT_INFO* pKeyAgree = pRecipientInfo->KeyAgree; T value = receiver(pKeyAgree); GC.KeepAlive(_pCmsgCmsRecipientInfoMemory); return value; } } internal unsafe delegate T KeyAgreeReceiver<T>(CMSG_KEY_AGREE_RECIPIENT_INFO* recipient); // This is the backing store for the CMSG_CMS_RECIPIENT_INFO* structure for this RecipientInfo. CMSG_CMS_RECIPIENT_INFO is full of interior // pointers so we store in a native heap block to keep it pinned. private readonly SafeHandle _pCmsgCmsRecipientInfoMemory; } }
// 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.Security.Cryptography; using System.Security.Cryptography.Pkcs; using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; using static Interop.Crypt32; namespace Internal.Cryptography.Pal.Windows { internal sealed class KeyAgreeRecipientInfoPalWindows : KeyAgreeRecipientInfoPal { internal KeyAgreeRecipientInfoPalWindows(SafeHandle pCmsgCmsRecipientInfoMemory, int index, int subIndex) : base() { _pCmsgCmsRecipientInfoMemory = pCmsgCmsRecipientInfoMemory; Index = index; SubIndex = subIndex; } public sealed override int Version { get { unsafe { return WithCmsgCmsRecipientInfo<int>( delegate (CMSG_KEY_AGREE_RECIPIENT_INFO* recipient) { return recipient->dwVersion; }); } } } public sealed override SubjectIdentifier RecipientIdentifier { get { unsafe { return WithCmsgCmsRecipientInfo<SubjectIdentifier>( delegate (CMSG_KEY_AGREE_RECIPIENT_INFO* recipient) { CMSG_RECIPIENT_ENCRYPTED_KEY_INFO* pEncryptedKeyInfo = recipient->rgpRecipientEncryptedKeys[SubIndex]; return pEncryptedKeyInfo->RecipientId.ToSubjectIdentifier(); }); } } } public sealed override AlgorithmIdentifier KeyEncryptionAlgorithm { get { unsafe { return WithCmsgCmsRecipientInfo<AlgorithmIdentifier>( delegate (CMSG_KEY_AGREE_RECIPIENT_INFO* recipient) { return recipient->KeyEncryptionAlgorithm.ToAlgorithmIdentifier(); }); } } } public sealed override byte[] EncryptedKey { get { unsafe { return WithCmsgCmsRecipientInfo<byte[]>( delegate (CMSG_KEY_AGREE_RECIPIENT_INFO* recipient) { CMSG_RECIPIENT_ENCRYPTED_KEY_INFO* pEncryptedKeyInfo = recipient->rgpRecipientEncryptedKeys[SubIndex]; return pEncryptedKeyInfo->EncryptedKey.ToByteArray(); }); } } } public sealed override SubjectIdentifierOrKey OriginatorIdentifierOrKey { get { unsafe { return WithCmsgCmsRecipientInfo<SubjectIdentifierOrKey>( delegate (CMSG_KEY_AGREE_RECIPIENT_INFO* recipient) { CMsgKeyAgreeOriginatorChoice originatorChoice = recipient->dwOriginatorChoice; return originatorChoice switch { CMsgKeyAgreeOriginatorChoice.CMSG_KEY_AGREE_ORIGINATOR_CERT => recipient->OriginatorCertId.ToSubjectIdentifierOrKey(), CMsgKeyAgreeOriginatorChoice.CMSG_KEY_AGREE_ORIGINATOR_PUBLIC_KEY => recipient->OriginatorPublicKeyInfo.ToSubjectIdentifierOrKey(), _ => throw new CryptographicException(SR.Format(SR.Cryptography_Cms_Invalid_Originator_Identifier_Choice, originatorChoice)), }; }); } } } public sealed override DateTime Date { get { if (RecipientIdentifier.Type != SubjectIdentifierType.SubjectKeyIdentifier) throw new InvalidOperationException(SR.Cryptography_Cms_Key_Agree_Date_Not_Available); unsafe { return WithCmsgCmsRecipientInfo<DateTime>( delegate (CMSG_KEY_AGREE_RECIPIENT_INFO* recipient) { CMSG_RECIPIENT_ENCRYPTED_KEY_INFO* pEncryptedKeyInfo = recipient->rgpRecipientEncryptedKeys[SubIndex]; long date = (((long)pEncryptedKeyInfo->Date.ftTimeHigh) << 32) | ((long)pEncryptedKeyInfo->Date.ftTimeLow); DateTime dateTime = DateTime.FromFileTimeUtc(date); return dateTime; }); } } } public sealed override CryptographicAttributeObject? OtherKeyAttribute { get { if (RecipientIdentifier.Type != SubjectIdentifierType.SubjectKeyIdentifier) throw new InvalidOperationException(SR.Cryptography_Cms_Key_Agree_Date_Not_Available); unsafe { return WithCmsgCmsRecipientInfo<CryptographicAttributeObject?>( delegate (CMSG_KEY_AGREE_RECIPIENT_INFO* recipient) { CMSG_RECIPIENT_ENCRYPTED_KEY_INFO* pEncryptedKeyInfo = recipient->rgpRecipientEncryptedKeys[SubIndex]; CRYPT_ATTRIBUTE_TYPE_VALUE* pCryptAttributeTypeValue = pEncryptedKeyInfo->pOtherAttr; if (pCryptAttributeTypeValue == null) return null; string oidValue = pCryptAttributeTypeValue->pszObjId.ToStringAnsi(); Oid oid = Oid.FromOidValue(oidValue, OidGroup.All); byte[] rawData = pCryptAttributeTypeValue->Value.ToByteArray(); Pkcs9AttributeObject pkcs9AttributeObject = new Pkcs9AttributeObject(oid, rawData); AsnEncodedDataCollection values = new AsnEncodedDataCollection(pkcs9AttributeObject); return new CryptographicAttributeObject(oid, values); }); } } } internal int Index { get; } internal int SubIndex { get; } // Provides access to the native CMSG_KEY_TRANS_RECIPIENT_INFO* structure. This helper is structured as taking a delegate to // help avoid the easy trap of forgetting to prevent the underlying memory block from being GC'd early. internal T WithCmsgCmsRecipientInfo<T>(KeyAgreeReceiver<T> receiver) { unsafe { CMSG_CMS_RECIPIENT_INFO* pRecipientInfo = (CMSG_CMS_RECIPIENT_INFO*)(_pCmsgCmsRecipientInfoMemory.DangerousGetHandle()); CMSG_KEY_AGREE_RECIPIENT_INFO* pKeyAgree = pRecipientInfo->KeyAgree; T value = receiver(pKeyAgree); GC.KeepAlive(_pCmsgCmsRecipientInfoMemory); return value; } } internal unsafe delegate T KeyAgreeReceiver<T>(CMSG_KEY_AGREE_RECIPIENT_INFO* recipient); // This is the backing store for the CMSG_CMS_RECIPIENT_INFO* structure for this RecipientInfo. CMSG_CMS_RECIPIENT_INFO is full of interior // pointers so we store in a native heap block to keep it pinned. private readonly SafeHandle _pCmsgCmsRecipientInfoMemory; } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/libraries/Common/src/System/Net/Sockets/SocketErrorPal.Unix.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; namespace System.Net.Sockets { internal static class SocketErrorPal { #if DEBUG static SocketErrorPal() { Debug.Assert(s_nativeErrorToSocketError.Count == NativeErrorToSocketErrorCount, $"Expected s_nativeErrorToSocketError to have {NativeErrorToSocketErrorCount} count instead of {s_nativeErrorToSocketError.Count}."); Debug.Assert(s_socketErrorToNativeError.Count == SocketErrorToNativeErrorCount, $"Expected s_socketErrorToNativeError to have {SocketErrorToNativeErrorCount} count instead of {s_socketErrorToNativeError.Count}."); } #endif private const int NativeErrorToSocketErrorCount = 42; private const int SocketErrorToNativeErrorCount = 41; // No Interop.Errors are included for the following SocketErrors, as there's no good mapping: // - SocketError.NoRecovery // - SocketError.NotInitialized // - SocketError.ProcessLimit // - SocketError.SocketError // - SocketError.SystemNotReady // - SocketError.TypeNotFound // - SocketError.VersionNotSupported private static readonly Dictionary<Interop.Error, SocketError> s_nativeErrorToSocketError = new Dictionary<Interop.Error, SocketError>(NativeErrorToSocketErrorCount) { { Interop.Error.EACCES, SocketError.AccessDenied }, { Interop.Error.EADDRINUSE, SocketError.AddressAlreadyInUse }, { Interop.Error.EADDRNOTAVAIL, SocketError.AddressNotAvailable }, { Interop.Error.EAFNOSUPPORT, SocketError.AddressFamilyNotSupported }, { Interop.Error.EAGAIN, SocketError.WouldBlock }, { Interop.Error.EALREADY, SocketError.AlreadyInProgress }, { Interop.Error.EBADF, SocketError.OperationAborted }, { Interop.Error.ECANCELED, SocketError.OperationAborted }, { Interop.Error.ECONNABORTED, SocketError.ConnectionAborted }, { Interop.Error.ECONNREFUSED, SocketError.ConnectionRefused }, { Interop.Error.ECONNRESET, SocketError.ConnectionReset }, { Interop.Error.EDESTADDRREQ, SocketError.DestinationAddressRequired }, { Interop.Error.EFAULT, SocketError.Fault }, { Interop.Error.EHOSTDOWN, SocketError.HostDown }, { Interop.Error.ENXIO, SocketError.HostNotFound }, // not perfect, but closest match available { Interop.Error.EHOSTUNREACH, SocketError.HostUnreachable }, { Interop.Error.EINPROGRESS, SocketError.InProgress }, { Interop.Error.EINTR, SocketError.Interrupted }, { Interop.Error.EINVAL, SocketError.InvalidArgument }, { Interop.Error.EISCONN, SocketError.IsConnected }, { Interop.Error.EMFILE, SocketError.TooManyOpenSockets }, { Interop.Error.EMSGSIZE, SocketError.MessageSize }, { Interop.Error.ENETDOWN, SocketError.NetworkDown }, { Interop.Error.ENETRESET, SocketError.NetworkReset }, { Interop.Error.ENETUNREACH, SocketError.NetworkUnreachable }, { Interop.Error.ENFILE, SocketError.TooManyOpenSockets }, { Interop.Error.ENOBUFS, SocketError.NoBufferSpaceAvailable }, { Interop.Error.ENODATA, SocketError.NoData }, { Interop.Error.ENOENT, SocketError.AddressNotAvailable }, { Interop.Error.ENOPROTOOPT, SocketError.ProtocolOption }, { Interop.Error.ENOTCONN, SocketError.NotConnected }, { Interop.Error.ENOTSOCK, SocketError.NotSocket }, { Interop.Error.ENOTSUP, SocketError.OperationNotSupported }, { Interop.Error.EPERM, SocketError.AccessDenied }, { Interop.Error.EPIPE, SocketError.Shutdown }, { Interop.Error.EPFNOSUPPORT, SocketError.ProtocolFamilyNotSupported }, { Interop.Error.EPROTONOSUPPORT, SocketError.ProtocolNotSupported }, { Interop.Error.EPROTOTYPE, SocketError.ProtocolType }, { Interop.Error.ESOCKTNOSUPPORT, SocketError.SocketNotSupported }, { Interop.Error.ESHUTDOWN, SocketError.Disconnecting }, { Interop.Error.SUCCESS, SocketError.Success }, { Interop.Error.ETIMEDOUT, SocketError.TimedOut }, }; private static readonly Dictionary<SocketError, Interop.Error> s_socketErrorToNativeError = new Dictionary<SocketError, Interop.Error>(SocketErrorToNativeErrorCount) { // This is *mostly* an inverse mapping of s_nativeErrorToSocketError. However, some options have multiple mappings and thus // can't be inverted directly. Other options don't have a mapping from native to SocketError, but when presented with a SocketError, // we want to provide the closest relevant Error possible, e.g. EINPROGRESS maps to SocketError.InProgress, and vice versa, but // SocketError.IOPending also maps closest to EINPROGRESS. As such, roundtripping won't necessarily provide the original value 100% of the time, // but it's the best we can do given the mismatch between Interop.Error and SocketError. { SocketError.AccessDenied, Interop.Error.EACCES}, // could also have been EPERM { SocketError.AddressAlreadyInUse, Interop.Error.EADDRINUSE }, { SocketError.AddressNotAvailable, Interop.Error.EADDRNOTAVAIL }, { SocketError.AddressFamilyNotSupported, Interop.Error.EAFNOSUPPORT }, { SocketError.AlreadyInProgress, Interop.Error.EALREADY }, { SocketError.ConnectionAborted, Interop.Error.ECONNABORTED }, { SocketError.ConnectionRefused, Interop.Error.ECONNREFUSED }, { SocketError.ConnectionReset, Interop.Error.ECONNRESET }, { SocketError.DestinationAddressRequired, Interop.Error.EDESTADDRREQ }, { SocketError.Disconnecting, Interop.Error.ESHUTDOWN }, { SocketError.Fault, Interop.Error.EFAULT }, { SocketError.HostDown, Interop.Error.EHOSTDOWN }, { SocketError.HostNotFound, Interop.Error.EHOSTNOTFOUND }, { SocketError.HostUnreachable, Interop.Error.EHOSTUNREACH }, { SocketError.InProgress, Interop.Error.EINPROGRESS }, { SocketError.Interrupted, Interop.Error.EINTR }, { SocketError.InvalidArgument, Interop.Error.EINVAL }, { SocketError.IOPending, Interop.Error.EINPROGRESS }, { SocketError.IsConnected, Interop.Error.EISCONN }, { SocketError.MessageSize, Interop.Error.EMSGSIZE }, { SocketError.NetworkDown, Interop.Error.ENETDOWN }, { SocketError.NetworkReset, Interop.Error.ENETRESET }, { SocketError.NetworkUnreachable, Interop.Error.ENETUNREACH }, { SocketError.NoBufferSpaceAvailable, Interop.Error.ENOBUFS }, { SocketError.NoData, Interop.Error.ENODATA }, { SocketError.NotConnected, Interop.Error.ENOTCONN }, { SocketError.NotSocket, Interop.Error.ENOTSOCK }, { SocketError.OperationAborted, Interop.Error.ECANCELED }, { SocketError.OperationNotSupported, Interop.Error.ENOTSUP }, { SocketError.ProtocolFamilyNotSupported, Interop.Error.EPFNOSUPPORT }, { SocketError.ProtocolNotSupported, Interop.Error.EPROTONOSUPPORT }, { SocketError.ProtocolOption, Interop.Error.ENOPROTOOPT }, { SocketError.ProtocolType, Interop.Error.EPROTOTYPE }, { SocketError.Shutdown, Interop.Error.EPIPE }, { SocketError.SocketNotSupported, Interop.Error.ESOCKTNOSUPPORT }, { SocketError.Success, Interop.Error.SUCCESS }, { SocketError.TimedOut, Interop.Error.ETIMEDOUT }, { SocketError.TooManyOpenSockets, Interop.Error.ENFILE }, // could also have been EMFILE { SocketError.TryAgain, Interop.Error.EAGAIN }, // not a perfect mapping, but better than nothing { SocketError.WouldBlock, Interop.Error.EAGAIN }, { SocketError.SocketError, Interop.Error.ESOCKETERROR }, }; internal static SocketError GetSocketErrorForNativeError(Interop.Error errno) { SocketError result; return s_nativeErrorToSocketError.TryGetValue(errno, out result) ? result : SocketError.SocketError; // unknown native error, just treat it as a generic SocketError } internal static Interop.Error GetNativeErrorForSocketError(SocketError error) { Interop.Error errno; if (!TryGetNativeErrorForSocketError(error, out errno)) { // Use the SocketError's value, as it at least retains some useful info errno = (Interop.Error)(int)error; } return errno; } internal static bool TryGetNativeErrorForSocketError(SocketError error, out Interop.Error errno) { return s_socketErrorToNativeError.TryGetValue(error, out errno); } } }
// 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; namespace System.Net.Sockets { internal static class SocketErrorPal { #if DEBUG static SocketErrorPal() { Debug.Assert(s_nativeErrorToSocketError.Count == NativeErrorToSocketErrorCount, $"Expected s_nativeErrorToSocketError to have {NativeErrorToSocketErrorCount} count instead of {s_nativeErrorToSocketError.Count}."); Debug.Assert(s_socketErrorToNativeError.Count == SocketErrorToNativeErrorCount, $"Expected s_socketErrorToNativeError to have {SocketErrorToNativeErrorCount} count instead of {s_socketErrorToNativeError.Count}."); } #endif private const int NativeErrorToSocketErrorCount = 42; private const int SocketErrorToNativeErrorCount = 41; // No Interop.Errors are included for the following SocketErrors, as there's no good mapping: // - SocketError.NoRecovery // - SocketError.NotInitialized // - SocketError.ProcessLimit // - SocketError.SocketError // - SocketError.SystemNotReady // - SocketError.TypeNotFound // - SocketError.VersionNotSupported private static readonly Dictionary<Interop.Error, SocketError> s_nativeErrorToSocketError = new Dictionary<Interop.Error, SocketError>(NativeErrorToSocketErrorCount) { { Interop.Error.EACCES, SocketError.AccessDenied }, { Interop.Error.EADDRINUSE, SocketError.AddressAlreadyInUse }, { Interop.Error.EADDRNOTAVAIL, SocketError.AddressNotAvailable }, { Interop.Error.EAFNOSUPPORT, SocketError.AddressFamilyNotSupported }, { Interop.Error.EAGAIN, SocketError.WouldBlock }, { Interop.Error.EALREADY, SocketError.AlreadyInProgress }, { Interop.Error.EBADF, SocketError.OperationAborted }, { Interop.Error.ECANCELED, SocketError.OperationAborted }, { Interop.Error.ECONNABORTED, SocketError.ConnectionAborted }, { Interop.Error.ECONNREFUSED, SocketError.ConnectionRefused }, { Interop.Error.ECONNRESET, SocketError.ConnectionReset }, { Interop.Error.EDESTADDRREQ, SocketError.DestinationAddressRequired }, { Interop.Error.EFAULT, SocketError.Fault }, { Interop.Error.EHOSTDOWN, SocketError.HostDown }, { Interop.Error.ENXIO, SocketError.HostNotFound }, // not perfect, but closest match available { Interop.Error.EHOSTUNREACH, SocketError.HostUnreachable }, { Interop.Error.EINPROGRESS, SocketError.InProgress }, { Interop.Error.EINTR, SocketError.Interrupted }, { Interop.Error.EINVAL, SocketError.InvalidArgument }, { Interop.Error.EISCONN, SocketError.IsConnected }, { Interop.Error.EMFILE, SocketError.TooManyOpenSockets }, { Interop.Error.EMSGSIZE, SocketError.MessageSize }, { Interop.Error.ENETDOWN, SocketError.NetworkDown }, { Interop.Error.ENETRESET, SocketError.NetworkReset }, { Interop.Error.ENETUNREACH, SocketError.NetworkUnreachable }, { Interop.Error.ENFILE, SocketError.TooManyOpenSockets }, { Interop.Error.ENOBUFS, SocketError.NoBufferSpaceAvailable }, { Interop.Error.ENODATA, SocketError.NoData }, { Interop.Error.ENOENT, SocketError.AddressNotAvailable }, { Interop.Error.ENOPROTOOPT, SocketError.ProtocolOption }, { Interop.Error.ENOTCONN, SocketError.NotConnected }, { Interop.Error.ENOTSOCK, SocketError.NotSocket }, { Interop.Error.ENOTSUP, SocketError.OperationNotSupported }, { Interop.Error.EPERM, SocketError.AccessDenied }, { Interop.Error.EPIPE, SocketError.Shutdown }, { Interop.Error.EPFNOSUPPORT, SocketError.ProtocolFamilyNotSupported }, { Interop.Error.EPROTONOSUPPORT, SocketError.ProtocolNotSupported }, { Interop.Error.EPROTOTYPE, SocketError.ProtocolType }, { Interop.Error.ESOCKTNOSUPPORT, SocketError.SocketNotSupported }, { Interop.Error.ESHUTDOWN, SocketError.Disconnecting }, { Interop.Error.SUCCESS, SocketError.Success }, { Interop.Error.ETIMEDOUT, SocketError.TimedOut }, }; private static readonly Dictionary<SocketError, Interop.Error> s_socketErrorToNativeError = new Dictionary<SocketError, Interop.Error>(SocketErrorToNativeErrorCount) { // This is *mostly* an inverse mapping of s_nativeErrorToSocketError. However, some options have multiple mappings and thus // can't be inverted directly. Other options don't have a mapping from native to SocketError, but when presented with a SocketError, // we want to provide the closest relevant Error possible, e.g. EINPROGRESS maps to SocketError.InProgress, and vice versa, but // SocketError.IOPending also maps closest to EINPROGRESS. As such, roundtripping won't necessarily provide the original value 100% of the time, // but it's the best we can do given the mismatch between Interop.Error and SocketError. { SocketError.AccessDenied, Interop.Error.EACCES}, // could also have been EPERM { SocketError.AddressAlreadyInUse, Interop.Error.EADDRINUSE }, { SocketError.AddressNotAvailable, Interop.Error.EADDRNOTAVAIL }, { SocketError.AddressFamilyNotSupported, Interop.Error.EAFNOSUPPORT }, { SocketError.AlreadyInProgress, Interop.Error.EALREADY }, { SocketError.ConnectionAborted, Interop.Error.ECONNABORTED }, { SocketError.ConnectionRefused, Interop.Error.ECONNREFUSED }, { SocketError.ConnectionReset, Interop.Error.ECONNRESET }, { SocketError.DestinationAddressRequired, Interop.Error.EDESTADDRREQ }, { SocketError.Disconnecting, Interop.Error.ESHUTDOWN }, { SocketError.Fault, Interop.Error.EFAULT }, { SocketError.HostDown, Interop.Error.EHOSTDOWN }, { SocketError.HostNotFound, Interop.Error.EHOSTNOTFOUND }, { SocketError.HostUnreachable, Interop.Error.EHOSTUNREACH }, { SocketError.InProgress, Interop.Error.EINPROGRESS }, { SocketError.Interrupted, Interop.Error.EINTR }, { SocketError.InvalidArgument, Interop.Error.EINVAL }, { SocketError.IOPending, Interop.Error.EINPROGRESS }, { SocketError.IsConnected, Interop.Error.EISCONN }, { SocketError.MessageSize, Interop.Error.EMSGSIZE }, { SocketError.NetworkDown, Interop.Error.ENETDOWN }, { SocketError.NetworkReset, Interop.Error.ENETRESET }, { SocketError.NetworkUnreachable, Interop.Error.ENETUNREACH }, { SocketError.NoBufferSpaceAvailable, Interop.Error.ENOBUFS }, { SocketError.NoData, Interop.Error.ENODATA }, { SocketError.NotConnected, Interop.Error.ENOTCONN }, { SocketError.NotSocket, Interop.Error.ENOTSOCK }, { SocketError.OperationAborted, Interop.Error.ECANCELED }, { SocketError.OperationNotSupported, Interop.Error.ENOTSUP }, { SocketError.ProtocolFamilyNotSupported, Interop.Error.EPFNOSUPPORT }, { SocketError.ProtocolNotSupported, Interop.Error.EPROTONOSUPPORT }, { SocketError.ProtocolOption, Interop.Error.ENOPROTOOPT }, { SocketError.ProtocolType, Interop.Error.EPROTOTYPE }, { SocketError.Shutdown, Interop.Error.EPIPE }, { SocketError.SocketNotSupported, Interop.Error.ESOCKTNOSUPPORT }, { SocketError.Success, Interop.Error.SUCCESS }, { SocketError.TimedOut, Interop.Error.ETIMEDOUT }, { SocketError.TooManyOpenSockets, Interop.Error.ENFILE }, // could also have been EMFILE { SocketError.TryAgain, Interop.Error.EAGAIN }, // not a perfect mapping, but better than nothing { SocketError.WouldBlock, Interop.Error.EAGAIN }, { SocketError.SocketError, Interop.Error.ESOCKETERROR }, }; internal static SocketError GetSocketErrorForNativeError(Interop.Error errno) { SocketError result; return s_nativeErrorToSocketError.TryGetValue(errno, out result) ? result : SocketError.SocketError; // unknown native error, just treat it as a generic SocketError } internal static Interop.Error GetNativeErrorForSocketError(SocketError error) { Interop.Error errno; if (!TryGetNativeErrorForSocketError(error, out errno)) { // Use the SocketError's value, as it at least retains some useful info errno = (Interop.Error)(int)error; } return errno; } internal static bool TryGetNativeErrorForSocketError(SocketError error, out Interop.Error errno) { return s_socketErrorToNativeError.TryGetValue(error, out errno); } } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/libraries/System.Collections.Concurrent/tests/ConcurrentDictionary/ConcurrentDictionary.Generic.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.Tests; using System.Collections.Generic; using System.Linq; using Xunit; namespace System.Collections.Concurrent.Tests { public class ConcurrentDictionary_Generic_Tests_enum_enum : ConcurrentDictionary_Generic_Tests<SimpleEnum, SimpleEnum> { protected override bool DefaultValueAllowed => true; protected override KeyValuePair<SimpleEnum, SimpleEnum> CreateT(int seed) { return new KeyValuePair<SimpleEnum, SimpleEnum>(CreateTKey(seed), CreateTValue(seed)); } protected override SimpleEnum CreateTKey(int seed) => (SimpleEnum)new Random(seed).Next(); protected override SimpleEnum CreateTValue(int seed) => CreateTKey(seed); } public class ConcurrentDictionary_Generic_Tests_string_string : ConcurrentDictionary_Generic_Tests<string, string> { protected override KeyValuePair<string, string> CreateT(int seed) { return new KeyValuePair<string, string>(CreateTKey(seed), CreateTKey(seed + 500)); } protected override string CreateTKey(int seed) { int stringLength = seed % 10 + 5; Random rand = new Random(seed); byte[] bytes1 = new byte[stringLength]; rand.NextBytes(bytes1); return Convert.ToBase64String(bytes1); } protected override string CreateTValue(int seed) => CreateTKey(seed); } public class ConcurrentDictionary_Generic_Tests_ulong_ulong : ConcurrentDictionary_Generic_Tests<ulong, ulong> { protected override bool DefaultValueAllowed => true; protected override KeyValuePair<ulong, ulong> CreateT(int seed) { ulong key = CreateTKey(seed); ulong value = CreateTKey(~seed); return new KeyValuePair<ulong, ulong>(key, value); } protected override ulong CreateTKey(int seed) { Random rand = new Random(seed); ulong hi = unchecked((ulong)rand.Next()); ulong lo = unchecked((ulong)rand.Next()); return (hi << 32) | lo; } protected override ulong CreateTValue(int seed) => CreateTKey(seed); } public class ConcurrentDictionary_Generic_Tests_int_int : ConcurrentDictionary_Generic_Tests<int, int> { protected override bool DefaultValueAllowed => true; protected override KeyValuePair<int, int> CreateT(int seed) { Random rand = new Random(seed); return new KeyValuePair<int, int>(rand.Next(), rand.Next()); } protected override int CreateTKey(int seed) => new Random(seed).Next(); protected override int CreateTValue(int seed) => CreateTKey(seed); } /// <summary> /// Contains tests that ensure the correctness of the ConcurrentDictionary class. /// </summary> public abstract class ConcurrentDictionary_Generic_Tests<TKey, TValue> : IDictionary_Generic_Tests<TKey, TValue> { #region IDictionary<TKey, TValue Helper Methods protected override IDictionary<TKey, TValue> GenericIDictionaryFactory() => new ConcurrentDictionary<TKey, TValue>(); protected override IDictionary<TKey, TValue> GenericIDictionaryFactory(IEqualityComparer<TKey> comparer) => new ConcurrentDictionary<TKey, TValue>(comparer); protected override IEnumerable<ModifyEnumerable> GetModifyEnumerables(ModifyOperation operations) => new List<ModifyEnumerable>(); protected override bool IDictionary_Generic_Keys_Values_Enumeration_ThrowsInvalidOperation_WhenParentModified => false; protected override bool IDictionary_Generic_Keys_Values_ModifyingTheDictionaryUpdatesTheCollection => false; protected override bool ResetImplemented => true; protected override bool IDictionary_Generic_Keys_Values_Enumeration_ResetImplemented => true; protected override EnumerableOrder Order => EnumerableOrder.Unspecified; #endregion #region Constructors [Theory] [MemberData(nameof(ValidCollectionSizes))] public void Ctor_IDictionary(int count) { IDictionary<TKey, TValue> source = GenericIDictionaryFactory(count); IDictionary<TKey, TValue> copied = new ConcurrentDictionary<TKey, TValue>(source); Assert.Equal(source, copied); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void Ctor_IDictionary_IEqualityComparer(int count) { IEqualityComparer<TKey> comparer = GetKeyIEqualityComparer(); IDictionary<TKey, TValue> source = GenericIDictionaryFactory(count); ConcurrentDictionary<TKey, TValue> copied = new ConcurrentDictionary<TKey, TValue>(source, comparer); Assert.Equal(source, copied); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void Ctor_IEqualityComparer(int count) { IEqualityComparer<TKey> comparer = GetKeyIEqualityComparer(); IDictionary<TKey, TValue> source = GenericIDictionaryFactory(count); ConcurrentDictionary<TKey, TValue> copied = new ConcurrentDictionary<TKey, TValue>(source, comparer); Assert.Equal(source, copied); } #endregion #region IReadOnlyDictionary<TKey, TValue>.Keys [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IReadOnlyDictionary_Generic_Keys_ContainsAllCorrectKeys(int count) { IDictionary<TKey, TValue> dictionary = GenericIDictionaryFactory(count); IEnumerable<TKey> expected = dictionary.Select((pair) => pair.Key); IEnumerable<TKey> keys = ((IReadOnlyDictionary<TKey, TValue>)dictionary).Keys; Assert.True(expected.SequenceEqual(keys)); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IReadOnlyDictionary_Generic_Values_ContainsAllCorrectValues(int count) { IDictionary<TKey, TValue> dictionary = GenericIDictionaryFactory(count); IEnumerable<TValue> expected = dictionary.Select((pair) => pair.Value); IEnumerable<TValue> values = ((IReadOnlyDictionary<TKey, TValue>)dictionary).Values; Assert.True(expected.SequenceEqual(values)); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Tests; using System.Collections.Generic; using System.Linq; using Xunit; namespace System.Collections.Concurrent.Tests { public class ConcurrentDictionary_Generic_Tests_enum_enum : ConcurrentDictionary_Generic_Tests<SimpleEnum, SimpleEnum> { protected override bool DefaultValueAllowed => true; protected override KeyValuePair<SimpleEnum, SimpleEnum> CreateT(int seed) { return new KeyValuePair<SimpleEnum, SimpleEnum>(CreateTKey(seed), CreateTValue(seed)); } protected override SimpleEnum CreateTKey(int seed) => (SimpleEnum)new Random(seed).Next(); protected override SimpleEnum CreateTValue(int seed) => CreateTKey(seed); } public class ConcurrentDictionary_Generic_Tests_string_string : ConcurrentDictionary_Generic_Tests<string, string> { protected override KeyValuePair<string, string> CreateT(int seed) { return new KeyValuePair<string, string>(CreateTKey(seed), CreateTKey(seed + 500)); } protected override string CreateTKey(int seed) { int stringLength = seed % 10 + 5; Random rand = new Random(seed); byte[] bytes1 = new byte[stringLength]; rand.NextBytes(bytes1); return Convert.ToBase64String(bytes1); } protected override string CreateTValue(int seed) => CreateTKey(seed); } public class ConcurrentDictionary_Generic_Tests_ulong_ulong : ConcurrentDictionary_Generic_Tests<ulong, ulong> { protected override bool DefaultValueAllowed => true; protected override KeyValuePair<ulong, ulong> CreateT(int seed) { ulong key = CreateTKey(seed); ulong value = CreateTKey(~seed); return new KeyValuePair<ulong, ulong>(key, value); } protected override ulong CreateTKey(int seed) { Random rand = new Random(seed); ulong hi = unchecked((ulong)rand.Next()); ulong lo = unchecked((ulong)rand.Next()); return (hi << 32) | lo; } protected override ulong CreateTValue(int seed) => CreateTKey(seed); } public class ConcurrentDictionary_Generic_Tests_int_int : ConcurrentDictionary_Generic_Tests<int, int> { protected override bool DefaultValueAllowed => true; protected override KeyValuePair<int, int> CreateT(int seed) { Random rand = new Random(seed); return new KeyValuePair<int, int>(rand.Next(), rand.Next()); } protected override int CreateTKey(int seed) => new Random(seed).Next(); protected override int CreateTValue(int seed) => CreateTKey(seed); } /// <summary> /// Contains tests that ensure the correctness of the ConcurrentDictionary class. /// </summary> public abstract class ConcurrentDictionary_Generic_Tests<TKey, TValue> : IDictionary_Generic_Tests<TKey, TValue> { #region IDictionary<TKey, TValue Helper Methods protected override IDictionary<TKey, TValue> GenericIDictionaryFactory() => new ConcurrentDictionary<TKey, TValue>(); protected override IDictionary<TKey, TValue> GenericIDictionaryFactory(IEqualityComparer<TKey> comparer) => new ConcurrentDictionary<TKey, TValue>(comparer); protected override IEnumerable<ModifyEnumerable> GetModifyEnumerables(ModifyOperation operations) => new List<ModifyEnumerable>(); protected override bool IDictionary_Generic_Keys_Values_Enumeration_ThrowsInvalidOperation_WhenParentModified => false; protected override bool IDictionary_Generic_Keys_Values_ModifyingTheDictionaryUpdatesTheCollection => false; protected override bool ResetImplemented => true; protected override bool IDictionary_Generic_Keys_Values_Enumeration_ResetImplemented => true; protected override EnumerableOrder Order => EnumerableOrder.Unspecified; #endregion #region Constructors [Theory] [MemberData(nameof(ValidCollectionSizes))] public void Ctor_IDictionary(int count) { IDictionary<TKey, TValue> source = GenericIDictionaryFactory(count); IDictionary<TKey, TValue> copied = new ConcurrentDictionary<TKey, TValue>(source); Assert.Equal(source, copied); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void Ctor_IDictionary_IEqualityComparer(int count) { IEqualityComparer<TKey> comparer = GetKeyIEqualityComparer(); IDictionary<TKey, TValue> source = GenericIDictionaryFactory(count); ConcurrentDictionary<TKey, TValue> copied = new ConcurrentDictionary<TKey, TValue>(source, comparer); Assert.Equal(source, copied); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void Ctor_IEqualityComparer(int count) { IEqualityComparer<TKey> comparer = GetKeyIEqualityComparer(); IDictionary<TKey, TValue> source = GenericIDictionaryFactory(count); ConcurrentDictionary<TKey, TValue> copied = new ConcurrentDictionary<TKey, TValue>(source, comparer); Assert.Equal(source, copied); } #endregion #region IReadOnlyDictionary<TKey, TValue>.Keys [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IReadOnlyDictionary_Generic_Keys_ContainsAllCorrectKeys(int count) { IDictionary<TKey, TValue> dictionary = GenericIDictionaryFactory(count); IEnumerable<TKey> expected = dictionary.Select((pair) => pair.Key); IEnumerable<TKey> keys = ((IReadOnlyDictionary<TKey, TValue>)dictionary).Keys; Assert.True(expected.SequenceEqual(keys)); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void IReadOnlyDictionary_Generic_Values_ContainsAllCorrectValues(int count) { IDictionary<TKey, TValue> dictionary = GenericIDictionaryFactory(count); IEnumerable<TValue> expected = dictionary.Select((pair) => pair.Value); IEnumerable<TValue> values = ((IReadOnlyDictionary<TKey, TValue>)dictionary).Values; Assert.True(expected.SequenceEqual(values)); } #endregion } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/tests/baseservices/threading/regressions/whidbey_m3/200176.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Threading; public class Stop { public static int Main(String[] args) { Stop tm = new Stop(); try { ThreadPool.QueueUserWorkItem(new WaitCallback(tm.RunTest)); Thread.Sleep(3000); } catch { return -1; } return 100; } public void RunTest(object foo) { try{ throw new Exception(); } catch {} } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Threading; public class Stop { public static int Main(String[] args) { Stop tm = new Stop(); try { ThreadPool.QueueUserWorkItem(new WaitCallback(tm.RunTest)); Thread.Sleep(3000); } catch { return -1; } return 100; } public void RunTest(object foo) { try{ throw new Exception(); } catch {} } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/tests/JIT/HardwareIntrinsics/General/Vector128_1/op_UnaryNegation.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 op_UnaryNegationUInt16() { var test = new VectorUnaryOpTest__op_UnaryNegationUInt16(); // 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_UnaryNegationUInt16 { 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 Vector128<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<Vector128<UInt16>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); return testStruct; } public void RunStructFldScenario(VectorUnaryOpTest__op_UnaryNegationUInt16 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<UInt16>>() / sizeof(UInt16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16); private static UInt16[] _data1 = new UInt16[Op1ElementCount]; private static Vector128<UInt16> _clsVar1; private Vector128<UInt16> _fld1; private DataTable _dataTable; static VectorUnaryOpTest__op_UnaryNegationUInt16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); } public VectorUnaryOpTest__op_UnaryNegationUInt16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<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 = -Unsafe.Read<Vector128<UInt16>>(_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<UInt16>).GetMethod("op_UnaryNegation", new Type[] { typeof(Vector128<UInt16>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(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<UInt16>>(_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_UnaryNegationUInt16(); 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<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<Vector128<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<Vector128<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(UInt16[] firstOp, UInt16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != (ushort)(0 - firstOp[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (ushort)(0 - firstOp[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector128)}.op_UnaryNegation<UInt16>(Vector128<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 op_UnaryNegationUInt16() { var test = new VectorUnaryOpTest__op_UnaryNegationUInt16(); // 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_UnaryNegationUInt16 { 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 Vector128<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<Vector128<UInt16>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); return testStruct; } public void RunStructFldScenario(VectorUnaryOpTest__op_UnaryNegationUInt16 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<UInt16>>() / sizeof(UInt16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16); private static UInt16[] _data1 = new UInt16[Op1ElementCount]; private static Vector128<UInt16> _clsVar1; private Vector128<UInt16> _fld1; private DataTable _dataTable; static VectorUnaryOpTest__op_UnaryNegationUInt16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); } public VectorUnaryOpTest__op_UnaryNegationUInt16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<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 = -Unsafe.Read<Vector128<UInt16>>(_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<UInt16>).GetMethod("op_UnaryNegation", new Type[] { typeof(Vector128<UInt16>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(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<UInt16>>(_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_UnaryNegationUInt16(); 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<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<Vector128<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<Vector128<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); ValidateResult(inArray1, outArray, method); } private void ValidateResult(UInt16[] firstOp, UInt16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != (ushort)(0 - firstOp[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (ushort)(0 - firstOp[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector128)}.op_UnaryNegation<UInt16>(Vector128<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,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/ShiftLeftLogicalSaturateUnsigned.Vector64.Int32.1.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void ShiftLeftLogicalSaturateUnsigned_Vector64_Int32_1() { var test = new ImmUnaryOpTest__ShiftLeftLogicalSaturateUnsigned_Vector64_Int32_1(); 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 ImmUnaryOpTest__ShiftLeftLogicalSaturateUnsigned_Vector64_Int32_1 { private struct DataTable { private byte[] inArray; private byte[] outArray; private GCHandle inHandle; private GCHandle outHandle; private ulong alignment; public DataTable(Int32[] inArray, UInt32[] outArray, int alignment) { int sizeOfinArray = inArray.Length * Unsafe.SizeOf<Int32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt32>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle = GCHandle.Alloc(this.inArray, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArrayPtr), ref Unsafe.As<Int32, byte>(ref inArray[0]), (uint)sizeOfinArray); } public void* inArrayPtr => Align((byte*)(inHandle.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<Int32> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref testStruct._fld), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); return testStruct; } public void RunStructFldScenario(ImmUnaryOpTest__ShiftLeftLogicalSaturateUnsigned_Vector64_Int32_1 testClass) { var result = AdvSimd.ShiftLeftLogicalSaturateUnsigned(_fld, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(ImmUnaryOpTest__ShiftLeftLogicalSaturateUnsigned_Vector64_Int32_1 testClass) { fixed (Vector64<Int32>* pFld = &_fld) { var result = AdvSimd.ShiftLeftLogicalSaturateUnsigned( AdvSimd.LoadVector64((Int32*)(pFld)), 1 ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<UInt32>>() / sizeof(UInt32); private static readonly byte Imm = 1; private static Int32[] _data = new Int32[Op1ElementCount]; private static Vector64<Int32> _clsVar; private Vector64<Int32> _fld; private DataTable _dataTable; static ImmUnaryOpTest__ShiftLeftLogicalSaturateUnsigned_Vector64_Int32_1() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _clsVar), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); } public ImmUnaryOpTest__ShiftLeftLogicalSaturateUnsigned_Vector64_Int32_1() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _fld), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new DataTable(_data, new UInt32[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.ShiftLeftLogicalSaturateUnsigned( Unsafe.Read<Vector64<Int32>>(_dataTable.inArrayPtr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.ShiftLeftLogicalSaturateUnsigned( AdvSimd.LoadVector64((Int32*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ShiftLeftLogicalSaturateUnsigned), new Type[] { typeof(Vector64<Int32>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Int32>>(_dataTable.inArrayPtr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ShiftLeftLogicalSaturateUnsigned), new Type[] { typeof(Vector64<Int32>), typeof(byte) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((Int32*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.ShiftLeftLogicalSaturateUnsigned( _clsVar, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<Int32>* pClsVar = &_clsVar) { var result = AdvSimd.ShiftLeftLogicalSaturateUnsigned( AdvSimd.LoadVector64((Int32*)(pClsVar)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector64<Int32>>(_dataTable.inArrayPtr); var result = AdvSimd.ShiftLeftLogicalSaturateUnsigned(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = AdvSimd.LoadVector64((Int32*)(_dataTable.inArrayPtr)); var result = AdvSimd.ShiftLeftLogicalSaturateUnsigned(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmUnaryOpTest__ShiftLeftLogicalSaturateUnsigned_Vector64_Int32_1(); var result = AdvSimd.ShiftLeftLogicalSaturateUnsigned(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new ImmUnaryOpTest__ShiftLeftLogicalSaturateUnsigned_Vector64_Int32_1(); fixed (Vector64<Int32>* pFld = &test._fld) { var result = AdvSimd.ShiftLeftLogicalSaturateUnsigned( AdvSimd.LoadVector64((Int32*)(pFld)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.ShiftLeftLogicalSaturateUnsigned(_fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<Int32>* pFld = &_fld) { var result = AdvSimd.ShiftLeftLogicalSaturateUnsigned( AdvSimd.LoadVector64((Int32*)(pFld)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.ShiftLeftLogicalSaturateUnsigned(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.ShiftLeftLogicalSaturateUnsigned( AdvSimd.LoadVector64((Int32*)(&test._fld)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector64<Int32> firstOp, void* result, [CallerMemberName] string method = "") { Int32[] inArray = new Int32[Op1ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt32>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Int32[] inArray = new Int32[Op1ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector64<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt32>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(Int32[] firstOp, UInt32[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.ShiftLeftLogicalSaturateUnsigned(firstOp[i], Imm) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ShiftLeftLogicalSaturateUnsigned)}<UInt32>(Vector64<Int32>, 1): {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.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void ShiftLeftLogicalSaturateUnsigned_Vector64_Int32_1() { var test = new ImmUnaryOpTest__ShiftLeftLogicalSaturateUnsigned_Vector64_Int32_1(); 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 ImmUnaryOpTest__ShiftLeftLogicalSaturateUnsigned_Vector64_Int32_1 { private struct DataTable { private byte[] inArray; private byte[] outArray; private GCHandle inHandle; private GCHandle outHandle; private ulong alignment; public DataTable(Int32[] inArray, UInt32[] outArray, int alignment) { int sizeOfinArray = inArray.Length * Unsafe.SizeOf<Int32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt32>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle = GCHandle.Alloc(this.inArray, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArrayPtr), ref Unsafe.As<Int32, byte>(ref inArray[0]), (uint)sizeOfinArray); } public void* inArrayPtr => Align((byte*)(inHandle.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<Int32> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref testStruct._fld), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); return testStruct; } public void RunStructFldScenario(ImmUnaryOpTest__ShiftLeftLogicalSaturateUnsigned_Vector64_Int32_1 testClass) { var result = AdvSimd.ShiftLeftLogicalSaturateUnsigned(_fld, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(ImmUnaryOpTest__ShiftLeftLogicalSaturateUnsigned_Vector64_Int32_1 testClass) { fixed (Vector64<Int32>* pFld = &_fld) { var result = AdvSimd.ShiftLeftLogicalSaturateUnsigned( AdvSimd.LoadVector64((Int32*)(pFld)), 1 ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<UInt32>>() / sizeof(UInt32); private static readonly byte Imm = 1; private static Int32[] _data = new Int32[Op1ElementCount]; private static Vector64<Int32> _clsVar; private Vector64<Int32> _fld; private DataTable _dataTable; static ImmUnaryOpTest__ShiftLeftLogicalSaturateUnsigned_Vector64_Int32_1() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _clsVar), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); } public ImmUnaryOpTest__ShiftLeftLogicalSaturateUnsigned_Vector64_Int32_1() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int32>, byte>(ref _fld), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector64<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new DataTable(_data, new UInt32[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.ShiftLeftLogicalSaturateUnsigned( Unsafe.Read<Vector64<Int32>>(_dataTable.inArrayPtr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.ShiftLeftLogicalSaturateUnsigned( AdvSimd.LoadVector64((Int32*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ShiftLeftLogicalSaturateUnsigned), new Type[] { typeof(Vector64<Int32>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Int32>>(_dataTable.inArrayPtr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.ShiftLeftLogicalSaturateUnsigned), new Type[] { typeof(Vector64<Int32>), typeof(byte) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((Int32*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<UInt32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.ShiftLeftLogicalSaturateUnsigned( _clsVar, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<Int32>* pClsVar = &_clsVar) { var result = AdvSimd.ShiftLeftLogicalSaturateUnsigned( AdvSimd.LoadVector64((Int32*)(pClsVar)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector64<Int32>>(_dataTable.inArrayPtr); var result = AdvSimd.ShiftLeftLogicalSaturateUnsigned(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = AdvSimd.LoadVector64((Int32*)(_dataTable.inArrayPtr)); var result = AdvSimd.ShiftLeftLogicalSaturateUnsigned(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmUnaryOpTest__ShiftLeftLogicalSaturateUnsigned_Vector64_Int32_1(); var result = AdvSimd.ShiftLeftLogicalSaturateUnsigned(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new ImmUnaryOpTest__ShiftLeftLogicalSaturateUnsigned_Vector64_Int32_1(); fixed (Vector64<Int32>* pFld = &test._fld) { var result = AdvSimd.ShiftLeftLogicalSaturateUnsigned( AdvSimd.LoadVector64((Int32*)(pFld)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.ShiftLeftLogicalSaturateUnsigned(_fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<Int32>* pFld = &_fld) { var result = AdvSimd.ShiftLeftLogicalSaturateUnsigned( AdvSimd.LoadVector64((Int32*)(pFld)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.ShiftLeftLogicalSaturateUnsigned(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.ShiftLeftLogicalSaturateUnsigned( AdvSimd.LoadVector64((Int32*)(&test._fld)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector64<Int32> firstOp, void* result, [CallerMemberName] string method = "") { Int32[] inArray = new Int32[Op1ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt32>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Int32[] inArray = new Int32[Op1ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector64<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<UInt32>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(Int32[] firstOp, UInt32[] result, [CallerMemberName] string method = "") { bool succeeded = true; for (var i = 0; i < RetElementCount; i++) { if (Helpers.ShiftLeftLogicalSaturateUnsigned(firstOp[i], Imm) != result[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.ShiftLeftLogicalSaturateUnsigned)}<UInt32>(Vector64<Int32>, 1): {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,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/tests/JIT/Generics/Conversions/Reference/GenToNonGen02.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 interface GenBase { Type MyVirtType(); } public class Gen<T> : GenBase { public virtual Type MyVirtType() { return typeof(Gen<T>); } } public class Converter<T> { public bool ToGenBaseOfT(object src, bool invalid, Type t) { try { GenBase dst = (GenBase)src; if (invalid) { return false; } return dst.MyVirtType().Equals(t); } catch (InvalidCastException) { return invalid; } catch { return false; } } public bool ToGenOfT(object src, bool invalid, Type t) { try { Gen<T> dst = (Gen<T>)src; if (invalid) { return false; } return dst.MyVirtType().Equals(t); } catch (InvalidCastException) { return invalid; } catch { return false; } } } public class Test_GenToNonGen02 { 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 Converter<int>().ToGenBaseOfT(new Gen<int>(), false, typeof(Gen<int>))); Eval(new Converter<string>().ToGenBaseOfT(new Gen<string>(), false, typeof(Gen<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 interface GenBase { Type MyVirtType(); } public class Gen<T> : GenBase { public virtual Type MyVirtType() { return typeof(Gen<T>); } } public class Converter<T> { public bool ToGenBaseOfT(object src, bool invalid, Type t) { try { GenBase dst = (GenBase)src; if (invalid) { return false; } return dst.MyVirtType().Equals(t); } catch (InvalidCastException) { return invalid; } catch { return false; } } public bool ToGenOfT(object src, bool invalid, Type t) { try { Gen<T> dst = (Gen<T>)src; if (invalid) { return false; } return dst.MyVirtType().Equals(t); } catch (InvalidCastException) { return invalid; } catch { return false; } } } public class Test_GenToNonGen02 { 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 Converter<int>().ToGenBaseOfT(new Gen<int>(), false, typeof(Gen<int>))); Eval(new Converter<string>().ToGenBaseOfT(new Gen<string>(), false, typeof(Gen<string>))); if (result) { Console.WriteLine("Test Passed"); return 100; } else { Console.WriteLine("Test Failed"); return 1; } } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingsSavingEventHandler.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.Configuration { /// <summary> /// Event handler for the SettingsSaving event. /// </summary> public delegate void SettingsSavingEventHandler(object sender, CancelEventArgs e); }
// 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.Configuration { /// <summary> /// Event handler for the SettingsSaving event. /// </summary> public delegate void SettingsSavingEventHandler(object sender, CancelEventArgs e); }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/libraries/System.Drawing.Common/src/System/Drawing/macFunctions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // // System.Drawing.carbonFunctions.cs // // Authors: // Geoff Norton ([email protected]> // // Copyright (C) 2007 Novell, Inc. (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.Collections; using System.Runtime.InteropServices; namespace System.Drawing { internal static partial class MacSupport { internal static readonly Hashtable contextReference = new Hashtable(); internal static readonly object lockobj = new object(); internal static CocoaContext GetCGContextForNSView(IntPtr handle) { IntPtr graphicsContext = intptr_objc_msgSend(objc_getClass("NSGraphicsContext"), sel_registerName("currentContext")); IntPtr ctx = intptr_objc_msgSend(graphicsContext, sel_registerName("graphicsPort")); CGContextSaveGState(ctx); Rect_objc_msgSend_stret(out Rect bounds, handle, sel_registerName("bounds")); var isFlipped = bool_objc_msgSend(handle, sel_registerName("isFlipped")); if (isFlipped) { CGContextTranslateCTM(ctx, bounds.origin.x, bounds.size.height); CGContextScaleCTM(ctx, 1.0f, -1.0f); } return new CocoaContext(ctx, (int)bounds.size.width, (int)bounds.size.height); } internal static CarbonContext GetCGContextForView(IntPtr handle) { IntPtr context = IntPtr.Zero; IntPtr port; IntPtr window; window = GetControlOwner(handle); if (handle == IntPtr.Zero || window == IntPtr.Zero) { // FIXME: Can we actually get a CGContextRef for the desktop? this makes context IntPtr.Zero port = GetQDGlobalsThePort(); CreateCGContextForPort(port, ref context); Rect desktop_bounds = CGDisplayBounds(CGMainDisplayID()); return new CarbonContext(port, context, (int)desktop_bounds.size.width, (int)desktop_bounds.size.height); } QDRect window_bounds = default(QDRect); Rect view_bounds = default(Rect); port = GetWindowPort(window); context = GetContext(port); GetWindowBounds(window, 32, ref window_bounds); HIViewGetBounds(handle, ref view_bounds); HIViewConvertRect(ref view_bounds, handle, IntPtr.Zero); if (view_bounds.size.height < 0) view_bounds.size.height = 0; if (view_bounds.size.width < 0) view_bounds.size.width = 0; CGContextTranslateCTM(context, view_bounds.origin.x, (window_bounds.bottom - window_bounds.top) - (view_bounds.origin.y + view_bounds.size.height)); // Create the original rect path and clip to it Rect rc_clip = new Rect(0, 0, view_bounds.size.width, view_bounds.size.height); CGContextSaveGState(context); CGContextBeginPath(context); CGContextAddRect(context, rc_clip); CGContextClosePath(context); CGContextClip(context); return new CarbonContext(port, context, (int)view_bounds.size.width, (int)view_bounds.size.height); } internal static IntPtr GetContext(IntPtr port) { IntPtr context = IntPtr.Zero; lock (lockobj) { #if FALSE if (contextReference [port] != null) { CreateCGContextForPort (port, ref context); } else { QDBeginCGContext (port, ref context); contextReference [port] = context; } #else CreateCGContextForPort(port, ref context); #endif } return context; } internal static void ReleaseContext(IntPtr port, IntPtr context) { CGContextRestoreGState(context); lock (lockobj) { #if FALSE if (contextReference [port] != null && context == (IntPtr) contextReference [port]) { QDEndCGContext (port, ref context); contextReference [port] = null; } else { CFRelease (context); } #else CFRelease(context); #endif } } #region Cocoa Methods [GeneratedDllImport("libobjc.dylib", StringMarshalling = StringMarshalling.Utf8)] public static partial IntPtr objc_getClass(string className); [GeneratedDllImport("libobjc.dylib", EntryPoint = "objc_msgSend")] public static partial IntPtr intptr_objc_msgSend(IntPtr basePtr, IntPtr selector); [GeneratedDllImport("libobjc.dylib", EntryPoint = "objc_msgSend_stret")] public static partial void Rect_objc_msgSend_stret(out Rect arect, IntPtr basePtr, IntPtr selector); [GeneratedDllImport("libobjc.dylib", EntryPoint = "objc_msgSend")] [return:MarshalAs(UnmanagedType.U1)] public static partial bool bool_objc_msgSend(IntPtr handle, IntPtr selector); [GeneratedDllImport("libobjc.dylib", StringMarshalling = StringMarshalling.Utf8)] public static partial IntPtr sel_registerName(string selectorName); #endregion [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial IntPtr CGMainDisplayID(); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial Rect CGDisplayBounds(IntPtr display); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial int HIViewGetBounds(IntPtr vHnd, ref Rect r); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial int HIViewConvertRect(ref Rect r, IntPtr a, IntPtr b); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial IntPtr GetControlOwner(IntPtr aView); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial int GetWindowBounds(IntPtr wHnd, uint reg, ref QDRect rect); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial IntPtr GetWindowPort(IntPtr hWnd); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial IntPtr GetQDGlobalsThePort(); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial void CreateCGContextForPort(IntPtr port, ref IntPtr context); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial void CFRelease(IntPtr context); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial void QDBeginCGContext(IntPtr port, ref IntPtr context); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial void QDEndCGContext(IntPtr port, ref IntPtr context); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial int CGContextClipToRect(IntPtr context, Rect clip); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial int CGContextClipToRects(IntPtr context, Rect[] clip_rects, int count); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial void CGContextTranslateCTM(IntPtr context, float tx, float ty); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial void CGContextScaleCTM(IntPtr context, float x, float y); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial void CGContextFlush(IntPtr context); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial void CGContextSynchronize(IntPtr context); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial IntPtr CGPathCreateMutable(); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial void CGPathAddRects(IntPtr path, IntPtr _void, Rect[] rects, int count); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial void CGPathAddRect(IntPtr path, IntPtr _void, Rect rect); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial void CGContextAddRects(IntPtr context, Rect[] rects, int count); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial void CGContextAddRect(IntPtr context, Rect rect); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial void CGContextBeginPath(IntPtr context); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial void CGContextClosePath(IntPtr context); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial void CGContextAddPath(IntPtr context, IntPtr path); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial void CGContextClip(IntPtr context); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial void CGContextEOClip(IntPtr context); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial void CGContextEOFillPath(IntPtr context); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial void CGContextSaveGState(IntPtr context); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial void CGContextRestoreGState(IntPtr context); } internal struct CGSize { public float width; public float height; } internal struct CGPoint { public float x; public float y; } internal struct Rect { public Rect(float x, float y, float width, float height) { this.origin.x = x; this.origin.y = y; this.size.width = width; this.size.height = height; } public CGPoint origin; public CGSize size; } internal struct QDRect { public short top; public short left; public short bottom; public short right; } internal struct CarbonContext : IMacContext { public IntPtr port; public IntPtr ctx; public int width; public int height; public CarbonContext(IntPtr port, IntPtr ctx, int width, int height) { this.port = port; this.ctx = ctx; this.width = width; this.height = height; } public void Synchronize() { MacSupport.CGContextSynchronize(ctx); } public void Release() { MacSupport.ReleaseContext(port, ctx); } } internal struct CocoaContext : IMacContext { public IntPtr ctx; public int width; public int height; public CocoaContext(IntPtr ctx, int width, int height) { this.ctx = ctx; this.width = width; this.height = height; } public void Synchronize() { MacSupport.CGContextSynchronize(ctx); } public void Release() { MacSupport.CGContextRestoreGState(ctx); } } internal interface IMacContext { void Synchronize(); void Release(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // // System.Drawing.carbonFunctions.cs // // Authors: // Geoff Norton ([email protected]> // // Copyright (C) 2007 Novell, Inc. (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.Collections; using System.Runtime.InteropServices; namespace System.Drawing { internal static partial class MacSupport { internal static readonly Hashtable contextReference = new Hashtable(); internal static readonly object lockobj = new object(); internal static CocoaContext GetCGContextForNSView(IntPtr handle) { IntPtr graphicsContext = intptr_objc_msgSend(objc_getClass("NSGraphicsContext"), sel_registerName("currentContext")); IntPtr ctx = intptr_objc_msgSend(graphicsContext, sel_registerName("graphicsPort")); CGContextSaveGState(ctx); Rect_objc_msgSend_stret(out Rect bounds, handle, sel_registerName("bounds")); var isFlipped = bool_objc_msgSend(handle, sel_registerName("isFlipped")); if (isFlipped) { CGContextTranslateCTM(ctx, bounds.origin.x, bounds.size.height); CGContextScaleCTM(ctx, 1.0f, -1.0f); } return new CocoaContext(ctx, (int)bounds.size.width, (int)bounds.size.height); } internal static CarbonContext GetCGContextForView(IntPtr handle) { IntPtr context = IntPtr.Zero; IntPtr port; IntPtr window; window = GetControlOwner(handle); if (handle == IntPtr.Zero || window == IntPtr.Zero) { // FIXME: Can we actually get a CGContextRef for the desktop? this makes context IntPtr.Zero port = GetQDGlobalsThePort(); CreateCGContextForPort(port, ref context); Rect desktop_bounds = CGDisplayBounds(CGMainDisplayID()); return new CarbonContext(port, context, (int)desktop_bounds.size.width, (int)desktop_bounds.size.height); } QDRect window_bounds = default(QDRect); Rect view_bounds = default(Rect); port = GetWindowPort(window); context = GetContext(port); GetWindowBounds(window, 32, ref window_bounds); HIViewGetBounds(handle, ref view_bounds); HIViewConvertRect(ref view_bounds, handle, IntPtr.Zero); if (view_bounds.size.height < 0) view_bounds.size.height = 0; if (view_bounds.size.width < 0) view_bounds.size.width = 0; CGContextTranslateCTM(context, view_bounds.origin.x, (window_bounds.bottom - window_bounds.top) - (view_bounds.origin.y + view_bounds.size.height)); // Create the original rect path and clip to it Rect rc_clip = new Rect(0, 0, view_bounds.size.width, view_bounds.size.height); CGContextSaveGState(context); CGContextBeginPath(context); CGContextAddRect(context, rc_clip); CGContextClosePath(context); CGContextClip(context); return new CarbonContext(port, context, (int)view_bounds.size.width, (int)view_bounds.size.height); } internal static IntPtr GetContext(IntPtr port) { IntPtr context = IntPtr.Zero; lock (lockobj) { #if FALSE if (contextReference [port] != null) { CreateCGContextForPort (port, ref context); } else { QDBeginCGContext (port, ref context); contextReference [port] = context; } #else CreateCGContextForPort(port, ref context); #endif } return context; } internal static void ReleaseContext(IntPtr port, IntPtr context) { CGContextRestoreGState(context); lock (lockobj) { #if FALSE if (contextReference [port] != null && context == (IntPtr) contextReference [port]) { QDEndCGContext (port, ref context); contextReference [port] = null; } else { CFRelease (context); } #else CFRelease(context); #endif } } #region Cocoa Methods [GeneratedDllImport("libobjc.dylib", StringMarshalling = StringMarshalling.Utf8)] public static partial IntPtr objc_getClass(string className); [GeneratedDllImport("libobjc.dylib", EntryPoint = "objc_msgSend")] public static partial IntPtr intptr_objc_msgSend(IntPtr basePtr, IntPtr selector); [GeneratedDllImport("libobjc.dylib", EntryPoint = "objc_msgSend_stret")] public static partial void Rect_objc_msgSend_stret(out Rect arect, IntPtr basePtr, IntPtr selector); [GeneratedDllImport("libobjc.dylib", EntryPoint = "objc_msgSend")] [return:MarshalAs(UnmanagedType.U1)] public static partial bool bool_objc_msgSend(IntPtr handle, IntPtr selector); [GeneratedDllImport("libobjc.dylib", StringMarshalling = StringMarshalling.Utf8)] public static partial IntPtr sel_registerName(string selectorName); #endregion [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial IntPtr CGMainDisplayID(); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial Rect CGDisplayBounds(IntPtr display); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial int HIViewGetBounds(IntPtr vHnd, ref Rect r); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial int HIViewConvertRect(ref Rect r, IntPtr a, IntPtr b); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial IntPtr GetControlOwner(IntPtr aView); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial int GetWindowBounds(IntPtr wHnd, uint reg, ref QDRect rect); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial IntPtr GetWindowPort(IntPtr hWnd); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial IntPtr GetQDGlobalsThePort(); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial void CreateCGContextForPort(IntPtr port, ref IntPtr context); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial void CFRelease(IntPtr context); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial void QDBeginCGContext(IntPtr port, ref IntPtr context); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial void QDEndCGContext(IntPtr port, ref IntPtr context); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial int CGContextClipToRect(IntPtr context, Rect clip); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial int CGContextClipToRects(IntPtr context, Rect[] clip_rects, int count); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial void CGContextTranslateCTM(IntPtr context, float tx, float ty); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial void CGContextScaleCTM(IntPtr context, float x, float y); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial void CGContextFlush(IntPtr context); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial void CGContextSynchronize(IntPtr context); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial IntPtr CGPathCreateMutable(); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial void CGPathAddRects(IntPtr path, IntPtr _void, Rect[] rects, int count); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial void CGPathAddRect(IntPtr path, IntPtr _void, Rect rect); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial void CGContextAddRects(IntPtr context, Rect[] rects, int count); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial void CGContextAddRect(IntPtr context, Rect rect); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial void CGContextBeginPath(IntPtr context); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial void CGContextClosePath(IntPtr context); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial void CGContextAddPath(IntPtr context, IntPtr path); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial void CGContextClip(IntPtr context); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial void CGContextEOClip(IntPtr context); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial void CGContextEOFillPath(IntPtr context); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial void CGContextSaveGState(IntPtr context); [GeneratedDllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] internal static partial void CGContextRestoreGState(IntPtr context); } internal struct CGSize { public float width; public float height; } internal struct CGPoint { public float x; public float y; } internal struct Rect { public Rect(float x, float y, float width, float height) { this.origin.x = x; this.origin.y = y; this.size.width = width; this.size.height = height; } public CGPoint origin; public CGSize size; } internal struct QDRect { public short top; public short left; public short bottom; public short right; } internal struct CarbonContext : IMacContext { public IntPtr port; public IntPtr ctx; public int width; public int height; public CarbonContext(IntPtr port, IntPtr ctx, int width, int height) { this.port = port; this.ctx = ctx; this.width = width; this.height = height; } public void Synchronize() { MacSupport.CGContextSynchronize(ctx); } public void Release() { MacSupport.ReleaseContext(port, ctx); } } internal struct CocoaContext : IMacContext { public IntPtr ctx; public int width; public int height; public CocoaContext(IntPtr ctx, int width, int height) { this.ctx = ctx; this.width = width; this.height = height; } public void Synchronize() { MacSupport.CGContextSynchronize(ctx); } public void Release() { MacSupport.CGContextRestoreGState(ctx); } } internal interface IMacContext { void Synchronize(); void Release(); } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/libraries/System.Runtime.InteropServices/tests/System.Runtime.InteropServices.UnitTests/System/Runtime/InteropServices/ComCompatibleVersionAttributeTests.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 Xunit; [assembly: ComCompatibleVersion(1, 2, 3, 4)] namespace System.Runtime.InteropServices.Tests { public class ComCompatibleVersionAttributeTests { [Fact] public void Exists() { Type type = typeof(ComCompatibleVersionAttributeTests); Assembly assembly = type.GetTypeInfo().Assembly; ComCompatibleVersionAttribute attribute = Assert.Single(assembly.GetCustomAttributes<ComCompatibleVersionAttribute>()); Assert.Equal(1, attribute.MajorVersion); Assert.Equal(2, attribute.MinorVersion); Assert.Equal(3, attribute.BuildNumber); Assert.Equal(4, attribute.RevisionNumber); } [Theory] [InlineData(-1, -2, -3, -4)] [InlineData(0, 0, 0, 0)] [InlineData(1, 2, 3, 4)] public void Ctor_Major_Minor_Build_Revision(int major, int minor, int build, int revision) { var attribute = new ComCompatibleVersionAttribute(major, minor, build, revision); Assert.Equal(major, attribute.MajorVersion); Assert.Equal(minor, attribute.MinorVersion); Assert.Equal(build, attribute.BuildNumber); Assert.Equal(revision, attribute.RevisionNumber); } } }
// 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 Xunit; [assembly: ComCompatibleVersion(1, 2, 3, 4)] namespace System.Runtime.InteropServices.Tests { public class ComCompatibleVersionAttributeTests { [Fact] public void Exists() { Type type = typeof(ComCompatibleVersionAttributeTests); Assembly assembly = type.GetTypeInfo().Assembly; ComCompatibleVersionAttribute attribute = Assert.Single(assembly.GetCustomAttributes<ComCompatibleVersionAttribute>()); Assert.Equal(1, attribute.MajorVersion); Assert.Equal(2, attribute.MinorVersion); Assert.Equal(3, attribute.BuildNumber); Assert.Equal(4, attribute.RevisionNumber); } [Theory] [InlineData(-1, -2, -3, -4)] [InlineData(0, 0, 0, 0)] [InlineData(1, 2, 3, 4)] public void Ctor_Major_Minor_Build_Revision(int major, int minor, int build, int revision) { var attribute = new ComCompatibleVersionAttribute(major, minor, build, revision); Assert.Equal(major, attribute.MajorVersion); Assert.Equal(minor, attribute.MinorVersion); Assert.Equal(build, attribute.BuildNumber); Assert.Equal(revision, attribute.RevisionNumber); } } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/libraries/System.Diagnostics.TraceSource/tests/TraceTestHelper.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.Text; using System.Runtime.InteropServices; namespace System.Diagnostics.TraceSourceTests { static class TraceTestHelper { /// <summary> /// Resets the static state of the trace objects before a unit test. /// </summary> public static void ResetState() { Trace.Listeners.Clear(); Trace.Listeners.Add(new DefaultTraceListener()); Trace.AutoFlush = false; Trace.IndentLevel = 0; Trace.IndentSize = 4; Trace.UseGlobalLock = true; // Trace holds on to instances through weak refs // this is intended to clean those up. GC.Collect(); Trace.Refresh(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Text; using System.Runtime.InteropServices; namespace System.Diagnostics.TraceSourceTests { static class TraceTestHelper { /// <summary> /// Resets the static state of the trace objects before a unit test. /// </summary> public static void ResetState() { Trace.Listeners.Clear(); Trace.Listeners.Add(new DefaultTraceListener()); Trace.AutoFlush = false; Trace.IndentLevel = 0; Trace.IndentSize = 4; Trace.UseGlobalLock = true; // Trace holds on to instances through weak refs // this is intended to clean those up. GC.Collect(); Trace.Refresh(); } } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/tests/GC/Stress/Framework/ReliabilityTest.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Threading; using System.Runtime.Loader; using System.Reflection; using System.Runtime.CompilerServices; public class TestAssemblyLoadContext : AssemblyLoadContext { List<string> _privatePaths = new List<string>(); string _applicationBase; public TestAssemblyLoadContext(string name, string applicationBase = null, string[] paths = null) : base(true) { FriendlyName = name; SetPaths(applicationBase, paths); } public void SetPaths(string applicationBase, string[] paths) { _applicationBase = applicationBase; if (paths != null) { _privatePaths.AddRange(paths); } } public void AppendPrivatePath(string path) { _privatePaths.Add(path); } public int ExecuteAssemblyByName(string name, string[] args) { return ExecuteAssembly(name + ".dll", args); } public int ExecuteAssembly(string path, string[] args) { Assembly assembly = LoadFromAssemblyPath(Path.Combine(_applicationBase, path)); object[] actualArgs = new object[] { args != null ? args : new string[0] }; return (int)assembly.EntryPoint.Invoke(null, actualArgs); } protected override Assembly Load(AssemblyName assemblyName) { Assembly assembly = null; foreach (string path in _privatePaths) { try { assembly = LoadFromAssemblyPath(Path.Combine(path, assemblyName.Name + ".dll")); break; } catch (Exception) { } } if (assembly == null) { try { assembly = LoadFromAssemblyPath(Path.Combine(_applicationBase, assemblyName.Name + ".dll")); } catch (Exception) { } } return assembly; } public string FriendlyName { get; private set; } } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// The reliability class is the place where we keep track of information for each individual test. ReliabilityConfiguration /// first builds a hashtable of ReliabilityTest's (index by their name attribute) available in the primary configuration file, /// and then uses this hashtable to pull out the actual tests which we want to run (from the test config file) by the ID attribute /// on each test specified. /// </summary> public class ReliabilityTest { private bool _suppressConsoleOutput = false; private string _assembly, _debugger, _debuggerOptions; private string _basePath; private MethodInfo _entryPointMethod = null; private string _refOrID; private string _arguments; private string _entryPoint; private int _successCode = 0; private int _runCount = 0; private TestAssemblyLoadContext _assemblyLoadContext; private Object _testObject; private object _myLoader; private int _concurrentCopies = 1; private int _runningCount = 0; private int _expectedDuration = -1; private bool _requiresSDK = false, _hasFailed = false; private Guid _guid = Guid.Empty; private TestStartModeEnum _testStartMode = TestStartModeEnum.AppDomainLoader; private DateTime _startTime = DateTime.Now; private string _testOwner = null; private string _resultFilename = null; private List<ReliabilityTest> _group; private List<string> _preCommands; private List<string> _postCommands; private int _appDomainIndex = 0; private int _assemblyLoadContextIndex = 0; private TestAttributes _testAttrs = TestAttributes.None; private CustomActionType _customAction = CustomActionType.None; private bool _testLoadFailed = false; private int _index; public ReliabilityTest(bool suppressConsoleOutput) { SuppressConsoleOutput = suppressConsoleOutput; } public void TestStarted() { Interlocked.Increment(ref _runCount); Interlocked.Increment(ref _runningCount); } public void TestStopped() { Interlocked.Decrement(ref _runningCount); } public bool SuppressConsoleOutput { get { return _suppressConsoleOutput; } set { _suppressConsoleOutput = value; } } public DateTime StartTime { get { return (_startTime); } set { _startTime = value; } } public TestAttributes TestAttrs { get { return (_testAttrs); } set { _testAttrs = value; } } public int ConcurrentCopies { get { return (_concurrentCopies); } set { _concurrentCopies = value; } } /// <summary> /// RunningCount is the number of instances of this test which are currently running /// </summary> public int RunningCount { get { return (_runningCount); } set { _runningCount = value; } } public Object TestObject { get { return (_testObject); } set { _testObject = value; } } public Object MyLoader { get { return (_myLoader); } set { _myLoader = value; } } public bool TestLoadFailed { get { return (_testLoadFailed); } set { _testLoadFailed = value; } } public TestAssemblyLoadContext AssemblyLoadContext { get { return _assemblyLoadContext; } set { _assemblyLoadContext = value; } } public bool HasAssemblyLoadContext { [MethodImpl(MethodImplOptions.NoInlining)] get { return _assemblyLoadContext != null; } } public string AssemblyLoadContextName { [MethodImpl(MethodImplOptions.NoInlining)] get { return _assemblyLoadContext.FriendlyName; } } public string Assembly { get { return (_assembly); } set { _assembly = value; } } public string RefOrID { get { return (_refOrID); } set { _refOrID = value; } } public string Arguments { get { return (_arguments); } set { _arguments = value; } } public string[] GetSplitArguments() { if (_arguments == null) { return (null); } //TODO: Handle quotes intelligently. return (_arguments.Split(' ')); } public string EntryPoint { get { return (_entryPoint); } set { _entryPoint = value; } } public int SuccessCode { get { return (_successCode); } set { _successCode = value; } } /// <summary> /// RunCount is the total times this test has been run /// </summary> public int RunCount { get { return (_runCount); } set { _runCount = value; } } public bool RequiresSDK { get { return (_requiresSDK); } set { _requiresSDK = value; } } public MethodInfo EntryPointMethod { get { return _entryPointMethod; } set { _entryPointMethod = value; } } public string BasePath { get { if (_basePath == null) { string strBVTRoot = Environment.GetEnvironmentVariable("BVT_ROOT"); if (String.IsNullOrEmpty(strBVTRoot)) return Path.Combine(Directory.GetCurrentDirectory(), "Tests"); else return strBVTRoot; } if (_basePath.Length > 0) { if (_basePath[_basePath.Length - 1] != Path.PathSeparator) { _basePath = _basePath + Path.PathSeparator; } } return (_basePath); } set { _basePath = value; } } /// <summary> /// returns the debugger, with full path. On assignment it should just be a simple filename (eg, "cdb", "windbg", or "ntsd") /// </summary> public string Debugger { get { if (_debugger == null || _debugger == String.Empty) { return (_debugger); } // first, check the current directory string curDir = Directory.GetCurrentDirectory(); string theAnswer; if (File.Exists(theAnswer = Path.Combine(curDir, _debugger))) { return (theAnswer); } // now check the path. string path = Environment.GetEnvironmentVariable("PATH"); if (path == null) { return (_debugger); } string[] splitPath = path.Split(new char[] { ';' }); foreach (string curPath in splitPath) { if (File.Exists(theAnswer = Path.Combine(curPath, _debugger))) { return (theAnswer); } } return (_debugger); } set { _debugger = value; } } public string DebuggerOptions { get { return (_debuggerOptions); } set { _debuggerOptions = value; } } // Expected duration of the test, in minutes public int ExpectedDuration { get { return (_expectedDuration); } set { _expectedDuration = value; } } public TestStartModeEnum TestStartMode { get { return (_testStartMode); } set { _testStartMode = value; } } public Guid Guid { get { return (_guid); } set { _guid = value; } } public string TestOwner { get { return (_testOwner); } set { _testOwner = value; } } /// <summary> /// This stores the filename used to get the result back from batch files on Win9x systems (exitcode.exe stores it in this file, we read it back) /// </summary> public string ResultFilename { get { return (_resultFilename); } set { _resultFilename = value; } } public List<ReliabilityTest> Group { get { return (_group); } set { _group = value; } } public List<string> PreCommands { get { return (_preCommands); } set { _preCommands = value; } } public List<string> PostCommands { get { return (_postCommands); } set { _postCommands = value; } } public bool HasFailed { get { return (_hasFailed); } set { _hasFailed = value; } } public int AppDomainIndex { get { return (_appDomainIndex); } set { _appDomainIndex = value; } } public int AssemblyLoadContextIndex { get { return (_assemblyLoadContextIndex); } set { _assemblyLoadContextIndex = value; } } public int Index { get { return (_index); } set { _index = value; } } public CustomActionType CustomAction { get { return (_customAction); } set { _customAction = value; } } public override string ToString() { return ("Ref/ID: " + _refOrID + " Assembly: " + _assembly + " Arguments: " + _arguments + " SuccessCode: " + _successCode.ToString()); } public object Clone() { return (this.MemberwiseClone()); } public int ExecuteInAssemblyLoadContext() { int exitCode; AssemblyLoadContext.AppendPrivatePath(BasePath); // Execute the test. if (Assembly.ToLower().IndexOf(".exe") == -1 && Assembly.ToLower().IndexOf(".dll") == -1) // must be a simple name or fullname... { exitCode = AssemblyLoadContext.ExecuteAssemblyByName(Assembly, GetSplitArguments()); } else { exitCode = AssemblyLoadContext.ExecuteAssembly(Assembly, GetSplitArguments()); } return exitCode; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Threading; using System.Runtime.Loader; using System.Reflection; using System.Runtime.CompilerServices; public class TestAssemblyLoadContext : AssemblyLoadContext { List<string> _privatePaths = new List<string>(); string _applicationBase; public TestAssemblyLoadContext(string name, string applicationBase = null, string[] paths = null) : base(true) { FriendlyName = name; SetPaths(applicationBase, paths); } public void SetPaths(string applicationBase, string[] paths) { _applicationBase = applicationBase; if (paths != null) { _privatePaths.AddRange(paths); } } public void AppendPrivatePath(string path) { _privatePaths.Add(path); } public int ExecuteAssemblyByName(string name, string[] args) { return ExecuteAssembly(name + ".dll", args); } public int ExecuteAssembly(string path, string[] args) { Assembly assembly = LoadFromAssemblyPath(Path.Combine(_applicationBase, path)); object[] actualArgs = new object[] { args != null ? args : new string[0] }; return (int)assembly.EntryPoint.Invoke(null, actualArgs); } protected override Assembly Load(AssemblyName assemblyName) { Assembly assembly = null; foreach (string path in _privatePaths) { try { assembly = LoadFromAssemblyPath(Path.Combine(path, assemblyName.Name + ".dll")); break; } catch (Exception) { } } if (assembly == null) { try { assembly = LoadFromAssemblyPath(Path.Combine(_applicationBase, assemblyName.Name + ".dll")); } catch (Exception) { } } return assembly; } public string FriendlyName { get; private set; } } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// The reliability class is the place where we keep track of information for each individual test. ReliabilityConfiguration /// first builds a hashtable of ReliabilityTest's (index by their name attribute) available in the primary configuration file, /// and then uses this hashtable to pull out the actual tests which we want to run (from the test config file) by the ID attribute /// on each test specified. /// </summary> public class ReliabilityTest { private bool _suppressConsoleOutput = false; private string _assembly, _debugger, _debuggerOptions; private string _basePath; private MethodInfo _entryPointMethod = null; private string _refOrID; private string _arguments; private string _entryPoint; private int _successCode = 0; private int _runCount = 0; private TestAssemblyLoadContext _assemblyLoadContext; private Object _testObject; private object _myLoader; private int _concurrentCopies = 1; private int _runningCount = 0; private int _expectedDuration = -1; private bool _requiresSDK = false, _hasFailed = false; private Guid _guid = Guid.Empty; private TestStartModeEnum _testStartMode = TestStartModeEnum.AppDomainLoader; private DateTime _startTime = DateTime.Now; private string _testOwner = null; private string _resultFilename = null; private List<ReliabilityTest> _group; private List<string> _preCommands; private List<string> _postCommands; private int _appDomainIndex = 0; private int _assemblyLoadContextIndex = 0; private TestAttributes _testAttrs = TestAttributes.None; private CustomActionType _customAction = CustomActionType.None; private bool _testLoadFailed = false; private int _index; public ReliabilityTest(bool suppressConsoleOutput) { SuppressConsoleOutput = suppressConsoleOutput; } public void TestStarted() { Interlocked.Increment(ref _runCount); Interlocked.Increment(ref _runningCount); } public void TestStopped() { Interlocked.Decrement(ref _runningCount); } public bool SuppressConsoleOutput { get { return _suppressConsoleOutput; } set { _suppressConsoleOutput = value; } } public DateTime StartTime { get { return (_startTime); } set { _startTime = value; } } public TestAttributes TestAttrs { get { return (_testAttrs); } set { _testAttrs = value; } } public int ConcurrentCopies { get { return (_concurrentCopies); } set { _concurrentCopies = value; } } /// <summary> /// RunningCount is the number of instances of this test which are currently running /// </summary> public int RunningCount { get { return (_runningCount); } set { _runningCount = value; } } public Object TestObject { get { return (_testObject); } set { _testObject = value; } } public Object MyLoader { get { return (_myLoader); } set { _myLoader = value; } } public bool TestLoadFailed { get { return (_testLoadFailed); } set { _testLoadFailed = value; } } public TestAssemblyLoadContext AssemblyLoadContext { get { return _assemblyLoadContext; } set { _assemblyLoadContext = value; } } public bool HasAssemblyLoadContext { [MethodImpl(MethodImplOptions.NoInlining)] get { return _assemblyLoadContext != null; } } public string AssemblyLoadContextName { [MethodImpl(MethodImplOptions.NoInlining)] get { return _assemblyLoadContext.FriendlyName; } } public string Assembly { get { return (_assembly); } set { _assembly = value; } } public string RefOrID { get { return (_refOrID); } set { _refOrID = value; } } public string Arguments { get { return (_arguments); } set { _arguments = value; } } public string[] GetSplitArguments() { if (_arguments == null) { return (null); } //TODO: Handle quotes intelligently. return (_arguments.Split(' ')); } public string EntryPoint { get { return (_entryPoint); } set { _entryPoint = value; } } public int SuccessCode { get { return (_successCode); } set { _successCode = value; } } /// <summary> /// RunCount is the total times this test has been run /// </summary> public int RunCount { get { return (_runCount); } set { _runCount = value; } } public bool RequiresSDK { get { return (_requiresSDK); } set { _requiresSDK = value; } } public MethodInfo EntryPointMethod { get { return _entryPointMethod; } set { _entryPointMethod = value; } } public string BasePath { get { if (_basePath == null) { string strBVTRoot = Environment.GetEnvironmentVariable("BVT_ROOT"); if (String.IsNullOrEmpty(strBVTRoot)) return Path.Combine(Directory.GetCurrentDirectory(), "Tests"); else return strBVTRoot; } if (_basePath.Length > 0) { if (_basePath[_basePath.Length - 1] != Path.PathSeparator) { _basePath = _basePath + Path.PathSeparator; } } return (_basePath); } set { _basePath = value; } } /// <summary> /// returns the debugger, with full path. On assignment it should just be a simple filename (eg, "cdb", "windbg", or "ntsd") /// </summary> public string Debugger { get { if (_debugger == null || _debugger == String.Empty) { return (_debugger); } // first, check the current directory string curDir = Directory.GetCurrentDirectory(); string theAnswer; if (File.Exists(theAnswer = Path.Combine(curDir, _debugger))) { return (theAnswer); } // now check the path. string path = Environment.GetEnvironmentVariable("PATH"); if (path == null) { return (_debugger); } string[] splitPath = path.Split(new char[] { ';' }); foreach (string curPath in splitPath) { if (File.Exists(theAnswer = Path.Combine(curPath, _debugger))) { return (theAnswer); } } return (_debugger); } set { _debugger = value; } } public string DebuggerOptions { get { return (_debuggerOptions); } set { _debuggerOptions = value; } } // Expected duration of the test, in minutes public int ExpectedDuration { get { return (_expectedDuration); } set { _expectedDuration = value; } } public TestStartModeEnum TestStartMode { get { return (_testStartMode); } set { _testStartMode = value; } } public Guid Guid { get { return (_guid); } set { _guid = value; } } public string TestOwner { get { return (_testOwner); } set { _testOwner = value; } } /// <summary> /// This stores the filename used to get the result back from batch files on Win9x systems (exitcode.exe stores it in this file, we read it back) /// </summary> public string ResultFilename { get { return (_resultFilename); } set { _resultFilename = value; } } public List<ReliabilityTest> Group { get { return (_group); } set { _group = value; } } public List<string> PreCommands { get { return (_preCommands); } set { _preCommands = value; } } public List<string> PostCommands { get { return (_postCommands); } set { _postCommands = value; } } public bool HasFailed { get { return (_hasFailed); } set { _hasFailed = value; } } public int AppDomainIndex { get { return (_appDomainIndex); } set { _appDomainIndex = value; } } public int AssemblyLoadContextIndex { get { return (_assemblyLoadContextIndex); } set { _assemblyLoadContextIndex = value; } } public int Index { get { return (_index); } set { _index = value; } } public CustomActionType CustomAction { get { return (_customAction); } set { _customAction = value; } } public override string ToString() { return ("Ref/ID: " + _refOrID + " Assembly: " + _assembly + " Arguments: " + _arguments + " SuccessCode: " + _successCode.ToString()); } public object Clone() { return (this.MemberwiseClone()); } public int ExecuteInAssemblyLoadContext() { int exitCode; AssemblyLoadContext.AppendPrivatePath(BasePath); // Execute the test. if (Assembly.ToLower().IndexOf(".exe") == -1 && Assembly.ToLower().IndexOf(".dll") == -1) // must be a simple name or fullname... { exitCode = AssemblyLoadContext.ExecuteAssemblyByName(Assembly, GetSplitArguments()); } else { exitCode = AssemblyLoadContext.ExecuteAssembly(Assembly, GetSplitArguments()); } return exitCode; } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/tests/JIT/HardwareIntrinsics/X86/Sse41/Max.SByte.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void MaxSByte() { var test = new SimpleBinaryOpTest__MaxSByte(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse2.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 (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse2.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 (Sse2.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 (Sse2.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 (Sse2.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__MaxSByte { 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 != 32 && alignment != 16) || (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__MaxSByte testClass) { var result = Sse41.Max(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__MaxSByte testClass) { fixed (Vector128<SByte>* pFld1 = &_fld1) fixed (Vector128<SByte>* pFld2 = &_fld2) { var result = Sse41.Max( Sse2.LoadVector128((SByte*)(pFld1)), Sse2.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__MaxSByte() { 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__MaxSByte() { 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 => Sse41.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse41.Max( 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 = Sse41.Max( Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse41.Max( Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((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(Sse41).GetMethod(nameof(Sse41.Max), 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(Sse41).GetMethod(nameof(Sse41.Max), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) }) .Invoke(null, new object[] { Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse41).GetMethod(nameof(Sse41.Max), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((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 = Sse41.Max( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<SByte>* pClsVar1 = &_clsVar1) fixed (Vector128<SByte>* pClsVar2 = &_clsVar2) { var result = Sse41.Max( Sse2.LoadVector128((SByte*)(pClsVar1)), Sse2.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 = Sse41.Max(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr)); var result = Sse41.Max(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray2Ptr)); var result = Sse41.Max(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__MaxSByte(); var result = Sse41.Max(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__MaxSByte(); fixed (Vector128<SByte>* pFld1 = &test._fld1) fixed (Vector128<SByte>* pFld2 = &test._fld2) { var result = Sse41.Max( Sse2.LoadVector128((SByte*)(pFld1)), Sse2.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 = Sse41.Max(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<SByte>* pFld1 = &_fld1) fixed (Vector128<SByte>* pFld2 = &_fld2) { var result = Sse41.Max( Sse2.LoadVector128((SByte*)(pFld1)), Sse2.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 = Sse41.Max(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse41.Max( Sse2.LoadVector128((SByte*)(&test._fld1)), Sse2.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; if (result[0] != Math.Max(left[0], right[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != Math.Max(left[i], right[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.Max)}<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\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 MaxSByte() { var test = new SimpleBinaryOpTest__MaxSByte(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse2.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 (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse2.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 (Sse2.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 (Sse2.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 (Sse2.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__MaxSByte { 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 != 32 && alignment != 16) || (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__MaxSByte testClass) { var result = Sse41.Max(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__MaxSByte testClass) { fixed (Vector128<SByte>* pFld1 = &_fld1) fixed (Vector128<SByte>* pFld2 = &_fld2) { var result = Sse41.Max( Sse2.LoadVector128((SByte*)(pFld1)), Sse2.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__MaxSByte() { 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__MaxSByte() { 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 => Sse41.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse41.Max( 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 = Sse41.Max( Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse41.Max( Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((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(Sse41).GetMethod(nameof(Sse41.Max), 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(Sse41).GetMethod(nameof(Sse41.Max), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) }) .Invoke(null, new object[] { Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse41).GetMethod(nameof(Sse41.Max), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((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 = Sse41.Max( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<SByte>* pClsVar1 = &_clsVar1) fixed (Vector128<SByte>* pClsVar2 = &_clsVar2) { var result = Sse41.Max( Sse2.LoadVector128((SByte*)(pClsVar1)), Sse2.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 = Sse41.Max(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr)); var result = Sse41.Max(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray2Ptr)); var result = Sse41.Max(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__MaxSByte(); var result = Sse41.Max(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__MaxSByte(); fixed (Vector128<SByte>* pFld1 = &test._fld1) fixed (Vector128<SByte>* pFld2 = &test._fld2) { var result = Sse41.Max( Sse2.LoadVector128((SByte*)(pFld1)), Sse2.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 = Sse41.Max(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<SByte>* pFld1 = &_fld1) fixed (Vector128<SByte>* pFld2 = &_fld2) { var result = Sse41.Max( Sse2.LoadVector128((SByte*)(pFld1)), Sse2.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 = Sse41.Max(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse41.Max( Sse2.LoadVector128((SByte*)(&test._fld1)), Sse2.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; if (result[0] != Math.Max(left[0], right[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != Math.Max(left[i], right[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.Max)}<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,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/libraries/System.Runtime.InteropServices/tests/TestAssets/NativeExports/Strings.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; namespace NativeExports { public static unsafe class Strings { [UnmanagedCallersOnly(EntryPoint = "return_length_ushort")] public static int ReturnLengthUShort(ushort* input) { if (input == null) return -1; return GetLength(input); } [UnmanagedCallersOnly(EntryPoint = "return_length_byte")] public static int ReturnLengthByte(byte* input) { if (input == null) return -1; return GetLength(input); } [UnmanagedCallersOnly(EntryPoint = "reverse_return_ushort")] public static ushort* ReverseReturnUShort(ushort* input) { return Reverse(input); } [UnmanagedCallersOnly(EntryPoint = "reverse_return_byte")] public static byte* ReverseReturnByte(byte* input) { return Reverse(input); } [UnmanagedCallersOnly(EntryPoint = "reverse_out_ushort")] public static void ReverseReturnAsOutUShort(ushort* input, ushort** ret) { *ret = Reverse(input); } [UnmanagedCallersOnly(EntryPoint = "reverse_out_byte")] public static void ReverseReturnAsOutByte(byte* input, byte** ret) { *ret = Reverse(input); } [UnmanagedCallersOnly(EntryPoint = "reverse_inplace_ref_ushort")] public static void ReverseInPlaceUShort(ushort** refInput) { if (*refInput == null) return; int len = GetLength(*refInput); var span = new Span<ushort>(*refInput, len); span.Reverse(); } [UnmanagedCallersOnly(EntryPoint = "reverse_inplace_ref_byte")] public static void ReverseInPlaceByte(byte** refInput) { int len = GetLength(*refInput); var span = new Span<byte>(*refInput, len); span.Reverse(); } [UnmanagedCallersOnly(EntryPoint = "reverse_replace_ref_ushort")] public static void ReverseReplaceRefUShort(ushort** s) { if (*s == null) return; ushort* ret = Reverse(*s); Marshal.FreeCoTaskMem((IntPtr)(*s)); *s = ret; } [UnmanagedCallersOnly(EntryPoint = "reverse_replace_ref_byte")] public static void ReverseReplaceRefByte(byte** s) { if (*s == null) return; byte* ret = Reverse(*s); Marshal.FreeCoTaskMem((IntPtr)(*s)); *s = ret; } internal static ushort* Reverse(ushort *s) { if (s == null) return null; int len = GetLength(s); ushort* ret = (ushort*)Marshal.AllocCoTaskMem((len + 1) * sizeof(ushort)); var span = new Span<ushort>(ret, len); new Span<ushort>(s, len).CopyTo(span); span.Reverse(); ret[len] = 0; return ret; } internal static byte* Reverse(byte* s) { if (s == null) return null; int len = GetLength(s); byte* ret = (byte*)Marshal.AllocCoTaskMem((len + 1) * sizeof(byte)); var span = new Span<byte>(ret, len); new Span<byte>(s, len).CopyTo(span); span.Reverse(); ret[len] = 0; return ret; } private static int GetLength(ushort* input) { if (input == null) return 0; int len = 0; while (*input != 0) { input++; len++; } return len; } private static int GetLength(byte* input) { if (input == null) return 0; int len = 0; while (*input != 0) { input++; len++; } return len; } } }
// 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; namespace NativeExports { public static unsafe class Strings { [UnmanagedCallersOnly(EntryPoint = "return_length_ushort")] public static int ReturnLengthUShort(ushort* input) { if (input == null) return -1; return GetLength(input); } [UnmanagedCallersOnly(EntryPoint = "return_length_byte")] public static int ReturnLengthByte(byte* input) { if (input == null) return -1; return GetLength(input); } [UnmanagedCallersOnly(EntryPoint = "reverse_return_ushort")] public static ushort* ReverseReturnUShort(ushort* input) { return Reverse(input); } [UnmanagedCallersOnly(EntryPoint = "reverse_return_byte")] public static byte* ReverseReturnByte(byte* input) { return Reverse(input); } [UnmanagedCallersOnly(EntryPoint = "reverse_out_ushort")] public static void ReverseReturnAsOutUShort(ushort* input, ushort** ret) { *ret = Reverse(input); } [UnmanagedCallersOnly(EntryPoint = "reverse_out_byte")] public static void ReverseReturnAsOutByte(byte* input, byte** ret) { *ret = Reverse(input); } [UnmanagedCallersOnly(EntryPoint = "reverse_inplace_ref_ushort")] public static void ReverseInPlaceUShort(ushort** refInput) { if (*refInput == null) return; int len = GetLength(*refInput); var span = new Span<ushort>(*refInput, len); span.Reverse(); } [UnmanagedCallersOnly(EntryPoint = "reverse_inplace_ref_byte")] public static void ReverseInPlaceByte(byte** refInput) { int len = GetLength(*refInput); var span = new Span<byte>(*refInput, len); span.Reverse(); } [UnmanagedCallersOnly(EntryPoint = "reverse_replace_ref_ushort")] public static void ReverseReplaceRefUShort(ushort** s) { if (*s == null) return; ushort* ret = Reverse(*s); Marshal.FreeCoTaskMem((IntPtr)(*s)); *s = ret; } [UnmanagedCallersOnly(EntryPoint = "reverse_replace_ref_byte")] public static void ReverseReplaceRefByte(byte** s) { if (*s == null) return; byte* ret = Reverse(*s); Marshal.FreeCoTaskMem((IntPtr)(*s)); *s = ret; } internal static ushort* Reverse(ushort *s) { if (s == null) return null; int len = GetLength(s); ushort* ret = (ushort*)Marshal.AllocCoTaskMem((len + 1) * sizeof(ushort)); var span = new Span<ushort>(ret, len); new Span<ushort>(s, len).CopyTo(span); span.Reverse(); ret[len] = 0; return ret; } internal static byte* Reverse(byte* s) { if (s == null) return null; int len = GetLength(s); byte* ret = (byte*)Marshal.AllocCoTaskMem((len + 1) * sizeof(byte)); var span = new Span<byte>(ret, len); new Span<byte>(s, len).CopyTo(span); span.Reverse(); ret[len] = 0; return ret; } private static int GetLength(ushort* input) { if (input == null) return 0; int len = 0; while (*input != 0) { input++; len++; } return len; } private static int GetLength(byte* input) { if (input == null) return 0; int len = 0; while (*input != 0) { input++; len++; } return len; } } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Internal/StringHeap.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.Reflection.Internal; using System.Runtime.InteropServices; using System.Text; using System.Threading; namespace System.Reflection.Metadata.Ecma335 { internal struct StringHeap { private static string[]? s_virtualValues; internal readonly MemoryBlock Block; private VirtualHeap? _lazyVirtualHeap; internal StringHeap(MemoryBlock block, MetadataKind metadataKind) { _lazyVirtualHeap = null; if (s_virtualValues == null && metadataKind != MetadataKind.Ecma335) { // Note: // Virtual values shall not contain surrogates, otherwise StartsWith might be inconsistent // when comparing to a text that ends with a high surrogate. var values = new string[(int)StringHandle.VirtualIndex.Count]; values[(int)StringHandle.VirtualIndex.System_Runtime_WindowsRuntime] = "System.Runtime.WindowsRuntime"; values[(int)StringHandle.VirtualIndex.System_Runtime] = "System.Runtime"; values[(int)StringHandle.VirtualIndex.System_ObjectModel] = "System.ObjectModel"; values[(int)StringHandle.VirtualIndex.System_Runtime_WindowsRuntime_UI_Xaml] = "System.Runtime.WindowsRuntime.UI.Xaml"; values[(int)StringHandle.VirtualIndex.System_Runtime_InteropServices_WindowsRuntime] = "System.Runtime.InteropServices.WindowsRuntime"; values[(int)StringHandle.VirtualIndex.System_Numerics_Vectors] = "System.Numerics.Vectors"; values[(int)StringHandle.VirtualIndex.Dispose] = "Dispose"; values[(int)StringHandle.VirtualIndex.AttributeTargets] = "AttributeTargets"; values[(int)StringHandle.VirtualIndex.AttributeUsageAttribute] = "AttributeUsageAttribute"; values[(int)StringHandle.VirtualIndex.Color] = "Color"; values[(int)StringHandle.VirtualIndex.CornerRadius] = "CornerRadius"; values[(int)StringHandle.VirtualIndex.DateTimeOffset] = "DateTimeOffset"; values[(int)StringHandle.VirtualIndex.Duration] = "Duration"; values[(int)StringHandle.VirtualIndex.DurationType] = "DurationType"; values[(int)StringHandle.VirtualIndex.EventHandler1] = "EventHandler`1"; values[(int)StringHandle.VirtualIndex.EventRegistrationToken] = "EventRegistrationToken"; values[(int)StringHandle.VirtualIndex.Exception] = "Exception"; values[(int)StringHandle.VirtualIndex.GeneratorPosition] = "GeneratorPosition"; values[(int)StringHandle.VirtualIndex.GridLength] = "GridLength"; values[(int)StringHandle.VirtualIndex.GridUnitType] = "GridUnitType"; values[(int)StringHandle.VirtualIndex.ICommand] = "ICommand"; values[(int)StringHandle.VirtualIndex.IDictionary2] = "IDictionary`2"; values[(int)StringHandle.VirtualIndex.IDisposable] = "IDisposable"; values[(int)StringHandle.VirtualIndex.IEnumerable] = "IEnumerable"; values[(int)StringHandle.VirtualIndex.IEnumerable1] = "IEnumerable`1"; values[(int)StringHandle.VirtualIndex.IList] = "IList"; values[(int)StringHandle.VirtualIndex.IList1] = "IList`1"; values[(int)StringHandle.VirtualIndex.INotifyCollectionChanged] = "INotifyCollectionChanged"; values[(int)StringHandle.VirtualIndex.INotifyPropertyChanged] = "INotifyPropertyChanged"; values[(int)StringHandle.VirtualIndex.IReadOnlyDictionary2] = "IReadOnlyDictionary`2"; values[(int)StringHandle.VirtualIndex.IReadOnlyList1] = "IReadOnlyList`1"; values[(int)StringHandle.VirtualIndex.KeyTime] = "KeyTime"; values[(int)StringHandle.VirtualIndex.KeyValuePair2] = "KeyValuePair`2"; values[(int)StringHandle.VirtualIndex.Matrix] = "Matrix"; values[(int)StringHandle.VirtualIndex.Matrix3D] = "Matrix3D"; values[(int)StringHandle.VirtualIndex.Matrix3x2] = "Matrix3x2"; values[(int)StringHandle.VirtualIndex.Matrix4x4] = "Matrix4x4"; values[(int)StringHandle.VirtualIndex.NotifyCollectionChangedAction] = "NotifyCollectionChangedAction"; values[(int)StringHandle.VirtualIndex.NotifyCollectionChangedEventArgs] = "NotifyCollectionChangedEventArgs"; values[(int)StringHandle.VirtualIndex.NotifyCollectionChangedEventHandler] = "NotifyCollectionChangedEventHandler"; values[(int)StringHandle.VirtualIndex.Nullable1] = "Nullable`1"; values[(int)StringHandle.VirtualIndex.Plane] = "Plane"; values[(int)StringHandle.VirtualIndex.Point] = "Point"; values[(int)StringHandle.VirtualIndex.PropertyChangedEventArgs] = "PropertyChangedEventArgs"; values[(int)StringHandle.VirtualIndex.PropertyChangedEventHandler] = "PropertyChangedEventHandler"; values[(int)StringHandle.VirtualIndex.Quaternion] = "Quaternion"; values[(int)StringHandle.VirtualIndex.Rect] = "Rect"; values[(int)StringHandle.VirtualIndex.RepeatBehavior] = "RepeatBehavior"; values[(int)StringHandle.VirtualIndex.RepeatBehaviorType] = "RepeatBehaviorType"; values[(int)StringHandle.VirtualIndex.Size] = "Size"; values[(int)StringHandle.VirtualIndex.System] = "System"; values[(int)StringHandle.VirtualIndex.System_Collections] = "System.Collections"; values[(int)StringHandle.VirtualIndex.System_Collections_Generic] = "System.Collections.Generic"; values[(int)StringHandle.VirtualIndex.System_Collections_Specialized] = "System.Collections.Specialized"; values[(int)StringHandle.VirtualIndex.System_ComponentModel] = "System.ComponentModel"; values[(int)StringHandle.VirtualIndex.System_Numerics] = "System.Numerics"; values[(int)StringHandle.VirtualIndex.System_Windows_Input] = "System.Windows.Input"; values[(int)StringHandle.VirtualIndex.Thickness] = "Thickness"; values[(int)StringHandle.VirtualIndex.TimeSpan] = "TimeSpan"; values[(int)StringHandle.VirtualIndex.Type] = "Type"; values[(int)StringHandle.VirtualIndex.Uri] = "Uri"; values[(int)StringHandle.VirtualIndex.Vector2] = "Vector2"; values[(int)StringHandle.VirtualIndex.Vector3] = "Vector3"; values[(int)StringHandle.VirtualIndex.Vector4] = "Vector4"; values[(int)StringHandle.VirtualIndex.Windows_Foundation] = "Windows.Foundation"; values[(int)StringHandle.VirtualIndex.Windows_UI] = "Windows.UI"; values[(int)StringHandle.VirtualIndex.Windows_UI_Xaml] = "Windows.UI.Xaml"; values[(int)StringHandle.VirtualIndex.Windows_UI_Xaml_Controls_Primitives] = "Windows.UI.Xaml.Controls.Primitives"; values[(int)StringHandle.VirtualIndex.Windows_UI_Xaml_Media] = "Windows.UI.Xaml.Media"; values[(int)StringHandle.VirtualIndex.Windows_UI_Xaml_Media_Animation] = "Windows.UI.Xaml.Media.Animation"; values[(int)StringHandle.VirtualIndex.Windows_UI_Xaml_Media_Media3D] = "Windows.UI.Xaml.Media.Media3D"; s_virtualValues = values; AssertFilled(); } this.Block = TrimEnd(block); } [Conditional("DEBUG")] private static void AssertFilled() { for (int i = 0; i < s_virtualValues!.Length; i++) { Debug.Assert(s_virtualValues[i] != null, $"Missing virtual value for StringHandle.VirtualIndex.{(StringHandle.VirtualIndex)i}"); } } // Trims the alignment padding of the heap. // See StgStringPool::InitOnMem in ndp\clr\src\Utilcode\StgPool.cpp. // This is especially important for EnC. private static MemoryBlock TrimEnd(MemoryBlock block) { if (block.Length == 0) { return block; } int i = block.Length - 1; while (i >= 0 && block.PeekByte(i) == 0) { i--; } // this shouldn't happen in valid metadata: if (i == block.Length - 1) { return block; } // +1 for terminating \0 return block.GetMemoryBlockAt(0, i + 2); } internal string GetString(StringHandle handle, MetadataStringDecoder utf8Decoder) { return handle.IsVirtual ? GetVirtualHandleString(handle, utf8Decoder) : GetNonVirtualString(handle, utf8Decoder, prefixOpt: null); } internal MemoryBlock GetMemoryBlock(StringHandle handle) { return handle.IsVirtual ? GetVirtualHandleMemoryBlock(handle) : GetNonVirtualStringMemoryBlock(handle); } internal static string GetVirtualString(StringHandle.VirtualIndex index) { return s_virtualValues![(int)index]; } private string GetNonVirtualString(StringHandle handle, MetadataStringDecoder utf8Decoder, byte[]? prefixOpt) { Debug.Assert(handle.StringKind != StringKind.Virtual); char otherTerminator = handle.StringKind == StringKind.DotTerminated ? '.' : '\0'; return Block.PeekUtf8NullTerminated(handle.GetHeapOffset(), prefixOpt, utf8Decoder, out _, otherTerminator); } private unsafe MemoryBlock GetNonVirtualStringMemoryBlock(StringHandle handle) { Debug.Assert(handle.StringKind != StringKind.Virtual); char otherTerminator = handle.StringKind == StringKind.DotTerminated ? '.' : '\0'; int offset = handle.GetHeapOffset(); int length = Block.GetUtf8NullTerminatedLength(offset, out _, otherTerminator); return new MemoryBlock(Block.Pointer + offset, length); } private unsafe byte[] GetNonVirtualStringBytes(StringHandle handle, byte[] prefix) { Debug.Assert(handle.StringKind != StringKind.Virtual); var block = GetNonVirtualStringMemoryBlock(handle); var bytes = new byte[prefix.Length + block.Length]; Buffer.BlockCopy(prefix, 0, bytes, 0, prefix.Length); Marshal.Copy((IntPtr)block.Pointer, bytes, prefix.Length, block.Length); return bytes; } private string GetVirtualHandleString(StringHandle handle, MetadataStringDecoder utf8Decoder) { Debug.Assert(handle.IsVirtual); return handle.StringKind switch { StringKind.Virtual => GetVirtualString(handle.GetVirtualIndex()), StringKind.WinRTPrefixed => GetNonVirtualString(handle, utf8Decoder, MetadataReader.WinRTPrefix), _ => throw ExceptionUtilities.UnexpectedValue(handle.StringKind), }; } private MemoryBlock GetVirtualHandleMemoryBlock(StringHandle handle) { Debug.Assert(handle.IsVirtual); var heap = VirtualHeap.GetOrCreateVirtualHeap(ref _lazyVirtualHeap); lock (heap) { if (!heap.TryGetMemoryBlock(handle.RawValue, out var block)) { byte[] bytes = handle.StringKind switch { StringKind.Virtual => Encoding.UTF8.GetBytes(GetVirtualString(handle.GetVirtualIndex())), StringKind.WinRTPrefixed => GetNonVirtualStringBytes(handle, MetadataReader.WinRTPrefix), _ => throw ExceptionUtilities.UnexpectedValue(handle.StringKind), }; block = heap.AddBlob(handle.RawValue, bytes); } return block; } } internal BlobReader GetBlobReader(StringHandle handle) { return new BlobReader(GetMemoryBlock(handle)); } internal StringHandle GetNextHandle(StringHandle handle) { if (handle.IsVirtual) { return default(StringHandle); } int terminator = this.Block.IndexOf(0, handle.GetHeapOffset()); if (terminator == -1 || terminator == Block.Length - 1) { return default(StringHandle); } return StringHandle.FromOffset(terminator + 1); } internal bool Equals(StringHandle handle, string value, MetadataStringDecoder utf8Decoder, bool ignoreCase) { Debug.Assert(value != null); if (handle.IsVirtual) { // TODO: This can allocate unnecessarily for <WinRT> prefixed handles. return string.Equals(GetString(handle, utf8Decoder), value, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); } if (handle.IsNil) { return value.Length == 0; } char otherTerminator = handle.StringKind == StringKind.DotTerminated ? '.' : '\0'; return this.Block.Utf8NullTerminatedEquals(handle.GetHeapOffset(), value, utf8Decoder, otherTerminator, ignoreCase); } internal bool StartsWith(StringHandle handle, string value, MetadataStringDecoder utf8Decoder, bool ignoreCase) { Debug.Assert(value != null); if (handle.IsVirtual) { // TODO: This can allocate unnecessarily for <WinRT> prefixed handles. return GetString(handle, utf8Decoder).StartsWith(value, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); } if (handle.IsNil) { return value.Length == 0; } char otherTerminator = handle.StringKind == StringKind.DotTerminated ? '.' : '\0'; return this.Block.Utf8NullTerminatedStartsWith(handle.GetHeapOffset(), value, utf8Decoder, otherTerminator, ignoreCase); } /// <summary> /// Returns true if the given raw (non-virtual) handle represents the same string as given ASCII string. /// </summary> internal bool EqualsRaw(StringHandle rawHandle, string asciiString) { Debug.Assert(!rawHandle.IsVirtual); Debug.Assert(rawHandle.StringKind != StringKind.DotTerminated, "Not supported"); return this.Block.CompareUtf8NullTerminatedStringWithAsciiString(rawHandle.GetHeapOffset(), asciiString) == 0; } /// <summary> /// Returns the heap index of the given ASCII character or -1 if not found prior null terminator or end of heap. /// </summary> internal int IndexOfRaw(int startIndex, char asciiChar) { Debug.Assert(asciiChar != 0 && asciiChar <= 0x7f); return this.Block.Utf8NullTerminatedOffsetOfAsciiChar(startIndex, asciiChar); } /// <summary> /// Returns true if the given raw (non-virtual) handle represents a string that starts with given ASCII prefix. /// </summary> internal bool StartsWithRaw(StringHandle rawHandle, string asciiPrefix) { Debug.Assert(!rawHandle.IsVirtual); Debug.Assert(rawHandle.StringKind != StringKind.DotTerminated, "Not supported"); return this.Block.Utf8NullTerminatedStringStartsWithAsciiPrefix(rawHandle.GetHeapOffset(), asciiPrefix); } /// <summary> /// Equivalent to Array.BinarySearch, searches for given raw (non-virtual) handle in given array of ASCII strings. /// </summary> internal int BinarySearchRaw(string[] asciiKeys, StringHandle rawHandle) { Debug.Assert(!rawHandle.IsVirtual); Debug.Assert(rawHandle.StringKind != StringKind.DotTerminated, "Not supported"); return this.Block.BinarySearch(asciiKeys, rawHandle.GetHeapOffset()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.Reflection.Internal; using System.Runtime.InteropServices; using System.Text; using System.Threading; namespace System.Reflection.Metadata.Ecma335 { internal struct StringHeap { private static string[]? s_virtualValues; internal readonly MemoryBlock Block; private VirtualHeap? _lazyVirtualHeap; internal StringHeap(MemoryBlock block, MetadataKind metadataKind) { _lazyVirtualHeap = null; if (s_virtualValues == null && metadataKind != MetadataKind.Ecma335) { // Note: // Virtual values shall not contain surrogates, otherwise StartsWith might be inconsistent // when comparing to a text that ends with a high surrogate. var values = new string[(int)StringHandle.VirtualIndex.Count]; values[(int)StringHandle.VirtualIndex.System_Runtime_WindowsRuntime] = "System.Runtime.WindowsRuntime"; values[(int)StringHandle.VirtualIndex.System_Runtime] = "System.Runtime"; values[(int)StringHandle.VirtualIndex.System_ObjectModel] = "System.ObjectModel"; values[(int)StringHandle.VirtualIndex.System_Runtime_WindowsRuntime_UI_Xaml] = "System.Runtime.WindowsRuntime.UI.Xaml"; values[(int)StringHandle.VirtualIndex.System_Runtime_InteropServices_WindowsRuntime] = "System.Runtime.InteropServices.WindowsRuntime"; values[(int)StringHandle.VirtualIndex.System_Numerics_Vectors] = "System.Numerics.Vectors"; values[(int)StringHandle.VirtualIndex.Dispose] = "Dispose"; values[(int)StringHandle.VirtualIndex.AttributeTargets] = "AttributeTargets"; values[(int)StringHandle.VirtualIndex.AttributeUsageAttribute] = "AttributeUsageAttribute"; values[(int)StringHandle.VirtualIndex.Color] = "Color"; values[(int)StringHandle.VirtualIndex.CornerRadius] = "CornerRadius"; values[(int)StringHandle.VirtualIndex.DateTimeOffset] = "DateTimeOffset"; values[(int)StringHandle.VirtualIndex.Duration] = "Duration"; values[(int)StringHandle.VirtualIndex.DurationType] = "DurationType"; values[(int)StringHandle.VirtualIndex.EventHandler1] = "EventHandler`1"; values[(int)StringHandle.VirtualIndex.EventRegistrationToken] = "EventRegistrationToken"; values[(int)StringHandle.VirtualIndex.Exception] = "Exception"; values[(int)StringHandle.VirtualIndex.GeneratorPosition] = "GeneratorPosition"; values[(int)StringHandle.VirtualIndex.GridLength] = "GridLength"; values[(int)StringHandle.VirtualIndex.GridUnitType] = "GridUnitType"; values[(int)StringHandle.VirtualIndex.ICommand] = "ICommand"; values[(int)StringHandle.VirtualIndex.IDictionary2] = "IDictionary`2"; values[(int)StringHandle.VirtualIndex.IDisposable] = "IDisposable"; values[(int)StringHandle.VirtualIndex.IEnumerable] = "IEnumerable"; values[(int)StringHandle.VirtualIndex.IEnumerable1] = "IEnumerable`1"; values[(int)StringHandle.VirtualIndex.IList] = "IList"; values[(int)StringHandle.VirtualIndex.IList1] = "IList`1"; values[(int)StringHandle.VirtualIndex.INotifyCollectionChanged] = "INotifyCollectionChanged"; values[(int)StringHandle.VirtualIndex.INotifyPropertyChanged] = "INotifyPropertyChanged"; values[(int)StringHandle.VirtualIndex.IReadOnlyDictionary2] = "IReadOnlyDictionary`2"; values[(int)StringHandle.VirtualIndex.IReadOnlyList1] = "IReadOnlyList`1"; values[(int)StringHandle.VirtualIndex.KeyTime] = "KeyTime"; values[(int)StringHandle.VirtualIndex.KeyValuePair2] = "KeyValuePair`2"; values[(int)StringHandle.VirtualIndex.Matrix] = "Matrix"; values[(int)StringHandle.VirtualIndex.Matrix3D] = "Matrix3D"; values[(int)StringHandle.VirtualIndex.Matrix3x2] = "Matrix3x2"; values[(int)StringHandle.VirtualIndex.Matrix4x4] = "Matrix4x4"; values[(int)StringHandle.VirtualIndex.NotifyCollectionChangedAction] = "NotifyCollectionChangedAction"; values[(int)StringHandle.VirtualIndex.NotifyCollectionChangedEventArgs] = "NotifyCollectionChangedEventArgs"; values[(int)StringHandle.VirtualIndex.NotifyCollectionChangedEventHandler] = "NotifyCollectionChangedEventHandler"; values[(int)StringHandle.VirtualIndex.Nullable1] = "Nullable`1"; values[(int)StringHandle.VirtualIndex.Plane] = "Plane"; values[(int)StringHandle.VirtualIndex.Point] = "Point"; values[(int)StringHandle.VirtualIndex.PropertyChangedEventArgs] = "PropertyChangedEventArgs"; values[(int)StringHandle.VirtualIndex.PropertyChangedEventHandler] = "PropertyChangedEventHandler"; values[(int)StringHandle.VirtualIndex.Quaternion] = "Quaternion"; values[(int)StringHandle.VirtualIndex.Rect] = "Rect"; values[(int)StringHandle.VirtualIndex.RepeatBehavior] = "RepeatBehavior"; values[(int)StringHandle.VirtualIndex.RepeatBehaviorType] = "RepeatBehaviorType"; values[(int)StringHandle.VirtualIndex.Size] = "Size"; values[(int)StringHandle.VirtualIndex.System] = "System"; values[(int)StringHandle.VirtualIndex.System_Collections] = "System.Collections"; values[(int)StringHandle.VirtualIndex.System_Collections_Generic] = "System.Collections.Generic"; values[(int)StringHandle.VirtualIndex.System_Collections_Specialized] = "System.Collections.Specialized"; values[(int)StringHandle.VirtualIndex.System_ComponentModel] = "System.ComponentModel"; values[(int)StringHandle.VirtualIndex.System_Numerics] = "System.Numerics"; values[(int)StringHandle.VirtualIndex.System_Windows_Input] = "System.Windows.Input"; values[(int)StringHandle.VirtualIndex.Thickness] = "Thickness"; values[(int)StringHandle.VirtualIndex.TimeSpan] = "TimeSpan"; values[(int)StringHandle.VirtualIndex.Type] = "Type"; values[(int)StringHandle.VirtualIndex.Uri] = "Uri"; values[(int)StringHandle.VirtualIndex.Vector2] = "Vector2"; values[(int)StringHandle.VirtualIndex.Vector3] = "Vector3"; values[(int)StringHandle.VirtualIndex.Vector4] = "Vector4"; values[(int)StringHandle.VirtualIndex.Windows_Foundation] = "Windows.Foundation"; values[(int)StringHandle.VirtualIndex.Windows_UI] = "Windows.UI"; values[(int)StringHandle.VirtualIndex.Windows_UI_Xaml] = "Windows.UI.Xaml"; values[(int)StringHandle.VirtualIndex.Windows_UI_Xaml_Controls_Primitives] = "Windows.UI.Xaml.Controls.Primitives"; values[(int)StringHandle.VirtualIndex.Windows_UI_Xaml_Media] = "Windows.UI.Xaml.Media"; values[(int)StringHandle.VirtualIndex.Windows_UI_Xaml_Media_Animation] = "Windows.UI.Xaml.Media.Animation"; values[(int)StringHandle.VirtualIndex.Windows_UI_Xaml_Media_Media3D] = "Windows.UI.Xaml.Media.Media3D"; s_virtualValues = values; AssertFilled(); } this.Block = TrimEnd(block); } [Conditional("DEBUG")] private static void AssertFilled() { for (int i = 0; i < s_virtualValues!.Length; i++) { Debug.Assert(s_virtualValues[i] != null, $"Missing virtual value for StringHandle.VirtualIndex.{(StringHandle.VirtualIndex)i}"); } } // Trims the alignment padding of the heap. // See StgStringPool::InitOnMem in ndp\clr\src\Utilcode\StgPool.cpp. // This is especially important for EnC. private static MemoryBlock TrimEnd(MemoryBlock block) { if (block.Length == 0) { return block; } int i = block.Length - 1; while (i >= 0 && block.PeekByte(i) == 0) { i--; } // this shouldn't happen in valid metadata: if (i == block.Length - 1) { return block; } // +1 for terminating \0 return block.GetMemoryBlockAt(0, i + 2); } internal string GetString(StringHandle handle, MetadataStringDecoder utf8Decoder) { return handle.IsVirtual ? GetVirtualHandleString(handle, utf8Decoder) : GetNonVirtualString(handle, utf8Decoder, prefixOpt: null); } internal MemoryBlock GetMemoryBlock(StringHandle handle) { return handle.IsVirtual ? GetVirtualHandleMemoryBlock(handle) : GetNonVirtualStringMemoryBlock(handle); } internal static string GetVirtualString(StringHandle.VirtualIndex index) { return s_virtualValues![(int)index]; } private string GetNonVirtualString(StringHandle handle, MetadataStringDecoder utf8Decoder, byte[]? prefixOpt) { Debug.Assert(handle.StringKind != StringKind.Virtual); char otherTerminator = handle.StringKind == StringKind.DotTerminated ? '.' : '\0'; return Block.PeekUtf8NullTerminated(handle.GetHeapOffset(), prefixOpt, utf8Decoder, out _, otherTerminator); } private unsafe MemoryBlock GetNonVirtualStringMemoryBlock(StringHandle handle) { Debug.Assert(handle.StringKind != StringKind.Virtual); char otherTerminator = handle.StringKind == StringKind.DotTerminated ? '.' : '\0'; int offset = handle.GetHeapOffset(); int length = Block.GetUtf8NullTerminatedLength(offset, out _, otherTerminator); return new MemoryBlock(Block.Pointer + offset, length); } private unsafe byte[] GetNonVirtualStringBytes(StringHandle handle, byte[] prefix) { Debug.Assert(handle.StringKind != StringKind.Virtual); var block = GetNonVirtualStringMemoryBlock(handle); var bytes = new byte[prefix.Length + block.Length]; Buffer.BlockCopy(prefix, 0, bytes, 0, prefix.Length); Marshal.Copy((IntPtr)block.Pointer, bytes, prefix.Length, block.Length); return bytes; } private string GetVirtualHandleString(StringHandle handle, MetadataStringDecoder utf8Decoder) { Debug.Assert(handle.IsVirtual); return handle.StringKind switch { StringKind.Virtual => GetVirtualString(handle.GetVirtualIndex()), StringKind.WinRTPrefixed => GetNonVirtualString(handle, utf8Decoder, MetadataReader.WinRTPrefix), _ => throw ExceptionUtilities.UnexpectedValue(handle.StringKind), }; } private MemoryBlock GetVirtualHandleMemoryBlock(StringHandle handle) { Debug.Assert(handle.IsVirtual); var heap = VirtualHeap.GetOrCreateVirtualHeap(ref _lazyVirtualHeap); lock (heap) { if (!heap.TryGetMemoryBlock(handle.RawValue, out var block)) { byte[] bytes = handle.StringKind switch { StringKind.Virtual => Encoding.UTF8.GetBytes(GetVirtualString(handle.GetVirtualIndex())), StringKind.WinRTPrefixed => GetNonVirtualStringBytes(handle, MetadataReader.WinRTPrefix), _ => throw ExceptionUtilities.UnexpectedValue(handle.StringKind), }; block = heap.AddBlob(handle.RawValue, bytes); } return block; } } internal BlobReader GetBlobReader(StringHandle handle) { return new BlobReader(GetMemoryBlock(handle)); } internal StringHandle GetNextHandle(StringHandle handle) { if (handle.IsVirtual) { return default(StringHandle); } int terminator = this.Block.IndexOf(0, handle.GetHeapOffset()); if (terminator == -1 || terminator == Block.Length - 1) { return default(StringHandle); } return StringHandle.FromOffset(terminator + 1); } internal bool Equals(StringHandle handle, string value, MetadataStringDecoder utf8Decoder, bool ignoreCase) { Debug.Assert(value != null); if (handle.IsVirtual) { // TODO: This can allocate unnecessarily for <WinRT> prefixed handles. return string.Equals(GetString(handle, utf8Decoder), value, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); } if (handle.IsNil) { return value.Length == 0; } char otherTerminator = handle.StringKind == StringKind.DotTerminated ? '.' : '\0'; return this.Block.Utf8NullTerminatedEquals(handle.GetHeapOffset(), value, utf8Decoder, otherTerminator, ignoreCase); } internal bool StartsWith(StringHandle handle, string value, MetadataStringDecoder utf8Decoder, bool ignoreCase) { Debug.Assert(value != null); if (handle.IsVirtual) { // TODO: This can allocate unnecessarily for <WinRT> prefixed handles. return GetString(handle, utf8Decoder).StartsWith(value, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); } if (handle.IsNil) { return value.Length == 0; } char otherTerminator = handle.StringKind == StringKind.DotTerminated ? '.' : '\0'; return this.Block.Utf8NullTerminatedStartsWith(handle.GetHeapOffset(), value, utf8Decoder, otherTerminator, ignoreCase); } /// <summary> /// Returns true if the given raw (non-virtual) handle represents the same string as given ASCII string. /// </summary> internal bool EqualsRaw(StringHandle rawHandle, string asciiString) { Debug.Assert(!rawHandle.IsVirtual); Debug.Assert(rawHandle.StringKind != StringKind.DotTerminated, "Not supported"); return this.Block.CompareUtf8NullTerminatedStringWithAsciiString(rawHandle.GetHeapOffset(), asciiString) == 0; } /// <summary> /// Returns the heap index of the given ASCII character or -1 if not found prior null terminator or end of heap. /// </summary> internal int IndexOfRaw(int startIndex, char asciiChar) { Debug.Assert(asciiChar != 0 && asciiChar <= 0x7f); return this.Block.Utf8NullTerminatedOffsetOfAsciiChar(startIndex, asciiChar); } /// <summary> /// Returns true if the given raw (non-virtual) handle represents a string that starts with given ASCII prefix. /// </summary> internal bool StartsWithRaw(StringHandle rawHandle, string asciiPrefix) { Debug.Assert(!rawHandle.IsVirtual); Debug.Assert(rawHandle.StringKind != StringKind.DotTerminated, "Not supported"); return this.Block.Utf8NullTerminatedStringStartsWithAsciiPrefix(rawHandle.GetHeapOffset(), asciiPrefix); } /// <summary> /// Equivalent to Array.BinarySearch, searches for given raw (non-virtual) handle in given array of ASCII strings. /// </summary> internal int BinarySearchRaw(string[] asciiKeys, StringHandle rawHandle) { Debug.Assert(!rawHandle.IsVirtual); Debug.Assert(rawHandle.StringKind != StringKind.DotTerminated, "Not supported"); return this.Block.BinarySearch(asciiKeys, rawHandle.GetHeapOffset()); } } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/tests/JIT/Regression/CLR-x86-JIT/V1-M10/b02352/b02352.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; internal class cb6054ToByte_all { #pragma warning disable 0414 public static readonly String s_strActiveBugNums = "None."; #pragma warning restore 0414 public static readonly String s_strDtTmVer = "1999/07/15 16:20"; // t-seansp public static readonly String s_strClassMethod = "Convert.ToByte( all )"; public static readonly String s_strTFName = "Cb6054ToByte_all"; public static readonly String s_strTFAbbrev = "Cb6054"; public static readonly String s_strTFPath = "Jit\\Regression\\m10\\b02352"; public bool verbose = false; public static String[] s_strMethodsCovered = { "Method_Covered: Convert.ToByte( Boolean )" //bool ,"Method_Covered: Convert.ToByte( Byte )" //byte ,"Method_Covered: Convert.ToByte( Double )" //double ,"Method_Covered: Convert.ToByte( Single )" //single ,"Method_Covered: Convert.ToByte( Int32 )" //int ,"Method_Covered: Convert.ToByte( Int64 )" //long ,"Method_Covered: Convert.ToByte( Int16 )" //short ,"Method_Covered: Convert.ToByte( Currency )" //System/Currency ,"Method_Covered: Convert.ToByte( Decimal )" //System/Decimal ,"Method_Covered: Convert.ToByte( String )" //System/String ,"Method_Covered: Convert.ToByte( Object )" //System/Object ,"Method_Covered: Convert.ToByte( String, Int32 )" //System/String, int }; public static void printoutCoveredMethods() { Console.Error.WriteLine(""); Console.Error.WriteLine("Method_Count==12 (" + s_strMethodsCovered.Length + "==confirm) !!"); Console.Error.WriteLine(""); for (int ia = 0; ia < s_strMethodsCovered.Length; ia++) { Console.Error.WriteLine(s_strMethodsCovered[ia]); } Console.Error.WriteLine(""); } public virtual Boolean runTest() { Console.Error.WriteLine(s_strTFPath + " " + s_strTFName + " ,for " + s_strClassMethod + " ,Source ver " + s_strDtTmVer); String strLoc = "Loc_000oo"; int inCountTestcases = 0; int inCountErrors = 0; if (verbose) Console.WriteLine("Method: Byte Convert.ToByte( Int32 )"); try { Int32[] int3Array = { 10, 0, 100, 255, }; Byte[] int3Results = { 10, 0, 100, 255, }; for (int i = 0; i < int3Array.Length; i++) { inCountTestcases++; if (verbose) Console.Write("Testing : " + int3Array[i] + "..."); try { Byte result = Convert.ToByte(int3Array[i]); if (verbose) Console.WriteLine(result + "==" + int3Results[i]); if (!result.Equals(int3Results[i])) { inCountErrors++; strLoc = "Err_rint3Ar," + i; Console.Error.WriteLine(strLoc + " Expected = '" + int3Results[i] + "' ... Received = '" + result + "'."); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xint3Ar," + i; Console.Error.WriteLine(strLoc + " Exception Thrown: " + e.GetType().FullName); } } inCountTestcases++; if (verbose) Console.WriteLine("Testing : Lower Bound"); try { Byte result = Convert.ToByte(((IConvertible)(-100)).ToInt32(null)); inCountErrors++; strLoc = "Err_xint3A1"; Console.Error.WriteLine(strLoc + " No Exception Thrown."); } catch (OverflowException e) { if (!e.GetType().FullName.Equals("System.OverflowException")) { inCountErrors++; strLoc = "Err_xint3B1"; Console.Error.WriteLine(strLoc + "More specific Exception thrown : " + e.GetType().FullName); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xint3C1"; Console.Error.WriteLine(strLoc + " Wrong Exception Thrown: " + e.GetType().FullName); } inCountTestcases++; if (verbose) Console.WriteLine("Testing : Upper Bound"); try { Byte result = Convert.ToByte(((IConvertible)1000).ToInt32(null)); inCountErrors++; strLoc = "Err_xint3A2"; Console.Error.WriteLine(strLoc + " No Exception Thrown."); } catch (OverflowException e) { if (!e.GetType().FullName.Equals("System.OverflowException")) { inCountErrors++; strLoc = "Err_xint3B2"; Console.Error.WriteLine(strLoc + "More specific Exception thrown : " + e.GetType().FullName); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xint3C2"; Console.Error.WriteLine(strLoc + " Wrong Exception Thrown: " + e.GetType().FullName); } } catch (Exception e) { Console.WriteLine("Uncaught Exception in Byte Convert.ToByte( Int32 )"); Console.WriteLine("Exception->" + e.GetType().FullName); } if (verbose) Console.WriteLine("Method: Byte Convert.ToByte( Int64 )"); try { Int64[] int6Array = { 10L, 100L, }; Byte[] int6Results = { (( (IConvertible)10 )).ToByte(null), (( (IConvertible)100 )).ToByte(null), }; for (int i = 0; i < int6Array.Length; i++) { inCountTestcases++; if (verbose) Console.Write("Testing : " + int6Array[i] + "..."); try { Byte result = Convert.ToByte(int6Array[i]); if (verbose) Console.WriteLine(result + "==" + int6Results[i]); if (!result.Equals(int6Results[i])) { inCountErrors++; strLoc = "Err_rint6Ar," + i; Console.Error.WriteLine(strLoc + " Expected = '" + int6Results[i] + "' ... Received = '" + result + "'."); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xint6Ar," + i; Console.Error.WriteLine(strLoc + " Exception Thrown: " + e.GetType().FullName); } } inCountTestcases++; if (verbose) Console.WriteLine("Testing : Lower Bound"); try { Byte result = Convert.ToByte(((IConvertible)(-100)).ToInt64(null)); inCountErrors++; strLoc = "Err_xInt6A1"; Console.Error.WriteLine(strLoc + " No Exception Thrown."); } catch (OverflowException e) { if (!e.GetType().FullName.Equals("System.OverflowException")) { inCountErrors++; strLoc = "Err_xInt6B1"; Console.Error.WriteLine(strLoc + "More specific Exception thrown : " + e.GetType().FullName); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xInt6C1"; Console.Error.WriteLine(strLoc + " Wrong Exception Thrown: " + e.GetType().FullName); } inCountTestcases++; if (verbose) Console.WriteLine("Testing : Upper Bound"); try { Byte result = Convert.ToByte(((IConvertible)1000).ToInt64(null)); inCountErrors++; strLoc = "Err_xInt6A2"; Console.Error.WriteLine(strLoc + " No Exception Thrown."); } catch (OverflowException e) { if (!e.GetType().FullName.Equals("System.OverflowException")) { inCountErrors++; strLoc = "Err_xInt6B2"; Console.Error.WriteLine(strLoc + "More specific Exception thrown : " + e.GetType().FullName); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xInt6C2"; Console.Error.WriteLine(strLoc + " Wrong Exception Thrown: " + e.GetType().FullName); } } catch (Exception e) { Console.WriteLine("Uncaught Exception in Byte Convert.ToByte( Int64 )"); Console.WriteLine("Exception->" + e.GetType().FullName); } if (verbose) Console.WriteLine("Method: Byte Convert.ToByte( Int16 )"); try { Int16[] int1Array = { 0, 255, 100, 2, }; Byte[] int1Results = { 0, 255, 100, 2, }; for (int i = 0; i < int1Array.Length; i++) { inCountTestcases++; if (verbose) Console.Write("Testing : " + int1Array[i] + "..."); try { Byte result = Convert.ToByte(int1Array[i]); if (verbose) Console.WriteLine(result + "==" + int1Results[i]); if (!result.Equals(int1Results[i])) { inCountErrors++; strLoc = "Err_rint1Ar," + i; Console.Error.WriteLine(strLoc + " Expected = '" + int1Results[i] + "' ... Received = '" + result + "'."); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xint1Ar," + i; Console.Error.WriteLine(strLoc + " Exception Thrown: " + e.GetType().FullName); } } inCountTestcases++; if (verbose) Console.WriteLine("Testing : Lower Bound"); try { Byte result = Convert.ToByte(((IConvertible)(-100)).ToInt16(null)); inCountErrors++; strLoc = "Err_xint1A1"; Console.Error.WriteLine(strLoc + " No Exception Thrown."); } catch (OverflowException e) { if (!e.GetType().FullName.Equals("System.OverflowException")) { inCountErrors++; strLoc = "Err_xint1B1"; Console.Error.WriteLine(strLoc + "More specific Exception thrown : " + e.GetType().FullName); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xint1C1"; Console.Error.WriteLine(strLoc + " Wrong Exception Thrown: " + e.GetType().FullName); } inCountTestcases++; if (verbose) Console.WriteLine("Testing : Upper Bound"); try { Byte result = Convert.ToByte(((IConvertible)1000).ToInt16(null)); inCountErrors++; strLoc = "Err_xint1A2"; Console.Error.WriteLine(strLoc + " No Exception Thrown."); } catch (OverflowException e) { if (!e.GetType().FullName.Equals("System.OverflowException")) { inCountErrors++; strLoc = "Err_xint1B2"; Console.Error.WriteLine(strLoc + "More specific Exception thrown : " + e.GetType().FullName); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xint1C2"; Console.Error.WriteLine(strLoc + " Wrong Exception Thrown: " + e.GetType().FullName); } } catch (Exception e) { Console.WriteLine("Uncaught Exception in Byte Convert.ToByte( Int16 )"); Console.WriteLine("Exception->" + e.GetType().FullName); } if (verbose) Console.WriteLine("Method: Byte Convert.ToByte( Decimal )"); try { Decimal[] deciArray = { ( (IConvertible)Byte.MaxValue ).ToDecimal(null), ( (IConvertible)Byte.MinValue ).ToDecimal(null), new Decimal( 254.01 ), ( (IConvertible) ( Byte.MaxValue/2 ) ).ToDecimal(null), }; Byte[] deciResults = { Byte.MaxValue, Byte.MinValue, 254, Byte.MaxValue/2, }; for (int i = 0; i < deciArray.Length; i++) { inCountTestcases++; if (verbose) Console.Write("Testing : " + deciArray[i] + "..."); try { Byte result = Convert.ToByte(deciArray[i]); if (verbose) Console.WriteLine(result + "==" + deciResults[i]); if (!result.Equals(deciResults[i])) { inCountErrors++; strLoc = "Err_rdeciAr," + i; Console.Error.WriteLine(strLoc + " Expected = '" + deciResults[i] + "' ... Received = '" + result + "'."); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xdeciAr," + i; Console.Error.WriteLine(strLoc + " Exception Thrown: " + e.GetType().FullName); } } inCountTestcases++; if (verbose) Console.WriteLine("Testing : Lower Bound"); try { Byte result = Convert.ToByte(((IConvertible)(-100)).ToDecimal(null)); inCountErrors++; strLoc = "Err_xdeciA1"; Console.Error.WriteLine(strLoc + " No Exception Thrown."); } catch (OverflowException e) { if (!e.GetType().FullName.Equals("System.OverflowException")) { inCountErrors++; strLoc = "Err_xdeciB1"; Console.Error.WriteLine(strLoc + "More specific Exception thrown : " + e.GetType().FullName); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xdeciC1"; Console.Error.WriteLine(strLoc + " Wrong Exception Thrown: " + e.GetType().FullName); } inCountTestcases++; if (verbose) Console.WriteLine("Testing : Upper Bound"); try { Byte result = Convert.ToByte(((IConvertible)1000).ToDecimal(null)); inCountErrors++; strLoc = "Err_xdeciA2"; Console.Error.WriteLine(strLoc + " No Exception Thrown."); } catch (OverflowException e) { if (!e.GetType().FullName.Equals("System.OverflowException")) { inCountErrors++; strLoc = "Err_xdeciB2"; Console.Error.WriteLine(strLoc + "More specific Exception thrown : " + e.GetType().FullName); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xdeciC2"; Console.Error.WriteLine(strLoc + " Wrong Exception Thrown: " + e.GetType().FullName); } } catch (Exception e) { Console.WriteLine("Uncaught Exception in Byte Convert.ToByte( Decimal )"); Console.WriteLine("Exception->" + e.GetType().FullName); } if (verbose) Console.WriteLine("Method: Byte Convert.ToByte( String )"); try { String[] striArray = { ( Byte.MaxValue ).ToString(), ( Byte.MinValue ).ToString(), }; Byte[] striResults = { Byte.MaxValue, Byte.MinValue, }; for (int i = 0; i < striArray.Length; i++) { inCountTestcases++; if (verbose) Console.Write("Testing : " + striArray[i] + "..."); try { Byte result = Convert.ToByte(striArray[i]); if (verbose) Console.WriteLine(result + "==" + striResults[i]); if (!result.Equals(striResults[i])) { inCountErrors++; strLoc = "Err_rstriAr," + i; Console.Error.WriteLine(strLoc + " Expected = '" + striResults[i] + "' ... Received = '" + result + "'."); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xstriAr," + i; Console.Error.WriteLine(strLoc + " Exception Thrown: " + e.GetType().FullName); } } inCountTestcases++; if (verbose) Console.WriteLine("Testing : Argument null"); try { String[] dummy = { null, }; throw new System.ArgumentNullException(); } catch (ArgumentNullException e) { if (!e.GetType().FullName.Equals("System.ArgumentNullException")) { inCountErrors++; strLoc = "Err_xstriB1"; Console.Error.WriteLine(strLoc + " More specific Exception thrown : " + e.GetType().FullName); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xstriC1"; Console.Error.WriteLine(strLoc + " Wrong Exception Thrown: " + e.GetType().FullName); } inCountTestcases++; if (verbose) Console.WriteLine("Testing : UpperBound"); try { Byte result = Convert.ToByte("256"); inCountErrors++; strLoc = "Err_xstriA2"; Console.Error.WriteLine(strLoc + " No Exception Thrown."); } catch (OverflowException e) { if (!e.GetType().FullName.Equals("System.OverflowException")) { inCountErrors++; strLoc = "Err_xstriB2"; Console.Error.WriteLine(strLoc + " More specific Exception thrown : " + e.GetType().FullName); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xstriC2"; Console.Error.WriteLine(strLoc + " Wrong Exception Thrown: " + e.GetType().FullName); } inCountTestcases++; if (verbose) Console.WriteLine("Testing : LowerBound"); try { Byte result = Convert.ToByte("-1"); inCountErrors++; strLoc = "Err_xstriA4"; Console.Error.WriteLine(strLoc + " No Exception Thrown."); } catch (OverflowException e) { if (!e.GetType().FullName.Equals("System.OverflowException")) { inCountErrors++; strLoc = "Err_xstriB4"; Console.Error.WriteLine(strLoc + " More specific Exception thrown : " + e.GetType().FullName); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xstriC4"; Console.Error.WriteLine(strLoc + " Wrong Exception Thrown: " + e.GetType().FullName); } inCountTestcases++; if (verbose) Console.WriteLine("Testing : Format"); try { Byte result = Convert.ToByte("!56"); inCountErrors++; strLoc = "Err_xstriA3"; Console.Error.WriteLine(strLoc + " No Exception Thrown."); } catch (FormatException e) { if (!e.GetType().FullName.Equals("System.FormatException")) { inCountErrors++; strLoc = "Err_xstriB3"; Console.Error.WriteLine(strLoc + " More specific Exception thrown : " + e.GetType().FullName); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xstriC3"; Console.Error.WriteLine(strLoc + " Wrong Exception Thrown: " + e.GetType().FullName); } } catch (Exception e) { Console.WriteLine("Uncaught Exception in Byte Convert.ToByte( String )"); Console.WriteLine("Exception->" + e.GetType().FullName); } if (verbose) Console.WriteLine("Method: Byte Convert.ToByte( String, Int32 )"); try { String[] striArray = { "10", "100", "1011", "ff", "0xff", "77", "11", "11111111", }; Int32[] striBase = { 10, 10, 2, 16, 16, 8, 2, 2, }; Byte[] striResults = { 10, 100, 11, 255, 255, 63, 3, 255, }; for (int i = 0; i < striArray.Length; i++) { inCountTestcases++; if (verbose) Console.Write("Testing : " + striArray[i] + "," + striBase[i] + "..."); try { Byte result = Convert.ToByte(striArray[i], striBase[i]); if (verbose) Console.WriteLine(result + "==" + striResults[i]); if (!result.Equals(striResults[i])) { inCountErrors++; strLoc = "Err_rstri2Ar," + i; Console.Error.WriteLine(strLoc + " Expected = '" + striResults[i] + "' ... Received = '" + result + "'."); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xstri2Ar," + i; Console.Error.WriteLine(strLoc + " Exception Thrown: " + e.GetType().FullName); } } inCountTestcases++; if (verbose) Console.WriteLine("Testing : Argument (bad base)"); try { String[] dummy = { null, }; Byte result = Convert.ToByte(dummy[0], 11); inCountErrors++; strLoc = "Err_xstri2A5"; Console.Error.WriteLine(strLoc + " No Exception Thrown."); } catch (ArgumentException e) { if (!e.GetType().FullName.Equals("System.ArgumentException")) { inCountErrors++; strLoc = "Err_xstri2B5"; Console.Error.WriteLine(strLoc + " More specific Exception thrown : " + e.GetType().FullName); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xstri2C5"; Console.Error.WriteLine(strLoc + " Wrong Exception Thrown: " + e.GetType().FullName); } inCountTestcases++; if (verbose) Console.WriteLine("Testing : Argument null"); try { String[] dummy = { null, }; Byte result = Convert.ToByte(dummy[0], 10); if (result != 0) { inCountErrors++; strLoc = "Err_xstri2A1"; } } catch (Exception e) { inCountErrors++; strLoc = "Err_xstri2C1"; Console.Error.WriteLine(strLoc + " Wrong Exception Thrown: " + e.GetType().FullName); } inCountTestcases++; if (verbose) Console.WriteLine("Testing : UpperBound"); try { Byte result = Convert.ToByte("256", 10); inCountErrors++; strLoc = "Err_xstri2A2"; Console.Error.WriteLine(strLoc + " No Exception Thrown."); } catch (OverflowException e) { if (!e.GetType().FullName.Equals("System.OverflowException")) { inCountErrors++; strLoc = "Err_xstri2B2"; Console.Error.WriteLine(strLoc + " More specific Exception thrown : " + e.GetType().FullName); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xstri2C2"; Console.Error.WriteLine(strLoc + " Wrong Exception Thrown: " + e.GetType().FullName); } inCountTestcases++; if (verbose) Console.WriteLine("Testing : UpperBound (binary)"); try { Byte result = Convert.ToByte("111111111", 2); inCountErrors++; strLoc = "Err_xstri2A5"; Console.Error.WriteLine(strLoc + " No Exception Thrown."); } catch (OverflowException e) { if (!e.GetType().FullName.Equals("System.OverflowException")) { inCountErrors++; strLoc = "Err_xstri2B5"; Console.Error.WriteLine(strLoc + " More specific Exception thrown : " + e.GetType().FullName); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xstri2C5"; Console.Error.WriteLine(strLoc + " Wrong Exception Thrown: " + e.GetType().FullName); } inCountTestcases++; if (verbose) Console.WriteLine("Testing : UpperBound (hex)"); try { Byte result = Convert.ToByte("ffffe", 16); inCountErrors++; strLoc = "Err_xstri2A6"; Console.Error.WriteLine(strLoc + " No Exception Thrown."); } catch (OverflowException e) { if (!e.GetType().FullName.Equals("System.OverflowException")) { inCountErrors++; strLoc = "Err_xstri2B6"; Console.Error.WriteLine(strLoc + " More specific Exception thrown : " + e.GetType().FullName); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xstri2C6"; Console.Error.WriteLine(strLoc + " Wrong Exception Thrown: " + e.GetType().FullName); } inCountTestcases++; if (verbose) Console.WriteLine("Testing : UpperBound (octal)"); try { Byte result = Convert.ToByte("7777777", 8); inCountErrors++; strLoc = "Err_xstri2A7"; Console.Error.WriteLine(strLoc + " No Exception Thrown."); } catch (OverflowException e) { if (!e.GetType().FullName.Equals("System.OverflowException")) { inCountErrors++; strLoc = "Err_xstri2B7"; Console.Error.WriteLine(strLoc + " More specific Exception thrown : " + e.GetType().FullName); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xstri2C7"; Console.Error.WriteLine(strLoc + " Wrong Exception Thrown: " + e.GetType().FullName); } inCountTestcases++; if (verbose) Console.WriteLine("Testing : Format (hex)"); try { Byte result = Convert.ToByte("fffg", 16); inCountErrors++; strLoc = "Err_xstri2A8"; Console.Error.WriteLine(strLoc + " No Exception Thrown."); } catch (FormatException e) { if (!e.GetType().FullName.Equals("System.FormatException")) { inCountErrors++; strLoc = "Err_xstri2B8"; Console.Error.WriteLine(strLoc + " More specific Exception thrown : " + e.GetType().FullName); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xstri2C8"; Console.Error.WriteLine(strLoc + " Wrong Exception Thrown: " + e.GetType().FullName); } inCountTestcases++; if (verbose) Console.WriteLine("Testing : Format (hex)"); try { Byte result = Convert.ToByte("0xxfff", 16); inCountErrors++; strLoc = "Err_xstri2A8"; Console.Error.WriteLine(strLoc + " No Exception Thrown."); } catch (FormatException e) { if (!e.GetType().FullName.Equals("System.FormatException")) { inCountErrors++; strLoc = "Err_xstri2B8"; Console.Error.WriteLine(strLoc + " More specific Exception thrown : " + e.GetType().FullName); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xstri2C8"; Console.Error.WriteLine(strLoc + " Wrong Exception Thrown: " + e.GetType().FullName); } inCountTestcases++; if (verbose) Console.WriteLine("Testing : Format (octal)"); try { Byte result = Convert.ToByte("8", 8); inCountErrors++; strLoc = "Err_xstri2A0"; Console.Error.WriteLine(strLoc + " No Exception Thrown."); } catch (FormatException e) { if (!e.GetType().FullName.Equals("System.FormatException")) { inCountErrors++; strLoc = "Err_xstri2B0"; Console.Error.WriteLine(strLoc + " More specific Exception thrown : " + e.GetType().FullName); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xstri2C0"; Console.Error.WriteLine(strLoc + " Wrong Exception Thrown: " + e.GetType().FullName); } inCountTestcases++; if (verbose) Console.WriteLine("Testing : Format (bin)"); try { Byte result = Convert.ToByte("112", 2); inCountErrors++; strLoc = "Err_xstri2A9"; Console.Error.WriteLine(strLoc + " No Exception Thrown."); } catch (FormatException e) { if (!e.GetType().FullName.Equals("System.FormatException")) { inCountErrors++; strLoc = "Err_xstri2B9"; Console.Error.WriteLine(strLoc + " More specific Exception thrown : " + e.GetType().FullName); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xstri2C9"; Console.Error.WriteLine(strLoc + " Wrong Exception Thrown: " + e.GetType().FullName); } inCountTestcases++; if (verbose) Console.WriteLine("Testing : LowerBound"); try { Byte result = Convert.ToByte("-1", 10); inCountErrors++; strLoc = "Err_xstri2A4"; Console.Error.WriteLine(strLoc + " No Exception Thrown."); } catch (OverflowException e) { if (!e.GetType().FullName.Equals("System.OverflowException")) { inCountErrors++; strLoc = "Err_xstri2B4"; Console.Error.WriteLine(strLoc + " More specific Exception thrown : " + e.GetType().FullName); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xstri2C4"; Console.Error.WriteLine(strLoc + " Wrong Exception Thrown: " + e.GetType().FullName); } inCountTestcases++; if (verbose) Console.WriteLine("Testing : Format"); try { Byte result = Convert.ToByte("!56", 10); inCountErrors++; strLoc = "Err_xstri2A3"; Console.Error.WriteLine(strLoc + " No Exception Thrown."); } catch (FormatException e) { if (!e.GetType().FullName.Equals("System.FormatException")) { inCountErrors++; strLoc = "Err_xstri2B3"; Console.Error.WriteLine(strLoc + " More specific Exception thrown : " + e.GetType().FullName); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xstri2C3"; Console.Error.WriteLine(strLoc + " Wrong Exception Thrown: " + e.GetType().FullName); } } catch (Exception e) { Console.WriteLine("Uncaught Exception in Byte Convert.ToByte( String, Int32 )"); Console.WriteLine("Exception->" + e.GetType().FullName); } Console.Error.Write(s_strTFName); Console.Error.Write(": "); if (inCountErrors == 0) { Console.Error.WriteLine(" inCountTestcases==" + inCountTestcases + " paSs"); return true; } else { Console.Error.WriteLine(s_strTFPath + s_strTFName + ".cs"); Console.Error.WriteLine(" inCountTestcases==" + inCountTestcases); Console.Error.WriteLine("FAiL"); Console.Error.WriteLine(" inCountErrors==" + inCountErrors); return false; } } public static int Main(String[] args) { bool bResult = false; // Assume FAiL cb6054ToByte_all cbX = new cb6054ToByte_all(); try { if (args[0].Equals("-v")) cbX.verbose = true; } catch (Exception) { } try { printoutCoveredMethods(); bResult = cbX.runTest(); } catch (Exception exc_main) { bResult = false; Console.WriteLine("FAiL! Error Err_9999zzz! Uncaught Exception caught in main(), exc_main==" + exc_main); } if (!bResult) { Console.WriteLine(s_strTFPath + s_strTFName); Console.Error.WriteLine(" "); Console.Error.WriteLine("Try 'cb6054ToByte_all.exe -v' to see tests..."); Console.Error.WriteLine("FAiL! " + s_strTFAbbrev); // Last line is a nice eye catcher location. Console.Error.WriteLine(" "); } return bResult ? 100 : 1; } } }
// 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; internal class cb6054ToByte_all { #pragma warning disable 0414 public static readonly String s_strActiveBugNums = "None."; #pragma warning restore 0414 public static readonly String s_strDtTmVer = "1999/07/15 16:20"; // t-seansp public static readonly String s_strClassMethod = "Convert.ToByte( all )"; public static readonly String s_strTFName = "Cb6054ToByte_all"; public static readonly String s_strTFAbbrev = "Cb6054"; public static readonly String s_strTFPath = "Jit\\Regression\\m10\\b02352"; public bool verbose = false; public static String[] s_strMethodsCovered = { "Method_Covered: Convert.ToByte( Boolean )" //bool ,"Method_Covered: Convert.ToByte( Byte )" //byte ,"Method_Covered: Convert.ToByte( Double )" //double ,"Method_Covered: Convert.ToByte( Single )" //single ,"Method_Covered: Convert.ToByte( Int32 )" //int ,"Method_Covered: Convert.ToByte( Int64 )" //long ,"Method_Covered: Convert.ToByte( Int16 )" //short ,"Method_Covered: Convert.ToByte( Currency )" //System/Currency ,"Method_Covered: Convert.ToByte( Decimal )" //System/Decimal ,"Method_Covered: Convert.ToByte( String )" //System/String ,"Method_Covered: Convert.ToByte( Object )" //System/Object ,"Method_Covered: Convert.ToByte( String, Int32 )" //System/String, int }; public static void printoutCoveredMethods() { Console.Error.WriteLine(""); Console.Error.WriteLine("Method_Count==12 (" + s_strMethodsCovered.Length + "==confirm) !!"); Console.Error.WriteLine(""); for (int ia = 0; ia < s_strMethodsCovered.Length; ia++) { Console.Error.WriteLine(s_strMethodsCovered[ia]); } Console.Error.WriteLine(""); } public virtual Boolean runTest() { Console.Error.WriteLine(s_strTFPath + " " + s_strTFName + " ,for " + s_strClassMethod + " ,Source ver " + s_strDtTmVer); String strLoc = "Loc_000oo"; int inCountTestcases = 0; int inCountErrors = 0; if (verbose) Console.WriteLine("Method: Byte Convert.ToByte( Int32 )"); try { Int32[] int3Array = { 10, 0, 100, 255, }; Byte[] int3Results = { 10, 0, 100, 255, }; for (int i = 0; i < int3Array.Length; i++) { inCountTestcases++; if (verbose) Console.Write("Testing : " + int3Array[i] + "..."); try { Byte result = Convert.ToByte(int3Array[i]); if (verbose) Console.WriteLine(result + "==" + int3Results[i]); if (!result.Equals(int3Results[i])) { inCountErrors++; strLoc = "Err_rint3Ar," + i; Console.Error.WriteLine(strLoc + " Expected = '" + int3Results[i] + "' ... Received = '" + result + "'."); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xint3Ar," + i; Console.Error.WriteLine(strLoc + " Exception Thrown: " + e.GetType().FullName); } } inCountTestcases++; if (verbose) Console.WriteLine("Testing : Lower Bound"); try { Byte result = Convert.ToByte(((IConvertible)(-100)).ToInt32(null)); inCountErrors++; strLoc = "Err_xint3A1"; Console.Error.WriteLine(strLoc + " No Exception Thrown."); } catch (OverflowException e) { if (!e.GetType().FullName.Equals("System.OverflowException")) { inCountErrors++; strLoc = "Err_xint3B1"; Console.Error.WriteLine(strLoc + "More specific Exception thrown : " + e.GetType().FullName); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xint3C1"; Console.Error.WriteLine(strLoc + " Wrong Exception Thrown: " + e.GetType().FullName); } inCountTestcases++; if (verbose) Console.WriteLine("Testing : Upper Bound"); try { Byte result = Convert.ToByte(((IConvertible)1000).ToInt32(null)); inCountErrors++; strLoc = "Err_xint3A2"; Console.Error.WriteLine(strLoc + " No Exception Thrown."); } catch (OverflowException e) { if (!e.GetType().FullName.Equals("System.OverflowException")) { inCountErrors++; strLoc = "Err_xint3B2"; Console.Error.WriteLine(strLoc + "More specific Exception thrown : " + e.GetType().FullName); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xint3C2"; Console.Error.WriteLine(strLoc + " Wrong Exception Thrown: " + e.GetType().FullName); } } catch (Exception e) { Console.WriteLine("Uncaught Exception in Byte Convert.ToByte( Int32 )"); Console.WriteLine("Exception->" + e.GetType().FullName); } if (verbose) Console.WriteLine("Method: Byte Convert.ToByte( Int64 )"); try { Int64[] int6Array = { 10L, 100L, }; Byte[] int6Results = { (( (IConvertible)10 )).ToByte(null), (( (IConvertible)100 )).ToByte(null), }; for (int i = 0; i < int6Array.Length; i++) { inCountTestcases++; if (verbose) Console.Write("Testing : " + int6Array[i] + "..."); try { Byte result = Convert.ToByte(int6Array[i]); if (verbose) Console.WriteLine(result + "==" + int6Results[i]); if (!result.Equals(int6Results[i])) { inCountErrors++; strLoc = "Err_rint6Ar," + i; Console.Error.WriteLine(strLoc + " Expected = '" + int6Results[i] + "' ... Received = '" + result + "'."); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xint6Ar," + i; Console.Error.WriteLine(strLoc + " Exception Thrown: " + e.GetType().FullName); } } inCountTestcases++; if (verbose) Console.WriteLine("Testing : Lower Bound"); try { Byte result = Convert.ToByte(((IConvertible)(-100)).ToInt64(null)); inCountErrors++; strLoc = "Err_xInt6A1"; Console.Error.WriteLine(strLoc + " No Exception Thrown."); } catch (OverflowException e) { if (!e.GetType().FullName.Equals("System.OverflowException")) { inCountErrors++; strLoc = "Err_xInt6B1"; Console.Error.WriteLine(strLoc + "More specific Exception thrown : " + e.GetType().FullName); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xInt6C1"; Console.Error.WriteLine(strLoc + " Wrong Exception Thrown: " + e.GetType().FullName); } inCountTestcases++; if (verbose) Console.WriteLine("Testing : Upper Bound"); try { Byte result = Convert.ToByte(((IConvertible)1000).ToInt64(null)); inCountErrors++; strLoc = "Err_xInt6A2"; Console.Error.WriteLine(strLoc + " No Exception Thrown."); } catch (OverflowException e) { if (!e.GetType().FullName.Equals("System.OverflowException")) { inCountErrors++; strLoc = "Err_xInt6B2"; Console.Error.WriteLine(strLoc + "More specific Exception thrown : " + e.GetType().FullName); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xInt6C2"; Console.Error.WriteLine(strLoc + " Wrong Exception Thrown: " + e.GetType().FullName); } } catch (Exception e) { Console.WriteLine("Uncaught Exception in Byte Convert.ToByte( Int64 )"); Console.WriteLine("Exception->" + e.GetType().FullName); } if (verbose) Console.WriteLine("Method: Byte Convert.ToByte( Int16 )"); try { Int16[] int1Array = { 0, 255, 100, 2, }; Byte[] int1Results = { 0, 255, 100, 2, }; for (int i = 0; i < int1Array.Length; i++) { inCountTestcases++; if (verbose) Console.Write("Testing : " + int1Array[i] + "..."); try { Byte result = Convert.ToByte(int1Array[i]); if (verbose) Console.WriteLine(result + "==" + int1Results[i]); if (!result.Equals(int1Results[i])) { inCountErrors++; strLoc = "Err_rint1Ar," + i; Console.Error.WriteLine(strLoc + " Expected = '" + int1Results[i] + "' ... Received = '" + result + "'."); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xint1Ar," + i; Console.Error.WriteLine(strLoc + " Exception Thrown: " + e.GetType().FullName); } } inCountTestcases++; if (verbose) Console.WriteLine("Testing : Lower Bound"); try { Byte result = Convert.ToByte(((IConvertible)(-100)).ToInt16(null)); inCountErrors++; strLoc = "Err_xint1A1"; Console.Error.WriteLine(strLoc + " No Exception Thrown."); } catch (OverflowException e) { if (!e.GetType().FullName.Equals("System.OverflowException")) { inCountErrors++; strLoc = "Err_xint1B1"; Console.Error.WriteLine(strLoc + "More specific Exception thrown : " + e.GetType().FullName); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xint1C1"; Console.Error.WriteLine(strLoc + " Wrong Exception Thrown: " + e.GetType().FullName); } inCountTestcases++; if (verbose) Console.WriteLine("Testing : Upper Bound"); try { Byte result = Convert.ToByte(((IConvertible)1000).ToInt16(null)); inCountErrors++; strLoc = "Err_xint1A2"; Console.Error.WriteLine(strLoc + " No Exception Thrown."); } catch (OverflowException e) { if (!e.GetType().FullName.Equals("System.OverflowException")) { inCountErrors++; strLoc = "Err_xint1B2"; Console.Error.WriteLine(strLoc + "More specific Exception thrown : " + e.GetType().FullName); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xint1C2"; Console.Error.WriteLine(strLoc + " Wrong Exception Thrown: " + e.GetType().FullName); } } catch (Exception e) { Console.WriteLine("Uncaught Exception in Byte Convert.ToByte( Int16 )"); Console.WriteLine("Exception->" + e.GetType().FullName); } if (verbose) Console.WriteLine("Method: Byte Convert.ToByte( Decimal )"); try { Decimal[] deciArray = { ( (IConvertible)Byte.MaxValue ).ToDecimal(null), ( (IConvertible)Byte.MinValue ).ToDecimal(null), new Decimal( 254.01 ), ( (IConvertible) ( Byte.MaxValue/2 ) ).ToDecimal(null), }; Byte[] deciResults = { Byte.MaxValue, Byte.MinValue, 254, Byte.MaxValue/2, }; for (int i = 0; i < deciArray.Length; i++) { inCountTestcases++; if (verbose) Console.Write("Testing : " + deciArray[i] + "..."); try { Byte result = Convert.ToByte(deciArray[i]); if (verbose) Console.WriteLine(result + "==" + deciResults[i]); if (!result.Equals(deciResults[i])) { inCountErrors++; strLoc = "Err_rdeciAr," + i; Console.Error.WriteLine(strLoc + " Expected = '" + deciResults[i] + "' ... Received = '" + result + "'."); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xdeciAr," + i; Console.Error.WriteLine(strLoc + " Exception Thrown: " + e.GetType().FullName); } } inCountTestcases++; if (verbose) Console.WriteLine("Testing : Lower Bound"); try { Byte result = Convert.ToByte(((IConvertible)(-100)).ToDecimal(null)); inCountErrors++; strLoc = "Err_xdeciA1"; Console.Error.WriteLine(strLoc + " No Exception Thrown."); } catch (OverflowException e) { if (!e.GetType().FullName.Equals("System.OverflowException")) { inCountErrors++; strLoc = "Err_xdeciB1"; Console.Error.WriteLine(strLoc + "More specific Exception thrown : " + e.GetType().FullName); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xdeciC1"; Console.Error.WriteLine(strLoc + " Wrong Exception Thrown: " + e.GetType().FullName); } inCountTestcases++; if (verbose) Console.WriteLine("Testing : Upper Bound"); try { Byte result = Convert.ToByte(((IConvertible)1000).ToDecimal(null)); inCountErrors++; strLoc = "Err_xdeciA2"; Console.Error.WriteLine(strLoc + " No Exception Thrown."); } catch (OverflowException e) { if (!e.GetType().FullName.Equals("System.OverflowException")) { inCountErrors++; strLoc = "Err_xdeciB2"; Console.Error.WriteLine(strLoc + "More specific Exception thrown : " + e.GetType().FullName); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xdeciC2"; Console.Error.WriteLine(strLoc + " Wrong Exception Thrown: " + e.GetType().FullName); } } catch (Exception e) { Console.WriteLine("Uncaught Exception in Byte Convert.ToByte( Decimal )"); Console.WriteLine("Exception->" + e.GetType().FullName); } if (verbose) Console.WriteLine("Method: Byte Convert.ToByte( String )"); try { String[] striArray = { ( Byte.MaxValue ).ToString(), ( Byte.MinValue ).ToString(), }; Byte[] striResults = { Byte.MaxValue, Byte.MinValue, }; for (int i = 0; i < striArray.Length; i++) { inCountTestcases++; if (verbose) Console.Write("Testing : " + striArray[i] + "..."); try { Byte result = Convert.ToByte(striArray[i]); if (verbose) Console.WriteLine(result + "==" + striResults[i]); if (!result.Equals(striResults[i])) { inCountErrors++; strLoc = "Err_rstriAr," + i; Console.Error.WriteLine(strLoc + " Expected = '" + striResults[i] + "' ... Received = '" + result + "'."); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xstriAr," + i; Console.Error.WriteLine(strLoc + " Exception Thrown: " + e.GetType().FullName); } } inCountTestcases++; if (verbose) Console.WriteLine("Testing : Argument null"); try { String[] dummy = { null, }; throw new System.ArgumentNullException(); } catch (ArgumentNullException e) { if (!e.GetType().FullName.Equals("System.ArgumentNullException")) { inCountErrors++; strLoc = "Err_xstriB1"; Console.Error.WriteLine(strLoc + " More specific Exception thrown : " + e.GetType().FullName); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xstriC1"; Console.Error.WriteLine(strLoc + " Wrong Exception Thrown: " + e.GetType().FullName); } inCountTestcases++; if (verbose) Console.WriteLine("Testing : UpperBound"); try { Byte result = Convert.ToByte("256"); inCountErrors++; strLoc = "Err_xstriA2"; Console.Error.WriteLine(strLoc + " No Exception Thrown."); } catch (OverflowException e) { if (!e.GetType().FullName.Equals("System.OverflowException")) { inCountErrors++; strLoc = "Err_xstriB2"; Console.Error.WriteLine(strLoc + " More specific Exception thrown : " + e.GetType().FullName); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xstriC2"; Console.Error.WriteLine(strLoc + " Wrong Exception Thrown: " + e.GetType().FullName); } inCountTestcases++; if (verbose) Console.WriteLine("Testing : LowerBound"); try { Byte result = Convert.ToByte("-1"); inCountErrors++; strLoc = "Err_xstriA4"; Console.Error.WriteLine(strLoc + " No Exception Thrown."); } catch (OverflowException e) { if (!e.GetType().FullName.Equals("System.OverflowException")) { inCountErrors++; strLoc = "Err_xstriB4"; Console.Error.WriteLine(strLoc + " More specific Exception thrown : " + e.GetType().FullName); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xstriC4"; Console.Error.WriteLine(strLoc + " Wrong Exception Thrown: " + e.GetType().FullName); } inCountTestcases++; if (verbose) Console.WriteLine("Testing : Format"); try { Byte result = Convert.ToByte("!56"); inCountErrors++; strLoc = "Err_xstriA3"; Console.Error.WriteLine(strLoc + " No Exception Thrown."); } catch (FormatException e) { if (!e.GetType().FullName.Equals("System.FormatException")) { inCountErrors++; strLoc = "Err_xstriB3"; Console.Error.WriteLine(strLoc + " More specific Exception thrown : " + e.GetType().FullName); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xstriC3"; Console.Error.WriteLine(strLoc + " Wrong Exception Thrown: " + e.GetType().FullName); } } catch (Exception e) { Console.WriteLine("Uncaught Exception in Byte Convert.ToByte( String )"); Console.WriteLine("Exception->" + e.GetType().FullName); } if (verbose) Console.WriteLine("Method: Byte Convert.ToByte( String, Int32 )"); try { String[] striArray = { "10", "100", "1011", "ff", "0xff", "77", "11", "11111111", }; Int32[] striBase = { 10, 10, 2, 16, 16, 8, 2, 2, }; Byte[] striResults = { 10, 100, 11, 255, 255, 63, 3, 255, }; for (int i = 0; i < striArray.Length; i++) { inCountTestcases++; if (verbose) Console.Write("Testing : " + striArray[i] + "," + striBase[i] + "..."); try { Byte result = Convert.ToByte(striArray[i], striBase[i]); if (verbose) Console.WriteLine(result + "==" + striResults[i]); if (!result.Equals(striResults[i])) { inCountErrors++; strLoc = "Err_rstri2Ar," + i; Console.Error.WriteLine(strLoc + " Expected = '" + striResults[i] + "' ... Received = '" + result + "'."); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xstri2Ar," + i; Console.Error.WriteLine(strLoc + " Exception Thrown: " + e.GetType().FullName); } } inCountTestcases++; if (verbose) Console.WriteLine("Testing : Argument (bad base)"); try { String[] dummy = { null, }; Byte result = Convert.ToByte(dummy[0], 11); inCountErrors++; strLoc = "Err_xstri2A5"; Console.Error.WriteLine(strLoc + " No Exception Thrown."); } catch (ArgumentException e) { if (!e.GetType().FullName.Equals("System.ArgumentException")) { inCountErrors++; strLoc = "Err_xstri2B5"; Console.Error.WriteLine(strLoc + " More specific Exception thrown : " + e.GetType().FullName); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xstri2C5"; Console.Error.WriteLine(strLoc + " Wrong Exception Thrown: " + e.GetType().FullName); } inCountTestcases++; if (verbose) Console.WriteLine("Testing : Argument null"); try { String[] dummy = { null, }; Byte result = Convert.ToByte(dummy[0], 10); if (result != 0) { inCountErrors++; strLoc = "Err_xstri2A1"; } } catch (Exception e) { inCountErrors++; strLoc = "Err_xstri2C1"; Console.Error.WriteLine(strLoc + " Wrong Exception Thrown: " + e.GetType().FullName); } inCountTestcases++; if (verbose) Console.WriteLine("Testing : UpperBound"); try { Byte result = Convert.ToByte("256", 10); inCountErrors++; strLoc = "Err_xstri2A2"; Console.Error.WriteLine(strLoc + " No Exception Thrown."); } catch (OverflowException e) { if (!e.GetType().FullName.Equals("System.OverflowException")) { inCountErrors++; strLoc = "Err_xstri2B2"; Console.Error.WriteLine(strLoc + " More specific Exception thrown : " + e.GetType().FullName); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xstri2C2"; Console.Error.WriteLine(strLoc + " Wrong Exception Thrown: " + e.GetType().FullName); } inCountTestcases++; if (verbose) Console.WriteLine("Testing : UpperBound (binary)"); try { Byte result = Convert.ToByte("111111111", 2); inCountErrors++; strLoc = "Err_xstri2A5"; Console.Error.WriteLine(strLoc + " No Exception Thrown."); } catch (OverflowException e) { if (!e.GetType().FullName.Equals("System.OverflowException")) { inCountErrors++; strLoc = "Err_xstri2B5"; Console.Error.WriteLine(strLoc + " More specific Exception thrown : " + e.GetType().FullName); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xstri2C5"; Console.Error.WriteLine(strLoc + " Wrong Exception Thrown: " + e.GetType().FullName); } inCountTestcases++; if (verbose) Console.WriteLine("Testing : UpperBound (hex)"); try { Byte result = Convert.ToByte("ffffe", 16); inCountErrors++; strLoc = "Err_xstri2A6"; Console.Error.WriteLine(strLoc + " No Exception Thrown."); } catch (OverflowException e) { if (!e.GetType().FullName.Equals("System.OverflowException")) { inCountErrors++; strLoc = "Err_xstri2B6"; Console.Error.WriteLine(strLoc + " More specific Exception thrown : " + e.GetType().FullName); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xstri2C6"; Console.Error.WriteLine(strLoc + " Wrong Exception Thrown: " + e.GetType().FullName); } inCountTestcases++; if (verbose) Console.WriteLine("Testing : UpperBound (octal)"); try { Byte result = Convert.ToByte("7777777", 8); inCountErrors++; strLoc = "Err_xstri2A7"; Console.Error.WriteLine(strLoc + " No Exception Thrown."); } catch (OverflowException e) { if (!e.GetType().FullName.Equals("System.OverflowException")) { inCountErrors++; strLoc = "Err_xstri2B7"; Console.Error.WriteLine(strLoc + " More specific Exception thrown : " + e.GetType().FullName); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xstri2C7"; Console.Error.WriteLine(strLoc + " Wrong Exception Thrown: " + e.GetType().FullName); } inCountTestcases++; if (verbose) Console.WriteLine("Testing : Format (hex)"); try { Byte result = Convert.ToByte("fffg", 16); inCountErrors++; strLoc = "Err_xstri2A8"; Console.Error.WriteLine(strLoc + " No Exception Thrown."); } catch (FormatException e) { if (!e.GetType().FullName.Equals("System.FormatException")) { inCountErrors++; strLoc = "Err_xstri2B8"; Console.Error.WriteLine(strLoc + " More specific Exception thrown : " + e.GetType().FullName); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xstri2C8"; Console.Error.WriteLine(strLoc + " Wrong Exception Thrown: " + e.GetType().FullName); } inCountTestcases++; if (verbose) Console.WriteLine("Testing : Format (hex)"); try { Byte result = Convert.ToByte("0xxfff", 16); inCountErrors++; strLoc = "Err_xstri2A8"; Console.Error.WriteLine(strLoc + " No Exception Thrown."); } catch (FormatException e) { if (!e.GetType().FullName.Equals("System.FormatException")) { inCountErrors++; strLoc = "Err_xstri2B8"; Console.Error.WriteLine(strLoc + " More specific Exception thrown : " + e.GetType().FullName); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xstri2C8"; Console.Error.WriteLine(strLoc + " Wrong Exception Thrown: " + e.GetType().FullName); } inCountTestcases++; if (verbose) Console.WriteLine("Testing : Format (octal)"); try { Byte result = Convert.ToByte("8", 8); inCountErrors++; strLoc = "Err_xstri2A0"; Console.Error.WriteLine(strLoc + " No Exception Thrown."); } catch (FormatException e) { if (!e.GetType().FullName.Equals("System.FormatException")) { inCountErrors++; strLoc = "Err_xstri2B0"; Console.Error.WriteLine(strLoc + " More specific Exception thrown : " + e.GetType().FullName); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xstri2C0"; Console.Error.WriteLine(strLoc + " Wrong Exception Thrown: " + e.GetType().FullName); } inCountTestcases++; if (verbose) Console.WriteLine("Testing : Format (bin)"); try { Byte result = Convert.ToByte("112", 2); inCountErrors++; strLoc = "Err_xstri2A9"; Console.Error.WriteLine(strLoc + " No Exception Thrown."); } catch (FormatException e) { if (!e.GetType().FullName.Equals("System.FormatException")) { inCountErrors++; strLoc = "Err_xstri2B9"; Console.Error.WriteLine(strLoc + " More specific Exception thrown : " + e.GetType().FullName); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xstri2C9"; Console.Error.WriteLine(strLoc + " Wrong Exception Thrown: " + e.GetType().FullName); } inCountTestcases++; if (verbose) Console.WriteLine("Testing : LowerBound"); try { Byte result = Convert.ToByte("-1", 10); inCountErrors++; strLoc = "Err_xstri2A4"; Console.Error.WriteLine(strLoc + " No Exception Thrown."); } catch (OverflowException e) { if (!e.GetType().FullName.Equals("System.OverflowException")) { inCountErrors++; strLoc = "Err_xstri2B4"; Console.Error.WriteLine(strLoc + " More specific Exception thrown : " + e.GetType().FullName); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xstri2C4"; Console.Error.WriteLine(strLoc + " Wrong Exception Thrown: " + e.GetType().FullName); } inCountTestcases++; if (verbose) Console.WriteLine("Testing : Format"); try { Byte result = Convert.ToByte("!56", 10); inCountErrors++; strLoc = "Err_xstri2A3"; Console.Error.WriteLine(strLoc + " No Exception Thrown."); } catch (FormatException e) { if (!e.GetType().FullName.Equals("System.FormatException")) { inCountErrors++; strLoc = "Err_xstri2B3"; Console.Error.WriteLine(strLoc + " More specific Exception thrown : " + e.GetType().FullName); } } catch (Exception e) { inCountErrors++; strLoc = "Err_xstri2C3"; Console.Error.WriteLine(strLoc + " Wrong Exception Thrown: " + e.GetType().FullName); } } catch (Exception e) { Console.WriteLine("Uncaught Exception in Byte Convert.ToByte( String, Int32 )"); Console.WriteLine("Exception->" + e.GetType().FullName); } Console.Error.Write(s_strTFName); Console.Error.Write(": "); if (inCountErrors == 0) { Console.Error.WriteLine(" inCountTestcases==" + inCountTestcases + " paSs"); return true; } else { Console.Error.WriteLine(s_strTFPath + s_strTFName + ".cs"); Console.Error.WriteLine(" inCountTestcases==" + inCountTestcases); Console.Error.WriteLine("FAiL"); Console.Error.WriteLine(" inCountErrors==" + inCountErrors); return false; } } public static int Main(String[] args) { bool bResult = false; // Assume FAiL cb6054ToByte_all cbX = new cb6054ToByte_all(); try { if (args[0].Equals("-v")) cbX.verbose = true; } catch (Exception) { } try { printoutCoveredMethods(); bResult = cbX.runTest(); } catch (Exception exc_main) { bResult = false; Console.WriteLine("FAiL! Error Err_9999zzz! Uncaught Exception caught in main(), exc_main==" + exc_main); } if (!bResult) { Console.WriteLine(s_strTFPath + s_strTFName); Console.Error.WriteLine(" "); Console.Error.WriteLine("Try 'cb6054ToByte_all.exe -v' to see tests..."); Console.Error.WriteLine("FAiL! " + s_strTFAbbrev); // Last line is a nice eye catcher location. Console.Error.WriteLine(" "); } return bResult ? 100 : 1; } } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/coreclr/tools/aot/ILLink.Shared/DiagnosticString.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 ILLink.Shared { public readonly struct DiagnosticString { readonly string _titleFormat; readonly string _messageFormat; public DiagnosticString(DiagnosticId diagnosticId) { var resourceManager = SharedStrings.ResourceManager; _titleFormat = resourceManager.GetString($"{diagnosticId}Title") ?? throw new InvalidOperationException($"{diagnosticId} does not have a matching resource called {diagnosticId}Title"); _messageFormat = resourceManager.GetString($"{diagnosticId}Message") ?? throw new InvalidOperationException($"{diagnosticId} does not have a matching resource called {diagnosticId}Message"); } public DiagnosticString(string diagnosticResourceStringName) { var resourceManager = SharedStrings.ResourceManager; _titleFormat = resourceManager.GetString($"{diagnosticResourceStringName}Title") ?? throw new InvalidOperationException($"{diagnosticResourceStringName} does not have a matching resource called {diagnosticResourceStringName}Title"); _messageFormat = resourceManager.GetString($"{diagnosticResourceStringName}Message") ?? throw new InvalidOperationException($"{diagnosticResourceStringName} does not have a matching resource called {diagnosticResourceStringName}Message"); } public string GetMessage(params string[] args) => string.Format(_messageFormat, args); public string GetMessageFormat() => _messageFormat; public string GetTitle(params string[] args) => string.Format(_titleFormat, args); public string GetTitleFormat() => _titleFormat; } }
// 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 ILLink.Shared { public readonly struct DiagnosticString { readonly string _titleFormat; readonly string _messageFormat; public DiagnosticString(DiagnosticId diagnosticId) { var resourceManager = SharedStrings.ResourceManager; _titleFormat = resourceManager.GetString($"{diagnosticId}Title") ?? throw new InvalidOperationException($"{diagnosticId} does not have a matching resource called {diagnosticId}Title"); _messageFormat = resourceManager.GetString($"{diagnosticId}Message") ?? throw new InvalidOperationException($"{diagnosticId} does not have a matching resource called {diagnosticId}Message"); } public DiagnosticString(string diagnosticResourceStringName) { var resourceManager = SharedStrings.ResourceManager; _titleFormat = resourceManager.GetString($"{diagnosticResourceStringName}Title") ?? throw new InvalidOperationException($"{diagnosticResourceStringName} does not have a matching resource called {diagnosticResourceStringName}Title"); _messageFormat = resourceManager.GetString($"{diagnosticResourceStringName}Message") ?? throw new InvalidOperationException($"{diagnosticResourceStringName} does not have a matching resource called {diagnosticResourceStringName}Message"); } public string GetMessage(params string[] args) => string.Format(_messageFormat, args); public string GetMessageFormat() => _messageFormat; public string GetTitle(params string[] args) => string.Format(_titleFormat, args); public string GetTitleFormat() => _titleFormat; } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/libraries/System.Net.NameResolution/src/System/Net/NameResolutionPal.Unix.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; using System.Net.Internals; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; namespace System.Net { internal static partial class NameResolutionPal { public const bool SupportsGetAddrInfoAsync = false; internal static Task? GetAddrInfoAsync(string hostName, bool justAddresses, AddressFamily family, CancellationToken cancellationToken) => throw new NotSupportedException(); private static SocketError GetSocketErrorForNativeError(int error) { switch (error) { case 0: return SocketError.Success; case (int)Interop.Sys.GetAddrInfoErrorFlags.EAI_AGAIN: return SocketError.TryAgain; case (int)Interop.Sys.GetAddrInfoErrorFlags.EAI_BADFLAGS: case (int)Interop.Sys.GetAddrInfoErrorFlags.EAI_BADARG: return SocketError.InvalidArgument; case (int)Interop.Sys.GetAddrInfoErrorFlags.EAI_FAIL: return SocketError.NoRecovery; case (int)Interop.Sys.GetAddrInfoErrorFlags.EAI_FAMILY: return SocketError.AddressFamilyNotSupported; case (int)Interop.Sys.GetAddrInfoErrorFlags.EAI_NONAME: return SocketError.HostNotFound; case (int)Interop.Sys.GetAddrInfoErrorFlags.EAI_MEMORY: throw new OutOfMemoryException(); default: Debug.Fail($"Unexpected error: {error}"); return SocketError.SocketError; } } private static unsafe void ParseHostEntry(Interop.Sys.HostEntry hostEntry, bool justAddresses, out string? hostName, out string[] aliases, out IPAddress[] addresses) { try { hostName = !justAddresses && hostEntry.CanonicalName != null ? Marshal.PtrToStringAnsi((IntPtr)hostEntry.CanonicalName) : null; IPAddress[] localAddresses; if (hostEntry.IPAddressCount == 0) { localAddresses = Array.Empty<IPAddress>(); } else { // getaddrinfo returns multiple entries per address, for each socket type (datagram, stream, etc.). // Our callers expect just one entry for each address. So we need to deduplicate the results. // It's important to keep the addresses in order, since they are returned in the order in which // connections should be attempted. // // We assume that the list returned by getaddrinfo is relatively short; after all, the intent is that // the caller may need to attempt to contact every address in the list before giving up on a connection // attempt. So an O(N^2) algorithm should be fine here. Keep in mind that any "better" algorithm // is likely to involve extra allocations, hashing, etc., and so will probably be more expensive than // this one in the typical (short list) case. var nativeAddresses = new Interop.Sys.IPAddress[hostEntry.IPAddressCount]; int nativeAddressCount = 0; Interop.Sys.IPAddress* addressHandle = hostEntry.IPAddressList; for (int i = 0; i < hostEntry.IPAddressCount; i++) { Interop.Sys.IPAddress nativeAddr = addressHandle[i]; if (Array.IndexOf(nativeAddresses, nativeAddr, 0, nativeAddressCount) == -1 && (!nativeAddr.IsIPv6 || SocketProtocolSupportPal.OSSupportsIPv6)) // Do not include IPv6 addresses if IPV6 support is force-disabled { nativeAddresses[nativeAddressCount++] = nativeAddr; } } localAddresses = new IPAddress[nativeAddressCount]; for (int i = 0; i < nativeAddressCount; i++) { localAddresses[i] = nativeAddresses[i].GetIPAddress(); } } string[] localAliases = Array.Empty<string>(); if (!justAddresses && hostEntry.Aliases != null) { int numAliases = 0; while (hostEntry.Aliases[numAliases] != null) { numAliases++; } if (numAliases > 0) { localAliases = new string[numAliases]; for (int i = 0; i < localAliases.Length; i++) { localAliases[i] = Marshal.PtrToStringAnsi((IntPtr)hostEntry.Aliases[i])!; } } } aliases = localAliases; addresses = localAddresses; } finally { Interop.Sys.FreeHostEntry(&hostEntry); } } public static unsafe SocketError TryGetAddrInfo(string name, bool justAddresses, AddressFamily addressFamily, out string? hostName, out string[] aliases, out IPAddress[] addresses, out int nativeErrorCode) { if (name == "") { // To match documented behavior on Windows, if an empty string is passed in, use the local host's name. name = Dns.GetHostName(); } Interop.Sys.HostEntry entry; int result = Interop.Sys.GetHostEntryForName(name, addressFamily, &entry); if (result != 0) { nativeErrorCode = result; hostName = name; aliases = Array.Empty<string>(); addresses = Array.Empty<IPAddress>(); return GetSocketErrorForNativeError(result); } ParseHostEntry(entry, justAddresses, out hostName, out aliases, out addresses); nativeErrorCode = 0; return SocketError.Success; } public static unsafe string? TryGetNameInfo(IPAddress addr, out SocketError socketError, out int nativeErrorCode) { byte* buffer = stackalloc byte[Interop.Sys.NI_MAXHOST + 1 /*for null*/]; byte isIPv6; int rawAddressLength; if (addr.AddressFamily == AddressFamily.InterNetwork) { isIPv6 = 0; rawAddressLength = IPAddressParserStatics.IPv4AddressBytes; } else { isIPv6 = 1; rawAddressLength = IPAddressParserStatics.IPv6AddressBytes; } byte* rawAddress = stackalloc byte[rawAddressLength]; addr.TryWriteBytes(new Span<byte>(rawAddress, rawAddressLength), out int bytesWritten); Debug.Assert(bytesWritten == rawAddressLength); int error = Interop.Sys.GetNameInfo( rawAddress, (uint)rawAddressLength, isIPv6, buffer, Interop.Sys.NI_MAXHOST, null, 0, Interop.Sys.GetNameInfoFlags.NI_NAMEREQD); socketError = GetSocketErrorForNativeError(error); nativeErrorCode = error; return socketError == SocketError.Success ? Marshal.PtrToStringAnsi((IntPtr)buffer) : null; } public static string GetHostName() => Interop.Sys.GetHostName(); } }
// 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.Net.Internals; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; namespace System.Net { internal static partial class NameResolutionPal { public const bool SupportsGetAddrInfoAsync = false; internal static Task? GetAddrInfoAsync(string hostName, bool justAddresses, AddressFamily family, CancellationToken cancellationToken) => throw new NotSupportedException(); private static SocketError GetSocketErrorForNativeError(int error) { switch (error) { case 0: return SocketError.Success; case (int)Interop.Sys.GetAddrInfoErrorFlags.EAI_AGAIN: return SocketError.TryAgain; case (int)Interop.Sys.GetAddrInfoErrorFlags.EAI_BADFLAGS: case (int)Interop.Sys.GetAddrInfoErrorFlags.EAI_BADARG: return SocketError.InvalidArgument; case (int)Interop.Sys.GetAddrInfoErrorFlags.EAI_FAIL: return SocketError.NoRecovery; case (int)Interop.Sys.GetAddrInfoErrorFlags.EAI_FAMILY: return SocketError.AddressFamilyNotSupported; case (int)Interop.Sys.GetAddrInfoErrorFlags.EAI_NONAME: return SocketError.HostNotFound; case (int)Interop.Sys.GetAddrInfoErrorFlags.EAI_MEMORY: throw new OutOfMemoryException(); default: Debug.Fail($"Unexpected error: {error}"); return SocketError.SocketError; } } private static unsafe void ParseHostEntry(Interop.Sys.HostEntry hostEntry, bool justAddresses, out string? hostName, out string[] aliases, out IPAddress[] addresses) { try { hostName = !justAddresses && hostEntry.CanonicalName != null ? Marshal.PtrToStringAnsi((IntPtr)hostEntry.CanonicalName) : null; IPAddress[] localAddresses; if (hostEntry.IPAddressCount == 0) { localAddresses = Array.Empty<IPAddress>(); } else { // getaddrinfo returns multiple entries per address, for each socket type (datagram, stream, etc.). // Our callers expect just one entry for each address. So we need to deduplicate the results. // It's important to keep the addresses in order, since they are returned in the order in which // connections should be attempted. // // We assume that the list returned by getaddrinfo is relatively short; after all, the intent is that // the caller may need to attempt to contact every address in the list before giving up on a connection // attempt. So an O(N^2) algorithm should be fine here. Keep in mind that any "better" algorithm // is likely to involve extra allocations, hashing, etc., and so will probably be more expensive than // this one in the typical (short list) case. var nativeAddresses = new Interop.Sys.IPAddress[hostEntry.IPAddressCount]; int nativeAddressCount = 0; Interop.Sys.IPAddress* addressHandle = hostEntry.IPAddressList; for (int i = 0; i < hostEntry.IPAddressCount; i++) { Interop.Sys.IPAddress nativeAddr = addressHandle[i]; if (Array.IndexOf(nativeAddresses, nativeAddr, 0, nativeAddressCount) == -1 && (!nativeAddr.IsIPv6 || SocketProtocolSupportPal.OSSupportsIPv6)) // Do not include IPv6 addresses if IPV6 support is force-disabled { nativeAddresses[nativeAddressCount++] = nativeAddr; } } localAddresses = new IPAddress[nativeAddressCount]; for (int i = 0; i < nativeAddressCount; i++) { localAddresses[i] = nativeAddresses[i].GetIPAddress(); } } string[] localAliases = Array.Empty<string>(); if (!justAddresses && hostEntry.Aliases != null) { int numAliases = 0; while (hostEntry.Aliases[numAliases] != null) { numAliases++; } if (numAliases > 0) { localAliases = new string[numAliases]; for (int i = 0; i < localAliases.Length; i++) { localAliases[i] = Marshal.PtrToStringAnsi((IntPtr)hostEntry.Aliases[i])!; } } } aliases = localAliases; addresses = localAddresses; } finally { Interop.Sys.FreeHostEntry(&hostEntry); } } public static unsafe SocketError TryGetAddrInfo(string name, bool justAddresses, AddressFamily addressFamily, out string? hostName, out string[] aliases, out IPAddress[] addresses, out int nativeErrorCode) { if (name == "") { // To match documented behavior on Windows, if an empty string is passed in, use the local host's name. name = Dns.GetHostName(); } Interop.Sys.HostEntry entry; int result = Interop.Sys.GetHostEntryForName(name, addressFamily, &entry); if (result != 0) { nativeErrorCode = result; hostName = name; aliases = Array.Empty<string>(); addresses = Array.Empty<IPAddress>(); return GetSocketErrorForNativeError(result); } ParseHostEntry(entry, justAddresses, out hostName, out aliases, out addresses); nativeErrorCode = 0; return SocketError.Success; } public static unsafe string? TryGetNameInfo(IPAddress addr, out SocketError socketError, out int nativeErrorCode) { byte* buffer = stackalloc byte[Interop.Sys.NI_MAXHOST + 1 /*for null*/]; byte isIPv6; int rawAddressLength; if (addr.AddressFamily == AddressFamily.InterNetwork) { isIPv6 = 0; rawAddressLength = IPAddressParserStatics.IPv4AddressBytes; } else { isIPv6 = 1; rawAddressLength = IPAddressParserStatics.IPv6AddressBytes; } byte* rawAddress = stackalloc byte[rawAddressLength]; addr.TryWriteBytes(new Span<byte>(rawAddress, rawAddressLength), out int bytesWritten); Debug.Assert(bytesWritten == rawAddressLength); int error = Interop.Sys.GetNameInfo( rawAddress, (uint)rawAddressLength, isIPv6, buffer, Interop.Sys.NI_MAXHOST, null, 0, Interop.Sys.GetNameInfoFlags.NI_NAMEREQD); socketError = GetSocketErrorForNativeError(error); nativeErrorCode = error; return socketError == SocketError.Success ? Marshal.PtrToStringAnsi((IntPtr)buffer) : null; } public static string GetHostName() => Interop.Sys.GetHostName(); } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/libraries/System.Net.Primitives/tests/FunctionalTests/CookieContainerAddTest.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.Threading.Tasks; using Xunit; namespace System.Net.Primitives.Functional.Tests { public partial class CookieContainerTest { [Fact] public static void AddCookieCollection_Null_Throws() { CookieContainer cc = new CookieContainer(); CookieCollection cookieCollection = null; Assert.Throws<ArgumentNullException>(() => cc.Add(cookieCollection)); } [Fact] public static void AddCookieCollection_Success() { CookieContainer cc = new CookieContainer(); CookieCollection cookieCollection = new CookieCollection(); cookieCollection.Add(new Cookie("name3", "value","/",".contoso.com")); cc.Add(cookieCollection); Assert.Equal(1, cc.Count); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Threading.Tasks; using Xunit; namespace System.Net.Primitives.Functional.Tests { public partial class CookieContainerTest { [Fact] public static void AddCookieCollection_Null_Throws() { CookieContainer cc = new CookieContainer(); CookieCollection cookieCollection = null; Assert.Throws<ArgumentNullException>(() => cc.Add(cookieCollection)); } [Fact] public static void AddCookieCollection_Success() { CookieContainer cc = new CookieContainer(); CookieCollection cookieCollection = new CookieCollection(); cookieCollection.Add(new Cookie("name3", "value","/",".contoso.com")); cc.Add(cookieCollection); Assert.Equal(1, cc.Count); } } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/tests/JIT/Directed/rvastatics/rvastatic4.il
.assembly extern mscorlib{} .assembly extern xunit.core {} .assembly rvastatic4{} .class public A{ .method static native int Call1(int64) {.maxstack 50 ldarg.0 conv.i8 dup dup xor xor conv.i conv.i ret } .method static native int Call2(float64) {.maxstack 50 ldarg.0 conv.i8 dup ldc.i8 0xffffffff00000000 and ldc.i4 32 shr.un conv.i8 dup ldc.i8 0x0000000000ffffff and ldc.i4 32 shl conv.i8 ldc.i4 32 shr.un or conv.i conv.i8 ldc.i4 32 shl or conv.i conv.i ret } .method static void V1() {.maxstack 50 ldsfld int32 [rvastatic4]A::a0100 ldc.i4 0 beq a0101 newobj instance void [mscorlib]System.Exception::.ctor() throw a0101: ldsfld int64 [rvastatic4]A::a0101 ldc.i8 1 beq a0102 newobj instance void [mscorlib]System.Exception::.ctor() throw a0102: ldsfld float32 [rvastatic4]A::a0102 ldc.r4 2.0 beq a0103 newobj instance void [mscorlib]System.Exception::.ctor() throw a0103: ldsfld int16 [rvastatic4]A::a0103 ldc.i4 3 beq a0104 newobj instance void [mscorlib]System.Exception::.ctor() throw a0104: ldsfld int16 [rvastatic4]A::a0104 ldc.i4 4 beq a0105 newobj instance void [mscorlib]System.Exception::.ctor() throw a0105: ldsfld int64 [rvastatic4]A::a0105 ldc.i8 5 beq a0106 newobj instance void [mscorlib]System.Exception::.ctor() throw a0106: ldsfld int16 [rvastatic4]A::a0106 ldc.i4 6 beq a0107 newobj instance void [mscorlib]System.Exception::.ctor() throw a0107: ldsfld int8 [rvastatic4]A::a0107 ldc.i4 7 beq a0108 newobj instance void [mscorlib]System.Exception::.ctor() throw a0108: ldsfld int64 [rvastatic4]A::a0108 ldc.i8 8 beq a0109 newobj instance void [mscorlib]System.Exception::.ctor() throw a0109: ldsfld int32 [rvastatic4]A::a0109 ldc.i4 9 beq a01010 newobj instance void [mscorlib]System.Exception::.ctor() throw a01010: ldsfld int16 [rvastatic4]A::a01010 ldc.i4 10 beq a01011 newobj instance void [mscorlib]System.Exception::.ctor() throw a01011: ldsfld float32 [rvastatic4]A::a01011 ldc.r4 11.0 beq a01012 newobj instance void [mscorlib]System.Exception::.ctor() throw a01012: ldsfld int16 [rvastatic4]A::a01012 ldc.i4 12 beq a01013 newobj instance void [mscorlib]System.Exception::.ctor() throw a01013: ldsfld float32 [rvastatic4]A::a01013 ldc.r4 13.0 beq a01014 newobj instance void [mscorlib]System.Exception::.ctor() throw a01014: ldsfld float32 [rvastatic4]A::a01014 ldc.r4 14.0 beq a01015 newobj instance void [mscorlib]System.Exception::.ctor() throw a01015: ldsfld int8 [rvastatic4]A::a01015 ldc.i4 15 beq a01016 newobj instance void [mscorlib]System.Exception::.ctor() throw a01016: ldsfld float32 [rvastatic4]A::a01016 ldc.r4 16.0 beq a01017 newobj instance void [mscorlib]System.Exception::.ctor() throw a01017: ldsfld int8 [rvastatic4]A::a01017 ldc.i4 17 beq a01018 newobj instance void [mscorlib]System.Exception::.ctor() throw a01018: ldsfld float32 [rvastatic4]A::a01018 ldc.r4 18.0 beq a01019 newobj instance void [mscorlib]System.Exception::.ctor() throw a01019: ldsfld float32 [rvastatic4]A::a01019 ldc.r4 19.0 beq a01020 newobj instance void [mscorlib]System.Exception::.ctor() throw a01020: ldsfld int8 [rvastatic4]A::a01020 ldc.i4 20 beq a01021 newobj instance void [mscorlib]System.Exception::.ctor() throw a01021: ldsfld float32 [rvastatic4]A::a01021 ldc.r4 21.0 beq a01022 newobj instance void [mscorlib]System.Exception::.ctor() throw a01022: ldsfld int64 [rvastatic4]A::a01022 ldc.i8 22 beq a01023 newobj instance void [mscorlib]System.Exception::.ctor() throw a01023: ldsfld int8 [rvastatic4]A::a01023 ldc.i4 23 beq a01024 newobj instance void [mscorlib]System.Exception::.ctor() throw a01024: ldsfld int32 [rvastatic4]A::a01024 ldc.i4 24 beq a01025 newobj instance void [mscorlib]System.Exception::.ctor() throw a01025: ldsfld int64 [rvastatic4]A::a01025 ldc.i8 25 beq a01026 newobj instance void [mscorlib]System.Exception::.ctor() throw a01026: ldsfld int16 [rvastatic4]A::a01026 ldc.i4 26 beq a01027 newobj instance void [mscorlib]System.Exception::.ctor() throw a01027: ldsfld int8 [rvastatic4]A::a01027 ldc.i4 27 beq a01028 newobj instance void [mscorlib]System.Exception::.ctor() throw a01028: ldsfld int16 [rvastatic4]A::a01028 ldc.i4 28 beq a01029 newobj instance void [mscorlib]System.Exception::.ctor() throw a01029: ldsfld int16 [rvastatic4]A::a01029 ldc.i4 29 beq a01030 newobj instance void [mscorlib]System.Exception::.ctor() throw a01030: ldsfld int8 [rvastatic4]A::a01030 ldc.i4 30 beq a01031 newobj instance void [mscorlib]System.Exception::.ctor() throw a01031: ldsfld int8 [rvastatic4]A::a01031 ldc.i4 31 beq a01032 newobj instance void [mscorlib]System.Exception::.ctor() throw a01032: ldsfld int64 [rvastatic4]A::a01032 ldc.i8 32 beq a01033 newobj instance void [mscorlib]System.Exception::.ctor() throw a01033: ldsfld float32 [rvastatic4]A::a01033 ldc.r4 33.0 beq a01034 newobj instance void [mscorlib]System.Exception::.ctor() throw a01034: ldsfld int16 [rvastatic4]A::a01034 ldc.i4 34 beq a01035 newobj instance void [mscorlib]System.Exception::.ctor() throw a01035: ldsfld int8 [rvastatic4]A::a01035 ldc.i4 35 beq a01036 newobj instance void [mscorlib]System.Exception::.ctor() throw a01036: ldsfld int8 [rvastatic4]A::a01036 ldc.i4 36 beq a01037 newobj instance void [mscorlib]System.Exception::.ctor() throw a01037: ldsfld int32 [rvastatic4]A::a01037 ldc.i4 37 beq a01038 newobj instance void [mscorlib]System.Exception::.ctor() throw a01038: ldsfld int16 [rvastatic4]A::a01038 ldc.i4 38 beq a01039 newobj instance void [mscorlib]System.Exception::.ctor() throw a01039: ldsfld int8 [rvastatic4]A::a01039 ldc.i4 39 beq a01040 newobj instance void [mscorlib]System.Exception::.ctor() throw a01040: ldsfld int8 [rvastatic4]A::a01040 ldc.i4 40 beq a01041 newobj instance void [mscorlib]System.Exception::.ctor() throw a01041: ldsfld int32 [rvastatic4]A::a01041 ldc.i4 41 beq a01042 newobj instance void [mscorlib]System.Exception::.ctor() throw a01042: ldsfld int64 [rvastatic4]A::a01042 ldc.i8 42 beq a01043 newobj instance void [mscorlib]System.Exception::.ctor() throw a01043: ldsfld int16 [rvastatic4]A::a01043 ldc.i4 43 beq a01044 newobj instance void [mscorlib]System.Exception::.ctor() throw a01044: ldsfld int64 [rvastatic4]A::a01044 ldc.i8 44 beq a01045 newobj instance void [mscorlib]System.Exception::.ctor() throw a01045: ldsfld int64 [rvastatic4]A::a01045 ldc.i8 45 beq a01046 newobj instance void [mscorlib]System.Exception::.ctor() throw a01046: ldsfld float32 [rvastatic4]A::a01046 ldc.r4 46.0 beq a01047 newobj instance void [mscorlib]System.Exception::.ctor() throw a01047: ldsfld int16 [rvastatic4]A::a01047 ldc.i4 47 beq a01048 newobj instance void [mscorlib]System.Exception::.ctor() throw a01048: ldsfld int64 [rvastatic4]A::a01048 ldc.i8 48 beq a01049 newobj instance void [mscorlib]System.Exception::.ctor() throw a01049: ldsfld int16 [rvastatic4]A::a01049 ldc.i4 49 beq a01050 newobj instance void [mscorlib]System.Exception::.ctor() throw a01050: ldsfld int32 [rvastatic4]A::a01050 ldc.i4 50 beq a01051 newobj instance void [mscorlib]System.Exception::.ctor() throw a01051: ldsfld int16 [rvastatic4]A::a01051 ldc.i4 51 beq a01052 newobj instance void [mscorlib]System.Exception::.ctor() throw a01052: ldsfld int32 [rvastatic4]A::a01052 ldc.i4 52 beq a01053 newobj instance void [mscorlib]System.Exception::.ctor() throw a01053: ldsfld int16 [rvastatic4]A::a01053 ldc.i4 53 beq a01054 newobj instance void [mscorlib]System.Exception::.ctor() throw a01054: ldsfld float32 [rvastatic4]A::a01054 ldc.r4 54.0 beq a01055 newobj instance void [mscorlib]System.Exception::.ctor() throw a01055: ldsfld int64 [rvastatic4]A::a01055 ldc.i8 55 beq a01056 newobj instance void [mscorlib]System.Exception::.ctor() throw a01056: ldsfld float32 [rvastatic4]A::a01056 ldc.r4 56.0 beq a01057 newobj instance void [mscorlib]System.Exception::.ctor() throw a01057: ldsfld int64 [rvastatic4]A::a01057 ldc.i8 57 beq a01058 newobj instance void [mscorlib]System.Exception::.ctor() throw a01058: ldsfld int64 [rvastatic4]A::a01058 ldc.i8 58 beq a01059 newobj instance void [mscorlib]System.Exception::.ctor() throw a01059: ldsfld int64 [rvastatic4]A::a01059 ldc.i8 59 beq a01060 newobj instance void [mscorlib]System.Exception::.ctor() throw a01060: ldsfld int16 [rvastatic4]A::a01060 ldc.i4 60 beq a01061 newobj instance void [mscorlib]System.Exception::.ctor() throw a01061: ldsfld int8 [rvastatic4]A::a01061 ldc.i4 61 beq a01062 newobj instance void [mscorlib]System.Exception::.ctor() throw a01062: ldsfld int64 [rvastatic4]A::a01062 ldc.i8 62 beq a01063 newobj instance void [mscorlib]System.Exception::.ctor() throw a01063: ldsfld int16 [rvastatic4]A::a01063 ldc.i4 63 beq a01064 newobj instance void [mscorlib]System.Exception::.ctor() throw a01064: ldsfld int32 [rvastatic4]A::a01064 ldc.i4 64 beq a01065 newobj instance void [mscorlib]System.Exception::.ctor() throw a01065: ldsfld int16 [rvastatic4]A::a01065 ldc.i4 65 beq a01066 newobj instance void [mscorlib]System.Exception::.ctor() throw a01066: ldsfld int8 [rvastatic4]A::a01066 ldc.i4 66 beq a01067 newobj instance void [mscorlib]System.Exception::.ctor() throw a01067: ldsfld int16 [rvastatic4]A::a01067 ldc.i4 67 beq a01068 newobj instance void [mscorlib]System.Exception::.ctor() throw a01068: ldsfld int32 [rvastatic4]A::a01068 ldc.i4 68 beq a01069 newobj instance void [mscorlib]System.Exception::.ctor() throw a01069: ldsfld float32 [rvastatic4]A::a01069 ldc.r4 69.0 beq a01070 newobj instance void [mscorlib]System.Exception::.ctor() throw a01070: ldsfld float32 [rvastatic4]A::a01070 ldc.r4 70.0 beq a01071 newobj instance void [mscorlib]System.Exception::.ctor() throw a01071: ldsfld int16 [rvastatic4]A::a01071 ldc.i4 71 beq a01072 newobj instance void [mscorlib]System.Exception::.ctor() throw a01072: ldsfld float32 [rvastatic4]A::a01072 ldc.r4 72.0 beq a01073 newobj instance void [mscorlib]System.Exception::.ctor() throw a01073: ldsfld int64 [rvastatic4]A::a01073 ldc.i8 73 beq a01074 newobj instance void [mscorlib]System.Exception::.ctor() throw a01074: ldsfld int64 [rvastatic4]A::a01074 ldc.i8 74 beq a01075 newobj instance void [mscorlib]System.Exception::.ctor() throw a01075: ldsfld int32 [rvastatic4]A::a01075 ldc.i4 75 beq a01076 newobj instance void [mscorlib]System.Exception::.ctor() throw a01076: ldsfld int8 [rvastatic4]A::a01076 ldc.i4 76 beq a01077 newobj instance void [mscorlib]System.Exception::.ctor() throw a01077: ldsfld int32 [rvastatic4]A::a01077 ldc.i4 77 beq a01078 newobj instance void [mscorlib]System.Exception::.ctor() throw a01078: ldsfld int16 [rvastatic4]A::a01078 ldc.i4 78 beq a01079 newobj instance void [mscorlib]System.Exception::.ctor() throw a01079: ldsfld float32 [rvastatic4]A::a01079 ldc.r4 79.0 beq a01080 newobj instance void [mscorlib]System.Exception::.ctor() throw a01080: ldsfld float32 [rvastatic4]A::a01080 ldc.r4 80.0 beq a01081 newobj instance void [mscorlib]System.Exception::.ctor() throw a01081: ldsfld float32 [rvastatic4]A::a01081 ldc.r4 81.0 beq a01082 newobj instance void [mscorlib]System.Exception::.ctor() throw a01082: ldsfld int32 [rvastatic4]A::a01082 ldc.i4 82 beq a01083 newobj instance void [mscorlib]System.Exception::.ctor() throw a01083: ldsfld int8 [rvastatic4]A::a01083 ldc.i4 83 beq a01084 newobj instance void [mscorlib]System.Exception::.ctor() throw a01084: ldsfld int64 [rvastatic4]A::a01084 ldc.i8 84 beq a01085 newobj instance void [mscorlib]System.Exception::.ctor() throw a01085: ldsfld int64 [rvastatic4]A::a01085 ldc.i8 85 beq a01086 newobj instance void [mscorlib]System.Exception::.ctor() throw a01086: ldsfld int32 [rvastatic4]A::a01086 ldc.i4 86 beq a01087 newobj instance void [mscorlib]System.Exception::.ctor() throw a01087: ldsfld int32 [rvastatic4]A::a01087 ldc.i4 87 beq a01088 newobj instance void [mscorlib]System.Exception::.ctor() throw a01088: ldsfld int8 [rvastatic4]A::a01088 ldc.i4 88 beq a01089 newobj instance void [mscorlib]System.Exception::.ctor() throw a01089: ldsfld int64 [rvastatic4]A::a01089 ldc.i8 89 beq a01090 newobj instance void [mscorlib]System.Exception::.ctor() throw a01090: ldsfld int8 [rvastatic4]A::a01090 ldc.i4 90 beq a01091 newobj instance void [mscorlib]System.Exception::.ctor() throw a01091: ldsfld int16 [rvastatic4]A::a01091 ldc.i4 91 beq a01092 newobj instance void [mscorlib]System.Exception::.ctor() throw a01092: ldsfld float32 [rvastatic4]A::a01092 ldc.r4 92.0 beq a01093 newobj instance void [mscorlib]System.Exception::.ctor() throw a01093: ldsfld int64 [rvastatic4]A::a01093 ldc.i8 93 beq a01094 newobj instance void [mscorlib]System.Exception::.ctor() throw a01094: ldsfld int64 [rvastatic4]A::a01094 ldc.i8 94 beq a01095 newobj instance void [mscorlib]System.Exception::.ctor() throw a01095: ldsfld int8 [rvastatic4]A::a01095 ldc.i4 95 beq a01096 newobj instance void [mscorlib]System.Exception::.ctor() throw a01096: ldsfld float32 [rvastatic4]A::a01096 ldc.r4 96.0 beq a01097 newobj instance void [mscorlib]System.Exception::.ctor() throw a01097: ldsfld int16 [rvastatic4]A::a01097 ldc.i4 97 beq a01098 newobj instance void [mscorlib]System.Exception::.ctor() throw a01098: ldsfld float32 [rvastatic4]A::a01098 ldc.r4 98.0 beq a01099 newobj instance void [mscorlib]System.Exception::.ctor() throw a01099: ldsfld int32 [rvastatic4]A::a01099 ldc.i4 99 beq a010100 newobj instance void [mscorlib]System.Exception::.ctor() throw a010100: ldsfld int64 [rvastatic4]A::a010100 ldc.i8 100 beq a010101 newobj instance void [mscorlib]System.Exception::.ctor() throw a010101: ldsfld int32 [rvastatic4]A::a010101 ldc.i4 101 beq a010102 newobj instance void [mscorlib]System.Exception::.ctor() throw a010102: ldsfld float32 [rvastatic4]A::a010102 ldc.r4 102.0 beq a010103 newobj instance void [mscorlib]System.Exception::.ctor() throw a010103: ldsfld int64 [rvastatic4]A::a010103 ldc.i8 103 beq a010104 newobj instance void [mscorlib]System.Exception::.ctor() throw a010104: ldsfld int32 [rvastatic4]A::a010104 ldc.i4 104 beq a010105 newobj instance void [mscorlib]System.Exception::.ctor() throw a010105: ldsfld int16 [rvastatic4]A::a010105 ldc.i4 105 beq a010106 newobj instance void [mscorlib]System.Exception::.ctor() throw a010106: ldsfld int16 [rvastatic4]A::a010106 ldc.i4 106 beq a010107 newobj instance void [mscorlib]System.Exception::.ctor() throw a010107: ldsfld float32 [rvastatic4]A::a010107 ldc.r4 107.0 beq a010108 newobj instance void [mscorlib]System.Exception::.ctor() throw a010108: ldsfld int32 [rvastatic4]A::a010108 ldc.i4 108 beq a010109 newobj instance void [mscorlib]System.Exception::.ctor() throw a010109: ldsfld int16 [rvastatic4]A::a010109 ldc.i4 109 beq a010110 newobj instance void [mscorlib]System.Exception::.ctor() throw a010110: ldsfld int32 [rvastatic4]A::a010110 ldc.i4 110 beq a010111 newobj instance void [mscorlib]System.Exception::.ctor() throw a010111: ldsfld int32 [rvastatic4]A::a010111 ldc.i4 111 beq a010112 newobj instance void [mscorlib]System.Exception::.ctor() throw a010112: ldsfld int32 [rvastatic4]A::a010112 ldc.i4 112 beq a010113 newobj instance void [mscorlib]System.Exception::.ctor() throw a010113: ldsfld int64 [rvastatic4]A::a010113 ldc.i8 113 beq a010114 newobj instance void [mscorlib]System.Exception::.ctor() throw a010114: ldsfld int64 [rvastatic4]A::a010114 ldc.i8 114 beq a010115 newobj instance void [mscorlib]System.Exception::.ctor() throw a010115: ldsfld int16 [rvastatic4]A::a010115 ldc.i4 115 beq a010116 newobj instance void [mscorlib]System.Exception::.ctor() throw a010116: ldsfld int64 [rvastatic4]A::a010116 ldc.i8 116 beq a010117 newobj instance void [mscorlib]System.Exception::.ctor() throw a010117: ldsfld int64 [rvastatic4]A::a010117 ldc.i8 117 beq a010118 newobj instance void [mscorlib]System.Exception::.ctor() throw a010118: ldsfld int32 [rvastatic4]A::a010118 ldc.i4 118 beq a010119 newobj instance void [mscorlib]System.Exception::.ctor() throw a010119: ldsfld int64 [rvastatic4]A::a010119 ldc.i8 119 beq a010120 newobj instance void [mscorlib]System.Exception::.ctor() throw a010120: ldsfld int64 [rvastatic4]A::a010120 ldc.i8 120 beq a010121 newobj instance void [mscorlib]System.Exception::.ctor() throw a010121: ldsfld int64 [rvastatic4]A::a010121 ldc.i8 121 beq a010122 newobj instance void [mscorlib]System.Exception::.ctor() throw a010122: ldsfld int16 [rvastatic4]A::a010122 ldc.i4 122 beq a010123 newobj instance void [mscorlib]System.Exception::.ctor() throw a010123: ldsfld int64 [rvastatic4]A::a010123 ldc.i8 123 beq a010124 newobj instance void [mscorlib]System.Exception::.ctor() throw a010124: ldsfld int64 [rvastatic4]A::a010124 ldc.i8 124 beq a010125 newobj instance void [mscorlib]System.Exception::.ctor() throw a010125: ldsfld int32 [rvastatic4]A::a010125 ldc.i4 125 beq a010126 newobj instance void [mscorlib]System.Exception::.ctor() throw a010126: ldsfld int16 [rvastatic4]A::a010126 ldc.i4 126 beq a010127 newobj instance void [mscorlib]System.Exception::.ctor() throw a010127: ldsfld int16 [rvastatic4]A::a010127 ldc.i4 127 beq a010128 newobj instance void [mscorlib]System.Exception::.ctor() throw a010128: ret} .method static void V2() {.maxstack 50 ldsflda int32 [rvastatic4]A::a0100 ldind.i4 ldc.i4 0 beq a0100 newobj instance void [mscorlib]System.Exception::.ctor() throw a0100: ldsflda int64 [rvastatic4]A::a0101 ldind.i8 ldc.i8 1 beq a0101 newobj instance void [mscorlib]System.Exception::.ctor() throw a0101: ldsflda float32 [rvastatic4]A::a0102 ldind.r4 ldc.r4 2.0 beq a0102 newobj instance void [mscorlib]System.Exception::.ctor() throw a0102: ldsflda int16 [rvastatic4]A::a0103 ldind.i2 ldc.i4 3 beq a0103 newobj instance void [mscorlib]System.Exception::.ctor() throw a0103: ldsflda int16 [rvastatic4]A::a0104 ldind.i2 ldc.i4 4 beq a0104 newobj instance void [mscorlib]System.Exception::.ctor() throw a0104: ldsflda int64 [rvastatic4]A::a0105 ldind.i8 ldc.i8 5 beq a0105 newobj instance void [mscorlib]System.Exception::.ctor() throw a0105: ldsflda int16 [rvastatic4]A::a0106 ldind.i2 ldc.i4 6 beq a0106 newobj instance void [mscorlib]System.Exception::.ctor() throw a0106: ldsflda int8 [rvastatic4]A::a0107 ldind.i1 ldc.i4 7 beq a0107 newobj instance void [mscorlib]System.Exception::.ctor() throw a0107: ldsflda int64 [rvastatic4]A::a0108 ldind.i8 ldc.i8 8 beq a0108 newobj instance void [mscorlib]System.Exception::.ctor() throw a0108: ldsflda int32 [rvastatic4]A::a0109 ldind.i4 ldc.i4 9 beq a0109 newobj instance void [mscorlib]System.Exception::.ctor() throw a0109: ldsflda int16 [rvastatic4]A::a01010 ldind.i2 ldc.i4 10 beq a01010 newobj instance void [mscorlib]System.Exception::.ctor() throw a01010: ldsflda float32 [rvastatic4]A::a01011 ldind.r4 ldc.r4 11.0 beq a01011 newobj instance void [mscorlib]System.Exception::.ctor() throw a01011: ldsflda int16 [rvastatic4]A::a01012 ldind.i2 ldc.i4 12 beq a01012 newobj instance void [mscorlib]System.Exception::.ctor() throw a01012: ldsflda float32 [rvastatic4]A::a01013 ldind.r4 ldc.r4 13.0 beq a01013 newobj instance void [mscorlib]System.Exception::.ctor() throw a01013: ldsflda float32 [rvastatic4]A::a01014 ldind.r4 ldc.r4 14.0 beq a01014 newobj instance void [mscorlib]System.Exception::.ctor() throw a01014: ldsflda int8 [rvastatic4]A::a01015 ldind.i1 ldc.i4 15 beq a01015 newobj instance void [mscorlib]System.Exception::.ctor() throw a01015: ldsflda float32 [rvastatic4]A::a01016 ldind.r4 ldc.r4 16.0 beq a01016 newobj instance void [mscorlib]System.Exception::.ctor() throw a01016: ldsflda int8 [rvastatic4]A::a01017 ldind.i1 ldc.i4 17 beq a01017 newobj instance void [mscorlib]System.Exception::.ctor() throw a01017: ldsflda float32 [rvastatic4]A::a01018 ldind.r4 ldc.r4 18.0 beq a01018 newobj instance void [mscorlib]System.Exception::.ctor() throw a01018: ldsflda float32 [rvastatic4]A::a01019 ldind.r4 ldc.r4 19.0 beq a01019 newobj instance void [mscorlib]System.Exception::.ctor() throw a01019: ldsflda int8 [rvastatic4]A::a01020 ldind.i1 ldc.i4 20 beq a01020 newobj instance void [mscorlib]System.Exception::.ctor() throw a01020: ldsflda float32 [rvastatic4]A::a01021 ldind.r4 ldc.r4 21.0 beq a01021 newobj instance void [mscorlib]System.Exception::.ctor() throw a01021: ldsflda int64 [rvastatic4]A::a01022 ldind.i8 ldc.i8 22 beq a01022 newobj instance void [mscorlib]System.Exception::.ctor() throw a01022: ldsflda int8 [rvastatic4]A::a01023 ldind.i1 ldc.i4 23 beq a01023 newobj instance void [mscorlib]System.Exception::.ctor() throw a01023: ldsflda int32 [rvastatic4]A::a01024 ldind.i4 ldc.i4 24 beq a01024 newobj instance void [mscorlib]System.Exception::.ctor() throw a01024: ldsflda int64 [rvastatic4]A::a01025 ldind.i8 ldc.i8 25 beq a01025 newobj instance void [mscorlib]System.Exception::.ctor() throw a01025: ldsflda int16 [rvastatic4]A::a01026 ldind.i2 ldc.i4 26 beq a01026 newobj instance void [mscorlib]System.Exception::.ctor() throw a01026: ldsflda int8 [rvastatic4]A::a01027 ldind.i1 ldc.i4 27 beq a01027 newobj instance void [mscorlib]System.Exception::.ctor() throw a01027: ldsflda int16 [rvastatic4]A::a01028 ldind.i2 ldc.i4 28 beq a01028 newobj instance void [mscorlib]System.Exception::.ctor() throw a01028: ldsflda int16 [rvastatic4]A::a01029 ldind.i2 ldc.i4 29 beq a01029 newobj instance void [mscorlib]System.Exception::.ctor() throw a01029: ldsflda int8 [rvastatic4]A::a01030 ldind.i1 ldc.i4 30 beq a01030 newobj instance void [mscorlib]System.Exception::.ctor() throw a01030: ldsflda int8 [rvastatic4]A::a01031 ldind.i1 ldc.i4 31 beq a01031 newobj instance void [mscorlib]System.Exception::.ctor() throw a01031: ldsflda int64 [rvastatic4]A::a01032 ldind.i8 ldc.i8 32 beq a01032 newobj instance void [mscorlib]System.Exception::.ctor() throw a01032: ldsflda float32 [rvastatic4]A::a01033 ldind.r4 ldc.r4 33.0 beq a01033 newobj instance void [mscorlib]System.Exception::.ctor() throw a01033: ldsflda int16 [rvastatic4]A::a01034 ldind.i2 ldc.i4 34 beq a01034 newobj instance void [mscorlib]System.Exception::.ctor() throw a01034: ldsflda int8 [rvastatic4]A::a01035 ldind.i1 ldc.i4 35 beq a01035 newobj instance void [mscorlib]System.Exception::.ctor() throw a01035: ldsflda int8 [rvastatic4]A::a01036 ldind.i1 ldc.i4 36 beq a01036 newobj instance void [mscorlib]System.Exception::.ctor() throw a01036: ldsflda int32 [rvastatic4]A::a01037 ldind.i4 ldc.i4 37 beq a01037 newobj instance void [mscorlib]System.Exception::.ctor() throw a01037: ldsflda int16 [rvastatic4]A::a01038 ldind.i2 ldc.i4 38 beq a01038 newobj instance void [mscorlib]System.Exception::.ctor() throw a01038: ldsflda int8 [rvastatic4]A::a01039 ldind.i1 ldc.i4 39 beq a01039 newobj instance void [mscorlib]System.Exception::.ctor() throw a01039: ldsflda int8 [rvastatic4]A::a01040 ldind.i1 ldc.i4 40 beq a01040 newobj instance void [mscorlib]System.Exception::.ctor() throw a01040: ldsflda int32 [rvastatic4]A::a01041 ldind.i4 ldc.i4 41 beq a01041 newobj instance void [mscorlib]System.Exception::.ctor() throw a01041: ldsflda int64 [rvastatic4]A::a01042 ldind.i8 ldc.i8 42 beq a01042 newobj instance void [mscorlib]System.Exception::.ctor() throw a01042: ldsflda int16 [rvastatic4]A::a01043 ldind.i2 ldc.i4 43 beq a01043 newobj instance void [mscorlib]System.Exception::.ctor() throw a01043: ldsflda int64 [rvastatic4]A::a01044 ldind.i8 ldc.i8 44 beq a01044 newobj instance void [mscorlib]System.Exception::.ctor() throw a01044: ldsflda int64 [rvastatic4]A::a01045 ldind.i8 ldc.i8 45 beq a01045 newobj instance void [mscorlib]System.Exception::.ctor() throw a01045: ldsflda float32 [rvastatic4]A::a01046 ldind.r4 ldc.r4 46.0 beq a01046 newobj instance void [mscorlib]System.Exception::.ctor() throw a01046: ldsflda int16 [rvastatic4]A::a01047 ldind.i2 ldc.i4 47 beq a01047 newobj instance void [mscorlib]System.Exception::.ctor() throw a01047: ldsflda int64 [rvastatic4]A::a01048 ldind.i8 ldc.i8 48 beq a01048 newobj instance void [mscorlib]System.Exception::.ctor() throw a01048: ldsflda int16 [rvastatic4]A::a01049 ldind.i2 ldc.i4 49 beq a01049 newobj instance void [mscorlib]System.Exception::.ctor() throw a01049: ldsflda int32 [rvastatic4]A::a01050 ldind.i4 ldc.i4 50 beq a01050 newobj instance void [mscorlib]System.Exception::.ctor() throw a01050: ldsflda int16 [rvastatic4]A::a01051 ldind.i2 ldc.i4 51 beq a01051 newobj instance void [mscorlib]System.Exception::.ctor() throw a01051: ldsflda int32 [rvastatic4]A::a01052 ldind.i4 ldc.i4 52 beq a01052 newobj instance void [mscorlib]System.Exception::.ctor() throw a01052: ldsflda int16 [rvastatic4]A::a01053 ldind.i2 ldc.i4 53 beq a01053 newobj instance void [mscorlib]System.Exception::.ctor() throw a01053: ldsflda float32 [rvastatic4]A::a01054 ldind.r4 ldc.r4 54.0 beq a01054 newobj instance void [mscorlib]System.Exception::.ctor() throw a01054: ldsflda int64 [rvastatic4]A::a01055 ldind.i8 ldc.i8 55 beq a01055 newobj instance void [mscorlib]System.Exception::.ctor() throw a01055: ldsflda float32 [rvastatic4]A::a01056 ldind.r4 ldc.r4 56.0 beq a01056 newobj instance void [mscorlib]System.Exception::.ctor() throw a01056: ldsflda int64 [rvastatic4]A::a01057 ldind.i8 ldc.i8 57 beq a01057 newobj instance void [mscorlib]System.Exception::.ctor() throw a01057: ldsflda int64 [rvastatic4]A::a01058 ldind.i8 ldc.i8 58 beq a01058 newobj instance void [mscorlib]System.Exception::.ctor() throw a01058: ldsflda int64 [rvastatic4]A::a01059 ldind.i8 ldc.i8 59 beq a01059 newobj instance void [mscorlib]System.Exception::.ctor() throw a01059: ldsflda int16 [rvastatic4]A::a01060 ldind.i2 ldc.i4 60 beq a01060 newobj instance void [mscorlib]System.Exception::.ctor() throw a01060: ldsflda int8 [rvastatic4]A::a01061 ldind.i1 ldc.i4 61 beq a01061 newobj instance void [mscorlib]System.Exception::.ctor() throw a01061: ldsflda int64 [rvastatic4]A::a01062 ldind.i8 ldc.i8 62 beq a01062 newobj instance void [mscorlib]System.Exception::.ctor() throw a01062: ldsflda int16 [rvastatic4]A::a01063 ldind.i2 ldc.i4 63 beq a01063 newobj instance void [mscorlib]System.Exception::.ctor() throw a01063: ldsflda int32 [rvastatic4]A::a01064 ldind.i4 ldc.i4 64 beq a01064 newobj instance void [mscorlib]System.Exception::.ctor() throw a01064: ldsflda int16 [rvastatic4]A::a01065 ldind.i2 ldc.i4 65 beq a01065 newobj instance void [mscorlib]System.Exception::.ctor() throw a01065: ldsflda int8 [rvastatic4]A::a01066 ldind.i1 ldc.i4 66 beq a01066 newobj instance void [mscorlib]System.Exception::.ctor() throw a01066: ldsflda int16 [rvastatic4]A::a01067 ldind.i2 ldc.i4 67 beq a01067 newobj instance void [mscorlib]System.Exception::.ctor() throw a01067: ldsflda int32 [rvastatic4]A::a01068 ldind.i4 ldc.i4 68 beq a01068 newobj instance void [mscorlib]System.Exception::.ctor() throw a01068: ldsflda float32 [rvastatic4]A::a01069 ldind.r4 ldc.r4 69.0 beq a01069 newobj instance void [mscorlib]System.Exception::.ctor() throw a01069: ldsflda float32 [rvastatic4]A::a01070 ldind.r4 ldc.r4 70.0 beq a01070 newobj instance void [mscorlib]System.Exception::.ctor() throw a01070: ldsflda int16 [rvastatic4]A::a01071 ldind.i2 ldc.i4 71 beq a01071 newobj instance void [mscorlib]System.Exception::.ctor() throw a01071: ldsflda float32 [rvastatic4]A::a01072 ldind.r4 ldc.r4 72.0 beq a01072 newobj instance void [mscorlib]System.Exception::.ctor() throw a01072: ldsflda int64 [rvastatic4]A::a01073 ldind.i8 ldc.i8 73 beq a01073 newobj instance void [mscorlib]System.Exception::.ctor() throw a01073: ldsflda int64 [rvastatic4]A::a01074 ldind.i8 ldc.i8 74 beq a01074 newobj instance void [mscorlib]System.Exception::.ctor() throw a01074: ldsflda int32 [rvastatic4]A::a01075 ldind.i4 ldc.i4 75 beq a01075 newobj instance void [mscorlib]System.Exception::.ctor() throw a01075: ldsflda int8 [rvastatic4]A::a01076 ldind.i1 ldc.i4 76 beq a01076 newobj instance void [mscorlib]System.Exception::.ctor() throw a01076: ldsflda int32 [rvastatic4]A::a01077 ldind.i4 ldc.i4 77 beq a01077 newobj instance void [mscorlib]System.Exception::.ctor() throw a01077: ldsflda int16 [rvastatic4]A::a01078 ldind.i2 ldc.i4 78 beq a01078 newobj instance void [mscorlib]System.Exception::.ctor() throw a01078: ldsflda float32 [rvastatic4]A::a01079 ldind.r4 ldc.r4 79.0 beq a01079 newobj instance void [mscorlib]System.Exception::.ctor() throw a01079: ldsflda float32 [rvastatic4]A::a01080 ldind.r4 ldc.r4 80.0 beq a01080 newobj instance void [mscorlib]System.Exception::.ctor() throw a01080: ldsflda float32 [rvastatic4]A::a01081 ldind.r4 ldc.r4 81.0 beq a01081 newobj instance void [mscorlib]System.Exception::.ctor() throw a01081: ldsflda int32 [rvastatic4]A::a01082 ldind.i4 ldc.i4 82 beq a01082 newobj instance void [mscorlib]System.Exception::.ctor() throw a01082: ldsflda int8 [rvastatic4]A::a01083 ldind.i1 ldc.i4 83 beq a01083 newobj instance void [mscorlib]System.Exception::.ctor() throw a01083: ldsflda int64 [rvastatic4]A::a01084 ldind.i8 ldc.i8 84 beq a01084 newobj instance void [mscorlib]System.Exception::.ctor() throw a01084: ldsflda int64 [rvastatic4]A::a01085 ldind.i8 ldc.i8 85 beq a01085 newobj instance void [mscorlib]System.Exception::.ctor() throw a01085: ldsflda int32 [rvastatic4]A::a01086 ldind.i4 ldc.i4 86 beq a01086 newobj instance void [mscorlib]System.Exception::.ctor() throw a01086: ldsflda int32 [rvastatic4]A::a01087 ldind.i4 ldc.i4 87 beq a01087 newobj instance void [mscorlib]System.Exception::.ctor() throw a01087: ldsflda int8 [rvastatic4]A::a01088 ldind.i1 ldc.i4 88 beq a01088 newobj instance void [mscorlib]System.Exception::.ctor() throw a01088: ldsflda int64 [rvastatic4]A::a01089 ldind.i8 ldc.i8 89 beq a01089 newobj instance void [mscorlib]System.Exception::.ctor() throw a01089: ldsflda int8 [rvastatic4]A::a01090 ldind.i1 ldc.i4 90 beq a01090 newobj instance void [mscorlib]System.Exception::.ctor() throw a01090: ldsflda int16 [rvastatic4]A::a01091 ldind.i2 ldc.i4 91 beq a01091 newobj instance void [mscorlib]System.Exception::.ctor() throw a01091: ldsflda float32 [rvastatic4]A::a01092 ldind.r4 ldc.r4 92.0 beq a01092 newobj instance void [mscorlib]System.Exception::.ctor() throw a01092: ldsflda int64 [rvastatic4]A::a01093 ldind.i8 ldc.i8 93 beq a01093 newobj instance void [mscorlib]System.Exception::.ctor() throw a01093: ldsflda int64 [rvastatic4]A::a01094 ldind.i8 ldc.i8 94 beq a01094 newobj instance void [mscorlib]System.Exception::.ctor() throw a01094: ldsflda int8 [rvastatic4]A::a01095 ldind.i1 ldc.i4 95 beq a01095 newobj instance void [mscorlib]System.Exception::.ctor() throw a01095: ldsflda float32 [rvastatic4]A::a01096 ldind.r4 ldc.r4 96.0 beq a01096 newobj instance void [mscorlib]System.Exception::.ctor() throw a01096: ldsflda int16 [rvastatic4]A::a01097 ldind.i2 ldc.i4 97 beq a01097 newobj instance void [mscorlib]System.Exception::.ctor() throw a01097: ldsflda float32 [rvastatic4]A::a01098 ldind.r4 ldc.r4 98.0 beq a01098 newobj instance void [mscorlib]System.Exception::.ctor() throw a01098: ldsflda int32 [rvastatic4]A::a01099 ldind.i4 ldc.i4 99 beq a01099 newobj instance void [mscorlib]System.Exception::.ctor() throw a01099: ldsflda int64 [rvastatic4]A::a010100 ldind.i8 ldc.i8 100 beq a010100 newobj instance void [mscorlib]System.Exception::.ctor() throw a010100: ldsflda int32 [rvastatic4]A::a010101 ldind.i4 ldc.i4 101 beq a010101 newobj instance void [mscorlib]System.Exception::.ctor() throw a010101: ldsflda float32 [rvastatic4]A::a010102 ldind.r4 ldc.r4 102.0 beq a010102 newobj instance void [mscorlib]System.Exception::.ctor() throw a010102: ldsflda int64 [rvastatic4]A::a010103 ldind.i8 ldc.i8 103 beq a010103 newobj instance void [mscorlib]System.Exception::.ctor() throw a010103: ldsflda int32 [rvastatic4]A::a010104 ldind.i4 ldc.i4 104 beq a010104 newobj instance void [mscorlib]System.Exception::.ctor() throw a010104: ldsflda int16 [rvastatic4]A::a010105 ldind.i2 ldc.i4 105 beq a010105 newobj instance void [mscorlib]System.Exception::.ctor() throw a010105: ldsflda int16 [rvastatic4]A::a010106 ldind.i2 ldc.i4 106 beq a010106 newobj instance void [mscorlib]System.Exception::.ctor() throw a010106: ldsflda float32 [rvastatic4]A::a010107 ldind.r4 ldc.r4 107.0 beq a010107 newobj instance void [mscorlib]System.Exception::.ctor() throw a010107: ldsflda int32 [rvastatic4]A::a010108 ldind.i4 ldc.i4 108 beq a010108 newobj instance void [mscorlib]System.Exception::.ctor() throw a010108: ldsflda int16 [rvastatic4]A::a010109 ldind.i2 ldc.i4 109 beq a010109 newobj instance void [mscorlib]System.Exception::.ctor() throw a010109: ldsflda int32 [rvastatic4]A::a010110 ldind.i4 ldc.i4 110 beq a010110 newobj instance void [mscorlib]System.Exception::.ctor() throw a010110: ldsflda int32 [rvastatic4]A::a010111 ldind.i4 ldc.i4 111 beq a010111 newobj instance void [mscorlib]System.Exception::.ctor() throw a010111: ldsflda int32 [rvastatic4]A::a010112 ldind.i4 ldc.i4 112 beq a010112 newobj instance void [mscorlib]System.Exception::.ctor() throw a010112: ldsflda int64 [rvastatic4]A::a010113 ldind.i8 ldc.i8 113 beq a010113 newobj instance void [mscorlib]System.Exception::.ctor() throw a010113: ldsflda int64 [rvastatic4]A::a010114 ldind.i8 ldc.i8 114 beq a010114 newobj instance void [mscorlib]System.Exception::.ctor() throw a010114: ldsflda int16 [rvastatic4]A::a010115 ldind.i2 ldc.i4 115 beq a010115 newobj instance void [mscorlib]System.Exception::.ctor() throw a010115: ldsflda int64 [rvastatic4]A::a010116 ldind.i8 ldc.i8 116 beq a010116 newobj instance void [mscorlib]System.Exception::.ctor() throw a010116: ldsflda int64 [rvastatic4]A::a010117 ldind.i8 ldc.i8 117 beq a010117 newobj instance void [mscorlib]System.Exception::.ctor() throw a010117: ldsflda int32 [rvastatic4]A::a010118 ldind.i4 ldc.i4 118 beq a010118 newobj instance void [mscorlib]System.Exception::.ctor() throw a010118: ldsflda int64 [rvastatic4]A::a010119 ldind.i8 ldc.i8 119 beq a010119 newobj instance void [mscorlib]System.Exception::.ctor() throw a010119: ldsflda int64 [rvastatic4]A::a010120 ldind.i8 ldc.i8 120 beq a010120 newobj instance void [mscorlib]System.Exception::.ctor() throw a010120: ldsflda int64 [rvastatic4]A::a010121 ldind.i8 ldc.i8 121 beq a010121 newobj instance void [mscorlib]System.Exception::.ctor() throw a010121: ldsflda int16 [rvastatic4]A::a010122 ldind.i2 ldc.i4 122 beq a010122 newobj instance void [mscorlib]System.Exception::.ctor() throw a010122: ldsflda int64 [rvastatic4]A::a010123 ldind.i8 ldc.i8 123 beq a010123 newobj instance void [mscorlib]System.Exception::.ctor() throw a010123: ldsflda int64 [rvastatic4]A::a010124 ldind.i8 ldc.i8 124 beq a010124 newobj instance void [mscorlib]System.Exception::.ctor() throw a010124: ldsflda int32 [rvastatic4]A::a010125 ldind.i4 ldc.i4 125 beq a010125 newobj instance void [mscorlib]System.Exception::.ctor() throw a010125: ldsflda int16 [rvastatic4]A::a010126 ldind.i2 ldc.i4 126 beq a010126 newobj instance void [mscorlib]System.Exception::.ctor() throw a010126: ldsflda int16 [rvastatic4]A::a010127 ldind.i2 ldc.i4 127 beq a010127 newobj instance void [mscorlib]System.Exception::.ctor() throw a010127: ret} .method static void V3() {.maxstack 50 ldsfld float32 [rvastatic4]A::a01079 ldc.r4 79.0 beq a010129 newobj instance void [mscorlib]System.Exception::.ctor() throw a010129: ldsfld int32 [rvastatic4]A::a010111 ldc.i4 111 beq a010130 newobj instance void [mscorlib]System.Exception::.ctor() throw a010130: ldsfld int16 [rvastatic4]A::a01034 ldc.i4 34 beq a010131 newobj instance void [mscorlib]System.Exception::.ctor() throw a010131: ldsfld int8 [rvastatic4]A::a01040 ldc.i4 40 beq a010132 newobj instance void [mscorlib]System.Exception::.ctor() throw a010132: ldsfld int16 [rvastatic4]A::a01012 ldc.i4 12 beq a010133 newobj instance void [mscorlib]System.Exception::.ctor() throw a010133: ldsfld int64 [rvastatic4]A::a01089 ldc.i8 89 beq a010134 newobj instance void [mscorlib]System.Exception::.ctor() throw a010134: ldsfld float32 [rvastatic4]A::a01070 ldc.r4 70.0 beq a010135 newobj instance void [mscorlib]System.Exception::.ctor() throw a010135: ldsfld int8 [rvastatic4]A::a01066 ldc.i4 66 beq a010136 newobj instance void [mscorlib]System.Exception::.ctor() throw a010136: ldsfld int64 [rvastatic4]A::a01048 ldc.i8 48 beq a010137 newobj instance void [mscorlib]System.Exception::.ctor() throw a010137: ldsfld float32 [rvastatic4]A::a01080 ldc.r4 80.0 beq a010138 newobj instance void [mscorlib]System.Exception::.ctor() throw a010138: ldsfld int32 [rvastatic4]A::a010104 ldc.i4 104 beq a010139 newobj instance void [mscorlib]System.Exception::.ctor() throw a010139: ldsfld int16 [rvastatic4]A::a01091 ldc.i4 91 beq a010140 newobj instance void [mscorlib]System.Exception::.ctor() throw a010140: ldsfld int32 [rvastatic4]A::a01024 ldc.i4 24 beq a010141 newobj instance void [mscorlib]System.Exception::.ctor() throw a010141: ldsfld float32 [rvastatic4]A::a01081 ldc.r4 81.0 beq a010142 newobj instance void [mscorlib]System.Exception::.ctor() throw a010142: ldsfld int64 [rvastatic4]A::a010121 ldc.i8 121 beq a010143 newobj instance void [mscorlib]System.Exception::.ctor() throw a010143: ldsfld int8 [rvastatic4]A::a01017 ldc.i4 17 beq a010144 newobj instance void [mscorlib]System.Exception::.ctor() throw a010144: ldsfld float32 [rvastatic4]A::a010107 ldc.r4 107.0 beq a010145 newobj instance void [mscorlib]System.Exception::.ctor() throw a010145: ldsfld int16 [rvastatic4]A::a01047 ldc.i4 47 beq a010146 newobj instance void [mscorlib]System.Exception::.ctor() throw a010146: ldsfld int64 [rvastatic4]A::a01048 ldc.i8 48 beq a010147 newobj instance void [mscorlib]System.Exception::.ctor() throw a010147: ldsfld int8 [rvastatic4]A::a01020 ldc.i4 20 beq a010148 newobj instance void [mscorlib]System.Exception::.ctor() throw a010148: ldsfld int16 [rvastatic4]A::a010115 ldc.i4 115 beq a010149 newobj instance void [mscorlib]System.Exception::.ctor() throw a010149: ldsfld int32 [rvastatic4]A::a01024 ldc.i4 24 beq a010150 newobj instance void [mscorlib]System.Exception::.ctor() throw a010150: ldsfld float32 [rvastatic4]A::a010102 ldc.r4 102.0 beq a010151 newobj instance void [mscorlib]System.Exception::.ctor() throw a010151: ldsfld int64 [rvastatic4]A::a010124 ldc.i8 124 beq a010152 newobj instance void [mscorlib]System.Exception::.ctor() throw a010152: ldsfld int16 [rvastatic4]A::a01028 ldc.i4 28 beq a010153 newobj instance void [mscorlib]System.Exception::.ctor() throw a010153: ldsfld int16 [rvastatic4]A::a01012 ldc.i4 12 beq a010154 newobj instance void [mscorlib]System.Exception::.ctor() throw a010154: ldsfld int64 [rvastatic4]A::a0105 ldc.i8 5 beq a010155 newobj instance void [mscorlib]System.Exception::.ctor() throw a010155: ldsfld int16 [rvastatic4]A::a010115 ldc.i4 115 beq a010156 newobj instance void [mscorlib]System.Exception::.ctor() throw a010156: ldsfld int64 [rvastatic4]A::a010113 ldc.i8 113 beq a010157 newobj instance void [mscorlib]System.Exception::.ctor() throw a010157: ldsfld int64 [rvastatic4]A::a0101 ldc.i8 1 beq a010158 newobj instance void [mscorlib]System.Exception::.ctor() throw a010158: ldsfld int16 [rvastatic4]A::a010122 ldc.i4 122 beq a010159 newobj instance void [mscorlib]System.Exception::.ctor() throw a010159: ldsfld int32 [rvastatic4]A::a010108 ldc.i4 108 beq a010160 newobj instance void [mscorlib]System.Exception::.ctor() throw a010160: ldsfld int8 [rvastatic4]A::a01090 ldc.i4 90 beq a010161 newobj instance void [mscorlib]System.Exception::.ctor() throw a010161: ldsfld int8 [rvastatic4]A::a01090 ldc.i4 90 beq a010162 newobj instance void [mscorlib]System.Exception::.ctor() throw a010162: ldsfld int32 [rvastatic4]A::a010112 ldc.i4 112 beq a010163 newobj instance void [mscorlib]System.Exception::.ctor() throw a010163: ldsfld int16 [rvastatic4]A::a01067 ldc.i4 67 beq a010164 newobj instance void [mscorlib]System.Exception::.ctor() throw a010164: ldsfld int32 [rvastatic4]A::a01064 ldc.i4 64 beq a010165 newobj instance void [mscorlib]System.Exception::.ctor() throw a010165: ldsfld int64 [rvastatic4]A::a01057 ldc.i8 57 beq a010166 newobj instance void [mscorlib]System.Exception::.ctor() throw a010166: ldsfld int32 [rvastatic4]A::a01037 ldc.i4 37 beq a010167 newobj instance void [mscorlib]System.Exception::.ctor() throw a010167: ldsfld int64 [rvastatic4]A::a010120 ldc.i8 120 beq a010168 newobj instance void [mscorlib]System.Exception::.ctor() throw a010168: ldsfld float32 [rvastatic4]A::a01019 ldc.r4 19.0 beq a010169 newobj instance void [mscorlib]System.Exception::.ctor() throw a010169: ldsfld int64 [rvastatic4]A::a010124 ldc.i8 124 beq a010170 newobj instance void [mscorlib]System.Exception::.ctor() throw a010170: ldsfld int32 [rvastatic4]A::a01037 ldc.i4 37 beq a010171 newobj instance void [mscorlib]System.Exception::.ctor() throw a010171: ldsfld int8 [rvastatic4]A::a0107 ldc.i4 7 beq a010172 newobj instance void [mscorlib]System.Exception::.ctor() throw a010172: ldsfld int16 [rvastatic4]A::a010106 ldc.i4 106 beq a010173 newobj instance void [mscorlib]System.Exception::.ctor() throw a010173: ldsfld int64 [rvastatic4]A::a01073 ldc.i8 73 beq a010174 newobj instance void [mscorlib]System.Exception::.ctor() throw a010174: ldsfld int64 [rvastatic4]A::a01074 ldc.i8 74 beq a010175 newobj instance void [mscorlib]System.Exception::.ctor() throw a010175: ldsfld int8 [rvastatic4]A::a01015 ldc.i4 15 beq a010176 newobj instance void [mscorlib]System.Exception::.ctor() throw a010176: ldsfld int32 [rvastatic4]A::a01077 ldc.i4 77 beq a010177 newobj instance void [mscorlib]System.Exception::.ctor() throw a010177: ldsfld int8 [rvastatic4]A::a01031 ldc.i4 31 beq a010178 newobj instance void [mscorlib]System.Exception::.ctor() throw a010178: ldsfld int16 [rvastatic4]A::a01067 ldc.i4 67 beq a010179 newobj instance void [mscorlib]System.Exception::.ctor() throw a010179: ldsfld int16 [rvastatic4]A::a01071 ldc.i4 71 beq a010180 newobj instance void [mscorlib]System.Exception::.ctor() throw a010180: ldsfld int16 [rvastatic4]A::a01047 ldc.i4 47 beq a010181 newobj instance void [mscorlib]System.Exception::.ctor() throw a010181: ldsfld int8 [rvastatic4]A::a01061 ldc.i4 61 beq a010182 newobj instance void [mscorlib]System.Exception::.ctor() throw a010182: ldsfld int64 [rvastatic4]A::a010114 ldc.i8 114 beq a010183 newobj instance void [mscorlib]System.Exception::.ctor() throw a010183: ldsfld float32 [rvastatic4]A::a01054 ldc.r4 54.0 beq a010184 newobj instance void [mscorlib]System.Exception::.ctor() throw a010184: ldsfld int32 [rvastatic4]A::a0109 ldc.i4 9 beq a010185 newobj instance void [mscorlib]System.Exception::.ctor() throw a010185: ldsfld int32 [rvastatic4]A::a01037 ldc.i4 37 beq a010186 newobj instance void [mscorlib]System.Exception::.ctor() throw a010186: ldsfld int16 [rvastatic4]A::a01012 ldc.i4 12 beq a010187 newobj instance void [mscorlib]System.Exception::.ctor() throw a010187: ldsfld int32 [rvastatic4]A::a0100 ldc.i4 0 beq a010188 newobj instance void [mscorlib]System.Exception::.ctor() throw a010188: ldsfld int8 [rvastatic4]A::a01083 ldc.i4 83 beq a010189 newobj instance void [mscorlib]System.Exception::.ctor() throw a010189: ldsfld int32 [rvastatic4]A::a01082 ldc.i4 82 beq a010190 newobj instance void [mscorlib]System.Exception::.ctor() throw a010190: ldsfld float32 [rvastatic4]A::a01081 ldc.r4 81.0 beq a010191 newobj instance void [mscorlib]System.Exception::.ctor() throw a010191: ldsfld float32 [rvastatic4]A::a01046 ldc.r4 46.0 beq a010192 newobj instance void [mscorlib]System.Exception::.ctor() throw a010192: ldsfld int64 [rvastatic4]A::a01085 ldc.i8 85 beq a010193 newobj instance void [mscorlib]System.Exception::.ctor() throw a010193: ldsfld int64 [rvastatic4]A::a010123 ldc.i8 123 beq a010194 newobj instance void [mscorlib]System.Exception::.ctor() throw a010194: ldsfld int32 [rvastatic4]A::a0100 ldc.i4 0 beq a010195 newobj instance void [mscorlib]System.Exception::.ctor() throw a010195: ldsfld int64 [rvastatic4]A::a01062 ldc.i8 62 beq a010196 newobj instance void [mscorlib]System.Exception::.ctor() throw a010196: ldsfld float32 [rvastatic4]A::a01096 ldc.r4 96.0 beq a010197 newobj instance void [mscorlib]System.Exception::.ctor() throw a010197: ldsfld int16 [rvastatic4]A::a01053 ldc.i4 53 beq a010198 newobj instance void [mscorlib]System.Exception::.ctor() throw a010198: ldsfld float32 [rvastatic4]A::a01081 ldc.r4 81.0 beq a010199 newobj instance void [mscorlib]System.Exception::.ctor() throw a010199: ldsfld int16 [rvastatic4]A::a01049 ldc.i4 49 beq a010200 newobj instance void [mscorlib]System.Exception::.ctor() throw a010200: ldsfld int32 [rvastatic4]A::a0109 ldc.i4 9 beq a010201 newobj instance void [mscorlib]System.Exception::.ctor() throw a010201: ldsfld float32 [rvastatic4]A::a01056 ldc.r4 56.0 beq a010202 newobj instance void [mscorlib]System.Exception::.ctor() throw a010202: ldsfld int64 [rvastatic4]A::a0101 ldc.i8 1 beq a010203 newobj instance void [mscorlib]System.Exception::.ctor() throw a010203: ldsfld int64 [rvastatic4]A::a010119 ldc.i8 119 beq a010204 newobj instance void [mscorlib]System.Exception::.ctor() throw a010204: ldsfld int16 [rvastatic4]A::a010115 ldc.i4 115 beq a010205 newobj instance void [mscorlib]System.Exception::.ctor() throw a010205: ldsfld int64 [rvastatic4]A::a01094 ldc.i8 94 beq a010206 newobj instance void [mscorlib]System.Exception::.ctor() throw a010206: ldsfld int8 [rvastatic4]A::a01017 ldc.i4 17 beq a010207 newobj instance void [mscorlib]System.Exception::.ctor() throw a010207: ldsfld int32 [rvastatic4]A::a01082 ldc.i4 82 beq a010208 newobj instance void [mscorlib]System.Exception::.ctor() throw a010208: ldsfld int16 [rvastatic4]A::a01065 ldc.i4 65 beq a010209 newobj instance void [mscorlib]System.Exception::.ctor() throw a010209: ldsfld int64 [rvastatic4]A::a010117 ldc.i8 117 beq a010210 newobj instance void [mscorlib]System.Exception::.ctor() throw a010210: ldsfld int16 [rvastatic4]A::a01038 ldc.i4 38 beq a010211 newobj instance void [mscorlib]System.Exception::.ctor() throw a010211: ldsfld int32 [rvastatic4]A::a01082 ldc.i4 82 beq a010212 newobj instance void [mscorlib]System.Exception::.ctor() throw a010212: ldsfld int64 [rvastatic4]A::a01062 ldc.i8 62 beq a010213 newobj instance void [mscorlib]System.Exception::.ctor() throw a010213: ldsfld int32 [rvastatic4]A::a01050 ldc.i4 50 beq a010214 newobj instance void [mscorlib]System.Exception::.ctor() throw a010214: ldsfld int8 [rvastatic4]A::a01061 ldc.i4 61 beq a010215 newobj instance void [mscorlib]System.Exception::.ctor() throw a010215: ldsfld int16 [rvastatic4]A::a01029 ldc.i4 29 beq a010216 newobj instance void [mscorlib]System.Exception::.ctor() throw a010216: ldsfld int32 [rvastatic4]A::a010104 ldc.i4 104 beq a010217 newobj instance void [mscorlib]System.Exception::.ctor() throw a010217: ldsfld int64 [rvastatic4]A::a01057 ldc.i8 57 beq a010218 newobj instance void [mscorlib]System.Exception::.ctor() throw a010218: ldsfld int64 [rvastatic4]A::a01057 ldc.i8 57 beq a010219 newobj instance void [mscorlib]System.Exception::.ctor() throw a010219: ldsfld int16 [rvastatic4]A::a01026 ldc.i4 26 beq a010220 newobj instance void [mscorlib]System.Exception::.ctor() throw a010220: ldsfld int64 [rvastatic4]A::a01045 ldc.i8 45 beq a010221 newobj instance void [mscorlib]System.Exception::.ctor() throw a010221: ldsfld int32 [rvastatic4]A::a01037 ldc.i4 37 beq a010222 newobj instance void [mscorlib]System.Exception::.ctor() throw a010222: ldsfld int8 [rvastatic4]A::a01036 ldc.i4 36 beq a010223 newobj instance void [mscorlib]System.Exception::.ctor() throw a010223: ldsfld int32 [rvastatic4]A::a01064 ldc.i4 64 beq a010224 newobj instance void [mscorlib]System.Exception::.ctor() throw a010224: ldsfld int16 [rvastatic4]A::a01043 ldc.i4 43 beq a010225 newobj instance void [mscorlib]System.Exception::.ctor() throw a010225: ldsfld int32 [rvastatic4]A::a010118 ldc.i4 118 beq a010226 newobj instance void [mscorlib]System.Exception::.ctor() throw a010226: ldsfld int32 [rvastatic4]A::a01050 ldc.i4 50 beq a010227 newobj instance void [mscorlib]System.Exception::.ctor() throw a010227: ldsfld int32 [rvastatic4]A::a010111 ldc.i4 111 beq a010228 newobj instance void [mscorlib]System.Exception::.ctor() throw a010228: ldsfld float32 [rvastatic4]A::a01072 ldc.r4 72.0 beq a010229 newobj instance void [mscorlib]System.Exception::.ctor() throw a010229: ldsfld int16 [rvastatic4]A::a01012 ldc.i4 12 beq a010230 newobj instance void [mscorlib]System.Exception::.ctor() throw a010230: ldsfld float32 [rvastatic4]A::a01046 ldc.r4 46.0 beq a010231 newobj instance void [mscorlib]System.Exception::.ctor() throw a010231: ldsfld int8 [rvastatic4]A::a01023 ldc.i4 23 beq a010232 newobj instance void [mscorlib]System.Exception::.ctor() throw a010232: ldsfld int32 [rvastatic4]A::a01077 ldc.i4 77 beq a010233 newobj instance void [mscorlib]System.Exception::.ctor() throw a010233: ldsfld float32 [rvastatic4]A::a01018 ldc.r4 18.0 beq a010234 newobj instance void [mscorlib]System.Exception::.ctor() throw a010234: ldsfld int8 [rvastatic4]A::a01061 ldc.i4 61 beq a010235 newobj instance void [mscorlib]System.Exception::.ctor() throw a010235: ldsfld int32 [rvastatic4]A::a010118 ldc.i4 118 beq a010236 newobj instance void [mscorlib]System.Exception::.ctor() throw a010236: ldsfld int64 [rvastatic4]A::a01059 ldc.i8 59 beq a010237 newobj instance void [mscorlib]System.Exception::.ctor() throw a010237: ldsfld int16 [rvastatic4]A::a010122 ldc.i4 122 beq a010238 newobj instance void [mscorlib]System.Exception::.ctor() throw a010238: ldsfld int8 [rvastatic4]A::a01066 ldc.i4 66 beq a010239 newobj instance void [mscorlib]System.Exception::.ctor() throw a010239: ldsfld int16 [rvastatic4]A::a01043 ldc.i4 43 beq a010240 newobj instance void [mscorlib]System.Exception::.ctor() throw a010240: ldsfld int8 [rvastatic4]A::a01020 ldc.i4 20 beq a010241 newobj instance void [mscorlib]System.Exception::.ctor() throw a010241: ldsfld int64 [rvastatic4]A::a01058 ldc.i8 58 beq a010242 newobj instance void [mscorlib]System.Exception::.ctor() throw a010242: ldsfld int64 [rvastatic4]A::a01062 ldc.i8 62 beq a010243 newobj instance void [mscorlib]System.Exception::.ctor() throw a010243: ldsfld int64 [rvastatic4]A::a01094 ldc.i8 94 beq a010244 newobj instance void [mscorlib]System.Exception::.ctor() throw a010244: ldsfld int64 [rvastatic4]A::a01044 ldc.i8 44 beq a010245 newobj instance void [mscorlib]System.Exception::.ctor() throw a010245: ldsfld int16 [rvastatic4]A::a010126 ldc.i4 126 beq a010246 newobj instance void [mscorlib]System.Exception::.ctor() throw a010246: ldsfld int32 [rvastatic4]A::a010112 ldc.i4 112 beq a010247 newobj instance void [mscorlib]System.Exception::.ctor() throw a010247: ldsfld int16 [rvastatic4]A::a01034 ldc.i4 34 beq a010248 newobj instance void [mscorlib]System.Exception::.ctor() throw a010248: ldsfld int64 [rvastatic4]A::a01062 ldc.i8 62 beq a010249 newobj instance void [mscorlib]System.Exception::.ctor() throw a010249: ldsfld int32 [rvastatic4]A::a01099 ldc.i4 99 beq a010250 newobj instance void [mscorlib]System.Exception::.ctor() throw a010250: ldsfld int64 [rvastatic4]A::a01085 ldc.i8 85 beq a010251 newobj instance void [mscorlib]System.Exception::.ctor() throw a010251: ldsfld int8 [rvastatic4]A::a01039 ldc.i4 39 beq a010252 newobj instance void [mscorlib]System.Exception::.ctor() throw a010252: ldsfld int64 [rvastatic4]A::a010124 ldc.i8 124 beq a010253 newobj instance void [mscorlib]System.Exception::.ctor() throw a010253: ldsfld int64 [rvastatic4]A::a01055 ldc.i8 55 beq a010254 newobj instance void [mscorlib]System.Exception::.ctor() throw a010254: ldsfld int16 [rvastatic4]A::a0104 ldc.i4 4 beq a010255 newobj instance void [mscorlib]System.Exception::.ctor() throw a010255: ldsfld int64 [rvastatic4]A::a010100 ldc.i8 100 beq a010256 newobj instance void [mscorlib]System.Exception::.ctor() throw a010256: ret} .method static void V4() {.maxstack 50 ldsflda int32 [rvastatic4]A::a0100 conv.i8 ldc.i8 19349 add conv.i8 ldc.i8 19349 sub conv.i ldind.i4 ldc.i4 0 beq a0100 ldstr "a0100" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a0100: ldsflda int64 [rvastatic4]A::a0101 conv.i8 dup ldc.i8 0x0000000000ffffff and ldc.i4 32 shl conv.i8 ldc.i4 32 shr.un or conv.i ldind.i8 ldc.i8 1 beq a0101 ldstr "a0101" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a0101: ldsflda float32 [rvastatic4]A::a0102 conv.r8 ldc.r8 234.098 add conv.r8 ldc.r8 -234.098 add conv.i ldind.r4 ldc.r4 2.0 beq a0102 ldstr "a0102" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a0102: ldsflda int16 [rvastatic4]A::a0103 conv.i8 dup ldc.i8 0x0000000000ffffff and ldc.i4 32 shl conv.i8 ldc.i4 32 shr.un or conv.i ldind.i2 ldc.i4 3 beq a0103 ldstr "a0103" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a0103: ldsflda int16 [rvastatic4]A::a0104 conv.i8 ldc.i8 46081 add conv.i8 ldc.i8 46081 sub conv.i ldind.i2 ldc.i4 4 beq a0104 ldstr "a0104" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a0104: ldsflda int64 [rvastatic4]A::a0105 conv.i8 dup dup xor xor conv.i ldind.i8 ldc.i8 5 beq a0105 ldstr "a0105" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a0105: ldsflda int16 [rvastatic4]A::a0106 conv.r8 ldc.r8 234.098 add conv.r8 ldc.r8 -234.098 add conv.i ldind.i2 ldc.i4 6 beq a0106 ldstr "a0106" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a0106: ldsflda int8 [rvastatic4]A::a0107 conv.i8 conv.r8 conv.u8 conv.i conv.i8 conv.r8 conv.u8 conv.i ldind.i1 ldc.i4 7 beq a0107 ldstr "a0107" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a0107: ldsflda int64 [rvastatic4]A::a0108 conv.i8 ldc.i8 3218 add conv.i8 ldc.i8 3218 sub conv.i ldind.i8 ldc.i8 8 beq a0108 ldstr "a0108" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a0108: ldsflda int32 [rvastatic4]A::a0109 conv.i8 conv.r8 conv.u8 conv.i conv.i8 conv.r8 conv.u8 conv.i ldind.i4 ldc.i4 9 beq a0109 ldstr "a0109" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a0109: ldsflda int16 [rvastatic4]A::a01010 conv.i8 ldc.i8 2 mul ldc.i4 1 shr.un conv.i ldind.i2 ldc.i4 10 beq a01010 ldstr "a01010" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01010: ldsflda float32 [rvastatic4]A::a01011 conv.i8 dup ldc.i8 0x0000000000ffffff and ldc.i4 32 shl conv.i8 ldc.i4 32 shr.un or conv.i ldind.r4 ldc.r4 11.0 beq a01011 ldstr "a01011" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01011: ldsflda int16 [rvastatic4]A::a01012 conv.i8 dup dup xor xor conv.i ldind.i2 ldc.i4 12 beq a01012 ldstr "a01012" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01012: ldsflda float32 [rvastatic4]A::a01013 conv.r8 ldc.r8 234.098 add conv.r8 ldc.r8 -234.098 add conv.i ldind.r4 ldc.r4 13.0 beq a01013 ldstr "a01013" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01013: ldsflda float32 [rvastatic4]A::a01014 conv.i8 dup ldc.i8 0xffffffff00000000 and ldc.i4 32 shr.un conv.i8 ldc.i4 32 shl or conv.i ldind.r4 ldc.r4 14.0 beq a01014 ldstr "a01014" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01014: ldsflda int8 [rvastatic4]A::a01015 conv.i8 conv.r8 conv.u8 conv.i conv.i8 conv.r8 conv.u8 conv.i ldind.i1 ldc.i4 15 beq a01015 ldstr "a01015" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01015: ldsflda float32 [rvastatic4]A::a01016 conv.i8 dup ldc.i8 0xffffffff00000000 and ldc.i4 32 shr.un conv.i8 ldc.i4 32 shl or conv.i ldind.r4 ldc.r4 16.0 beq a01016 ldstr "a01016" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01016: ldsflda int8 [rvastatic4]A::a01017 conv.i8 ldc.i8 15229 add conv.i8 ldc.i8 15229 sub conv.i ldind.i1 ldc.i4 17 beq a01017 ldstr "a01017" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01017: ldsflda float32 [rvastatic4]A::a01018 conv.i8 ldc.i8 2 mul ldc.i4 1 shr.un conv.i ldind.r4 ldc.r4 18.0 beq a01018 ldstr "a01018" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01018: ldsflda float32 [rvastatic4]A::a01019 conv.i8 conv.r8 conv.u8 conv.i conv.i8 conv.r8 conv.u8 conv.i ldind.r4 ldc.r4 19.0 beq a01019 ldstr "a01019" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01019: ldsflda int8 [rvastatic4]A::a01020 conv.i8 ldc.i8 28655 add conv.i8 ldc.i8 28655 sub conv.i ldind.i1 ldc.i4 20 beq a01020 ldstr "a01020" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01020: ldsflda float32 [rvastatic4]A::a01021 conv.i8 ldc.i8 33205 add conv.i8 ldc.i8 33205 sub conv.i ldind.r4 ldc.r4 21.0 beq a01021 ldstr "a01021" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01021: ldsflda int64 [rvastatic4]A::a01022 conv.i8 dup ldc.i8 0x0000000000ffffff and ldc.i4 32 shl conv.i8 ldc.i4 32 shr.un or conv.i ldind.i8 ldc.i8 22 beq a01022 ldstr "a01022" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01022: ldsflda int8 [rvastatic4]A::a01023 conv.i8 conv.r8 conv.u8 conv.i conv.i8 conv.r8 conv.u8 conv.i ldind.i1 ldc.i4 23 beq a01023 ldstr "a01023" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01023: ldsflda int32 [rvastatic4]A::a01024 conv.i8 dup ldc.i8 0x0000000000ffffff and ldc.i4 32 shl conv.i8 ldc.i4 32 shr.un or conv.i ldind.i4 ldc.i4 24 beq a01024 ldstr "a01024" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01024: ldsflda int64 [rvastatic4]A::a01025 conv.i8 dup ldc.i8 0xffffffff00000000 and ldc.i4 32 shr.un conv.i8 ldc.i4 32 shl or conv.i ldind.i8 ldc.i8 25 beq a01025 ldstr "a01025" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01025: ldsflda int16 [rvastatic4]A::a01026 conv.i8 dup dup xor xor conv.i ldind.i2 ldc.i4 26 beq a01026 ldstr "a01026" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01026: ldsflda int8 [rvastatic4]A::a01027 conv.i8 dup ldc.i8 0xffffffff00000000 and ldc.i4 32 shr.un conv.i8 ldc.i4 32 shl or conv.i ldind.i1 ldc.i4 27 beq a01027 ldstr "a01027" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01027: ldsflda int16 [rvastatic4]A::a01028 conv.i8 dup ldc.i8 0xffffffff00000000 and ldc.i4 32 shr.un conv.i8 ldc.i4 32 shl or conv.i ldind.i2 ldc.i4 28 beq a01028 ldstr "a01028" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01028: ldsflda int16 [rvastatic4]A::a01029 conv.i8 dup ldc.i8 0x0000000000ffffff and ldc.i4 32 shl conv.i8 ldc.i4 32 shr.un or conv.i ldind.i2 ldc.i4 29 beq a01029 ldstr "a01029" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01029: ldsflda int8 [rvastatic4]A::a01030 conv.i8 dup dup xor xor conv.i ldind.i1 ldc.i4 30 beq a01030 ldstr "a01030" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01030: ldsflda int8 [rvastatic4]A::a01031 conv.r8 ldc.r8 234.098 add conv.r8 ldc.r8 -234.098 add conv.i ldind.i1 ldc.i4 31 beq a01031 ldstr "a01031" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01031: ldsflda int64 [rvastatic4]A::a01032 conv.r8 ldc.r8 234.098 add conv.r8 ldc.r8 -234.098 add conv.i ldind.i8 ldc.i8 32 beq a01032 ldstr "a01032" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01032: ldsflda float32 [rvastatic4]A::a01033 conv.i8 dup dup xor xor conv.i ldind.r4 ldc.r4 33.0 beq a01033 ldstr "a01033" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01033: ldsflda int16 [rvastatic4]A::a01034 conv.i8 ldc.i8 2 mul ldc.i4 1 shr.un conv.i ldind.i2 ldc.i4 34 beq a01034 ldstr "a01034" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01034: ldsflda int8 [rvastatic4]A::a01035 conv.i8 dup dup xor xor conv.i ldind.i1 ldc.i4 35 beq a01035 ldstr "a01035" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01035: ldsflda int8 [rvastatic4]A::a01036 conv.r8 ldc.r8 234.098 add conv.r8 ldc.r8 -234.098 add conv.i ldind.i1 ldc.i4 36 beq a01036 ldstr "a01036" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01036: ldsflda int32 [rvastatic4]A::a01037 conv.r8 ldc.r8 234.098 add conv.r8 ldc.r8 -234.098 add conv.i ldind.i4 ldc.i4 37 beq a01037 ldstr "a01037" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01037: ldsflda int16 [rvastatic4]A::a01038 conv.i8 dup ldc.i8 0x0000000000ffffff and ldc.i4 32 shl conv.i8 ldc.i4 32 shr.un or conv.i ldind.i2 ldc.i4 38 beq a01038 ldstr "a01038" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01038: ldsflda int8 [rvastatic4]A::a01039 conv.i8 ldc.i8 2 mul ldc.i4 1 shr.un conv.i ldind.i1 ldc.i4 39 beq a01039 ldstr "a01039" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01039: ldsflda int8 [rvastatic4]A::a01040 conv.i8 ldc.i8 65464 add conv.i8 ldc.i8 65464 sub conv.i ldind.i1 ldc.i4 40 beq a01040 ldstr "a01040" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01040: ldsflda int32 [rvastatic4]A::a01041 conv.i8 dup ldc.i8 0xffffffff00000000 and ldc.i4 32 shr.un conv.i8 ldc.i4 32 shl or conv.i ldind.i4 ldc.i4 41 beq a01041 ldstr "a01041" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01041: ldsflda int64 [rvastatic4]A::a01042 conv.i8 conv.r8 conv.u8 conv.i conv.i8 conv.r8 conv.u8 conv.i ldind.i8 ldc.i8 42 beq a01042 ldstr "a01042" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01042: ldsflda int16 [rvastatic4]A::a01043 conv.i8 dup ldc.i8 0x0000000000ffffff and ldc.i4 32 shl conv.i8 ldc.i4 32 shr.un or conv.i ldind.i2 ldc.i4 43 beq a01043 ldstr "a01043" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01043: ldsflda int64 [rvastatic4]A::a01044 conv.i8 conv.r8 conv.u8 conv.i conv.i8 conv.r8 conv.u8 conv.i ldind.i8 ldc.i8 44 beq a01044 ldstr "a01044" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01044: ldsflda int64 [rvastatic4]A::a01045 conv.r8 ldc.r8 234.098 add conv.r8 ldc.r8 -234.098 add conv.i ldind.i8 ldc.i8 45 beq a01045 ldstr "a01045" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01045: ldsflda float32 [rvastatic4]A::a01046 conv.i8 ldc.i8 2 mul ldc.i4 1 shr.un conv.i ldind.r4 ldc.r4 46.0 beq a01046 ldstr "a01046" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01046: ldsflda int16 [rvastatic4]A::a01047 conv.i8 dup dup xor xor conv.i ldind.i2 ldc.i4 47 beq a01047 ldstr "a01047" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01047: ldsflda int64 [rvastatic4]A::a01048 conv.i8 ldc.i8 2 mul ldc.i4 1 shr.un conv.i ldind.i8 ldc.i8 48 beq a01048 ldstr "a01048" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01048: ldsflda int16 [rvastatic4]A::a01049 conv.i8 ldc.i8 2 mul ldc.i4 1 shr.un conv.i ldind.i2 ldc.i4 49 beq a01049 ldstr "a01049" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01049: ldsflda int32 [rvastatic4]A::a01050 conv.i8 dup ldc.i8 0xffffffff00000000 and ldc.i4 32 shr.un conv.i8 ldc.i4 32 shl or conv.i ldind.i4 ldc.i4 50 beq a01050 ldstr "a01050" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01050: ldsflda int16 [rvastatic4]A::a01051 conv.i8 dup dup xor xor conv.i ldind.i2 ldc.i4 51 beq a01051 ldstr "a01051" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01051: ldsflda int32 [rvastatic4]A::a01052 conv.i8 dup ldc.i8 0xffffffff00000000 and ldc.i4 32 shr.un conv.i8 ldc.i4 32 shl or conv.i ldind.i4 ldc.i4 52 beq a01052 ldstr "a01052" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01052: ldsflda int16 [rvastatic4]A::a01053 conv.i8 ldc.i8 26716 add conv.i8 ldc.i8 26716 sub conv.i ldind.i2 ldc.i4 53 beq a01053 ldstr "a01053" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01053: ldsflda float32 [rvastatic4]A::a01054 conv.r8 ldc.r8 234.098 add conv.r8 ldc.r8 -234.098 add conv.i ldind.r4 ldc.r4 54.0 beq a01054 ldstr "a01054" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01054: ldsflda int64 [rvastatic4]A::a01055 conv.i8 dup dup xor xor conv.i ldind.i8 ldc.i8 55 beq a01055 ldstr "a01055" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01055: ldsflda float32 [rvastatic4]A::a01056 conv.i8 dup dup xor xor conv.i ldind.r4 ldc.r4 56.0 beq a01056 ldstr "a01056" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01056: ldsflda int64 [rvastatic4]A::a01057 conv.i8 ldc.i8 62605 add conv.i8 ldc.i8 62605 sub conv.i ldind.i8 ldc.i8 57 beq a01057 ldstr "a01057" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01057: ldsflda int64 [rvastatic4]A::a01058 conv.i8 dup dup xor xor conv.i ldind.i8 ldc.i8 58 beq a01058 ldstr "a01058" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01058: ldsflda int64 [rvastatic4]A::a01059 conv.r8 ldc.r8 234.098 add conv.r8 ldc.r8 -234.098 add conv.i ldind.i8 ldc.i8 59 beq a01059 ldstr "a01059" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01059: ldsflda int16 [rvastatic4]A::a01060 conv.i8 conv.r8 conv.u8 conv.i conv.i8 conv.r8 conv.u8 conv.i ldind.i2 ldc.i4 60 beq a01060 ldstr "a01060" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01060: ldsflda int8 [rvastatic4]A::a01061 conv.i8 dup ldc.i8 0x0000000000ffffff and ldc.i4 32 shl conv.i8 ldc.i4 32 shr.un or conv.i ldind.i1 ldc.i4 61 beq a01061 ldstr "a01061" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01061: ldsflda int64 [rvastatic4]A::a01062 conv.i8 ldc.i8 2 mul ldc.i4 1 shr.un conv.i ldind.i8 ldc.i8 62 beq a01062 ldstr "a01062" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01062: ldsflda int16 [rvastatic4]A::a01063 conv.i8 ldc.i8 2 mul ldc.i4 1 shr.un conv.i ldind.i2 ldc.i4 63 beq a01063 ldstr "a01063" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01063: ldsflda int32 [rvastatic4]A::a01064 conv.i8 ldc.i8 2 mul ldc.i4 1 shr.un conv.i ldind.i4 ldc.i4 64 beq a01064 ldstr "a01064" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01064: ldsflda int16 [rvastatic4]A::a01065 conv.i8 ldc.i8 2 mul ldc.i4 1 shr.un conv.i ldind.i2 ldc.i4 65 beq a01065 ldstr "a01065" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01065: ldsflda int8 [rvastatic4]A::a01066 conv.i8 conv.r8 conv.u8 conv.i conv.i8 conv.r8 conv.u8 conv.i ldind.i1 ldc.i4 66 beq a01066 ldstr "a01066" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01066: ldsflda int16 [rvastatic4]A::a01067 conv.i8 dup ldc.i8 0xffffffff00000000 and ldc.i4 32 shr.un conv.i8 ldc.i4 32 shl or conv.i ldind.i2 ldc.i4 67 beq a01067 ldstr "a01067" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01067: ldsflda int32 [rvastatic4]A::a01068 conv.i8 conv.r8 conv.u8 conv.i conv.i8 conv.r8 conv.u8 conv.i ldind.i4 ldc.i4 68 beq a01068 ldstr "a01068" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01068: ldsflda float32 [rvastatic4]A::a01069 conv.i8 ldc.i8 2 mul ldc.i4 1 shr.un conv.i ldind.r4 ldc.r4 69.0 beq a01069 ldstr "a01069" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01069: ldsflda float32 [rvastatic4]A::a01070 conv.i8 ldc.i8 48606 add conv.i8 ldc.i8 48606 sub conv.i ldind.r4 ldc.r4 70.0 beq a01070 ldstr "a01070" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01070: ldsflda int16 [rvastatic4]A::a01071 conv.r8 ldc.r8 234.098 add conv.r8 ldc.r8 -234.098 add conv.i ldind.i2 ldc.i4 71 beq a01071 ldstr "a01071" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01071: ldsflda float32 [rvastatic4]A::a01072 conv.i8 conv.r8 conv.u8 conv.i conv.i8 conv.r8 conv.u8 conv.i ldind.r4 ldc.r4 72.0 beq a01072 ldstr "a01072" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01072: ldsflda int64 [rvastatic4]A::a01073 conv.i8 ldc.i8 5680 add conv.i8 ldc.i8 5680 sub conv.i ldind.i8 ldc.i8 73 beq a01073 ldstr "a01073" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01073: ldsflda int64 [rvastatic4]A::a01074 conv.i8 ldc.i8 2 mul ldc.i4 1 shr.un conv.i ldind.i8 ldc.i8 74 beq a01074 ldstr "a01074" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01074: ldsflda int32 [rvastatic4]A::a01075 conv.i8 ldc.i8 32361 add conv.i8 ldc.i8 32361 sub conv.i ldind.i4 ldc.i4 75 beq a01075 ldstr "a01075" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01075: ldsflda int8 [rvastatic4]A::a01076 conv.i8 dup ldc.i8 0x0000000000ffffff and ldc.i4 32 shl conv.i8 ldc.i4 32 shr.un or conv.i ldind.i1 ldc.i4 76 beq a01076 ldstr "a01076" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01076: ldsflda int32 [rvastatic4]A::a01077 conv.i8 conv.r8 conv.u8 conv.i conv.i8 conv.r8 conv.u8 conv.i ldind.i4 ldc.i4 77 beq a01077 ldstr "a01077" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01077: ldsflda int16 [rvastatic4]A::a01078 conv.i8 dup ldc.i8 0x0000000000ffffff and ldc.i4 32 shl conv.i8 ldc.i4 32 shr.un or conv.i ldind.i2 ldc.i4 78 beq a01078 ldstr "a01078" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01078: ldsflda float32 [rvastatic4]A::a01079 conv.r8 ldc.r8 234.098 add conv.r8 ldc.r8 -234.098 add conv.i ldind.r4 ldc.r4 79.0 beq a01079 ldstr "a01079" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01079: ldsflda float32 [rvastatic4]A::a01080 conv.i8 dup ldc.i8 0xffffffff00000000 and ldc.i4 32 shr.un conv.i8 ldc.i4 32 shl or conv.i ldind.r4 ldc.r4 80.0 beq a01080 ldstr "a01080" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01080: ldsflda float32 [rvastatic4]A::a01081 conv.i8 conv.r8 conv.u8 conv.i conv.i8 conv.r8 conv.u8 conv.i ldind.r4 ldc.r4 81.0 beq a01081 ldstr "a01081" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01081: ldsflda int32 [rvastatic4]A::a01082 conv.i8 ldc.i8 30180 add conv.i8 ldc.i8 30180 sub conv.i ldind.i4 ldc.i4 82 beq a01082 ldstr "a01082" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01082: ldsflda int8 [rvastatic4]A::a01083 conv.i8 conv.r8 conv.u8 conv.i conv.i8 conv.r8 conv.u8 conv.i ldind.i1 ldc.i4 83 beq a01083 ldstr "a01083" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01083: ldsflda int64 [rvastatic4]A::a01084 conv.i8 dup ldc.i8 0xffffffff00000000 and ldc.i4 32 shr.un conv.i8 ldc.i4 32 shl or conv.i ldind.i8 ldc.i8 84 beq a01084 ldstr "a01084" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01084: ldsflda int64 [rvastatic4]A::a01085 conv.i8 ldc.i8 18787 add conv.i8 ldc.i8 18787 sub conv.i ldind.i8 ldc.i8 85 beq a01085 ldstr "a01085" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01085: ldsflda int32 [rvastatic4]A::a01086 conv.i8 dup dup xor xor conv.i ldind.i4 ldc.i4 86 beq a01086 ldstr "a01086" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01086: ldsflda int32 [rvastatic4]A::a01087 conv.i8 ldc.i8 16913 add conv.i8 ldc.i8 16913 sub conv.i ldind.i4 ldc.i4 87 beq a01087 ldstr "a01087" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01087: ldsflda int8 [rvastatic4]A::a01088 conv.i8 dup ldc.i8 0x0000000000ffffff and ldc.i4 32 shl conv.i8 ldc.i4 32 shr.un or conv.i ldind.i1 ldc.i4 88 beq a01088 ldstr "a01088" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01088: ldsflda int64 [rvastatic4]A::a01089 conv.r8 ldc.r8 234.098 add conv.r8 ldc.r8 -234.098 add conv.i ldind.i8 ldc.i8 89 beq a01089 ldstr "a01089" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01089: ldsflda int8 [rvastatic4]A::a01090 conv.i8 ldc.i8 42807 add conv.i8 ldc.i8 42807 sub conv.i ldind.i1 ldc.i4 90 beq a01090 ldstr "a01090" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01090: ldsflda int16 [rvastatic4]A::a01091 conv.i8 dup ldc.i8 0xffffffff00000000 and ldc.i4 32 shr.un conv.i8 ldc.i4 32 shl or conv.i ldind.i2 ldc.i4 91 beq a01091 ldstr "a01091" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01091: ldsflda float32 [rvastatic4]A::a01092 conv.i8 conv.r8 conv.u8 conv.i conv.i8 conv.r8 conv.u8 conv.i ldind.r4 ldc.r4 92.0 beq a01092 ldstr "a01092" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01092: ldsflda int64 [rvastatic4]A::a01093 conv.i8 ldc.i8 37525 add conv.i8 ldc.i8 37525 sub conv.i ldind.i8 ldc.i8 93 beq a01093 ldstr "a01093" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01093: ldsflda int64 [rvastatic4]A::a01094 conv.r8 ldc.r8 234.098 add conv.r8 ldc.r8 -234.098 add conv.i ldind.i8 ldc.i8 94 beq a01094 ldstr "a01094" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01094: ldsflda int8 [rvastatic4]A::a01095 conv.i8 dup dup xor xor conv.i ldind.i1 ldc.i4 95 beq a01095 ldstr "a01095" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01095: ldsflda float32 [rvastatic4]A::a01096 conv.i8 conv.r8 conv.u8 conv.i conv.i8 conv.r8 conv.u8 conv.i ldind.r4 ldc.r4 96.0 beq a01096 ldstr "a01096" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01096: ldsflda int16 [rvastatic4]A::a01097 conv.i8 ldc.i8 41331 add conv.i8 ldc.i8 41331 sub conv.i ldind.i2 ldc.i4 97 beq a01097 ldstr "a01097" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01097: ldsflda float32 [rvastatic4]A::a01098 conv.i8 conv.r8 conv.u8 conv.i conv.i8 conv.r8 conv.u8 conv.i ldind.r4 ldc.r4 98.0 beq a01098 ldstr "a01098" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01098: ldsflda int32 [rvastatic4]A::a01099 conv.i8 ldc.i8 4072 add conv.i8 ldc.i8 4072 sub conv.i ldind.i4 ldc.i4 99 beq a01099 ldstr "a01099" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01099: ldsflda int64 [rvastatic4]A::a010100 conv.i8 conv.r8 conv.u8 conv.i conv.i8 conv.r8 conv.u8 conv.i ldind.i8 ldc.i8 100 beq a010100 ldstr "a010100" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010100: ldsflda int32 [rvastatic4]A::a010101 conv.i8 dup dup xor xor conv.i ldind.i4 ldc.i4 101 beq a010101 ldstr "a010101" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010101: ldsflda float32 [rvastatic4]A::a010102 conv.i8 conv.r8 conv.u8 conv.i conv.i8 conv.r8 conv.u8 conv.i ldind.r4 ldc.r4 102.0 beq a010102 ldstr "a010102" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010102: ldsflda int64 [rvastatic4]A::a010103 conv.i8 conv.r8 conv.u8 conv.i conv.i8 conv.r8 conv.u8 conv.i ldind.i8 ldc.i8 103 beq a010103 ldstr "a010103" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010103: ldsflda int32 [rvastatic4]A::a010104 conv.r8 ldc.r8 234.098 add conv.r8 ldc.r8 -234.098 add conv.i ldind.i4 ldc.i4 104 beq a010104 ldstr "a010104" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010104: ldsflda int16 [rvastatic4]A::a010105 conv.i8 dup ldc.i8 0x0000000000ffffff and ldc.i4 32 shl conv.i8 ldc.i4 32 shr.un or conv.i ldind.i2 ldc.i4 105 beq a010105 ldstr "a010105" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010105: ldsflda int16 [rvastatic4]A::a010106 conv.i8 ldc.i8 2 mul ldc.i4 1 shr.un conv.i ldind.i2 ldc.i4 106 beq a010106 ldstr "a010106" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010106: ldsflda float32 [rvastatic4]A::a010107 conv.i8 ldc.i8 61555 add conv.i8 ldc.i8 61555 sub conv.i ldind.r4 ldc.r4 107.0 beq a010107 ldstr "a010107" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010107: ldsflda int32 [rvastatic4]A::a010108 conv.i8 dup ldc.i8 0x0000000000ffffff and ldc.i4 32 shl conv.i8 ldc.i4 32 shr.un or conv.i ldind.i4 ldc.i4 108 beq a010108 ldstr "a010108" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010108: ldsflda int16 [rvastatic4]A::a010109 conv.i8 dup ldc.i8 0xffffffff00000000 and ldc.i4 32 shr.un conv.i8 ldc.i4 32 shl or conv.i ldind.i2 ldc.i4 109 beq a010109 ldstr "a010109" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010109: ldsflda int32 [rvastatic4]A::a010110 conv.i8 conv.r8 conv.u8 conv.i conv.i8 conv.r8 conv.u8 conv.i ldind.i4 ldc.i4 110 beq a010110 ldstr "a010110" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010110: ldsflda int32 [rvastatic4]A::a010111 conv.i8 dup dup xor xor conv.i ldind.i4 ldc.i4 111 beq a010111 ldstr "a010111" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010111: ldsflda int32 [rvastatic4]A::a010112 conv.i8 dup dup xor xor conv.i ldind.i4 ldc.i4 112 beq a010112 ldstr "a010112" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010112: ldsflda int64 [rvastatic4]A::a010113 conv.i8 ldc.i8 45274 add conv.i8 ldc.i8 45274 sub conv.i ldind.i8 ldc.i8 113 beq a010113 ldstr "a010113" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010113: ldsflda int64 [rvastatic4]A::a010114 conv.r8 ldc.r8 234.098 add conv.r8 ldc.r8 -234.098 add conv.i ldind.i8 ldc.i8 114 beq a010114 ldstr "a010114" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010114: ldsflda int16 [rvastatic4]A::a010115 conv.i8 dup ldc.i8 0xffffffff00000000 and ldc.i4 32 shr.un conv.i8 ldc.i4 32 shl or conv.i ldind.i2 ldc.i4 115 beq a010115 ldstr "a010115" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010115: ldsflda int64 [rvastatic4]A::a010116 conv.i8 ldc.i8 2 mul ldc.i4 1 shr.un conv.i ldind.i8 ldc.i8 116 beq a010116 ldstr "a010116" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010116: ldsflda int64 [rvastatic4]A::a010117 conv.i8 dup ldc.i8 0xffffffff00000000 and ldc.i4 32 shr.un conv.i8 ldc.i4 32 shl or conv.i ldind.i8 ldc.i8 117 beq a010117 ldstr "a010117" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010117: ldsflda int32 [rvastatic4]A::a010118 conv.i8 ldc.i8 9701 add conv.i8 ldc.i8 9701 sub conv.i ldind.i4 ldc.i4 118 beq a010118 ldstr "a010118" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010118: ldsflda int64 [rvastatic4]A::a010119 conv.r8 ldc.r8 234.098 add conv.r8 ldc.r8 -234.098 add conv.i ldind.i8 ldc.i8 119 beq a010119 ldstr "a010119" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010119: ldsflda int64 [rvastatic4]A::a010120 conv.i8 dup ldc.i8 0x0000000000ffffff and ldc.i4 32 shl conv.i8 ldc.i4 32 shr.un or conv.i ldind.i8 ldc.i8 120 beq a010120 ldstr "a010120" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010120: ldsflda int64 [rvastatic4]A::a010121 conv.i8 dup ldc.i8 0x0000000000ffffff and ldc.i4 32 shl conv.i8 ldc.i4 32 shr.un or conv.i ldind.i8 ldc.i8 121 beq a010121 ldstr "a010121" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010121: ldsflda int16 [rvastatic4]A::a010122 conv.r8 ldc.r8 234.098 add conv.r8 ldc.r8 -234.098 add conv.i ldind.i2 ldc.i4 122 beq a010122 ldstr "a010122" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010122: ldsflda int64 [rvastatic4]A::a010123 conv.i8 ldc.i8 2 mul ldc.i4 1 shr.un conv.i ldind.i8 ldc.i8 123 beq a010123 ldstr "a010123" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010123: ldsflda int64 [rvastatic4]A::a010124 conv.i8 conv.r8 conv.u8 conv.i conv.i8 conv.r8 conv.u8 conv.i ldind.i8 ldc.i8 124 beq a010124 ldstr "a010124" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010124: ldsflda int32 [rvastatic4]A::a010125 conv.i8 conv.r8 conv.u8 conv.i conv.i8 conv.r8 conv.u8 conv.i ldind.i4 ldc.i4 125 beq a010125 ldstr "a010125" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010125: ldsflda int16 [rvastatic4]A::a010126 conv.i8 dup dup xor xor conv.i ldind.i2 ldc.i4 126 beq a010126 ldstr "a010126" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010126: ldsflda int16 [rvastatic4]A::a010127 conv.i8 dup ldc.i8 0xffffffff00000000 and ldc.i4 32 shr.un conv.i8 ldc.i4 32 shl or conv.i ldind.i2 ldc.i4 127 beq a010127 ldstr "a010127" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010127: ret} .method static void V5() {.maxstack 50 ldsflda int32 [rvastatic4]A::a0100 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i4 ldc.i4 0 beq a0100 ldstr "a0100" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a0100: ldsflda int64 [rvastatic4]A::a0101 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i8 ldc.i8 1 beq a0101 ldstr "a0101" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a0101: ldsflda float32 [rvastatic4]A::a0102 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.r4 ldc.r4 2.0 beq a0102 ldstr "a0102" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a0102: ldsflda int16 [rvastatic4]A::a0103 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i2 ldc.i4 3 beq a0103 ldstr "a0103" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a0103: ldsflda int16 [rvastatic4]A::a0104 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i2 ldc.i4 4 beq a0104 ldstr "a0104" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a0104: ldsflda int64 [rvastatic4]A::a0105 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i8 ldc.i8 5 beq a0105 ldstr "a0105" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a0105: ldsflda int16 [rvastatic4]A::a0106 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.i2 ldc.i4 6 beq a0106 ldstr "a0106" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a0106: ldsflda int8 [rvastatic4]A::a0107 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i1 ldc.i4 7 beq a0107 ldstr "a0107" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a0107: ldsflda int64 [rvastatic4]A::a0108 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i8 ldc.i8 8 beq a0108 ldstr "a0108" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a0108: ldsflda int32 [rvastatic4]A::a0109 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i4 ldc.i4 9 beq a0109 ldstr "a0109" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a0109: ldsflda int16 [rvastatic4]A::a01010 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.i2 ldc.i4 10 beq a01010 ldstr "a01010" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01010: ldsflda float32 [rvastatic4]A::a01011 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.r4 ldc.r4 11.0 beq a01011 ldstr "a01011" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01011: ldsflda int16 [rvastatic4]A::a01012 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i2 ldc.i4 12 beq a01012 ldstr "a01012" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01012: ldsflda float32 [rvastatic4]A::a01013 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.r4 ldc.r4 13.0 beq a01013 ldstr "a01013" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01013: ldsflda float32 [rvastatic4]A::a01014 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.r4 ldc.r4 14.0 beq a01014 ldstr "a01014" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01014: ldsflda int8 [rvastatic4]A::a01015 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i1 ldc.i4 15 beq a01015 ldstr "a01015" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01015: ldsflda float32 [rvastatic4]A::a01016 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.r4 ldc.r4 16.0 beq a01016 ldstr "a01016" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01016: ldsflda int8 [rvastatic4]A::a01017 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i1 ldc.i4 17 beq a01017 ldstr "a01017" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01017: ldsflda float32 [rvastatic4]A::a01018 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.r4 ldc.r4 18.0 beq a01018 ldstr "a01018" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01018: ldsflda float32 [rvastatic4]A::a01019 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.r4 ldc.r4 19.0 beq a01019 ldstr "a01019" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01019: ldsflda int8 [rvastatic4]A::a01020 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i1 ldc.i4 20 beq a01020 ldstr "a01020" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01020: ldsflda float32 [rvastatic4]A::a01021 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.r4 ldc.r4 21.0 beq a01021 ldstr "a01021" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01021: ldsflda int64 [rvastatic4]A::a01022 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i8 ldc.i8 22 beq a01022 ldstr "a01022" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01022: ldsflda int8 [rvastatic4]A::a01023 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i1 ldc.i4 23 beq a01023 ldstr "a01023" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01023: ldsflda int32 [rvastatic4]A::a01024 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.i4 ldc.i4 24 beq a01024 ldstr "a01024" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01024: ldsflda int64 [rvastatic4]A::a01025 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.i8 ldc.i8 25 beq a01025 ldstr "a01025" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01025: ldsflda int16 [rvastatic4]A::a01026 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i2 ldc.i4 26 beq a01026 ldstr "a01026" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01026: ldsflda int8 [rvastatic4]A::a01027 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i1 ldc.i4 27 beq a01027 ldstr "a01027" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01027: ldsflda int16 [rvastatic4]A::a01028 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.i2 ldc.i4 28 beq a01028 ldstr "a01028" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01028: ldsflda int16 [rvastatic4]A::a01029 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i2 ldc.i4 29 beq a01029 ldstr "a01029" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01029: ldsflda int8 [rvastatic4]A::a01030 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i1 ldc.i4 30 beq a01030 ldstr "a01030" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01030: ldsflda int8 [rvastatic4]A::a01031 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.i1 ldc.i4 31 beq a01031 ldstr "a01031" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01031: ldsflda int64 [rvastatic4]A::a01032 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i8 ldc.i8 32 beq a01032 ldstr "a01032" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01032: ldsflda float32 [rvastatic4]A::a01033 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.r4 ldc.r4 33.0 beq a01033 ldstr "a01033" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01033: ldsflda int16 [rvastatic4]A::a01034 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i2 ldc.i4 34 beq a01034 ldstr "a01034" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01034: ldsflda int8 [rvastatic4]A::a01035 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i1 ldc.i4 35 beq a01035 ldstr "a01035" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01035: ldsflda int8 [rvastatic4]A::a01036 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i1 ldc.i4 36 beq a01036 ldstr "a01036" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01036: ldsflda int32 [rvastatic4]A::a01037 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.i4 ldc.i4 37 beq a01037 ldstr "a01037" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01037: ldsflda int16 [rvastatic4]A::a01038 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.i2 ldc.i4 38 beq a01038 ldstr "a01038" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01038: ldsflda int8 [rvastatic4]A::a01039 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i1 ldc.i4 39 beq a01039 ldstr "a01039" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01039: ldsflda int8 [rvastatic4]A::a01040 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.i1 ldc.i4 40 beq a01040 ldstr "a01040" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01040: ldsflda int32 [rvastatic4]A::a01041 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.i4 ldc.i4 41 beq a01041 ldstr "a01041" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01041: ldsflda int64 [rvastatic4]A::a01042 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i8 ldc.i8 42 beq a01042 ldstr "a01042" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01042: ldsflda int16 [rvastatic4]A::a01043 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i2 ldc.i4 43 beq a01043 ldstr "a01043" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01043: ldsflda int64 [rvastatic4]A::a01044 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i8 ldc.i8 44 beq a01044 ldstr "a01044" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01044: ldsflda int64 [rvastatic4]A::a01045 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i8 ldc.i8 45 beq a01045 ldstr "a01045" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01045: ldsflda float32 [rvastatic4]A::a01046 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.r4 ldc.r4 46.0 beq a01046 ldstr "a01046" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01046: ldsflda int16 [rvastatic4]A::a01047 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i2 ldc.i4 47 beq a01047 ldstr "a01047" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01047: ldsflda int64 [rvastatic4]A::a01048 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i8 ldc.i8 48 beq a01048 ldstr "a01048" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01048: ldsflda int16 [rvastatic4]A::a01049 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i2 ldc.i4 49 beq a01049 ldstr "a01049" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01049: ldsflda int32 [rvastatic4]A::a01050 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i4 ldc.i4 50 beq a01050 ldstr "a01050" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01050: ldsflda int16 [rvastatic4]A::a01051 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i2 ldc.i4 51 beq a01051 ldstr "a01051" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01051: ldsflda int32 [rvastatic4]A::a01052 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i4 ldc.i4 52 beq a01052 ldstr "a01052" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01052: ldsflda int16 [rvastatic4]A::a01053 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i2 ldc.i4 53 beq a01053 ldstr "a01053" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01053: ldsflda float32 [rvastatic4]A::a01054 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.r4 ldc.r4 54.0 beq a01054 ldstr "a01054" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01054: ldsflda int64 [rvastatic4]A::a01055 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i8 ldc.i8 55 beq a01055 ldstr "a01055" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01055: ldsflda float32 [rvastatic4]A::a01056 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.r4 ldc.r4 56.0 beq a01056 ldstr "a01056" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01056: ldsflda int64 [rvastatic4]A::a01057 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i8 ldc.i8 57 beq a01057 ldstr "a01057" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01057: ldsflda int64 [rvastatic4]A::a01058 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i8 ldc.i8 58 beq a01058 ldstr "a01058" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01058: ldsflda int64 [rvastatic4]A::a01059 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i8 ldc.i8 59 beq a01059 ldstr "a01059" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01059: ldsflda int16 [rvastatic4]A::a01060 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.i2 ldc.i4 60 beq a01060 ldstr "a01060" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01060: ldsflda int8 [rvastatic4]A::a01061 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i1 ldc.i4 61 beq a01061 ldstr "a01061" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01061: ldsflda int64 [rvastatic4]A::a01062 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i8 ldc.i8 62 beq a01062 ldstr "a01062" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01062: ldsflda int16 [rvastatic4]A::a01063 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i2 ldc.i4 63 beq a01063 ldstr "a01063" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01063: ldsflda int32 [rvastatic4]A::a01064 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.i4 ldc.i4 64 beq a01064 ldstr "a01064" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01064: ldsflda int16 [rvastatic4]A::a01065 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.i2 ldc.i4 65 beq a01065 ldstr "a01065" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01065: ldsflda int8 [rvastatic4]A::a01066 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.i1 ldc.i4 66 beq a01066 ldstr "a01066" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01066: ldsflda int16 [rvastatic4]A::a01067 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i2 ldc.i4 67 beq a01067 ldstr "a01067" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01067: ldsflda int32 [rvastatic4]A::a01068 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.i4 ldc.i4 68 beq a01068 ldstr "a01068" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01068: ldsflda float32 [rvastatic4]A::a01069 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.r4 ldc.r4 69.0 beq a01069 ldstr "a01069" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01069: ldsflda float32 [rvastatic4]A::a01070 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.r4 ldc.r4 70.0 beq a01070 ldstr "a01070" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01070: ldsflda int16 [rvastatic4]A::a01071 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i2 ldc.i4 71 beq a01071 ldstr "a01071" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01071: ldsflda float32 [rvastatic4]A::a01072 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.r4 ldc.r4 72.0 beq a01072 ldstr "a01072" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01072: ldsflda int64 [rvastatic4]A::a01073 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i8 ldc.i8 73 beq a01073 ldstr "a01073" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01073: ldsflda int64 [rvastatic4]A::a01074 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i8 ldc.i8 74 beq a01074 ldstr "a01074" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01074: ldsflda int32 [rvastatic4]A::a01075 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i4 ldc.i4 75 beq a01075 ldstr "a01075" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01075: ldsflda int8 [rvastatic4]A::a01076 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.i1 ldc.i4 76 beq a01076 ldstr "a01076" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01076: ldsflda int32 [rvastatic4]A::a01077 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i4 ldc.i4 77 beq a01077 ldstr "a01077" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01077: ldsflda int16 [rvastatic4]A::a01078 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i2 ldc.i4 78 beq a01078 ldstr "a01078" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01078: ldsflda float32 [rvastatic4]A::a01079 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.r4 ldc.r4 79.0 beq a01079 ldstr "a01079" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01079: ldsflda float32 [rvastatic4]A::a01080 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.r4 ldc.r4 80.0 beq a01080 ldstr "a01080" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01080: ldsflda float32 [rvastatic4]A::a01081 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.r4 ldc.r4 81.0 beq a01081 ldstr "a01081" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01081: ldsflda int32 [rvastatic4]A::a01082 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i4 ldc.i4 82 beq a01082 ldstr "a01082" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01082: ldsflda int8 [rvastatic4]A::a01083 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i1 ldc.i4 83 beq a01083 ldstr "a01083" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01083: ldsflda int64 [rvastatic4]A::a01084 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.i8 ldc.i8 84 beq a01084 ldstr "a01084" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01084: ldsflda int64 [rvastatic4]A::a01085 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i8 ldc.i8 85 beq a01085 ldstr "a01085" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01085: ldsflda int32 [rvastatic4]A::a01086 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.i4 ldc.i4 86 beq a01086 ldstr "a01086" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01086: ldsflda int32 [rvastatic4]A::a01087 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i4 ldc.i4 87 beq a01087 ldstr "a01087" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01087: ldsflda int8 [rvastatic4]A::a01088 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i1 ldc.i4 88 beq a01088 ldstr "a01088" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01088: ldsflda int64 [rvastatic4]A::a01089 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i8 ldc.i8 89 beq a01089 ldstr "a01089" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01089: ldsflda int8 [rvastatic4]A::a01090 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.i1 ldc.i4 90 beq a01090 ldstr "a01090" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01090: ldsflda int16 [rvastatic4]A::a01091 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i2 ldc.i4 91 beq a01091 ldstr "a01091" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01091: ldsflda float32 [rvastatic4]A::a01092 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.r4 ldc.r4 92.0 beq a01092 ldstr "a01092" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01092: ldsflda int64 [rvastatic4]A::a01093 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i8 ldc.i8 93 beq a01093 ldstr "a01093" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01093: ldsflda int64 [rvastatic4]A::a01094 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i8 ldc.i8 94 beq a01094 ldstr "a01094" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01094: ldsflda int8 [rvastatic4]A::a01095 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i1 ldc.i4 95 beq a01095 ldstr "a01095" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01095: ldsflda float32 [rvastatic4]A::a01096 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.r4 ldc.r4 96.0 beq a01096 ldstr "a01096" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01096: ldsflda int16 [rvastatic4]A::a01097 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i2 ldc.i4 97 beq a01097 ldstr "a01097" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01097: ldsflda float32 [rvastatic4]A::a01098 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.r4 ldc.r4 98.0 beq a01098 ldstr "a01098" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01098: ldsflda int32 [rvastatic4]A::a01099 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i4 ldc.i4 99 beq a01099 ldstr "a01099" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01099: ldsflda int64 [rvastatic4]A::a010100 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i8 ldc.i8 100 beq a010100 ldstr "a010100" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010100: ldsflda int32 [rvastatic4]A::a010101 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i4 ldc.i4 101 beq a010101 ldstr "a010101" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010101: ldsflda float32 [rvastatic4]A::a010102 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.r4 ldc.r4 102.0 beq a010102 ldstr "a010102" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010102: ldsflda int64 [rvastatic4]A::a010103 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.i8 ldc.i8 103 beq a010103 ldstr "a010103" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010103: ldsflda int32 [rvastatic4]A::a010104 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i4 ldc.i4 104 beq a010104 ldstr "a010104" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010104: ldsflda int16 [rvastatic4]A::a010105 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.i2 ldc.i4 105 beq a010105 ldstr "a010105" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010105: ldsflda int16 [rvastatic4]A::a010106 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i2 ldc.i4 106 beq a010106 ldstr "a010106" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010106: ldsflda float32 [rvastatic4]A::a010107 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.r4 ldc.r4 107.0 beq a010107 ldstr "a010107" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010107: ldsflda int32 [rvastatic4]A::a010108 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i4 ldc.i4 108 beq a010108 ldstr "a010108" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010108: ldsflda int16 [rvastatic4]A::a010109 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i2 ldc.i4 109 beq a010109 ldstr "a010109" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010109: ldsflda int32 [rvastatic4]A::a010110 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i4 ldc.i4 110 beq a010110 ldstr "a010110" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010110: ldsflda int32 [rvastatic4]A::a010111 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i4 ldc.i4 111 beq a010111 ldstr "a010111" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010111: ldsflda int32 [rvastatic4]A::a010112 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i4 ldc.i4 112 beq a010112 ldstr "a010112" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010112: ldsflda int64 [rvastatic4]A::a010113 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i8 ldc.i8 113 beq a010113 ldstr "a010113" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010113: ldsflda int64 [rvastatic4]A::a010114 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i8 ldc.i8 114 beq a010114 ldstr "a010114" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010114: ldsflda int16 [rvastatic4]A::a010115 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i2 ldc.i4 115 beq a010115 ldstr "a010115" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010115: ldsflda int64 [rvastatic4]A::a010116 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i8 ldc.i8 116 beq a010116 ldstr "a010116" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010116: ldsflda int64 [rvastatic4]A::a010117 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.i8 ldc.i8 117 beq a010117 ldstr "a010117" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010117: ldsflda int32 [rvastatic4]A::a010118 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i4 ldc.i4 118 beq a010118 ldstr "a010118" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010118: ldsflda int64 [rvastatic4]A::a010119 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i8 ldc.i8 119 beq a010119 ldstr "a010119" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010119: ldsflda int64 [rvastatic4]A::a010120 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i8 ldc.i8 120 beq a010120 ldstr "a010120" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010120: ldsflda int64 [rvastatic4]A::a010121 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.i8 ldc.i8 121 beq a010121 ldstr "a010121" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010121: ldsflda int16 [rvastatic4]A::a010122 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.i2 ldc.i4 122 beq a010122 ldstr "a010122" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010122: ldsflda int64 [rvastatic4]A::a010123 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.i8 ldc.i8 123 beq a010123 ldstr "a010123" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010123: ldsflda int64 [rvastatic4]A::a010124 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i8 ldc.i8 124 beq a010124 ldstr "a010124" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010124: ldsflda int32 [rvastatic4]A::a010125 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i4 ldc.i4 125 beq a010125 ldstr "a010125" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010125: ldsflda int16 [rvastatic4]A::a010126 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i2 ldc.i4 126 beq a010126 ldstr "a010126" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010126: ldsflda int16 [rvastatic4]A::a010127 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i2 ldc.i4 127 beq a010127 ldstr "a010127" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010127: ret} .method static void V6() {.maxstack 50 ldsfld int32 [rvastatic4]A::a0100 ldc.i4 1 add stsfld int32 [rvastatic4]A::a0100 ldsfld int32 [rvastatic4]A::a0100 ldc.i4 1 beq a0100 newobj instance void [mscorlib]System.Exception::.ctor() throw a0100: ldsfld int64 [rvastatic4]A::a0101 ldc.i8 1 add stsfld int64 [rvastatic4]A::a0101 ldsfld int64 [rvastatic4]A::a0101 ldc.i8 2 beq a0101 newobj instance void [mscorlib]System.Exception::.ctor() throw a0101: ldsfld float32 [rvastatic4]A::a0102 ldc.r4 1 add stsfld float32 [rvastatic4]A::a0102 ldsfld float32 [rvastatic4]A::a0102 ldc.r4 3.0 beq a0102 newobj instance void [mscorlib]System.Exception::.ctor() throw a0102: ldsfld int16 [rvastatic4]A::a0103 ldc.i4 1 add stsfld int16 [rvastatic4]A::a0103 ldsfld int16 [rvastatic4]A::a0103 ldc.i4 4 beq a0103 newobj instance void [mscorlib]System.Exception::.ctor() throw a0103: ldsfld int16 [rvastatic4]A::a0104 ldc.i4 1 add stsfld int16 [rvastatic4]A::a0104 ldsfld int16 [rvastatic4]A::a0104 ldc.i4 5 beq a0104 newobj instance void [mscorlib]System.Exception::.ctor() throw a0104: ldsfld int64 [rvastatic4]A::a0105 ldc.i8 1 add stsfld int64 [rvastatic4]A::a0105 ldsfld int64 [rvastatic4]A::a0105 ldc.i8 6 beq a0105 newobj instance void [mscorlib]System.Exception::.ctor() throw a0105: ldsfld int16 [rvastatic4]A::a0106 ldc.i4 1 add stsfld int16 [rvastatic4]A::a0106 ldsfld int16 [rvastatic4]A::a0106 ldc.i4 7 beq a0106 newobj instance void [mscorlib]System.Exception::.ctor() throw a0106: ldsfld int8 [rvastatic4]A::a0107 ldc.i4 1 add stsfld int8 [rvastatic4]A::a0107 ldsfld int8 [rvastatic4]A::a0107 ldc.i4 8 beq a0107 newobj instance void [mscorlib]System.Exception::.ctor() throw a0107: ldsfld int64 [rvastatic4]A::a0108 ldc.i8 1 add stsfld int64 [rvastatic4]A::a0108 ldsfld int64 [rvastatic4]A::a0108 ldc.i8 9 beq a0108 newobj instance void [mscorlib]System.Exception::.ctor() throw a0108: ldsfld int32 [rvastatic4]A::a0109 ldc.i4 1 add stsfld int32 [rvastatic4]A::a0109 ldsfld int32 [rvastatic4]A::a0109 ldc.i4 10 beq a0109 newobj instance void [mscorlib]System.Exception::.ctor() throw a0109: ldsfld int16 [rvastatic4]A::a01010 ldc.i4 1 add stsfld int16 [rvastatic4]A::a01010 ldsfld int16 [rvastatic4]A::a01010 ldc.i4 11 beq a01010 newobj instance void [mscorlib]System.Exception::.ctor() throw a01010: ldsfld float32 [rvastatic4]A::a01011 ldc.r4 1 add stsfld float32 [rvastatic4]A::a01011 ldsfld float32 [rvastatic4]A::a01011 ldc.r4 12.0 beq a01011 newobj instance void [mscorlib]System.Exception::.ctor() throw a01011: ldsfld int16 [rvastatic4]A::a01012 ldc.i4 1 add stsfld int16 [rvastatic4]A::a01012 ldsfld int16 [rvastatic4]A::a01012 ldc.i4 13 beq a01012 newobj instance void [mscorlib]System.Exception::.ctor() throw a01012: ldsfld float32 [rvastatic4]A::a01013 ldc.r4 1 add stsfld float32 [rvastatic4]A::a01013 ldsfld float32 [rvastatic4]A::a01013 ldc.r4 14.0 beq a01013 newobj instance void [mscorlib]System.Exception::.ctor() throw a01013: ldsfld float32 [rvastatic4]A::a01014 ldc.r4 1 add stsfld float32 [rvastatic4]A::a01014 ldsfld float32 [rvastatic4]A::a01014 ldc.r4 15.0 beq a01014 newobj instance void [mscorlib]System.Exception::.ctor() throw a01014: ldsfld int8 [rvastatic4]A::a01015 ldc.i4 1 add stsfld int8 [rvastatic4]A::a01015 ldsfld int8 [rvastatic4]A::a01015 ldc.i4 16 beq a01015 newobj instance void [mscorlib]System.Exception::.ctor() throw a01015: ldsfld float32 [rvastatic4]A::a01016 ldc.r4 1 add stsfld float32 [rvastatic4]A::a01016 ldsfld float32 [rvastatic4]A::a01016 ldc.r4 17.0 beq a01016 newobj instance void [mscorlib]System.Exception::.ctor() throw a01016: ldsfld int8 [rvastatic4]A::a01017 ldc.i4 1 add stsfld int8 [rvastatic4]A::a01017 ldsfld int8 [rvastatic4]A::a01017 ldc.i4 18 beq a01017 newobj instance void [mscorlib]System.Exception::.ctor() throw a01017: ldsfld float32 [rvastatic4]A::a01018 ldc.r4 1 add stsfld float32 [rvastatic4]A::a01018 ldsfld float32 [rvastatic4]A::a01018 ldc.r4 19.0 beq a01018 newobj instance void [mscorlib]System.Exception::.ctor() throw a01018: ldsfld float32 [rvastatic4]A::a01019 ldc.r4 1 add stsfld float32 [rvastatic4]A::a01019 ldsfld float32 [rvastatic4]A::a01019 ldc.r4 20.0 beq a01019 newobj instance void [mscorlib]System.Exception::.ctor() throw a01019: ldsfld int8 [rvastatic4]A::a01020 ldc.i4 1 add stsfld int8 [rvastatic4]A::a01020 ldsfld int8 [rvastatic4]A::a01020 ldc.i4 21 beq a01020 newobj instance void [mscorlib]System.Exception::.ctor() throw a01020: ldsfld float32 [rvastatic4]A::a01021 ldc.r4 1 add stsfld float32 [rvastatic4]A::a01021 ldsfld float32 [rvastatic4]A::a01021 ldc.r4 22.0 beq a01021 newobj instance void [mscorlib]System.Exception::.ctor() throw a01021: ldsfld int64 [rvastatic4]A::a01022 ldc.i8 1 add stsfld int64 [rvastatic4]A::a01022 ldsfld int64 [rvastatic4]A::a01022 ldc.i8 23 beq a01022 newobj instance void [mscorlib]System.Exception::.ctor() throw a01022: ldsfld int8 [rvastatic4]A::a01023 ldc.i4 1 add stsfld int8 [rvastatic4]A::a01023 ldsfld int8 [rvastatic4]A::a01023 ldc.i4 24 beq a01023 newobj instance void [mscorlib]System.Exception::.ctor() throw a01023: ldsfld int32 [rvastatic4]A::a01024 ldc.i4 1 add stsfld int32 [rvastatic4]A::a01024 ldsfld int32 [rvastatic4]A::a01024 ldc.i4 25 beq a01024 newobj instance void [mscorlib]System.Exception::.ctor() throw a01024: ldsfld int64 [rvastatic4]A::a01025 ldc.i8 1 add stsfld int64 [rvastatic4]A::a01025 ldsfld int64 [rvastatic4]A::a01025 ldc.i8 26 beq a01025 newobj instance void [mscorlib]System.Exception::.ctor() throw a01025: ldsfld int16 [rvastatic4]A::a01026 ldc.i4 1 add stsfld int16 [rvastatic4]A::a01026 ldsfld int16 [rvastatic4]A::a01026 ldc.i4 27 beq a01026 newobj instance void [mscorlib]System.Exception::.ctor() throw a01026: ldsfld int8 [rvastatic4]A::a01027 ldc.i4 1 add stsfld int8 [rvastatic4]A::a01027 ldsfld int8 [rvastatic4]A::a01027 ldc.i4 28 beq a01027 newobj instance void [mscorlib]System.Exception::.ctor() throw a01027: ldsfld int16 [rvastatic4]A::a01028 ldc.i4 1 add stsfld int16 [rvastatic4]A::a01028 ldsfld int16 [rvastatic4]A::a01028 ldc.i4 29 beq a01028 newobj instance void [mscorlib]System.Exception::.ctor() throw a01028: ldsfld int16 [rvastatic4]A::a01029 ldc.i4 1 add stsfld int16 [rvastatic4]A::a01029 ldsfld int16 [rvastatic4]A::a01029 ldc.i4 30 beq a01029 newobj instance void [mscorlib]System.Exception::.ctor() throw a01029: ldsfld int8 [rvastatic4]A::a01030 ldc.i4 1 add stsfld int8 [rvastatic4]A::a01030 ldsfld int8 [rvastatic4]A::a01030 ldc.i4 31 beq a01030 newobj instance void [mscorlib]System.Exception::.ctor() throw a01030: ldsfld int8 [rvastatic4]A::a01031 ldc.i4 1 add stsfld int8 [rvastatic4]A::a01031 ldsfld int8 [rvastatic4]A::a01031 ldc.i4 32 beq a01031 newobj instance void [mscorlib]System.Exception::.ctor() throw a01031: ldsfld int64 [rvastatic4]A::a01032 ldc.i8 1 add stsfld int64 [rvastatic4]A::a01032 ldsfld int64 [rvastatic4]A::a01032 ldc.i8 33 beq a01032 newobj instance void [mscorlib]System.Exception::.ctor() throw a01032: ldsfld float32 [rvastatic4]A::a01033 ldc.r4 1 add stsfld float32 [rvastatic4]A::a01033 ldsfld float32 [rvastatic4]A::a01033 ldc.r4 34.0 beq a01033 newobj instance void [mscorlib]System.Exception::.ctor() throw a01033: ldsfld int16 [rvastatic4]A::a01034 ldc.i4 1 add stsfld int16 [rvastatic4]A::a01034 ldsfld int16 [rvastatic4]A::a01034 ldc.i4 35 beq a01034 newobj instance void [mscorlib]System.Exception::.ctor() throw a01034: ldsfld int8 [rvastatic4]A::a01035 ldc.i4 1 add stsfld int8 [rvastatic4]A::a01035 ldsfld int8 [rvastatic4]A::a01035 ldc.i4 36 beq a01035 newobj instance void [mscorlib]System.Exception::.ctor() throw a01035: ldsfld int8 [rvastatic4]A::a01036 ldc.i4 1 add stsfld int8 [rvastatic4]A::a01036 ldsfld int8 [rvastatic4]A::a01036 ldc.i4 37 beq a01036 newobj instance void [mscorlib]System.Exception::.ctor() throw a01036: ldsfld int32 [rvastatic4]A::a01037 ldc.i4 1 add stsfld int32 [rvastatic4]A::a01037 ldsfld int32 [rvastatic4]A::a01037 ldc.i4 38 beq a01037 newobj instance void [mscorlib]System.Exception::.ctor() throw a01037: ldsfld int16 [rvastatic4]A::a01038 ldc.i4 1 add stsfld int16 [rvastatic4]A::a01038 ldsfld int16 [rvastatic4]A::a01038 ldc.i4 39 beq a01038 newobj instance void [mscorlib]System.Exception::.ctor() throw a01038: ldsfld int8 [rvastatic4]A::a01039 ldc.i4 1 add stsfld int8 [rvastatic4]A::a01039 ldsfld int8 [rvastatic4]A::a01039 ldc.i4 40 beq a01039 newobj instance void [mscorlib]System.Exception::.ctor() throw a01039: ldsfld int8 [rvastatic4]A::a01040 ldc.i4 1 add stsfld int8 [rvastatic4]A::a01040 ldsfld int8 [rvastatic4]A::a01040 ldc.i4 41 beq a01040 newobj instance void [mscorlib]System.Exception::.ctor() throw a01040: ldsfld int32 [rvastatic4]A::a01041 ldc.i4 1 add stsfld int32 [rvastatic4]A::a01041 ldsfld int32 [rvastatic4]A::a01041 ldc.i4 42 beq a01041 newobj instance void [mscorlib]System.Exception::.ctor() throw a01041: ldsfld int64 [rvastatic4]A::a01042 ldc.i8 1 add stsfld int64 [rvastatic4]A::a01042 ldsfld int64 [rvastatic4]A::a01042 ldc.i8 43 beq a01042 newobj instance void [mscorlib]System.Exception::.ctor() throw a01042: ldsfld int16 [rvastatic4]A::a01043 ldc.i4 1 add stsfld int16 [rvastatic4]A::a01043 ldsfld int16 [rvastatic4]A::a01043 ldc.i4 44 beq a01043 newobj instance void [mscorlib]System.Exception::.ctor() throw a01043: ldsfld int64 [rvastatic4]A::a01044 ldc.i8 1 add stsfld int64 [rvastatic4]A::a01044 ldsfld int64 [rvastatic4]A::a01044 ldc.i8 45 beq a01044 newobj instance void [mscorlib]System.Exception::.ctor() throw a01044: ldsfld int64 [rvastatic4]A::a01045 ldc.i8 1 add stsfld int64 [rvastatic4]A::a01045 ldsfld int64 [rvastatic4]A::a01045 ldc.i8 46 beq a01045 newobj instance void [mscorlib]System.Exception::.ctor() throw a01045: ldsfld float32 [rvastatic4]A::a01046 ldc.r4 1 add stsfld float32 [rvastatic4]A::a01046 ldsfld float32 [rvastatic4]A::a01046 ldc.r4 47.0 beq a01046 newobj instance void [mscorlib]System.Exception::.ctor() throw a01046: ldsfld int16 [rvastatic4]A::a01047 ldc.i4 1 add stsfld int16 [rvastatic4]A::a01047 ldsfld int16 [rvastatic4]A::a01047 ldc.i4 48 beq a01047 newobj instance void [mscorlib]System.Exception::.ctor() throw a01047: ldsfld int64 [rvastatic4]A::a01048 ldc.i8 1 add stsfld int64 [rvastatic4]A::a01048 ldsfld int64 [rvastatic4]A::a01048 ldc.i8 49 beq a01048 newobj instance void [mscorlib]System.Exception::.ctor() throw a01048: ldsfld int16 [rvastatic4]A::a01049 ldc.i4 1 add stsfld int16 [rvastatic4]A::a01049 ldsfld int16 [rvastatic4]A::a01049 ldc.i4 50 beq a01049 newobj instance void [mscorlib]System.Exception::.ctor() throw a01049: ldsfld int32 [rvastatic4]A::a01050 ldc.i4 1 add stsfld int32 [rvastatic4]A::a01050 ldsfld int32 [rvastatic4]A::a01050 ldc.i4 51 beq a01050 newobj instance void [mscorlib]System.Exception::.ctor() throw a01050: ldsfld int16 [rvastatic4]A::a01051 ldc.i4 1 add stsfld int16 [rvastatic4]A::a01051 ldsfld int16 [rvastatic4]A::a01051 ldc.i4 52 beq a01051 newobj instance void [mscorlib]System.Exception::.ctor() throw a01051: ldsfld int32 [rvastatic4]A::a01052 ldc.i4 1 add stsfld int32 [rvastatic4]A::a01052 ldsfld int32 [rvastatic4]A::a01052 ldc.i4 53 beq a01052 newobj instance void [mscorlib]System.Exception::.ctor() throw a01052: ldsfld int16 [rvastatic4]A::a01053 ldc.i4 1 add stsfld int16 [rvastatic4]A::a01053 ldsfld int16 [rvastatic4]A::a01053 ldc.i4 54 beq a01053 newobj instance void [mscorlib]System.Exception::.ctor() throw a01053: ldsfld float32 [rvastatic4]A::a01054 ldc.r4 1 add stsfld float32 [rvastatic4]A::a01054 ldsfld float32 [rvastatic4]A::a01054 ldc.r4 55.0 beq a01054 newobj instance void [mscorlib]System.Exception::.ctor() throw a01054: ldsfld int64 [rvastatic4]A::a01055 ldc.i8 1 add stsfld int64 [rvastatic4]A::a01055 ldsfld int64 [rvastatic4]A::a01055 ldc.i8 56 beq a01055 newobj instance void [mscorlib]System.Exception::.ctor() throw a01055: ldsfld float32 [rvastatic4]A::a01056 ldc.r4 1 add stsfld float32 [rvastatic4]A::a01056 ldsfld float32 [rvastatic4]A::a01056 ldc.r4 57.0 beq a01056 newobj instance void [mscorlib]System.Exception::.ctor() throw a01056: ldsfld int64 [rvastatic4]A::a01057 ldc.i8 1 add stsfld int64 [rvastatic4]A::a01057 ldsfld int64 [rvastatic4]A::a01057 ldc.i8 58 beq a01057 newobj instance void [mscorlib]System.Exception::.ctor() throw a01057: ldsfld int64 [rvastatic4]A::a01058 ldc.i8 1 add stsfld int64 [rvastatic4]A::a01058 ldsfld int64 [rvastatic4]A::a01058 ldc.i8 59 beq a01058 newobj instance void [mscorlib]System.Exception::.ctor() throw a01058: ldsfld int64 [rvastatic4]A::a01059 ldc.i8 1 add stsfld int64 [rvastatic4]A::a01059 ldsfld int64 [rvastatic4]A::a01059 ldc.i8 60 beq a01059 newobj instance void [mscorlib]System.Exception::.ctor() throw a01059: ldsfld int16 [rvastatic4]A::a01060 ldc.i4 1 add stsfld int16 [rvastatic4]A::a01060 ldsfld int16 [rvastatic4]A::a01060 ldc.i4 61 beq a01060 newobj instance void [mscorlib]System.Exception::.ctor() throw a01060: ldsfld int8 [rvastatic4]A::a01061 ldc.i4 1 add stsfld int8 [rvastatic4]A::a01061 ldsfld int8 [rvastatic4]A::a01061 ldc.i4 62 beq a01061 newobj instance void [mscorlib]System.Exception::.ctor() throw a01061: ldsfld int64 [rvastatic4]A::a01062 ldc.i8 1 add stsfld int64 [rvastatic4]A::a01062 ldsfld int64 [rvastatic4]A::a01062 ldc.i8 63 beq a01062 newobj instance void [mscorlib]System.Exception::.ctor() throw a01062: ldsfld int16 [rvastatic4]A::a01063 ldc.i4 1 add stsfld int16 [rvastatic4]A::a01063 ldsfld int16 [rvastatic4]A::a01063 ldc.i4 64 beq a01063 newobj instance void [mscorlib]System.Exception::.ctor() throw a01063: ldsfld int32 [rvastatic4]A::a01064 ldc.i4 1 add stsfld int32 [rvastatic4]A::a01064 ldsfld int32 [rvastatic4]A::a01064 ldc.i4 65 beq a01064 newobj instance void [mscorlib]System.Exception::.ctor() throw a01064: ldsfld int16 [rvastatic4]A::a01065 ldc.i4 1 add stsfld int16 [rvastatic4]A::a01065 ldsfld int16 [rvastatic4]A::a01065 ldc.i4 66 beq a01065 newobj instance void [mscorlib]System.Exception::.ctor() throw a01065: ldsfld int8 [rvastatic4]A::a01066 ldc.i4 1 add stsfld int8 [rvastatic4]A::a01066 ldsfld int8 [rvastatic4]A::a01066 ldc.i4 67 beq a01066 newobj instance void [mscorlib]System.Exception::.ctor() throw a01066: ldsfld int16 [rvastatic4]A::a01067 ldc.i4 1 add stsfld int16 [rvastatic4]A::a01067 ldsfld int16 [rvastatic4]A::a01067 ldc.i4 68 beq a01067 newobj instance void [mscorlib]System.Exception::.ctor() throw a01067: ldsfld int32 [rvastatic4]A::a01068 ldc.i4 1 add stsfld int32 [rvastatic4]A::a01068 ldsfld int32 [rvastatic4]A::a01068 ldc.i4 69 beq a01068 newobj instance void [mscorlib]System.Exception::.ctor() throw a01068: ldsfld float32 [rvastatic4]A::a01069 ldc.r4 1 add stsfld float32 [rvastatic4]A::a01069 ldsfld float32 [rvastatic4]A::a01069 ldc.r4 70.0 beq a01069 newobj instance void [mscorlib]System.Exception::.ctor() throw a01069: ldsfld float32 [rvastatic4]A::a01070 ldc.r4 1 add stsfld float32 [rvastatic4]A::a01070 ldsfld float32 [rvastatic4]A::a01070 ldc.r4 71.0 beq a01070 newobj instance void [mscorlib]System.Exception::.ctor() throw a01070: ldsfld int16 [rvastatic4]A::a01071 ldc.i4 1 add stsfld int16 [rvastatic4]A::a01071 ldsfld int16 [rvastatic4]A::a01071 ldc.i4 72 beq a01071 newobj instance void [mscorlib]System.Exception::.ctor() throw a01071: ldsfld float32 [rvastatic4]A::a01072 ldc.r4 1 add stsfld float32 [rvastatic4]A::a01072 ldsfld float32 [rvastatic4]A::a01072 ldc.r4 73.0 beq a01072 newobj instance void [mscorlib]System.Exception::.ctor() throw a01072: ldsfld int64 [rvastatic4]A::a01073 ldc.i8 1 add stsfld int64 [rvastatic4]A::a01073 ldsfld int64 [rvastatic4]A::a01073 ldc.i8 74 beq a01073 newobj instance void [mscorlib]System.Exception::.ctor() throw a01073: ldsfld int64 [rvastatic4]A::a01074 ldc.i8 1 add stsfld int64 [rvastatic4]A::a01074 ldsfld int64 [rvastatic4]A::a01074 ldc.i8 75 beq a01074 newobj instance void [mscorlib]System.Exception::.ctor() throw a01074: ldsfld int32 [rvastatic4]A::a01075 ldc.i4 1 add stsfld int32 [rvastatic4]A::a01075 ldsfld int32 [rvastatic4]A::a01075 ldc.i4 76 beq a01075 newobj instance void [mscorlib]System.Exception::.ctor() throw a01075: ldsfld int8 [rvastatic4]A::a01076 ldc.i4 1 add stsfld int8 [rvastatic4]A::a01076 ldsfld int8 [rvastatic4]A::a01076 ldc.i4 77 beq a01076 newobj instance void [mscorlib]System.Exception::.ctor() throw a01076: ldsfld int32 [rvastatic4]A::a01077 ldc.i4 1 add stsfld int32 [rvastatic4]A::a01077 ldsfld int32 [rvastatic4]A::a01077 ldc.i4 78 beq a01077 newobj instance void [mscorlib]System.Exception::.ctor() throw a01077: ldsfld int16 [rvastatic4]A::a01078 ldc.i4 1 add stsfld int16 [rvastatic4]A::a01078 ldsfld int16 [rvastatic4]A::a01078 ldc.i4 79 beq a01078 newobj instance void [mscorlib]System.Exception::.ctor() throw a01078: ldsfld float32 [rvastatic4]A::a01079 ldc.r4 1 add stsfld float32 [rvastatic4]A::a01079 ldsfld float32 [rvastatic4]A::a01079 ldc.r4 80.0 beq a01079 newobj instance void [mscorlib]System.Exception::.ctor() throw a01079: ldsfld float32 [rvastatic4]A::a01080 ldc.r4 1 add stsfld float32 [rvastatic4]A::a01080 ldsfld float32 [rvastatic4]A::a01080 ldc.r4 81.0 beq a01080 newobj instance void [mscorlib]System.Exception::.ctor() throw a01080: ldsfld float32 [rvastatic4]A::a01081 ldc.r4 1 add stsfld float32 [rvastatic4]A::a01081 ldsfld float32 [rvastatic4]A::a01081 ldc.r4 82.0 beq a01081 newobj instance void [mscorlib]System.Exception::.ctor() throw a01081: ldsfld int32 [rvastatic4]A::a01082 ldc.i4 1 add stsfld int32 [rvastatic4]A::a01082 ldsfld int32 [rvastatic4]A::a01082 ldc.i4 83 beq a01082 newobj instance void [mscorlib]System.Exception::.ctor() throw a01082: ldsfld int8 [rvastatic4]A::a01083 ldc.i4 1 add stsfld int8 [rvastatic4]A::a01083 ldsfld int8 [rvastatic4]A::a01083 ldc.i4 84 beq a01083 newobj instance void [mscorlib]System.Exception::.ctor() throw a01083: ldsfld int64 [rvastatic4]A::a01084 ldc.i8 1 add stsfld int64 [rvastatic4]A::a01084 ldsfld int64 [rvastatic4]A::a01084 ldc.i8 85 beq a01084 newobj instance void [mscorlib]System.Exception::.ctor() throw a01084: ldsfld int64 [rvastatic4]A::a01085 ldc.i8 1 add stsfld int64 [rvastatic4]A::a01085 ldsfld int64 [rvastatic4]A::a01085 ldc.i8 86 beq a01085 newobj instance void [mscorlib]System.Exception::.ctor() throw a01085: ldsfld int32 [rvastatic4]A::a01086 ldc.i4 1 add stsfld int32 [rvastatic4]A::a01086 ldsfld int32 [rvastatic4]A::a01086 ldc.i4 87 beq a01086 newobj instance void [mscorlib]System.Exception::.ctor() throw a01086: ldsfld int32 [rvastatic4]A::a01087 ldc.i4 1 add stsfld int32 [rvastatic4]A::a01087 ldsfld int32 [rvastatic4]A::a01087 ldc.i4 88 beq a01087 newobj instance void [mscorlib]System.Exception::.ctor() throw a01087: ldsfld int8 [rvastatic4]A::a01088 ldc.i4 1 add stsfld int8 [rvastatic4]A::a01088 ldsfld int8 [rvastatic4]A::a01088 ldc.i4 89 beq a01088 newobj instance void [mscorlib]System.Exception::.ctor() throw a01088: ldsfld int64 [rvastatic4]A::a01089 ldc.i8 1 add stsfld int64 [rvastatic4]A::a01089 ldsfld int64 [rvastatic4]A::a01089 ldc.i8 90 beq a01089 newobj instance void [mscorlib]System.Exception::.ctor() throw a01089: ldsfld int8 [rvastatic4]A::a01090 ldc.i4 1 add stsfld int8 [rvastatic4]A::a01090 ldsfld int8 [rvastatic4]A::a01090 ldc.i4 91 beq a01090 newobj instance void [mscorlib]System.Exception::.ctor() throw a01090: ldsfld int16 [rvastatic4]A::a01091 ldc.i4 1 add stsfld int16 [rvastatic4]A::a01091 ldsfld int16 [rvastatic4]A::a01091 ldc.i4 92 beq a01091 newobj instance void [mscorlib]System.Exception::.ctor() throw a01091: ldsfld float32 [rvastatic4]A::a01092 ldc.r4 1 add stsfld float32 [rvastatic4]A::a01092 ldsfld float32 [rvastatic4]A::a01092 ldc.r4 93.0 beq a01092 newobj instance void [mscorlib]System.Exception::.ctor() throw a01092: ldsfld int64 [rvastatic4]A::a01093 ldc.i8 1 add stsfld int64 [rvastatic4]A::a01093 ldsfld int64 [rvastatic4]A::a01093 ldc.i8 94 beq a01093 newobj instance void [mscorlib]System.Exception::.ctor() throw a01093: ldsfld int64 [rvastatic4]A::a01094 ldc.i8 1 add stsfld int64 [rvastatic4]A::a01094 ldsfld int64 [rvastatic4]A::a01094 ldc.i8 95 beq a01094 newobj instance void [mscorlib]System.Exception::.ctor() throw a01094: ldsfld int8 [rvastatic4]A::a01095 ldc.i4 1 add stsfld int8 [rvastatic4]A::a01095 ldsfld int8 [rvastatic4]A::a01095 ldc.i4 96 beq a01095 newobj instance void [mscorlib]System.Exception::.ctor() throw a01095: ldsfld float32 [rvastatic4]A::a01096 ldc.r4 1 add stsfld float32 [rvastatic4]A::a01096 ldsfld float32 [rvastatic4]A::a01096 ldc.r4 97.0 beq a01096 newobj instance void [mscorlib]System.Exception::.ctor() throw a01096: ldsfld int16 [rvastatic4]A::a01097 ldc.i4 1 add stsfld int16 [rvastatic4]A::a01097 ldsfld int16 [rvastatic4]A::a01097 ldc.i4 98 beq a01097 newobj instance void [mscorlib]System.Exception::.ctor() throw a01097: ldsfld float32 [rvastatic4]A::a01098 ldc.r4 1 add stsfld float32 [rvastatic4]A::a01098 ldsfld float32 [rvastatic4]A::a01098 ldc.r4 99.0 beq a01098 newobj instance void [mscorlib]System.Exception::.ctor() throw a01098: ldsfld int32 [rvastatic4]A::a01099 ldc.i4 1 add stsfld int32 [rvastatic4]A::a01099 ldsfld int32 [rvastatic4]A::a01099 ldc.i4 100 beq a01099 newobj instance void [mscorlib]System.Exception::.ctor() throw a01099: ldsfld int64 [rvastatic4]A::a010100 ldc.i8 1 add stsfld int64 [rvastatic4]A::a010100 ldsfld int64 [rvastatic4]A::a010100 ldc.i8 101 beq a010100 newobj instance void [mscorlib]System.Exception::.ctor() throw a010100: ldsfld int32 [rvastatic4]A::a010101 ldc.i4 1 add stsfld int32 [rvastatic4]A::a010101 ldsfld int32 [rvastatic4]A::a010101 ldc.i4 102 beq a010101 newobj instance void [mscorlib]System.Exception::.ctor() throw a010101: ldsfld float32 [rvastatic4]A::a010102 ldc.r4 1 add stsfld float32 [rvastatic4]A::a010102 ldsfld float32 [rvastatic4]A::a010102 ldc.r4 103.0 beq a010102 newobj instance void [mscorlib]System.Exception::.ctor() throw a010102: ldsfld int64 [rvastatic4]A::a010103 ldc.i8 1 add stsfld int64 [rvastatic4]A::a010103 ldsfld int64 [rvastatic4]A::a010103 ldc.i8 104 beq a010103 newobj instance void [mscorlib]System.Exception::.ctor() throw a010103: ldsfld int32 [rvastatic4]A::a010104 ldc.i4 1 add stsfld int32 [rvastatic4]A::a010104 ldsfld int32 [rvastatic4]A::a010104 ldc.i4 105 beq a010104 newobj instance void [mscorlib]System.Exception::.ctor() throw a010104: ldsfld int16 [rvastatic4]A::a010105 ldc.i4 1 add stsfld int16 [rvastatic4]A::a010105 ldsfld int16 [rvastatic4]A::a010105 ldc.i4 106 beq a010105 newobj instance void [mscorlib]System.Exception::.ctor() throw a010105: ldsfld int16 [rvastatic4]A::a010106 ldc.i4 1 add stsfld int16 [rvastatic4]A::a010106 ldsfld int16 [rvastatic4]A::a010106 ldc.i4 107 beq a010106 newobj instance void [mscorlib]System.Exception::.ctor() throw a010106: ldsfld float32 [rvastatic4]A::a010107 ldc.r4 1 add stsfld float32 [rvastatic4]A::a010107 ldsfld float32 [rvastatic4]A::a010107 ldc.r4 108.0 beq a010107 newobj instance void [mscorlib]System.Exception::.ctor() throw a010107: ldsfld int32 [rvastatic4]A::a010108 ldc.i4 1 add stsfld int32 [rvastatic4]A::a010108 ldsfld int32 [rvastatic4]A::a010108 ldc.i4 109 beq a010108 newobj instance void [mscorlib]System.Exception::.ctor() throw a010108: ldsfld int16 [rvastatic4]A::a010109 ldc.i4 1 add stsfld int16 [rvastatic4]A::a010109 ldsfld int16 [rvastatic4]A::a010109 ldc.i4 110 beq a010109 newobj instance void [mscorlib]System.Exception::.ctor() throw a010109: ldsfld int32 [rvastatic4]A::a010110 ldc.i4 1 add stsfld int32 [rvastatic4]A::a010110 ldsfld int32 [rvastatic4]A::a010110 ldc.i4 111 beq a010110 newobj instance void [mscorlib]System.Exception::.ctor() throw a010110: ldsfld int32 [rvastatic4]A::a010111 ldc.i4 1 add stsfld int32 [rvastatic4]A::a010111 ldsfld int32 [rvastatic4]A::a010111 ldc.i4 112 beq a010111 newobj instance void [mscorlib]System.Exception::.ctor() throw a010111: ldsfld int32 [rvastatic4]A::a010112 ldc.i4 1 add stsfld int32 [rvastatic4]A::a010112 ldsfld int32 [rvastatic4]A::a010112 ldc.i4 113 beq a010112 newobj instance void [mscorlib]System.Exception::.ctor() throw a010112: ldsfld int64 [rvastatic4]A::a010113 ldc.i8 1 add stsfld int64 [rvastatic4]A::a010113 ldsfld int64 [rvastatic4]A::a010113 ldc.i8 114 beq a010113 newobj instance void [mscorlib]System.Exception::.ctor() throw a010113: ldsfld int64 [rvastatic4]A::a010114 ldc.i8 1 add stsfld int64 [rvastatic4]A::a010114 ldsfld int64 [rvastatic4]A::a010114 ldc.i8 115 beq a010114 newobj instance void [mscorlib]System.Exception::.ctor() throw a010114: ldsfld int16 [rvastatic4]A::a010115 ldc.i4 1 add stsfld int16 [rvastatic4]A::a010115 ldsfld int16 [rvastatic4]A::a010115 ldc.i4 116 beq a010115 newobj instance void [mscorlib]System.Exception::.ctor() throw a010115: ldsfld int64 [rvastatic4]A::a010116 ldc.i8 1 add stsfld int64 [rvastatic4]A::a010116 ldsfld int64 [rvastatic4]A::a010116 ldc.i8 117 beq a010116 newobj instance void [mscorlib]System.Exception::.ctor() throw a010116: ldsfld int64 [rvastatic4]A::a010117 ldc.i8 1 add stsfld int64 [rvastatic4]A::a010117 ldsfld int64 [rvastatic4]A::a010117 ldc.i8 118 beq a010117 newobj instance void [mscorlib]System.Exception::.ctor() throw a010117: ldsfld int32 [rvastatic4]A::a010118 ldc.i4 1 add stsfld int32 [rvastatic4]A::a010118 ldsfld int32 [rvastatic4]A::a010118 ldc.i4 119 beq a010118 newobj instance void [mscorlib]System.Exception::.ctor() throw a010118: ldsfld int64 [rvastatic4]A::a010119 ldc.i8 1 add stsfld int64 [rvastatic4]A::a010119 ldsfld int64 [rvastatic4]A::a010119 ldc.i8 120 beq a010119 newobj instance void [mscorlib]System.Exception::.ctor() throw a010119: ldsfld int64 [rvastatic4]A::a010120 ldc.i8 1 add stsfld int64 [rvastatic4]A::a010120 ldsfld int64 [rvastatic4]A::a010120 ldc.i8 121 beq a010120 newobj instance void [mscorlib]System.Exception::.ctor() throw a010120: ldsfld int64 [rvastatic4]A::a010121 ldc.i8 1 add stsfld int64 [rvastatic4]A::a010121 ldsfld int64 [rvastatic4]A::a010121 ldc.i8 122 beq a010121 newobj instance void [mscorlib]System.Exception::.ctor() throw a010121: ldsfld int16 [rvastatic4]A::a010122 ldc.i4 1 add stsfld int16 [rvastatic4]A::a010122 ldsfld int16 [rvastatic4]A::a010122 ldc.i4 123 beq a010122 newobj instance void [mscorlib]System.Exception::.ctor() throw a010122: ldsfld int64 [rvastatic4]A::a010123 ldc.i8 1 add stsfld int64 [rvastatic4]A::a010123 ldsfld int64 [rvastatic4]A::a010123 ldc.i8 124 beq a010123 newobj instance void [mscorlib]System.Exception::.ctor() throw a010123: ldsfld int64 [rvastatic4]A::a010124 ldc.i8 1 add stsfld int64 [rvastatic4]A::a010124 ldsfld int64 [rvastatic4]A::a010124 ldc.i8 125 beq a010124 newobj instance void [mscorlib]System.Exception::.ctor() throw a010124: ldsfld int32 [rvastatic4]A::a010125 ldc.i4 1 add stsfld int32 [rvastatic4]A::a010125 ldsfld int32 [rvastatic4]A::a010125 ldc.i4 126 beq a010125 newobj instance void [mscorlib]System.Exception::.ctor() throw a010125: ldsfld int16 [rvastatic4]A::a010126 ldc.i4 1 add stsfld int16 [rvastatic4]A::a010126 ldsfld int16 [rvastatic4]A::a010126 ldc.i4 127 beq a010126 newobj instance void [mscorlib]System.Exception::.ctor() throw a010126: ldsfld int16 [rvastatic4]A::a010127 ldc.i4 1 add stsfld int16 [rvastatic4]A::a010127 ldsfld int16 [rvastatic4]A::a010127 ldc.i4 128 beq a010127 newobj instance void [mscorlib]System.Exception::.ctor() throw a010127: ret} .method static int32 Main(string[] args){.entrypoint .maxstack 5 .custom instance void [xunit.core]Xunit.FactAttribute::.ctor() = ( 01 00 00 00 ) call void [rvastatic4]A::V1() call void [rvastatic4]A::V2() call void [rvastatic4]A::V3() call void [rvastatic4]A::V4() call void [rvastatic4]A::V5() call void [rvastatic4]A::V6() ldc.i4 100 ret} .field public static int32 a0100 at b0100 .field private static int32 aALIGN10100 at bALIGN10100 .field public static int64 a0101 at b0101 .field public static float32 a0102 at b0102 .field private static int32 aALIGN10102 at bALIGN10102 .field public static int16 a0103 at b0103 .field private static int16 aALIGN10103 at bALIGN10103 .field private static int32 aALIGN20103 at bALIGN20103 .field public static int16 a0104 at b0104 .field private static int16 aALIGN10104 at bALIGN10104 .field private static int32 aALIGN20104 at bALIGN20104 .field public static int64 a0105 at b0105 .field public static int16 a0106 at b0106 .field private static int16 aALIGN10106 at bALIGN10106 .field private static int32 aALIGN20106 at bALIGN20106 .field public static int8 a0107 at b0107 .field private static int32 aALIGN10107 at bALIGN10107 .field private static int16 aALIGN20107 at bALIGN20107 .field private static int8 aALIGN20107 at bALIGN30107 .field public static int64 a0108 at b0108 .field public static int32 a0109 at b0109 .field private static int32 aALIGN10109 at bALIGN10109 .field public static int16 a01010 at b01010 .field private static int16 aALIGN101010 at bALIGN101010 .field private static int32 aALIGN201010 at bALIGN201010 .field public static float32 a01011 at b01011 .field private static int32 aALIGN101011 at bALIGN101011 .field public static int16 a01012 at b01012 .field private static int16 aALIGN101012 at bALIGN101012 .field private static int32 aALIGN201012 at bALIGN201012 .field public static float32 a01013 at b01013 .field private static int32 aALIGN101013 at bALIGN101013 .field public static float32 a01014 at b01014 .field private static int32 aALIGN101014 at bALIGN101014 .field public static int8 a01015 at b01015 .field private static int32 aALIGN101015 at bALIGN101015 .field private static int16 aALIGN201015 at bALIGN201015 .field private static int8 aALIGN201015 at bALIGN301015 .field public static float32 a01016 at b01016 .field private static int32 aALIGN101016 at bALIGN101016 .field public static int8 a01017 at b01017 .field private static int32 aALIGN101017 at bALIGN101017 .field private static int16 aALIGN201017 at bALIGN201017 .field private static int8 aALIGN201017 at bALIGN301017 .field public static float32 a01018 at b01018 .field private static int32 aALIGN101018 at bALIGN101018 .field public static float32 a01019 at b01019 .field private static int32 aALIGN101019 at bALIGN101019 .field public static int8 a01020 at b01020 .field private static int32 aALIGN101020 at bALIGN101020 .field private static int16 aALIGN201020 at bALIGN201020 .field private static int8 aALIGN201020 at bALIGN301020 .field public static float32 a01021 at b01021 .field private static int32 aALIGN101021 at bALIGN101021 .field public static int64 a01022 at b01022 .field public static int8 a01023 at b01023 .field private static int32 aALIGN101023 at bALIGN101023 .field private static int16 aALIGN201023 at bALIGN201023 .field private static int8 aALIGN201023 at bALIGN301023 .field public static int32 a01024 at b01024 .field private static int32 aALIGN101024 at bALIGN101024 .field public static int64 a01025 at b01025 .field public static int16 a01026 at b01026 .field private static int16 aALIGN101026 at bALIGN101026 .field private static int32 aALIGN201026 at bALIGN201026 .field public static int8 a01027 at b01027 .field private static int32 aALIGN101027 at bALIGN101027 .field private static int16 aALIGN201027 at bALIGN201027 .field private static int8 aALIGN201027 at bALIGN301027 .field public static int16 a01028 at b01028 .field private static int16 aALIGN101028 at bALIGN101028 .field private static int32 aALIGN201028 at bALIGN201028 .field public static int16 a01029 at b01029 .field private static int16 aALIGN101029 at bALIGN101029 .field private static int32 aALIGN201029 at bALIGN201029 .field public static int8 a01030 at b01030 .field private static int32 aALIGN101030 at bALIGN101030 .field private static int16 aALIGN201030 at bALIGN201030 .field private static int8 aALIGN201030 at bALIGN301030 .field public static int8 a01031 at b01031 .field private static int32 aALIGN101031 at bALIGN101031 .field private static int16 aALIGN201031 at bALIGN201031 .field private static int8 aALIGN201031 at bALIGN301031 .field public static int64 a01032 at b01032 .field public static float32 a01033 at b01033 .field private static int32 aALIGN101033 at bALIGN101033 .field public static int16 a01034 at b01034 .field private static int16 aALIGN101034 at bALIGN101034 .field private static int32 aALIGN201034 at bALIGN201034 .field public static int8 a01035 at b01035 .field private static int32 aALIGN101035 at bALIGN101035 .field private static int16 aALIGN201035 at bALIGN201035 .field private static int8 aALIGN201035 at bALIGN301035 .field public static int8 a01036 at b01036 .field private static int32 aALIGN101036 at bALIGN101036 .field private static int16 aALIGN201036 at bALIGN201036 .field private static int8 aALIGN201036 at bALIGN301036 .field public static int32 a01037 at b01037 .field private static int32 aALIGN101037 at bALIGN101037 .field public static int16 a01038 at b01038 .field private static int16 aALIGN101038 at bALIGN101038 .field private static int32 aALIGN201038 at bALIGN201038 .field public static int8 a01039 at b01039 .field private static int32 aALIGN101039 at bALIGN101039 .field private static int16 aALIGN201039 at bALIGN201039 .field private static int8 aALIGN201039 at bALIGN301039 .field public static int8 a01040 at b01040 .field private static int32 aALIGN101040 at bALIGN101040 .field private static int16 aALIGN201040 at bALIGN201040 .field private static int8 aALIGN201040 at bALIGN301040 .field public static int32 a01041 at b01041 .field private static int32 aALIGN101041 at bALIGN101041 .field public static int64 a01042 at b01042 .field public static int16 a01043 at b01043 .field private static int16 aALIGN101043 at bALIGN101043 .field private static int32 aALIGN201043 at bALIGN201043 .field public static int64 a01044 at b01044 .field public static int64 a01045 at b01045 .field public static float32 a01046 at b01046 .field private static int32 aALIGN101046 at bALIGN101046 .field public static int16 a01047 at b01047 .field private static int16 aALIGN101047 at bALIGN101047 .field private static int32 aALIGN201047 at bALIGN201047 .field public static int64 a01048 at b01048 .field public static int16 a01049 at b01049 .field private static int16 aALIGN101049 at bALIGN101049 .field private static int32 aALIGN201049 at bALIGN201049 .field public static int32 a01050 at b01050 .field private static int32 aALIGN101050 at bALIGN101050 .field public static int16 a01051 at b01051 .field private static int16 aALIGN101051 at bALIGN101051 .field private static int32 aALIGN201051 at bALIGN201051 .field public static int32 a01052 at b01052 .field private static int32 aALIGN101052 at bALIGN101052 .field public static int16 a01053 at b01053 .field private static int16 aALIGN101053 at bALIGN101053 .field private static int32 aALIGN201053 at bALIGN201053 .field public static float32 a01054 at b01054 .field private static int32 aALIGN101054 at bALIGN101054 .field public static int64 a01055 at b01055 .field public static float32 a01056 at b01056 .field private static int32 aALIGN101056 at bALIGN101056 .field public static int64 a01057 at b01057 .field public static int64 a01058 at b01058 .field public static int64 a01059 at b01059 .field public static int16 a01060 at b01060 .field private static int16 aALIGN101060 at bALIGN101060 .field private static int32 aALIGN201060 at bALIGN201060 .field public static int8 a01061 at b01061 .field private static int32 aALIGN101061 at bALIGN101061 .field private static int16 aALIGN201061 at bALIGN201061 .field private static int8 aALIGN201061 at bALIGN301061 .field public static int64 a01062 at b01062 .field public static int16 a01063 at b01063 .field private static int16 aALIGN101063 at bALIGN101063 .field private static int32 aALIGN201063 at bALIGN201063 .field public static int32 a01064 at b01064 .field private static int32 aALIGN101064 at bALIGN101064 .field public static int16 a01065 at b01065 .field private static int16 aALIGN101065 at bALIGN101065 .field private static int32 aALIGN201065 at bALIGN201065 .field public static int8 a01066 at b01066 .field private static int32 aALIGN101066 at bALIGN101066 .field private static int16 aALIGN201066 at bALIGN201066 .field private static int8 aALIGN201066 at bALIGN301066 .field public static int16 a01067 at b01067 .field private static int16 aALIGN101067 at bALIGN101067 .field private static int32 aALIGN201067 at bALIGN201067 .field public static int32 a01068 at b01068 .field private static int32 aALIGN101068 at bALIGN101068 .field public static float32 a01069 at b01069 .field private static int32 aALIGN101069 at bALIGN101069 .field public static float32 a01070 at b01070 .field private static int32 aALIGN101070 at bALIGN101070 .field public static int16 a01071 at b01071 .field private static int16 aALIGN101071 at bALIGN101071 .field private static int32 aALIGN201071 at bALIGN201071 .field public static float32 a01072 at b01072 .field private static int32 aALIGN101072 at bALIGN101072 .field public static int64 a01073 at b01073 .field public static int64 a01074 at b01074 .field public static int32 a01075 at b01075 .field private static int32 aALIGN101075 at bALIGN101075 .field public static int8 a01076 at b01076 .field private static int32 aALIGN101076 at bALIGN101076 .field private static int16 aALIGN201076 at bALIGN201076 .field private static int8 aALIGN201076 at bALIGN301076 .field public static int32 a01077 at b01077 .field private static int32 aALIGN101077 at bALIGN101077 .field public static int16 a01078 at b01078 .field private static int16 aALIGN101078 at bALIGN101078 .field private static int32 aALIGN201078 at bALIGN201078 .field public static float32 a01079 at b01079 .field private static int32 aALIGN101079 at bALIGN101079 .field public static float32 a01080 at b01080 .field private static int32 aALIGN101080 at bALIGN101080 .field public static float32 a01081 at b01081 .field private static int32 aALIGN101081 at bALIGN101081 .field public static int32 a01082 at b01082 .field private static int32 aALIGN101082 at bALIGN101082 .field public static int8 a01083 at b01083 .field private static int32 aALIGN101083 at bALIGN101083 .field private static int16 aALIGN201083 at bALIGN201083 .field private static int8 aALIGN201083 at bALIGN301083 .field public static int64 a01084 at b01084 .field public static int64 a01085 at b01085 .field public static int32 a01086 at b01086 .field private static int32 aALIGN101086 at bALIGN101086 .field public static int32 a01087 at b01087 .field private static int32 aALIGN101087 at bALIGN101087 .field public static int8 a01088 at b01088 .field private static int32 aALIGN101088 at bALIGN101088 .field private static int16 aALIGN201088 at bALIGN201088 .field private static int8 aALIGN201088 at bALIGN301088 .field public static int64 a01089 at b01089 .field public static int8 a01090 at b01090 .field private static int32 aALIGN101090 at bALIGN101090 .field private static int16 aALIGN201090 at bALIGN201090 .field private static int8 aALIGN201090 at bALIGN301090 .field public static int16 a01091 at b01091 .field private static int16 aALIGN101091 at bALIGN101091 .field private static int32 aALIGN201091 at bALIGN201091 .field public static float32 a01092 at b01092 .field private static int32 aALIGN101092 at bALIGN101092 .field public static int64 a01093 at b01093 .field public static int64 a01094 at b01094 .field public static int8 a01095 at b01095 .field private static int32 aALIGN101095 at bALIGN101095 .field private static int16 aALIGN201095 at bALIGN201095 .field private static int8 aALIGN201095 at bALIGN301095 .field public static float32 a01096 at b01096 .field private static int32 aALIGN101096 at bALIGN101096 .field public static int16 a01097 at b01097 .field private static int16 aALIGN101097 at bALIGN101097 .field private static int32 aALIGN201097 at bALIGN201097 .field public static float32 a01098 at b01098 .field private static int32 aALIGN101098 at bALIGN101098 .field public static int32 a01099 at b01099 .field private static int32 aALIGN101099 at bALIGN101099 .field public static int64 a010100 at b010100 .field public static int32 a010101 at b010101 .field private static int32 aALIGN1010101 at bALIGN1010101 .field public static float32 a010102 at b010102 .field private static int32 aALIGN1010102 at bALIGN1010102 .field public static int64 a010103 at b010103 .field public static int32 a010104 at b010104 .field private static int32 aALIGN1010104 at bALIGN1010104 .field public static int16 a010105 at b010105 .field private static int16 aALIGN1010105 at bALIGN1010105 .field private static int32 aALIGN2010105 at bALIGN2010105 .field public static int16 a010106 at b010106 .field private static int16 aALIGN1010106 at bALIGN1010106 .field private static int32 aALIGN2010106 at bALIGN2010106 .field public static float32 a010107 at b010107 .field private static int32 aALIGN1010107 at bALIGN1010107 .field public static int32 a010108 at b010108 .field private static int32 aALIGN1010108 at bALIGN1010108 .field public static int16 a010109 at b010109 .field private static int16 aALIGN1010109 at bALIGN1010109 .field private static int32 aALIGN2010109 at bALIGN2010109 .field public static int32 a010110 at b010110 .field private static int32 aALIGN1010110 at bALIGN1010110 .field public static int32 a010111 at b010111 .field private static int32 aALIGN1010111 at bALIGN1010111 .field public static int32 a010112 at b010112 .field private static int32 aALIGN1010112 at bALIGN1010112 .field public static int64 a010113 at b010113 .field public static int64 a010114 at b010114 .field public static int16 a010115 at b010115 .field private static int16 aALIGN1010115 at bALIGN1010115 .field private static int32 aALIGN2010115 at bALIGN2010115 .field public static int64 a010116 at b010116 .field public static int64 a010117 at b010117 .field public static int32 a010118 at b010118 .field private static int32 aALIGN1010118 at bALIGN1010118 .field public static int64 a010119 at b010119 .field public static int64 a010120 at b010120 .field public static int64 a010121 at b010121 .field public static int16 a010122 at b010122 .field private static int16 aALIGN1010122 at bALIGN1010122 .field private static int32 aALIGN2010122 at bALIGN2010122 .field public static int64 a010123 at b010123 .field public static int64 a010124 at b010124 .field public static int32 a010125 at b010125 .field private static int32 aALIGN1010125 at bALIGN1010125 .field public static int16 a010126 at b010126 .field private static int16 aALIGN1010126 at bALIGN1010126 .field private static int32 aALIGN2010126 at bALIGN2010126 .field public static int16 a010127 at b010127 .field private static int16 aALIGN1010127 at bALIGN1010127 .field private static int32 aALIGN2010127 at bALIGN2010127 } .data b0100 = int32(0) .data bALIGN10100 = int32(0) .data b0101 = int64(1) .data b0102 = float32(2.0) .data bALIGN10102 = int32(0) .data b0103 = int16(3) .data bALIGN10103 = int16(0) .data bALIGN20103 = int32(0) .data b0104 = int16(4) .data bALIGN10104 = int16(0) .data bALIGN20104 = int32(0) .data b0105 = int64(5) .data b0106 = int16(6) .data bALIGN10106 = int16(0) .data bALIGN20106 = int32(0) .data b0107 = int8(7) .data bALIGN10107 = int32(0) .data bALIGN20107 = int16(0) .data bALIGN30107 = int8(0) .data b0108 = int64(8) .data b0109 = int32(9) .data bALIGN10109 = int32(0) .data b01010 = int16(10) .data bALIGN101010 = int16(0) .data bALIGN201010 = int32(0) .data b01011 = float32(11.0) .data bALIGN101011 = int32(0) .data b01012 = int16(12) .data bALIGN101012 = int16(0) .data bALIGN201012 = int32(0) .data b01013 = float32(13.0) .data bALIGN101013 = int32(0) .data b01014 = float32(14.0) .data bALIGN101014 = int32(0) .data b01015 = int8(15) .data bALIGN101015 = int32(0) .data bALIGN201015 = int16(0) .data bALIGN301015 = int8(0) .data b01016 = float32(16.0) .data bALIGN101016 = int32(0) .data b01017 = int8(17) .data bALIGN101017 = int32(0) .data bALIGN201017 = int16(0) .data bALIGN301017 = int8(0) .data b01018 = float32(18.0) .data bALIGN101018 = int32(0) .data b01019 = float32(19.0) .data bALIGN101019 = int32(0) .data b01020 = int8(20) .data bALIGN101020 = int32(0) .data bALIGN201020 = int16(0) .data bALIGN301020 = int8(0) .data b01021 = float32(21.0) .data bALIGN101021 = int32(0) .data b01022 = int64(22) .data b01023 = int8(23) .data bALIGN101023 = int32(0) .data bALIGN201023 = int16(0) .data bALIGN301023 = int8(0) .data b01024 = int32(24) .data bALIGN101024 = int32(0) .data b01025 = int64(25) .data b01026 = int16(26) .data bALIGN101026 = int16(0) .data bALIGN201026 = int32(0) .data b01027 = int8(27) .data bALIGN101027 = int32(0) .data bALIGN201027 = int16(0) .data bALIGN301027 = int8(0) .data b01028 = int16(28) .data bALIGN101028 = int16(0) .data bALIGN201028 = int32(0) .data b01029 = int16(29) .data bALIGN101029 = int16(0) .data bALIGN201029 = int32(0) .data b01030 = int8(30) .data bALIGN101030 = int32(0) .data bALIGN201030 = int16(0) .data bALIGN301030 = int8(0) .data b01031 = int8(31) .data bALIGN101031 = int32(0) .data bALIGN201031 = int16(0) .data bALIGN301031 = int8(0) .data b01032 = int64(32) .data b01033 = float32(33.0) .data bALIGN101033 = int32(0) .data b01034 = int16(34) .data bALIGN101034 = int16(0) .data bALIGN201034 = int32(0) .data b01035 = int8(35) .data bALIGN101035 = int32(0) .data bALIGN201035 = int16(0) .data bALIGN301035 = int8(0) .data b01036 = int8(36) .data bALIGN101036 = int32(0) .data bALIGN201036 = int16(0) .data bALIGN301036 = int8(0) .data b01037 = int32(37) .data bALIGN101037 = int32(0) .data b01038 = int16(38) .data bALIGN101038 = int16(0) .data bALIGN201038 = int32(0) .data b01039 = int8(39) .data bALIGN101039 = int32(0) .data bALIGN201039 = int16(0) .data bALIGN301039 = int8(0) .data b01040 = int8(40) .data bALIGN101040 = int32(0) .data bALIGN201040 = int16(0) .data bALIGN301040 = int8(0) .data b01041 = int32(41) .data bALIGN101041 = int32(0) .data b01042 = int64(42) .data b01043 = int16(43) .data bALIGN101043 = int16(0) .data bALIGN201043 = int32(0) .data b01044 = int64(44) .data b01045 = int64(45) .data b01046 = float32(46.0) .data bALIGN101046 = int32(0) .data b01047 = int16(47) .data bALIGN101047 = int16(0) .data bALIGN201047 = int32(0) .data b01048 = int64(48) .data b01049 = int16(49) .data bALIGN101049 = int16(0) .data bALIGN201049 = int32(0) .data b01050 = int32(50) .data bALIGN101050 = int32(0) .data b01051 = int16(51) .data bALIGN101051 = int16(0) .data bALIGN201051 = int32(0) .data b01052 = int32(52) .data bALIGN101052 = int32(0) .data b01053 = int16(53) .data bALIGN101053 = int16(0) .data bALIGN201053 = int32(0) .data b01054 = float32(54.0) .data bALIGN101054 = int32(0) .data b01055 = int64(55) .data b01056 = float32(56.0) .data bALIGN101056 = int32(0) .data b01057 = int64(57) .data b01058 = int64(58) .data b01059 = int64(59) .data b01060 = int16(60) .data bALIGN101060 = int16(0) .data bALIGN201060 = int32(0) .data b01061 = int8(61) .data bALIGN101061 = int32(0) .data bALIGN201061 = int16(0) .data bALIGN301061 = int8(0) .data b01062 = int64(62) .data b01063 = int16(63) .data bALIGN101063 = int16(0) .data bALIGN201063 = int32(0) .data b01064 = int32(64) .data bALIGN101064 = int32(0) .data b01065 = int16(65) .data bALIGN101065 = int16(0) .data bALIGN201065 = int32(0) .data b01066 = int8(66) .data bALIGN101066 = int32(0) .data bALIGN201066 = int16(0) .data bALIGN301066 = int8(0) .data b01067 = int16(67) .data bALIGN101067 = int16(0) .data bALIGN201067 = int32(0) .data b01068 = int32(68) .data bALIGN101068 = int32(0) .data b01069 = float32(69.0) .data bALIGN101069 = int32(0) .data b01070 = float32(70.0) .data bALIGN101070 = int32(0) .data b01071 = int16(71) .data bALIGN101071 = int16(0) .data bALIGN201071 = int32(0) .data b01072 = float32(72.0) .data bALIGN101072 = int32(0) .data b01073 = int64(73) .data b01074 = int64(74) .data b01075 = int32(75) .data bALIGN101075 = int32(0) .data b01076 = int8(76) .data bALIGN101076 = int32(0) .data bALIGN201076 = int16(0) .data bALIGN301076 = int8(0) .data b01077 = int32(77) .data bALIGN101077 = int32(0) .data b01078 = int16(78) .data bALIGN101078 = int16(0) .data bALIGN201078 = int32(0) .data b01079 = float32(79.0) .data bALIGN101079 = int32(0) .data b01080 = float32(80.0) .data bALIGN101080 = int32(0) .data b01081 = float32(81.0) .data bALIGN101081 = int32(0) .data b01082 = int32(82) .data bALIGN101082 = int32(0) .data b01083 = int8(83) .data bALIGN101083 = int32(0) .data bALIGN201083 = int16(0) .data bALIGN301083 = int8(0) .data b01084 = int64(84) .data b01085 = int64(85) .data b01086 = int32(86) .data bALIGN101086 = int32(0) .data b01087 = int32(87) .data bALIGN101087 = int32(0) .data b01088 = int8(88) .data bALIGN101088 = int32(0) .data bALIGN201088 = int16(0) .data bALIGN301088 = int8(0) .data b01089 = int64(89) .data b01090 = int8(90) .data bALIGN101090 = int32(0) .data bALIGN201090 = int16(0) .data bALIGN301090 = int8(0) .data b01091 = int16(91) .data bALIGN101091 = int16(0) .data bALIGN201091 = int32(0) .data b01092 = float32(92.0) .data bALIGN101092 = int32(0) .data b01093 = int64(93) .data b01094 = int64(94) .data b01095 = int8(95) .data bALIGN101095 = int32(0) .data bALIGN201095 = int16(0) .data bALIGN301095 = int8(0) .data b01096 = float32(96.0) .data bALIGN101096 = int32(0) .data b01097 = int16(97) .data bALIGN101097 = int16(0) .data bALIGN201097 = int32(0) .data b01098 = float32(98.0) .data bALIGN101098 = int32(0) .data b01099 = int32(99) .data bALIGN101099 = int32(0) .data b010100 = int64(100) .data b010101 = int32(101) .data bALIGN1010101 = int32(0) .data b010102 = float32(102.0) .data bALIGN1010102 = int32(0) .data b010103 = int64(103) .data b010104 = int32(104) .data bALIGN1010104 = int32(0) .data b010105 = int16(105) .data bALIGN1010105 = int16(0) .data bALIGN2010105 = int32(0) .data b010106 = int16(106) .data bALIGN1010106 = int16(0) .data bALIGN2010106 = int32(0) .data b010107 = float32(107.0) .data bALIGN1010107 = int32(0) .data b010108 = int32(108) .data bALIGN1010108 = int32(0) .data b010109 = int16(109) .data bALIGN1010109 = int16(0) .data bALIGN2010109 = int32(0) .data b010110 = int32(110) .data bALIGN1010110 = int32(0) .data b010111 = int32(111) .data bALIGN1010111 = int32(0) .data b010112 = int32(112) .data bALIGN1010112 = int32(0) .data b010113 = int64(113) .data b010114 = int64(114) .data b010115 = int16(115) .data bALIGN1010115 = int16(0) .data bALIGN2010115 = int32(0) .data b010116 = int64(116) .data b010117 = int64(117) .data b010118 = int32(118) .data bALIGN1010118 = int32(0) .data b010119 = int64(119) .data b010120 = int64(120) .data b010121 = int64(121) .data b010122 = int16(122) .data bALIGN1010122 = int16(0) .data bALIGN2010122 = int32(0) .data b010123 = int64(123) .data b010124 = int64(124) .data b010125 = int32(125) .data bALIGN1010125 = int32(0) .data b010126 = int16(126) .data bALIGN1010126 = int16(0) .data bALIGN2010126 = int32(0) .data b010127 = int16(127) .data bALIGN1010127 = int16(0) .data bALIGN2010127 = int32(0)
.assembly extern mscorlib{} .assembly extern xunit.core {} .assembly rvastatic4{} .class public A{ .method static native int Call1(int64) {.maxstack 50 ldarg.0 conv.i8 dup dup xor xor conv.i conv.i ret } .method static native int Call2(float64) {.maxstack 50 ldarg.0 conv.i8 dup ldc.i8 0xffffffff00000000 and ldc.i4 32 shr.un conv.i8 dup ldc.i8 0x0000000000ffffff and ldc.i4 32 shl conv.i8 ldc.i4 32 shr.un or conv.i conv.i8 ldc.i4 32 shl or conv.i conv.i ret } .method static void V1() {.maxstack 50 ldsfld int32 [rvastatic4]A::a0100 ldc.i4 0 beq a0101 newobj instance void [mscorlib]System.Exception::.ctor() throw a0101: ldsfld int64 [rvastatic4]A::a0101 ldc.i8 1 beq a0102 newobj instance void [mscorlib]System.Exception::.ctor() throw a0102: ldsfld float32 [rvastatic4]A::a0102 ldc.r4 2.0 beq a0103 newobj instance void [mscorlib]System.Exception::.ctor() throw a0103: ldsfld int16 [rvastatic4]A::a0103 ldc.i4 3 beq a0104 newobj instance void [mscorlib]System.Exception::.ctor() throw a0104: ldsfld int16 [rvastatic4]A::a0104 ldc.i4 4 beq a0105 newobj instance void [mscorlib]System.Exception::.ctor() throw a0105: ldsfld int64 [rvastatic4]A::a0105 ldc.i8 5 beq a0106 newobj instance void [mscorlib]System.Exception::.ctor() throw a0106: ldsfld int16 [rvastatic4]A::a0106 ldc.i4 6 beq a0107 newobj instance void [mscorlib]System.Exception::.ctor() throw a0107: ldsfld int8 [rvastatic4]A::a0107 ldc.i4 7 beq a0108 newobj instance void [mscorlib]System.Exception::.ctor() throw a0108: ldsfld int64 [rvastatic4]A::a0108 ldc.i8 8 beq a0109 newobj instance void [mscorlib]System.Exception::.ctor() throw a0109: ldsfld int32 [rvastatic4]A::a0109 ldc.i4 9 beq a01010 newobj instance void [mscorlib]System.Exception::.ctor() throw a01010: ldsfld int16 [rvastatic4]A::a01010 ldc.i4 10 beq a01011 newobj instance void [mscorlib]System.Exception::.ctor() throw a01011: ldsfld float32 [rvastatic4]A::a01011 ldc.r4 11.0 beq a01012 newobj instance void [mscorlib]System.Exception::.ctor() throw a01012: ldsfld int16 [rvastatic4]A::a01012 ldc.i4 12 beq a01013 newobj instance void [mscorlib]System.Exception::.ctor() throw a01013: ldsfld float32 [rvastatic4]A::a01013 ldc.r4 13.0 beq a01014 newobj instance void [mscorlib]System.Exception::.ctor() throw a01014: ldsfld float32 [rvastatic4]A::a01014 ldc.r4 14.0 beq a01015 newobj instance void [mscorlib]System.Exception::.ctor() throw a01015: ldsfld int8 [rvastatic4]A::a01015 ldc.i4 15 beq a01016 newobj instance void [mscorlib]System.Exception::.ctor() throw a01016: ldsfld float32 [rvastatic4]A::a01016 ldc.r4 16.0 beq a01017 newobj instance void [mscorlib]System.Exception::.ctor() throw a01017: ldsfld int8 [rvastatic4]A::a01017 ldc.i4 17 beq a01018 newobj instance void [mscorlib]System.Exception::.ctor() throw a01018: ldsfld float32 [rvastatic4]A::a01018 ldc.r4 18.0 beq a01019 newobj instance void [mscorlib]System.Exception::.ctor() throw a01019: ldsfld float32 [rvastatic4]A::a01019 ldc.r4 19.0 beq a01020 newobj instance void [mscorlib]System.Exception::.ctor() throw a01020: ldsfld int8 [rvastatic4]A::a01020 ldc.i4 20 beq a01021 newobj instance void [mscorlib]System.Exception::.ctor() throw a01021: ldsfld float32 [rvastatic4]A::a01021 ldc.r4 21.0 beq a01022 newobj instance void [mscorlib]System.Exception::.ctor() throw a01022: ldsfld int64 [rvastatic4]A::a01022 ldc.i8 22 beq a01023 newobj instance void [mscorlib]System.Exception::.ctor() throw a01023: ldsfld int8 [rvastatic4]A::a01023 ldc.i4 23 beq a01024 newobj instance void [mscorlib]System.Exception::.ctor() throw a01024: ldsfld int32 [rvastatic4]A::a01024 ldc.i4 24 beq a01025 newobj instance void [mscorlib]System.Exception::.ctor() throw a01025: ldsfld int64 [rvastatic4]A::a01025 ldc.i8 25 beq a01026 newobj instance void [mscorlib]System.Exception::.ctor() throw a01026: ldsfld int16 [rvastatic4]A::a01026 ldc.i4 26 beq a01027 newobj instance void [mscorlib]System.Exception::.ctor() throw a01027: ldsfld int8 [rvastatic4]A::a01027 ldc.i4 27 beq a01028 newobj instance void [mscorlib]System.Exception::.ctor() throw a01028: ldsfld int16 [rvastatic4]A::a01028 ldc.i4 28 beq a01029 newobj instance void [mscorlib]System.Exception::.ctor() throw a01029: ldsfld int16 [rvastatic4]A::a01029 ldc.i4 29 beq a01030 newobj instance void [mscorlib]System.Exception::.ctor() throw a01030: ldsfld int8 [rvastatic4]A::a01030 ldc.i4 30 beq a01031 newobj instance void [mscorlib]System.Exception::.ctor() throw a01031: ldsfld int8 [rvastatic4]A::a01031 ldc.i4 31 beq a01032 newobj instance void [mscorlib]System.Exception::.ctor() throw a01032: ldsfld int64 [rvastatic4]A::a01032 ldc.i8 32 beq a01033 newobj instance void [mscorlib]System.Exception::.ctor() throw a01033: ldsfld float32 [rvastatic4]A::a01033 ldc.r4 33.0 beq a01034 newobj instance void [mscorlib]System.Exception::.ctor() throw a01034: ldsfld int16 [rvastatic4]A::a01034 ldc.i4 34 beq a01035 newobj instance void [mscorlib]System.Exception::.ctor() throw a01035: ldsfld int8 [rvastatic4]A::a01035 ldc.i4 35 beq a01036 newobj instance void [mscorlib]System.Exception::.ctor() throw a01036: ldsfld int8 [rvastatic4]A::a01036 ldc.i4 36 beq a01037 newobj instance void [mscorlib]System.Exception::.ctor() throw a01037: ldsfld int32 [rvastatic4]A::a01037 ldc.i4 37 beq a01038 newobj instance void [mscorlib]System.Exception::.ctor() throw a01038: ldsfld int16 [rvastatic4]A::a01038 ldc.i4 38 beq a01039 newobj instance void [mscorlib]System.Exception::.ctor() throw a01039: ldsfld int8 [rvastatic4]A::a01039 ldc.i4 39 beq a01040 newobj instance void [mscorlib]System.Exception::.ctor() throw a01040: ldsfld int8 [rvastatic4]A::a01040 ldc.i4 40 beq a01041 newobj instance void [mscorlib]System.Exception::.ctor() throw a01041: ldsfld int32 [rvastatic4]A::a01041 ldc.i4 41 beq a01042 newobj instance void [mscorlib]System.Exception::.ctor() throw a01042: ldsfld int64 [rvastatic4]A::a01042 ldc.i8 42 beq a01043 newobj instance void [mscorlib]System.Exception::.ctor() throw a01043: ldsfld int16 [rvastatic4]A::a01043 ldc.i4 43 beq a01044 newobj instance void [mscorlib]System.Exception::.ctor() throw a01044: ldsfld int64 [rvastatic4]A::a01044 ldc.i8 44 beq a01045 newobj instance void [mscorlib]System.Exception::.ctor() throw a01045: ldsfld int64 [rvastatic4]A::a01045 ldc.i8 45 beq a01046 newobj instance void [mscorlib]System.Exception::.ctor() throw a01046: ldsfld float32 [rvastatic4]A::a01046 ldc.r4 46.0 beq a01047 newobj instance void [mscorlib]System.Exception::.ctor() throw a01047: ldsfld int16 [rvastatic4]A::a01047 ldc.i4 47 beq a01048 newobj instance void [mscorlib]System.Exception::.ctor() throw a01048: ldsfld int64 [rvastatic4]A::a01048 ldc.i8 48 beq a01049 newobj instance void [mscorlib]System.Exception::.ctor() throw a01049: ldsfld int16 [rvastatic4]A::a01049 ldc.i4 49 beq a01050 newobj instance void [mscorlib]System.Exception::.ctor() throw a01050: ldsfld int32 [rvastatic4]A::a01050 ldc.i4 50 beq a01051 newobj instance void [mscorlib]System.Exception::.ctor() throw a01051: ldsfld int16 [rvastatic4]A::a01051 ldc.i4 51 beq a01052 newobj instance void [mscorlib]System.Exception::.ctor() throw a01052: ldsfld int32 [rvastatic4]A::a01052 ldc.i4 52 beq a01053 newobj instance void [mscorlib]System.Exception::.ctor() throw a01053: ldsfld int16 [rvastatic4]A::a01053 ldc.i4 53 beq a01054 newobj instance void [mscorlib]System.Exception::.ctor() throw a01054: ldsfld float32 [rvastatic4]A::a01054 ldc.r4 54.0 beq a01055 newobj instance void [mscorlib]System.Exception::.ctor() throw a01055: ldsfld int64 [rvastatic4]A::a01055 ldc.i8 55 beq a01056 newobj instance void [mscorlib]System.Exception::.ctor() throw a01056: ldsfld float32 [rvastatic4]A::a01056 ldc.r4 56.0 beq a01057 newobj instance void [mscorlib]System.Exception::.ctor() throw a01057: ldsfld int64 [rvastatic4]A::a01057 ldc.i8 57 beq a01058 newobj instance void [mscorlib]System.Exception::.ctor() throw a01058: ldsfld int64 [rvastatic4]A::a01058 ldc.i8 58 beq a01059 newobj instance void [mscorlib]System.Exception::.ctor() throw a01059: ldsfld int64 [rvastatic4]A::a01059 ldc.i8 59 beq a01060 newobj instance void [mscorlib]System.Exception::.ctor() throw a01060: ldsfld int16 [rvastatic4]A::a01060 ldc.i4 60 beq a01061 newobj instance void [mscorlib]System.Exception::.ctor() throw a01061: ldsfld int8 [rvastatic4]A::a01061 ldc.i4 61 beq a01062 newobj instance void [mscorlib]System.Exception::.ctor() throw a01062: ldsfld int64 [rvastatic4]A::a01062 ldc.i8 62 beq a01063 newobj instance void [mscorlib]System.Exception::.ctor() throw a01063: ldsfld int16 [rvastatic4]A::a01063 ldc.i4 63 beq a01064 newobj instance void [mscorlib]System.Exception::.ctor() throw a01064: ldsfld int32 [rvastatic4]A::a01064 ldc.i4 64 beq a01065 newobj instance void [mscorlib]System.Exception::.ctor() throw a01065: ldsfld int16 [rvastatic4]A::a01065 ldc.i4 65 beq a01066 newobj instance void [mscorlib]System.Exception::.ctor() throw a01066: ldsfld int8 [rvastatic4]A::a01066 ldc.i4 66 beq a01067 newobj instance void [mscorlib]System.Exception::.ctor() throw a01067: ldsfld int16 [rvastatic4]A::a01067 ldc.i4 67 beq a01068 newobj instance void [mscorlib]System.Exception::.ctor() throw a01068: ldsfld int32 [rvastatic4]A::a01068 ldc.i4 68 beq a01069 newobj instance void [mscorlib]System.Exception::.ctor() throw a01069: ldsfld float32 [rvastatic4]A::a01069 ldc.r4 69.0 beq a01070 newobj instance void [mscorlib]System.Exception::.ctor() throw a01070: ldsfld float32 [rvastatic4]A::a01070 ldc.r4 70.0 beq a01071 newobj instance void [mscorlib]System.Exception::.ctor() throw a01071: ldsfld int16 [rvastatic4]A::a01071 ldc.i4 71 beq a01072 newobj instance void [mscorlib]System.Exception::.ctor() throw a01072: ldsfld float32 [rvastatic4]A::a01072 ldc.r4 72.0 beq a01073 newobj instance void [mscorlib]System.Exception::.ctor() throw a01073: ldsfld int64 [rvastatic4]A::a01073 ldc.i8 73 beq a01074 newobj instance void [mscorlib]System.Exception::.ctor() throw a01074: ldsfld int64 [rvastatic4]A::a01074 ldc.i8 74 beq a01075 newobj instance void [mscorlib]System.Exception::.ctor() throw a01075: ldsfld int32 [rvastatic4]A::a01075 ldc.i4 75 beq a01076 newobj instance void [mscorlib]System.Exception::.ctor() throw a01076: ldsfld int8 [rvastatic4]A::a01076 ldc.i4 76 beq a01077 newobj instance void [mscorlib]System.Exception::.ctor() throw a01077: ldsfld int32 [rvastatic4]A::a01077 ldc.i4 77 beq a01078 newobj instance void [mscorlib]System.Exception::.ctor() throw a01078: ldsfld int16 [rvastatic4]A::a01078 ldc.i4 78 beq a01079 newobj instance void [mscorlib]System.Exception::.ctor() throw a01079: ldsfld float32 [rvastatic4]A::a01079 ldc.r4 79.0 beq a01080 newobj instance void [mscorlib]System.Exception::.ctor() throw a01080: ldsfld float32 [rvastatic4]A::a01080 ldc.r4 80.0 beq a01081 newobj instance void [mscorlib]System.Exception::.ctor() throw a01081: ldsfld float32 [rvastatic4]A::a01081 ldc.r4 81.0 beq a01082 newobj instance void [mscorlib]System.Exception::.ctor() throw a01082: ldsfld int32 [rvastatic4]A::a01082 ldc.i4 82 beq a01083 newobj instance void [mscorlib]System.Exception::.ctor() throw a01083: ldsfld int8 [rvastatic4]A::a01083 ldc.i4 83 beq a01084 newobj instance void [mscorlib]System.Exception::.ctor() throw a01084: ldsfld int64 [rvastatic4]A::a01084 ldc.i8 84 beq a01085 newobj instance void [mscorlib]System.Exception::.ctor() throw a01085: ldsfld int64 [rvastatic4]A::a01085 ldc.i8 85 beq a01086 newobj instance void [mscorlib]System.Exception::.ctor() throw a01086: ldsfld int32 [rvastatic4]A::a01086 ldc.i4 86 beq a01087 newobj instance void [mscorlib]System.Exception::.ctor() throw a01087: ldsfld int32 [rvastatic4]A::a01087 ldc.i4 87 beq a01088 newobj instance void [mscorlib]System.Exception::.ctor() throw a01088: ldsfld int8 [rvastatic4]A::a01088 ldc.i4 88 beq a01089 newobj instance void [mscorlib]System.Exception::.ctor() throw a01089: ldsfld int64 [rvastatic4]A::a01089 ldc.i8 89 beq a01090 newobj instance void [mscorlib]System.Exception::.ctor() throw a01090: ldsfld int8 [rvastatic4]A::a01090 ldc.i4 90 beq a01091 newobj instance void [mscorlib]System.Exception::.ctor() throw a01091: ldsfld int16 [rvastatic4]A::a01091 ldc.i4 91 beq a01092 newobj instance void [mscorlib]System.Exception::.ctor() throw a01092: ldsfld float32 [rvastatic4]A::a01092 ldc.r4 92.0 beq a01093 newobj instance void [mscorlib]System.Exception::.ctor() throw a01093: ldsfld int64 [rvastatic4]A::a01093 ldc.i8 93 beq a01094 newobj instance void [mscorlib]System.Exception::.ctor() throw a01094: ldsfld int64 [rvastatic4]A::a01094 ldc.i8 94 beq a01095 newobj instance void [mscorlib]System.Exception::.ctor() throw a01095: ldsfld int8 [rvastatic4]A::a01095 ldc.i4 95 beq a01096 newobj instance void [mscorlib]System.Exception::.ctor() throw a01096: ldsfld float32 [rvastatic4]A::a01096 ldc.r4 96.0 beq a01097 newobj instance void [mscorlib]System.Exception::.ctor() throw a01097: ldsfld int16 [rvastatic4]A::a01097 ldc.i4 97 beq a01098 newobj instance void [mscorlib]System.Exception::.ctor() throw a01098: ldsfld float32 [rvastatic4]A::a01098 ldc.r4 98.0 beq a01099 newobj instance void [mscorlib]System.Exception::.ctor() throw a01099: ldsfld int32 [rvastatic4]A::a01099 ldc.i4 99 beq a010100 newobj instance void [mscorlib]System.Exception::.ctor() throw a010100: ldsfld int64 [rvastatic4]A::a010100 ldc.i8 100 beq a010101 newobj instance void [mscorlib]System.Exception::.ctor() throw a010101: ldsfld int32 [rvastatic4]A::a010101 ldc.i4 101 beq a010102 newobj instance void [mscorlib]System.Exception::.ctor() throw a010102: ldsfld float32 [rvastatic4]A::a010102 ldc.r4 102.0 beq a010103 newobj instance void [mscorlib]System.Exception::.ctor() throw a010103: ldsfld int64 [rvastatic4]A::a010103 ldc.i8 103 beq a010104 newobj instance void [mscorlib]System.Exception::.ctor() throw a010104: ldsfld int32 [rvastatic4]A::a010104 ldc.i4 104 beq a010105 newobj instance void [mscorlib]System.Exception::.ctor() throw a010105: ldsfld int16 [rvastatic4]A::a010105 ldc.i4 105 beq a010106 newobj instance void [mscorlib]System.Exception::.ctor() throw a010106: ldsfld int16 [rvastatic4]A::a010106 ldc.i4 106 beq a010107 newobj instance void [mscorlib]System.Exception::.ctor() throw a010107: ldsfld float32 [rvastatic4]A::a010107 ldc.r4 107.0 beq a010108 newobj instance void [mscorlib]System.Exception::.ctor() throw a010108: ldsfld int32 [rvastatic4]A::a010108 ldc.i4 108 beq a010109 newobj instance void [mscorlib]System.Exception::.ctor() throw a010109: ldsfld int16 [rvastatic4]A::a010109 ldc.i4 109 beq a010110 newobj instance void [mscorlib]System.Exception::.ctor() throw a010110: ldsfld int32 [rvastatic4]A::a010110 ldc.i4 110 beq a010111 newobj instance void [mscorlib]System.Exception::.ctor() throw a010111: ldsfld int32 [rvastatic4]A::a010111 ldc.i4 111 beq a010112 newobj instance void [mscorlib]System.Exception::.ctor() throw a010112: ldsfld int32 [rvastatic4]A::a010112 ldc.i4 112 beq a010113 newobj instance void [mscorlib]System.Exception::.ctor() throw a010113: ldsfld int64 [rvastatic4]A::a010113 ldc.i8 113 beq a010114 newobj instance void [mscorlib]System.Exception::.ctor() throw a010114: ldsfld int64 [rvastatic4]A::a010114 ldc.i8 114 beq a010115 newobj instance void [mscorlib]System.Exception::.ctor() throw a010115: ldsfld int16 [rvastatic4]A::a010115 ldc.i4 115 beq a010116 newobj instance void [mscorlib]System.Exception::.ctor() throw a010116: ldsfld int64 [rvastatic4]A::a010116 ldc.i8 116 beq a010117 newobj instance void [mscorlib]System.Exception::.ctor() throw a010117: ldsfld int64 [rvastatic4]A::a010117 ldc.i8 117 beq a010118 newobj instance void [mscorlib]System.Exception::.ctor() throw a010118: ldsfld int32 [rvastatic4]A::a010118 ldc.i4 118 beq a010119 newobj instance void [mscorlib]System.Exception::.ctor() throw a010119: ldsfld int64 [rvastatic4]A::a010119 ldc.i8 119 beq a010120 newobj instance void [mscorlib]System.Exception::.ctor() throw a010120: ldsfld int64 [rvastatic4]A::a010120 ldc.i8 120 beq a010121 newobj instance void [mscorlib]System.Exception::.ctor() throw a010121: ldsfld int64 [rvastatic4]A::a010121 ldc.i8 121 beq a010122 newobj instance void [mscorlib]System.Exception::.ctor() throw a010122: ldsfld int16 [rvastatic4]A::a010122 ldc.i4 122 beq a010123 newobj instance void [mscorlib]System.Exception::.ctor() throw a010123: ldsfld int64 [rvastatic4]A::a010123 ldc.i8 123 beq a010124 newobj instance void [mscorlib]System.Exception::.ctor() throw a010124: ldsfld int64 [rvastatic4]A::a010124 ldc.i8 124 beq a010125 newobj instance void [mscorlib]System.Exception::.ctor() throw a010125: ldsfld int32 [rvastatic4]A::a010125 ldc.i4 125 beq a010126 newobj instance void [mscorlib]System.Exception::.ctor() throw a010126: ldsfld int16 [rvastatic4]A::a010126 ldc.i4 126 beq a010127 newobj instance void [mscorlib]System.Exception::.ctor() throw a010127: ldsfld int16 [rvastatic4]A::a010127 ldc.i4 127 beq a010128 newobj instance void [mscorlib]System.Exception::.ctor() throw a010128: ret} .method static void V2() {.maxstack 50 ldsflda int32 [rvastatic4]A::a0100 ldind.i4 ldc.i4 0 beq a0100 newobj instance void [mscorlib]System.Exception::.ctor() throw a0100: ldsflda int64 [rvastatic4]A::a0101 ldind.i8 ldc.i8 1 beq a0101 newobj instance void [mscorlib]System.Exception::.ctor() throw a0101: ldsflda float32 [rvastatic4]A::a0102 ldind.r4 ldc.r4 2.0 beq a0102 newobj instance void [mscorlib]System.Exception::.ctor() throw a0102: ldsflda int16 [rvastatic4]A::a0103 ldind.i2 ldc.i4 3 beq a0103 newobj instance void [mscorlib]System.Exception::.ctor() throw a0103: ldsflda int16 [rvastatic4]A::a0104 ldind.i2 ldc.i4 4 beq a0104 newobj instance void [mscorlib]System.Exception::.ctor() throw a0104: ldsflda int64 [rvastatic4]A::a0105 ldind.i8 ldc.i8 5 beq a0105 newobj instance void [mscorlib]System.Exception::.ctor() throw a0105: ldsflda int16 [rvastatic4]A::a0106 ldind.i2 ldc.i4 6 beq a0106 newobj instance void [mscorlib]System.Exception::.ctor() throw a0106: ldsflda int8 [rvastatic4]A::a0107 ldind.i1 ldc.i4 7 beq a0107 newobj instance void [mscorlib]System.Exception::.ctor() throw a0107: ldsflda int64 [rvastatic4]A::a0108 ldind.i8 ldc.i8 8 beq a0108 newobj instance void [mscorlib]System.Exception::.ctor() throw a0108: ldsflda int32 [rvastatic4]A::a0109 ldind.i4 ldc.i4 9 beq a0109 newobj instance void [mscorlib]System.Exception::.ctor() throw a0109: ldsflda int16 [rvastatic4]A::a01010 ldind.i2 ldc.i4 10 beq a01010 newobj instance void [mscorlib]System.Exception::.ctor() throw a01010: ldsflda float32 [rvastatic4]A::a01011 ldind.r4 ldc.r4 11.0 beq a01011 newobj instance void [mscorlib]System.Exception::.ctor() throw a01011: ldsflda int16 [rvastatic4]A::a01012 ldind.i2 ldc.i4 12 beq a01012 newobj instance void [mscorlib]System.Exception::.ctor() throw a01012: ldsflda float32 [rvastatic4]A::a01013 ldind.r4 ldc.r4 13.0 beq a01013 newobj instance void [mscorlib]System.Exception::.ctor() throw a01013: ldsflda float32 [rvastatic4]A::a01014 ldind.r4 ldc.r4 14.0 beq a01014 newobj instance void [mscorlib]System.Exception::.ctor() throw a01014: ldsflda int8 [rvastatic4]A::a01015 ldind.i1 ldc.i4 15 beq a01015 newobj instance void [mscorlib]System.Exception::.ctor() throw a01015: ldsflda float32 [rvastatic4]A::a01016 ldind.r4 ldc.r4 16.0 beq a01016 newobj instance void [mscorlib]System.Exception::.ctor() throw a01016: ldsflda int8 [rvastatic4]A::a01017 ldind.i1 ldc.i4 17 beq a01017 newobj instance void [mscorlib]System.Exception::.ctor() throw a01017: ldsflda float32 [rvastatic4]A::a01018 ldind.r4 ldc.r4 18.0 beq a01018 newobj instance void [mscorlib]System.Exception::.ctor() throw a01018: ldsflda float32 [rvastatic4]A::a01019 ldind.r4 ldc.r4 19.0 beq a01019 newobj instance void [mscorlib]System.Exception::.ctor() throw a01019: ldsflda int8 [rvastatic4]A::a01020 ldind.i1 ldc.i4 20 beq a01020 newobj instance void [mscorlib]System.Exception::.ctor() throw a01020: ldsflda float32 [rvastatic4]A::a01021 ldind.r4 ldc.r4 21.0 beq a01021 newobj instance void [mscorlib]System.Exception::.ctor() throw a01021: ldsflda int64 [rvastatic4]A::a01022 ldind.i8 ldc.i8 22 beq a01022 newobj instance void [mscorlib]System.Exception::.ctor() throw a01022: ldsflda int8 [rvastatic4]A::a01023 ldind.i1 ldc.i4 23 beq a01023 newobj instance void [mscorlib]System.Exception::.ctor() throw a01023: ldsflda int32 [rvastatic4]A::a01024 ldind.i4 ldc.i4 24 beq a01024 newobj instance void [mscorlib]System.Exception::.ctor() throw a01024: ldsflda int64 [rvastatic4]A::a01025 ldind.i8 ldc.i8 25 beq a01025 newobj instance void [mscorlib]System.Exception::.ctor() throw a01025: ldsflda int16 [rvastatic4]A::a01026 ldind.i2 ldc.i4 26 beq a01026 newobj instance void [mscorlib]System.Exception::.ctor() throw a01026: ldsflda int8 [rvastatic4]A::a01027 ldind.i1 ldc.i4 27 beq a01027 newobj instance void [mscorlib]System.Exception::.ctor() throw a01027: ldsflda int16 [rvastatic4]A::a01028 ldind.i2 ldc.i4 28 beq a01028 newobj instance void [mscorlib]System.Exception::.ctor() throw a01028: ldsflda int16 [rvastatic4]A::a01029 ldind.i2 ldc.i4 29 beq a01029 newobj instance void [mscorlib]System.Exception::.ctor() throw a01029: ldsflda int8 [rvastatic4]A::a01030 ldind.i1 ldc.i4 30 beq a01030 newobj instance void [mscorlib]System.Exception::.ctor() throw a01030: ldsflda int8 [rvastatic4]A::a01031 ldind.i1 ldc.i4 31 beq a01031 newobj instance void [mscorlib]System.Exception::.ctor() throw a01031: ldsflda int64 [rvastatic4]A::a01032 ldind.i8 ldc.i8 32 beq a01032 newobj instance void [mscorlib]System.Exception::.ctor() throw a01032: ldsflda float32 [rvastatic4]A::a01033 ldind.r4 ldc.r4 33.0 beq a01033 newobj instance void [mscorlib]System.Exception::.ctor() throw a01033: ldsflda int16 [rvastatic4]A::a01034 ldind.i2 ldc.i4 34 beq a01034 newobj instance void [mscorlib]System.Exception::.ctor() throw a01034: ldsflda int8 [rvastatic4]A::a01035 ldind.i1 ldc.i4 35 beq a01035 newobj instance void [mscorlib]System.Exception::.ctor() throw a01035: ldsflda int8 [rvastatic4]A::a01036 ldind.i1 ldc.i4 36 beq a01036 newobj instance void [mscorlib]System.Exception::.ctor() throw a01036: ldsflda int32 [rvastatic4]A::a01037 ldind.i4 ldc.i4 37 beq a01037 newobj instance void [mscorlib]System.Exception::.ctor() throw a01037: ldsflda int16 [rvastatic4]A::a01038 ldind.i2 ldc.i4 38 beq a01038 newobj instance void [mscorlib]System.Exception::.ctor() throw a01038: ldsflda int8 [rvastatic4]A::a01039 ldind.i1 ldc.i4 39 beq a01039 newobj instance void [mscorlib]System.Exception::.ctor() throw a01039: ldsflda int8 [rvastatic4]A::a01040 ldind.i1 ldc.i4 40 beq a01040 newobj instance void [mscorlib]System.Exception::.ctor() throw a01040: ldsflda int32 [rvastatic4]A::a01041 ldind.i4 ldc.i4 41 beq a01041 newobj instance void [mscorlib]System.Exception::.ctor() throw a01041: ldsflda int64 [rvastatic4]A::a01042 ldind.i8 ldc.i8 42 beq a01042 newobj instance void [mscorlib]System.Exception::.ctor() throw a01042: ldsflda int16 [rvastatic4]A::a01043 ldind.i2 ldc.i4 43 beq a01043 newobj instance void [mscorlib]System.Exception::.ctor() throw a01043: ldsflda int64 [rvastatic4]A::a01044 ldind.i8 ldc.i8 44 beq a01044 newobj instance void [mscorlib]System.Exception::.ctor() throw a01044: ldsflda int64 [rvastatic4]A::a01045 ldind.i8 ldc.i8 45 beq a01045 newobj instance void [mscorlib]System.Exception::.ctor() throw a01045: ldsflda float32 [rvastatic4]A::a01046 ldind.r4 ldc.r4 46.0 beq a01046 newobj instance void [mscorlib]System.Exception::.ctor() throw a01046: ldsflda int16 [rvastatic4]A::a01047 ldind.i2 ldc.i4 47 beq a01047 newobj instance void [mscorlib]System.Exception::.ctor() throw a01047: ldsflda int64 [rvastatic4]A::a01048 ldind.i8 ldc.i8 48 beq a01048 newobj instance void [mscorlib]System.Exception::.ctor() throw a01048: ldsflda int16 [rvastatic4]A::a01049 ldind.i2 ldc.i4 49 beq a01049 newobj instance void [mscorlib]System.Exception::.ctor() throw a01049: ldsflda int32 [rvastatic4]A::a01050 ldind.i4 ldc.i4 50 beq a01050 newobj instance void [mscorlib]System.Exception::.ctor() throw a01050: ldsflda int16 [rvastatic4]A::a01051 ldind.i2 ldc.i4 51 beq a01051 newobj instance void [mscorlib]System.Exception::.ctor() throw a01051: ldsflda int32 [rvastatic4]A::a01052 ldind.i4 ldc.i4 52 beq a01052 newobj instance void [mscorlib]System.Exception::.ctor() throw a01052: ldsflda int16 [rvastatic4]A::a01053 ldind.i2 ldc.i4 53 beq a01053 newobj instance void [mscorlib]System.Exception::.ctor() throw a01053: ldsflda float32 [rvastatic4]A::a01054 ldind.r4 ldc.r4 54.0 beq a01054 newobj instance void [mscorlib]System.Exception::.ctor() throw a01054: ldsflda int64 [rvastatic4]A::a01055 ldind.i8 ldc.i8 55 beq a01055 newobj instance void [mscorlib]System.Exception::.ctor() throw a01055: ldsflda float32 [rvastatic4]A::a01056 ldind.r4 ldc.r4 56.0 beq a01056 newobj instance void [mscorlib]System.Exception::.ctor() throw a01056: ldsflda int64 [rvastatic4]A::a01057 ldind.i8 ldc.i8 57 beq a01057 newobj instance void [mscorlib]System.Exception::.ctor() throw a01057: ldsflda int64 [rvastatic4]A::a01058 ldind.i8 ldc.i8 58 beq a01058 newobj instance void [mscorlib]System.Exception::.ctor() throw a01058: ldsflda int64 [rvastatic4]A::a01059 ldind.i8 ldc.i8 59 beq a01059 newobj instance void [mscorlib]System.Exception::.ctor() throw a01059: ldsflda int16 [rvastatic4]A::a01060 ldind.i2 ldc.i4 60 beq a01060 newobj instance void [mscorlib]System.Exception::.ctor() throw a01060: ldsflda int8 [rvastatic4]A::a01061 ldind.i1 ldc.i4 61 beq a01061 newobj instance void [mscorlib]System.Exception::.ctor() throw a01061: ldsflda int64 [rvastatic4]A::a01062 ldind.i8 ldc.i8 62 beq a01062 newobj instance void [mscorlib]System.Exception::.ctor() throw a01062: ldsflda int16 [rvastatic4]A::a01063 ldind.i2 ldc.i4 63 beq a01063 newobj instance void [mscorlib]System.Exception::.ctor() throw a01063: ldsflda int32 [rvastatic4]A::a01064 ldind.i4 ldc.i4 64 beq a01064 newobj instance void [mscorlib]System.Exception::.ctor() throw a01064: ldsflda int16 [rvastatic4]A::a01065 ldind.i2 ldc.i4 65 beq a01065 newobj instance void [mscorlib]System.Exception::.ctor() throw a01065: ldsflda int8 [rvastatic4]A::a01066 ldind.i1 ldc.i4 66 beq a01066 newobj instance void [mscorlib]System.Exception::.ctor() throw a01066: ldsflda int16 [rvastatic4]A::a01067 ldind.i2 ldc.i4 67 beq a01067 newobj instance void [mscorlib]System.Exception::.ctor() throw a01067: ldsflda int32 [rvastatic4]A::a01068 ldind.i4 ldc.i4 68 beq a01068 newobj instance void [mscorlib]System.Exception::.ctor() throw a01068: ldsflda float32 [rvastatic4]A::a01069 ldind.r4 ldc.r4 69.0 beq a01069 newobj instance void [mscorlib]System.Exception::.ctor() throw a01069: ldsflda float32 [rvastatic4]A::a01070 ldind.r4 ldc.r4 70.0 beq a01070 newobj instance void [mscorlib]System.Exception::.ctor() throw a01070: ldsflda int16 [rvastatic4]A::a01071 ldind.i2 ldc.i4 71 beq a01071 newobj instance void [mscorlib]System.Exception::.ctor() throw a01071: ldsflda float32 [rvastatic4]A::a01072 ldind.r4 ldc.r4 72.0 beq a01072 newobj instance void [mscorlib]System.Exception::.ctor() throw a01072: ldsflda int64 [rvastatic4]A::a01073 ldind.i8 ldc.i8 73 beq a01073 newobj instance void [mscorlib]System.Exception::.ctor() throw a01073: ldsflda int64 [rvastatic4]A::a01074 ldind.i8 ldc.i8 74 beq a01074 newobj instance void [mscorlib]System.Exception::.ctor() throw a01074: ldsflda int32 [rvastatic4]A::a01075 ldind.i4 ldc.i4 75 beq a01075 newobj instance void [mscorlib]System.Exception::.ctor() throw a01075: ldsflda int8 [rvastatic4]A::a01076 ldind.i1 ldc.i4 76 beq a01076 newobj instance void [mscorlib]System.Exception::.ctor() throw a01076: ldsflda int32 [rvastatic4]A::a01077 ldind.i4 ldc.i4 77 beq a01077 newobj instance void [mscorlib]System.Exception::.ctor() throw a01077: ldsflda int16 [rvastatic4]A::a01078 ldind.i2 ldc.i4 78 beq a01078 newobj instance void [mscorlib]System.Exception::.ctor() throw a01078: ldsflda float32 [rvastatic4]A::a01079 ldind.r4 ldc.r4 79.0 beq a01079 newobj instance void [mscorlib]System.Exception::.ctor() throw a01079: ldsflda float32 [rvastatic4]A::a01080 ldind.r4 ldc.r4 80.0 beq a01080 newobj instance void [mscorlib]System.Exception::.ctor() throw a01080: ldsflda float32 [rvastatic4]A::a01081 ldind.r4 ldc.r4 81.0 beq a01081 newobj instance void [mscorlib]System.Exception::.ctor() throw a01081: ldsflda int32 [rvastatic4]A::a01082 ldind.i4 ldc.i4 82 beq a01082 newobj instance void [mscorlib]System.Exception::.ctor() throw a01082: ldsflda int8 [rvastatic4]A::a01083 ldind.i1 ldc.i4 83 beq a01083 newobj instance void [mscorlib]System.Exception::.ctor() throw a01083: ldsflda int64 [rvastatic4]A::a01084 ldind.i8 ldc.i8 84 beq a01084 newobj instance void [mscorlib]System.Exception::.ctor() throw a01084: ldsflda int64 [rvastatic4]A::a01085 ldind.i8 ldc.i8 85 beq a01085 newobj instance void [mscorlib]System.Exception::.ctor() throw a01085: ldsflda int32 [rvastatic4]A::a01086 ldind.i4 ldc.i4 86 beq a01086 newobj instance void [mscorlib]System.Exception::.ctor() throw a01086: ldsflda int32 [rvastatic4]A::a01087 ldind.i4 ldc.i4 87 beq a01087 newobj instance void [mscorlib]System.Exception::.ctor() throw a01087: ldsflda int8 [rvastatic4]A::a01088 ldind.i1 ldc.i4 88 beq a01088 newobj instance void [mscorlib]System.Exception::.ctor() throw a01088: ldsflda int64 [rvastatic4]A::a01089 ldind.i8 ldc.i8 89 beq a01089 newobj instance void [mscorlib]System.Exception::.ctor() throw a01089: ldsflda int8 [rvastatic4]A::a01090 ldind.i1 ldc.i4 90 beq a01090 newobj instance void [mscorlib]System.Exception::.ctor() throw a01090: ldsflda int16 [rvastatic4]A::a01091 ldind.i2 ldc.i4 91 beq a01091 newobj instance void [mscorlib]System.Exception::.ctor() throw a01091: ldsflda float32 [rvastatic4]A::a01092 ldind.r4 ldc.r4 92.0 beq a01092 newobj instance void [mscorlib]System.Exception::.ctor() throw a01092: ldsflda int64 [rvastatic4]A::a01093 ldind.i8 ldc.i8 93 beq a01093 newobj instance void [mscorlib]System.Exception::.ctor() throw a01093: ldsflda int64 [rvastatic4]A::a01094 ldind.i8 ldc.i8 94 beq a01094 newobj instance void [mscorlib]System.Exception::.ctor() throw a01094: ldsflda int8 [rvastatic4]A::a01095 ldind.i1 ldc.i4 95 beq a01095 newobj instance void [mscorlib]System.Exception::.ctor() throw a01095: ldsflda float32 [rvastatic4]A::a01096 ldind.r4 ldc.r4 96.0 beq a01096 newobj instance void [mscorlib]System.Exception::.ctor() throw a01096: ldsflda int16 [rvastatic4]A::a01097 ldind.i2 ldc.i4 97 beq a01097 newobj instance void [mscorlib]System.Exception::.ctor() throw a01097: ldsflda float32 [rvastatic4]A::a01098 ldind.r4 ldc.r4 98.0 beq a01098 newobj instance void [mscorlib]System.Exception::.ctor() throw a01098: ldsflda int32 [rvastatic4]A::a01099 ldind.i4 ldc.i4 99 beq a01099 newobj instance void [mscorlib]System.Exception::.ctor() throw a01099: ldsflda int64 [rvastatic4]A::a010100 ldind.i8 ldc.i8 100 beq a010100 newobj instance void [mscorlib]System.Exception::.ctor() throw a010100: ldsflda int32 [rvastatic4]A::a010101 ldind.i4 ldc.i4 101 beq a010101 newobj instance void [mscorlib]System.Exception::.ctor() throw a010101: ldsflda float32 [rvastatic4]A::a010102 ldind.r4 ldc.r4 102.0 beq a010102 newobj instance void [mscorlib]System.Exception::.ctor() throw a010102: ldsflda int64 [rvastatic4]A::a010103 ldind.i8 ldc.i8 103 beq a010103 newobj instance void [mscorlib]System.Exception::.ctor() throw a010103: ldsflda int32 [rvastatic4]A::a010104 ldind.i4 ldc.i4 104 beq a010104 newobj instance void [mscorlib]System.Exception::.ctor() throw a010104: ldsflda int16 [rvastatic4]A::a010105 ldind.i2 ldc.i4 105 beq a010105 newobj instance void [mscorlib]System.Exception::.ctor() throw a010105: ldsflda int16 [rvastatic4]A::a010106 ldind.i2 ldc.i4 106 beq a010106 newobj instance void [mscorlib]System.Exception::.ctor() throw a010106: ldsflda float32 [rvastatic4]A::a010107 ldind.r4 ldc.r4 107.0 beq a010107 newobj instance void [mscorlib]System.Exception::.ctor() throw a010107: ldsflda int32 [rvastatic4]A::a010108 ldind.i4 ldc.i4 108 beq a010108 newobj instance void [mscorlib]System.Exception::.ctor() throw a010108: ldsflda int16 [rvastatic4]A::a010109 ldind.i2 ldc.i4 109 beq a010109 newobj instance void [mscorlib]System.Exception::.ctor() throw a010109: ldsflda int32 [rvastatic4]A::a010110 ldind.i4 ldc.i4 110 beq a010110 newobj instance void [mscorlib]System.Exception::.ctor() throw a010110: ldsflda int32 [rvastatic4]A::a010111 ldind.i4 ldc.i4 111 beq a010111 newobj instance void [mscorlib]System.Exception::.ctor() throw a010111: ldsflda int32 [rvastatic4]A::a010112 ldind.i4 ldc.i4 112 beq a010112 newobj instance void [mscorlib]System.Exception::.ctor() throw a010112: ldsflda int64 [rvastatic4]A::a010113 ldind.i8 ldc.i8 113 beq a010113 newobj instance void [mscorlib]System.Exception::.ctor() throw a010113: ldsflda int64 [rvastatic4]A::a010114 ldind.i8 ldc.i8 114 beq a010114 newobj instance void [mscorlib]System.Exception::.ctor() throw a010114: ldsflda int16 [rvastatic4]A::a010115 ldind.i2 ldc.i4 115 beq a010115 newobj instance void [mscorlib]System.Exception::.ctor() throw a010115: ldsflda int64 [rvastatic4]A::a010116 ldind.i8 ldc.i8 116 beq a010116 newobj instance void [mscorlib]System.Exception::.ctor() throw a010116: ldsflda int64 [rvastatic4]A::a010117 ldind.i8 ldc.i8 117 beq a010117 newobj instance void [mscorlib]System.Exception::.ctor() throw a010117: ldsflda int32 [rvastatic4]A::a010118 ldind.i4 ldc.i4 118 beq a010118 newobj instance void [mscorlib]System.Exception::.ctor() throw a010118: ldsflda int64 [rvastatic4]A::a010119 ldind.i8 ldc.i8 119 beq a010119 newobj instance void [mscorlib]System.Exception::.ctor() throw a010119: ldsflda int64 [rvastatic4]A::a010120 ldind.i8 ldc.i8 120 beq a010120 newobj instance void [mscorlib]System.Exception::.ctor() throw a010120: ldsflda int64 [rvastatic4]A::a010121 ldind.i8 ldc.i8 121 beq a010121 newobj instance void [mscorlib]System.Exception::.ctor() throw a010121: ldsflda int16 [rvastatic4]A::a010122 ldind.i2 ldc.i4 122 beq a010122 newobj instance void [mscorlib]System.Exception::.ctor() throw a010122: ldsflda int64 [rvastatic4]A::a010123 ldind.i8 ldc.i8 123 beq a010123 newobj instance void [mscorlib]System.Exception::.ctor() throw a010123: ldsflda int64 [rvastatic4]A::a010124 ldind.i8 ldc.i8 124 beq a010124 newobj instance void [mscorlib]System.Exception::.ctor() throw a010124: ldsflda int32 [rvastatic4]A::a010125 ldind.i4 ldc.i4 125 beq a010125 newobj instance void [mscorlib]System.Exception::.ctor() throw a010125: ldsflda int16 [rvastatic4]A::a010126 ldind.i2 ldc.i4 126 beq a010126 newobj instance void [mscorlib]System.Exception::.ctor() throw a010126: ldsflda int16 [rvastatic4]A::a010127 ldind.i2 ldc.i4 127 beq a010127 newobj instance void [mscorlib]System.Exception::.ctor() throw a010127: ret} .method static void V3() {.maxstack 50 ldsfld float32 [rvastatic4]A::a01079 ldc.r4 79.0 beq a010129 newobj instance void [mscorlib]System.Exception::.ctor() throw a010129: ldsfld int32 [rvastatic4]A::a010111 ldc.i4 111 beq a010130 newobj instance void [mscorlib]System.Exception::.ctor() throw a010130: ldsfld int16 [rvastatic4]A::a01034 ldc.i4 34 beq a010131 newobj instance void [mscorlib]System.Exception::.ctor() throw a010131: ldsfld int8 [rvastatic4]A::a01040 ldc.i4 40 beq a010132 newobj instance void [mscorlib]System.Exception::.ctor() throw a010132: ldsfld int16 [rvastatic4]A::a01012 ldc.i4 12 beq a010133 newobj instance void [mscorlib]System.Exception::.ctor() throw a010133: ldsfld int64 [rvastatic4]A::a01089 ldc.i8 89 beq a010134 newobj instance void [mscorlib]System.Exception::.ctor() throw a010134: ldsfld float32 [rvastatic4]A::a01070 ldc.r4 70.0 beq a010135 newobj instance void [mscorlib]System.Exception::.ctor() throw a010135: ldsfld int8 [rvastatic4]A::a01066 ldc.i4 66 beq a010136 newobj instance void [mscorlib]System.Exception::.ctor() throw a010136: ldsfld int64 [rvastatic4]A::a01048 ldc.i8 48 beq a010137 newobj instance void [mscorlib]System.Exception::.ctor() throw a010137: ldsfld float32 [rvastatic4]A::a01080 ldc.r4 80.0 beq a010138 newobj instance void [mscorlib]System.Exception::.ctor() throw a010138: ldsfld int32 [rvastatic4]A::a010104 ldc.i4 104 beq a010139 newobj instance void [mscorlib]System.Exception::.ctor() throw a010139: ldsfld int16 [rvastatic4]A::a01091 ldc.i4 91 beq a010140 newobj instance void [mscorlib]System.Exception::.ctor() throw a010140: ldsfld int32 [rvastatic4]A::a01024 ldc.i4 24 beq a010141 newobj instance void [mscorlib]System.Exception::.ctor() throw a010141: ldsfld float32 [rvastatic4]A::a01081 ldc.r4 81.0 beq a010142 newobj instance void [mscorlib]System.Exception::.ctor() throw a010142: ldsfld int64 [rvastatic4]A::a010121 ldc.i8 121 beq a010143 newobj instance void [mscorlib]System.Exception::.ctor() throw a010143: ldsfld int8 [rvastatic4]A::a01017 ldc.i4 17 beq a010144 newobj instance void [mscorlib]System.Exception::.ctor() throw a010144: ldsfld float32 [rvastatic4]A::a010107 ldc.r4 107.0 beq a010145 newobj instance void [mscorlib]System.Exception::.ctor() throw a010145: ldsfld int16 [rvastatic4]A::a01047 ldc.i4 47 beq a010146 newobj instance void [mscorlib]System.Exception::.ctor() throw a010146: ldsfld int64 [rvastatic4]A::a01048 ldc.i8 48 beq a010147 newobj instance void [mscorlib]System.Exception::.ctor() throw a010147: ldsfld int8 [rvastatic4]A::a01020 ldc.i4 20 beq a010148 newobj instance void [mscorlib]System.Exception::.ctor() throw a010148: ldsfld int16 [rvastatic4]A::a010115 ldc.i4 115 beq a010149 newobj instance void [mscorlib]System.Exception::.ctor() throw a010149: ldsfld int32 [rvastatic4]A::a01024 ldc.i4 24 beq a010150 newobj instance void [mscorlib]System.Exception::.ctor() throw a010150: ldsfld float32 [rvastatic4]A::a010102 ldc.r4 102.0 beq a010151 newobj instance void [mscorlib]System.Exception::.ctor() throw a010151: ldsfld int64 [rvastatic4]A::a010124 ldc.i8 124 beq a010152 newobj instance void [mscorlib]System.Exception::.ctor() throw a010152: ldsfld int16 [rvastatic4]A::a01028 ldc.i4 28 beq a010153 newobj instance void [mscorlib]System.Exception::.ctor() throw a010153: ldsfld int16 [rvastatic4]A::a01012 ldc.i4 12 beq a010154 newobj instance void [mscorlib]System.Exception::.ctor() throw a010154: ldsfld int64 [rvastatic4]A::a0105 ldc.i8 5 beq a010155 newobj instance void [mscorlib]System.Exception::.ctor() throw a010155: ldsfld int16 [rvastatic4]A::a010115 ldc.i4 115 beq a010156 newobj instance void [mscorlib]System.Exception::.ctor() throw a010156: ldsfld int64 [rvastatic4]A::a010113 ldc.i8 113 beq a010157 newobj instance void [mscorlib]System.Exception::.ctor() throw a010157: ldsfld int64 [rvastatic4]A::a0101 ldc.i8 1 beq a010158 newobj instance void [mscorlib]System.Exception::.ctor() throw a010158: ldsfld int16 [rvastatic4]A::a010122 ldc.i4 122 beq a010159 newobj instance void [mscorlib]System.Exception::.ctor() throw a010159: ldsfld int32 [rvastatic4]A::a010108 ldc.i4 108 beq a010160 newobj instance void [mscorlib]System.Exception::.ctor() throw a010160: ldsfld int8 [rvastatic4]A::a01090 ldc.i4 90 beq a010161 newobj instance void [mscorlib]System.Exception::.ctor() throw a010161: ldsfld int8 [rvastatic4]A::a01090 ldc.i4 90 beq a010162 newobj instance void [mscorlib]System.Exception::.ctor() throw a010162: ldsfld int32 [rvastatic4]A::a010112 ldc.i4 112 beq a010163 newobj instance void [mscorlib]System.Exception::.ctor() throw a010163: ldsfld int16 [rvastatic4]A::a01067 ldc.i4 67 beq a010164 newobj instance void [mscorlib]System.Exception::.ctor() throw a010164: ldsfld int32 [rvastatic4]A::a01064 ldc.i4 64 beq a010165 newobj instance void [mscorlib]System.Exception::.ctor() throw a010165: ldsfld int64 [rvastatic4]A::a01057 ldc.i8 57 beq a010166 newobj instance void [mscorlib]System.Exception::.ctor() throw a010166: ldsfld int32 [rvastatic4]A::a01037 ldc.i4 37 beq a010167 newobj instance void [mscorlib]System.Exception::.ctor() throw a010167: ldsfld int64 [rvastatic4]A::a010120 ldc.i8 120 beq a010168 newobj instance void [mscorlib]System.Exception::.ctor() throw a010168: ldsfld float32 [rvastatic4]A::a01019 ldc.r4 19.0 beq a010169 newobj instance void [mscorlib]System.Exception::.ctor() throw a010169: ldsfld int64 [rvastatic4]A::a010124 ldc.i8 124 beq a010170 newobj instance void [mscorlib]System.Exception::.ctor() throw a010170: ldsfld int32 [rvastatic4]A::a01037 ldc.i4 37 beq a010171 newobj instance void [mscorlib]System.Exception::.ctor() throw a010171: ldsfld int8 [rvastatic4]A::a0107 ldc.i4 7 beq a010172 newobj instance void [mscorlib]System.Exception::.ctor() throw a010172: ldsfld int16 [rvastatic4]A::a010106 ldc.i4 106 beq a010173 newobj instance void [mscorlib]System.Exception::.ctor() throw a010173: ldsfld int64 [rvastatic4]A::a01073 ldc.i8 73 beq a010174 newobj instance void [mscorlib]System.Exception::.ctor() throw a010174: ldsfld int64 [rvastatic4]A::a01074 ldc.i8 74 beq a010175 newobj instance void [mscorlib]System.Exception::.ctor() throw a010175: ldsfld int8 [rvastatic4]A::a01015 ldc.i4 15 beq a010176 newobj instance void [mscorlib]System.Exception::.ctor() throw a010176: ldsfld int32 [rvastatic4]A::a01077 ldc.i4 77 beq a010177 newobj instance void [mscorlib]System.Exception::.ctor() throw a010177: ldsfld int8 [rvastatic4]A::a01031 ldc.i4 31 beq a010178 newobj instance void [mscorlib]System.Exception::.ctor() throw a010178: ldsfld int16 [rvastatic4]A::a01067 ldc.i4 67 beq a010179 newobj instance void [mscorlib]System.Exception::.ctor() throw a010179: ldsfld int16 [rvastatic4]A::a01071 ldc.i4 71 beq a010180 newobj instance void [mscorlib]System.Exception::.ctor() throw a010180: ldsfld int16 [rvastatic4]A::a01047 ldc.i4 47 beq a010181 newobj instance void [mscorlib]System.Exception::.ctor() throw a010181: ldsfld int8 [rvastatic4]A::a01061 ldc.i4 61 beq a010182 newobj instance void [mscorlib]System.Exception::.ctor() throw a010182: ldsfld int64 [rvastatic4]A::a010114 ldc.i8 114 beq a010183 newobj instance void [mscorlib]System.Exception::.ctor() throw a010183: ldsfld float32 [rvastatic4]A::a01054 ldc.r4 54.0 beq a010184 newobj instance void [mscorlib]System.Exception::.ctor() throw a010184: ldsfld int32 [rvastatic4]A::a0109 ldc.i4 9 beq a010185 newobj instance void [mscorlib]System.Exception::.ctor() throw a010185: ldsfld int32 [rvastatic4]A::a01037 ldc.i4 37 beq a010186 newobj instance void [mscorlib]System.Exception::.ctor() throw a010186: ldsfld int16 [rvastatic4]A::a01012 ldc.i4 12 beq a010187 newobj instance void [mscorlib]System.Exception::.ctor() throw a010187: ldsfld int32 [rvastatic4]A::a0100 ldc.i4 0 beq a010188 newobj instance void [mscorlib]System.Exception::.ctor() throw a010188: ldsfld int8 [rvastatic4]A::a01083 ldc.i4 83 beq a010189 newobj instance void [mscorlib]System.Exception::.ctor() throw a010189: ldsfld int32 [rvastatic4]A::a01082 ldc.i4 82 beq a010190 newobj instance void [mscorlib]System.Exception::.ctor() throw a010190: ldsfld float32 [rvastatic4]A::a01081 ldc.r4 81.0 beq a010191 newobj instance void [mscorlib]System.Exception::.ctor() throw a010191: ldsfld float32 [rvastatic4]A::a01046 ldc.r4 46.0 beq a010192 newobj instance void [mscorlib]System.Exception::.ctor() throw a010192: ldsfld int64 [rvastatic4]A::a01085 ldc.i8 85 beq a010193 newobj instance void [mscorlib]System.Exception::.ctor() throw a010193: ldsfld int64 [rvastatic4]A::a010123 ldc.i8 123 beq a010194 newobj instance void [mscorlib]System.Exception::.ctor() throw a010194: ldsfld int32 [rvastatic4]A::a0100 ldc.i4 0 beq a010195 newobj instance void [mscorlib]System.Exception::.ctor() throw a010195: ldsfld int64 [rvastatic4]A::a01062 ldc.i8 62 beq a010196 newobj instance void [mscorlib]System.Exception::.ctor() throw a010196: ldsfld float32 [rvastatic4]A::a01096 ldc.r4 96.0 beq a010197 newobj instance void [mscorlib]System.Exception::.ctor() throw a010197: ldsfld int16 [rvastatic4]A::a01053 ldc.i4 53 beq a010198 newobj instance void [mscorlib]System.Exception::.ctor() throw a010198: ldsfld float32 [rvastatic4]A::a01081 ldc.r4 81.0 beq a010199 newobj instance void [mscorlib]System.Exception::.ctor() throw a010199: ldsfld int16 [rvastatic4]A::a01049 ldc.i4 49 beq a010200 newobj instance void [mscorlib]System.Exception::.ctor() throw a010200: ldsfld int32 [rvastatic4]A::a0109 ldc.i4 9 beq a010201 newobj instance void [mscorlib]System.Exception::.ctor() throw a010201: ldsfld float32 [rvastatic4]A::a01056 ldc.r4 56.0 beq a010202 newobj instance void [mscorlib]System.Exception::.ctor() throw a010202: ldsfld int64 [rvastatic4]A::a0101 ldc.i8 1 beq a010203 newobj instance void [mscorlib]System.Exception::.ctor() throw a010203: ldsfld int64 [rvastatic4]A::a010119 ldc.i8 119 beq a010204 newobj instance void [mscorlib]System.Exception::.ctor() throw a010204: ldsfld int16 [rvastatic4]A::a010115 ldc.i4 115 beq a010205 newobj instance void [mscorlib]System.Exception::.ctor() throw a010205: ldsfld int64 [rvastatic4]A::a01094 ldc.i8 94 beq a010206 newobj instance void [mscorlib]System.Exception::.ctor() throw a010206: ldsfld int8 [rvastatic4]A::a01017 ldc.i4 17 beq a010207 newobj instance void [mscorlib]System.Exception::.ctor() throw a010207: ldsfld int32 [rvastatic4]A::a01082 ldc.i4 82 beq a010208 newobj instance void [mscorlib]System.Exception::.ctor() throw a010208: ldsfld int16 [rvastatic4]A::a01065 ldc.i4 65 beq a010209 newobj instance void [mscorlib]System.Exception::.ctor() throw a010209: ldsfld int64 [rvastatic4]A::a010117 ldc.i8 117 beq a010210 newobj instance void [mscorlib]System.Exception::.ctor() throw a010210: ldsfld int16 [rvastatic4]A::a01038 ldc.i4 38 beq a010211 newobj instance void [mscorlib]System.Exception::.ctor() throw a010211: ldsfld int32 [rvastatic4]A::a01082 ldc.i4 82 beq a010212 newobj instance void [mscorlib]System.Exception::.ctor() throw a010212: ldsfld int64 [rvastatic4]A::a01062 ldc.i8 62 beq a010213 newobj instance void [mscorlib]System.Exception::.ctor() throw a010213: ldsfld int32 [rvastatic4]A::a01050 ldc.i4 50 beq a010214 newobj instance void [mscorlib]System.Exception::.ctor() throw a010214: ldsfld int8 [rvastatic4]A::a01061 ldc.i4 61 beq a010215 newobj instance void [mscorlib]System.Exception::.ctor() throw a010215: ldsfld int16 [rvastatic4]A::a01029 ldc.i4 29 beq a010216 newobj instance void [mscorlib]System.Exception::.ctor() throw a010216: ldsfld int32 [rvastatic4]A::a010104 ldc.i4 104 beq a010217 newobj instance void [mscorlib]System.Exception::.ctor() throw a010217: ldsfld int64 [rvastatic4]A::a01057 ldc.i8 57 beq a010218 newobj instance void [mscorlib]System.Exception::.ctor() throw a010218: ldsfld int64 [rvastatic4]A::a01057 ldc.i8 57 beq a010219 newobj instance void [mscorlib]System.Exception::.ctor() throw a010219: ldsfld int16 [rvastatic4]A::a01026 ldc.i4 26 beq a010220 newobj instance void [mscorlib]System.Exception::.ctor() throw a010220: ldsfld int64 [rvastatic4]A::a01045 ldc.i8 45 beq a010221 newobj instance void [mscorlib]System.Exception::.ctor() throw a010221: ldsfld int32 [rvastatic4]A::a01037 ldc.i4 37 beq a010222 newobj instance void [mscorlib]System.Exception::.ctor() throw a010222: ldsfld int8 [rvastatic4]A::a01036 ldc.i4 36 beq a010223 newobj instance void [mscorlib]System.Exception::.ctor() throw a010223: ldsfld int32 [rvastatic4]A::a01064 ldc.i4 64 beq a010224 newobj instance void [mscorlib]System.Exception::.ctor() throw a010224: ldsfld int16 [rvastatic4]A::a01043 ldc.i4 43 beq a010225 newobj instance void [mscorlib]System.Exception::.ctor() throw a010225: ldsfld int32 [rvastatic4]A::a010118 ldc.i4 118 beq a010226 newobj instance void [mscorlib]System.Exception::.ctor() throw a010226: ldsfld int32 [rvastatic4]A::a01050 ldc.i4 50 beq a010227 newobj instance void [mscorlib]System.Exception::.ctor() throw a010227: ldsfld int32 [rvastatic4]A::a010111 ldc.i4 111 beq a010228 newobj instance void [mscorlib]System.Exception::.ctor() throw a010228: ldsfld float32 [rvastatic4]A::a01072 ldc.r4 72.0 beq a010229 newobj instance void [mscorlib]System.Exception::.ctor() throw a010229: ldsfld int16 [rvastatic4]A::a01012 ldc.i4 12 beq a010230 newobj instance void [mscorlib]System.Exception::.ctor() throw a010230: ldsfld float32 [rvastatic4]A::a01046 ldc.r4 46.0 beq a010231 newobj instance void [mscorlib]System.Exception::.ctor() throw a010231: ldsfld int8 [rvastatic4]A::a01023 ldc.i4 23 beq a010232 newobj instance void [mscorlib]System.Exception::.ctor() throw a010232: ldsfld int32 [rvastatic4]A::a01077 ldc.i4 77 beq a010233 newobj instance void [mscorlib]System.Exception::.ctor() throw a010233: ldsfld float32 [rvastatic4]A::a01018 ldc.r4 18.0 beq a010234 newobj instance void [mscorlib]System.Exception::.ctor() throw a010234: ldsfld int8 [rvastatic4]A::a01061 ldc.i4 61 beq a010235 newobj instance void [mscorlib]System.Exception::.ctor() throw a010235: ldsfld int32 [rvastatic4]A::a010118 ldc.i4 118 beq a010236 newobj instance void [mscorlib]System.Exception::.ctor() throw a010236: ldsfld int64 [rvastatic4]A::a01059 ldc.i8 59 beq a010237 newobj instance void [mscorlib]System.Exception::.ctor() throw a010237: ldsfld int16 [rvastatic4]A::a010122 ldc.i4 122 beq a010238 newobj instance void [mscorlib]System.Exception::.ctor() throw a010238: ldsfld int8 [rvastatic4]A::a01066 ldc.i4 66 beq a010239 newobj instance void [mscorlib]System.Exception::.ctor() throw a010239: ldsfld int16 [rvastatic4]A::a01043 ldc.i4 43 beq a010240 newobj instance void [mscorlib]System.Exception::.ctor() throw a010240: ldsfld int8 [rvastatic4]A::a01020 ldc.i4 20 beq a010241 newobj instance void [mscorlib]System.Exception::.ctor() throw a010241: ldsfld int64 [rvastatic4]A::a01058 ldc.i8 58 beq a010242 newobj instance void [mscorlib]System.Exception::.ctor() throw a010242: ldsfld int64 [rvastatic4]A::a01062 ldc.i8 62 beq a010243 newobj instance void [mscorlib]System.Exception::.ctor() throw a010243: ldsfld int64 [rvastatic4]A::a01094 ldc.i8 94 beq a010244 newobj instance void [mscorlib]System.Exception::.ctor() throw a010244: ldsfld int64 [rvastatic4]A::a01044 ldc.i8 44 beq a010245 newobj instance void [mscorlib]System.Exception::.ctor() throw a010245: ldsfld int16 [rvastatic4]A::a010126 ldc.i4 126 beq a010246 newobj instance void [mscorlib]System.Exception::.ctor() throw a010246: ldsfld int32 [rvastatic4]A::a010112 ldc.i4 112 beq a010247 newobj instance void [mscorlib]System.Exception::.ctor() throw a010247: ldsfld int16 [rvastatic4]A::a01034 ldc.i4 34 beq a010248 newobj instance void [mscorlib]System.Exception::.ctor() throw a010248: ldsfld int64 [rvastatic4]A::a01062 ldc.i8 62 beq a010249 newobj instance void [mscorlib]System.Exception::.ctor() throw a010249: ldsfld int32 [rvastatic4]A::a01099 ldc.i4 99 beq a010250 newobj instance void [mscorlib]System.Exception::.ctor() throw a010250: ldsfld int64 [rvastatic4]A::a01085 ldc.i8 85 beq a010251 newobj instance void [mscorlib]System.Exception::.ctor() throw a010251: ldsfld int8 [rvastatic4]A::a01039 ldc.i4 39 beq a010252 newobj instance void [mscorlib]System.Exception::.ctor() throw a010252: ldsfld int64 [rvastatic4]A::a010124 ldc.i8 124 beq a010253 newobj instance void [mscorlib]System.Exception::.ctor() throw a010253: ldsfld int64 [rvastatic4]A::a01055 ldc.i8 55 beq a010254 newobj instance void [mscorlib]System.Exception::.ctor() throw a010254: ldsfld int16 [rvastatic4]A::a0104 ldc.i4 4 beq a010255 newobj instance void [mscorlib]System.Exception::.ctor() throw a010255: ldsfld int64 [rvastatic4]A::a010100 ldc.i8 100 beq a010256 newobj instance void [mscorlib]System.Exception::.ctor() throw a010256: ret} .method static void V4() {.maxstack 50 ldsflda int32 [rvastatic4]A::a0100 conv.i8 ldc.i8 19349 add conv.i8 ldc.i8 19349 sub conv.i ldind.i4 ldc.i4 0 beq a0100 ldstr "a0100" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a0100: ldsflda int64 [rvastatic4]A::a0101 conv.i8 dup ldc.i8 0x0000000000ffffff and ldc.i4 32 shl conv.i8 ldc.i4 32 shr.un or conv.i ldind.i8 ldc.i8 1 beq a0101 ldstr "a0101" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a0101: ldsflda float32 [rvastatic4]A::a0102 conv.r8 ldc.r8 234.098 add conv.r8 ldc.r8 -234.098 add conv.i ldind.r4 ldc.r4 2.0 beq a0102 ldstr "a0102" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a0102: ldsflda int16 [rvastatic4]A::a0103 conv.i8 dup ldc.i8 0x0000000000ffffff and ldc.i4 32 shl conv.i8 ldc.i4 32 shr.un or conv.i ldind.i2 ldc.i4 3 beq a0103 ldstr "a0103" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a0103: ldsflda int16 [rvastatic4]A::a0104 conv.i8 ldc.i8 46081 add conv.i8 ldc.i8 46081 sub conv.i ldind.i2 ldc.i4 4 beq a0104 ldstr "a0104" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a0104: ldsflda int64 [rvastatic4]A::a0105 conv.i8 dup dup xor xor conv.i ldind.i8 ldc.i8 5 beq a0105 ldstr "a0105" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a0105: ldsflda int16 [rvastatic4]A::a0106 conv.r8 ldc.r8 234.098 add conv.r8 ldc.r8 -234.098 add conv.i ldind.i2 ldc.i4 6 beq a0106 ldstr "a0106" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a0106: ldsflda int8 [rvastatic4]A::a0107 conv.i8 conv.r8 conv.u8 conv.i conv.i8 conv.r8 conv.u8 conv.i ldind.i1 ldc.i4 7 beq a0107 ldstr "a0107" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a0107: ldsflda int64 [rvastatic4]A::a0108 conv.i8 ldc.i8 3218 add conv.i8 ldc.i8 3218 sub conv.i ldind.i8 ldc.i8 8 beq a0108 ldstr "a0108" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a0108: ldsflda int32 [rvastatic4]A::a0109 conv.i8 conv.r8 conv.u8 conv.i conv.i8 conv.r8 conv.u8 conv.i ldind.i4 ldc.i4 9 beq a0109 ldstr "a0109" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a0109: ldsflda int16 [rvastatic4]A::a01010 conv.i8 ldc.i8 2 mul ldc.i4 1 shr.un conv.i ldind.i2 ldc.i4 10 beq a01010 ldstr "a01010" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01010: ldsflda float32 [rvastatic4]A::a01011 conv.i8 dup ldc.i8 0x0000000000ffffff and ldc.i4 32 shl conv.i8 ldc.i4 32 shr.un or conv.i ldind.r4 ldc.r4 11.0 beq a01011 ldstr "a01011" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01011: ldsflda int16 [rvastatic4]A::a01012 conv.i8 dup dup xor xor conv.i ldind.i2 ldc.i4 12 beq a01012 ldstr "a01012" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01012: ldsflda float32 [rvastatic4]A::a01013 conv.r8 ldc.r8 234.098 add conv.r8 ldc.r8 -234.098 add conv.i ldind.r4 ldc.r4 13.0 beq a01013 ldstr "a01013" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01013: ldsflda float32 [rvastatic4]A::a01014 conv.i8 dup ldc.i8 0xffffffff00000000 and ldc.i4 32 shr.un conv.i8 ldc.i4 32 shl or conv.i ldind.r4 ldc.r4 14.0 beq a01014 ldstr "a01014" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01014: ldsflda int8 [rvastatic4]A::a01015 conv.i8 conv.r8 conv.u8 conv.i conv.i8 conv.r8 conv.u8 conv.i ldind.i1 ldc.i4 15 beq a01015 ldstr "a01015" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01015: ldsflda float32 [rvastatic4]A::a01016 conv.i8 dup ldc.i8 0xffffffff00000000 and ldc.i4 32 shr.un conv.i8 ldc.i4 32 shl or conv.i ldind.r4 ldc.r4 16.0 beq a01016 ldstr "a01016" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01016: ldsflda int8 [rvastatic4]A::a01017 conv.i8 ldc.i8 15229 add conv.i8 ldc.i8 15229 sub conv.i ldind.i1 ldc.i4 17 beq a01017 ldstr "a01017" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01017: ldsflda float32 [rvastatic4]A::a01018 conv.i8 ldc.i8 2 mul ldc.i4 1 shr.un conv.i ldind.r4 ldc.r4 18.0 beq a01018 ldstr "a01018" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01018: ldsflda float32 [rvastatic4]A::a01019 conv.i8 conv.r8 conv.u8 conv.i conv.i8 conv.r8 conv.u8 conv.i ldind.r4 ldc.r4 19.0 beq a01019 ldstr "a01019" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01019: ldsflda int8 [rvastatic4]A::a01020 conv.i8 ldc.i8 28655 add conv.i8 ldc.i8 28655 sub conv.i ldind.i1 ldc.i4 20 beq a01020 ldstr "a01020" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01020: ldsflda float32 [rvastatic4]A::a01021 conv.i8 ldc.i8 33205 add conv.i8 ldc.i8 33205 sub conv.i ldind.r4 ldc.r4 21.0 beq a01021 ldstr "a01021" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01021: ldsflda int64 [rvastatic4]A::a01022 conv.i8 dup ldc.i8 0x0000000000ffffff and ldc.i4 32 shl conv.i8 ldc.i4 32 shr.un or conv.i ldind.i8 ldc.i8 22 beq a01022 ldstr "a01022" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01022: ldsflda int8 [rvastatic4]A::a01023 conv.i8 conv.r8 conv.u8 conv.i conv.i8 conv.r8 conv.u8 conv.i ldind.i1 ldc.i4 23 beq a01023 ldstr "a01023" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01023: ldsflda int32 [rvastatic4]A::a01024 conv.i8 dup ldc.i8 0x0000000000ffffff and ldc.i4 32 shl conv.i8 ldc.i4 32 shr.un or conv.i ldind.i4 ldc.i4 24 beq a01024 ldstr "a01024" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01024: ldsflda int64 [rvastatic4]A::a01025 conv.i8 dup ldc.i8 0xffffffff00000000 and ldc.i4 32 shr.un conv.i8 ldc.i4 32 shl or conv.i ldind.i8 ldc.i8 25 beq a01025 ldstr "a01025" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01025: ldsflda int16 [rvastatic4]A::a01026 conv.i8 dup dup xor xor conv.i ldind.i2 ldc.i4 26 beq a01026 ldstr "a01026" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01026: ldsflda int8 [rvastatic4]A::a01027 conv.i8 dup ldc.i8 0xffffffff00000000 and ldc.i4 32 shr.un conv.i8 ldc.i4 32 shl or conv.i ldind.i1 ldc.i4 27 beq a01027 ldstr "a01027" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01027: ldsflda int16 [rvastatic4]A::a01028 conv.i8 dup ldc.i8 0xffffffff00000000 and ldc.i4 32 shr.un conv.i8 ldc.i4 32 shl or conv.i ldind.i2 ldc.i4 28 beq a01028 ldstr "a01028" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01028: ldsflda int16 [rvastatic4]A::a01029 conv.i8 dup ldc.i8 0x0000000000ffffff and ldc.i4 32 shl conv.i8 ldc.i4 32 shr.un or conv.i ldind.i2 ldc.i4 29 beq a01029 ldstr "a01029" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01029: ldsflda int8 [rvastatic4]A::a01030 conv.i8 dup dup xor xor conv.i ldind.i1 ldc.i4 30 beq a01030 ldstr "a01030" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01030: ldsflda int8 [rvastatic4]A::a01031 conv.r8 ldc.r8 234.098 add conv.r8 ldc.r8 -234.098 add conv.i ldind.i1 ldc.i4 31 beq a01031 ldstr "a01031" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01031: ldsflda int64 [rvastatic4]A::a01032 conv.r8 ldc.r8 234.098 add conv.r8 ldc.r8 -234.098 add conv.i ldind.i8 ldc.i8 32 beq a01032 ldstr "a01032" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01032: ldsflda float32 [rvastatic4]A::a01033 conv.i8 dup dup xor xor conv.i ldind.r4 ldc.r4 33.0 beq a01033 ldstr "a01033" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01033: ldsflda int16 [rvastatic4]A::a01034 conv.i8 ldc.i8 2 mul ldc.i4 1 shr.un conv.i ldind.i2 ldc.i4 34 beq a01034 ldstr "a01034" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01034: ldsflda int8 [rvastatic4]A::a01035 conv.i8 dup dup xor xor conv.i ldind.i1 ldc.i4 35 beq a01035 ldstr "a01035" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01035: ldsflda int8 [rvastatic4]A::a01036 conv.r8 ldc.r8 234.098 add conv.r8 ldc.r8 -234.098 add conv.i ldind.i1 ldc.i4 36 beq a01036 ldstr "a01036" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01036: ldsflda int32 [rvastatic4]A::a01037 conv.r8 ldc.r8 234.098 add conv.r8 ldc.r8 -234.098 add conv.i ldind.i4 ldc.i4 37 beq a01037 ldstr "a01037" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01037: ldsflda int16 [rvastatic4]A::a01038 conv.i8 dup ldc.i8 0x0000000000ffffff and ldc.i4 32 shl conv.i8 ldc.i4 32 shr.un or conv.i ldind.i2 ldc.i4 38 beq a01038 ldstr "a01038" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01038: ldsflda int8 [rvastatic4]A::a01039 conv.i8 ldc.i8 2 mul ldc.i4 1 shr.un conv.i ldind.i1 ldc.i4 39 beq a01039 ldstr "a01039" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01039: ldsflda int8 [rvastatic4]A::a01040 conv.i8 ldc.i8 65464 add conv.i8 ldc.i8 65464 sub conv.i ldind.i1 ldc.i4 40 beq a01040 ldstr "a01040" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01040: ldsflda int32 [rvastatic4]A::a01041 conv.i8 dup ldc.i8 0xffffffff00000000 and ldc.i4 32 shr.un conv.i8 ldc.i4 32 shl or conv.i ldind.i4 ldc.i4 41 beq a01041 ldstr "a01041" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01041: ldsflda int64 [rvastatic4]A::a01042 conv.i8 conv.r8 conv.u8 conv.i conv.i8 conv.r8 conv.u8 conv.i ldind.i8 ldc.i8 42 beq a01042 ldstr "a01042" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01042: ldsflda int16 [rvastatic4]A::a01043 conv.i8 dup ldc.i8 0x0000000000ffffff and ldc.i4 32 shl conv.i8 ldc.i4 32 shr.un or conv.i ldind.i2 ldc.i4 43 beq a01043 ldstr "a01043" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01043: ldsflda int64 [rvastatic4]A::a01044 conv.i8 conv.r8 conv.u8 conv.i conv.i8 conv.r8 conv.u8 conv.i ldind.i8 ldc.i8 44 beq a01044 ldstr "a01044" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01044: ldsflda int64 [rvastatic4]A::a01045 conv.r8 ldc.r8 234.098 add conv.r8 ldc.r8 -234.098 add conv.i ldind.i8 ldc.i8 45 beq a01045 ldstr "a01045" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01045: ldsflda float32 [rvastatic4]A::a01046 conv.i8 ldc.i8 2 mul ldc.i4 1 shr.un conv.i ldind.r4 ldc.r4 46.0 beq a01046 ldstr "a01046" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01046: ldsflda int16 [rvastatic4]A::a01047 conv.i8 dup dup xor xor conv.i ldind.i2 ldc.i4 47 beq a01047 ldstr "a01047" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01047: ldsflda int64 [rvastatic4]A::a01048 conv.i8 ldc.i8 2 mul ldc.i4 1 shr.un conv.i ldind.i8 ldc.i8 48 beq a01048 ldstr "a01048" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01048: ldsflda int16 [rvastatic4]A::a01049 conv.i8 ldc.i8 2 mul ldc.i4 1 shr.un conv.i ldind.i2 ldc.i4 49 beq a01049 ldstr "a01049" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01049: ldsflda int32 [rvastatic4]A::a01050 conv.i8 dup ldc.i8 0xffffffff00000000 and ldc.i4 32 shr.un conv.i8 ldc.i4 32 shl or conv.i ldind.i4 ldc.i4 50 beq a01050 ldstr "a01050" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01050: ldsflda int16 [rvastatic4]A::a01051 conv.i8 dup dup xor xor conv.i ldind.i2 ldc.i4 51 beq a01051 ldstr "a01051" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01051: ldsflda int32 [rvastatic4]A::a01052 conv.i8 dup ldc.i8 0xffffffff00000000 and ldc.i4 32 shr.un conv.i8 ldc.i4 32 shl or conv.i ldind.i4 ldc.i4 52 beq a01052 ldstr "a01052" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01052: ldsflda int16 [rvastatic4]A::a01053 conv.i8 ldc.i8 26716 add conv.i8 ldc.i8 26716 sub conv.i ldind.i2 ldc.i4 53 beq a01053 ldstr "a01053" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01053: ldsflda float32 [rvastatic4]A::a01054 conv.r8 ldc.r8 234.098 add conv.r8 ldc.r8 -234.098 add conv.i ldind.r4 ldc.r4 54.0 beq a01054 ldstr "a01054" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01054: ldsflda int64 [rvastatic4]A::a01055 conv.i8 dup dup xor xor conv.i ldind.i8 ldc.i8 55 beq a01055 ldstr "a01055" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01055: ldsflda float32 [rvastatic4]A::a01056 conv.i8 dup dup xor xor conv.i ldind.r4 ldc.r4 56.0 beq a01056 ldstr "a01056" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01056: ldsflda int64 [rvastatic4]A::a01057 conv.i8 ldc.i8 62605 add conv.i8 ldc.i8 62605 sub conv.i ldind.i8 ldc.i8 57 beq a01057 ldstr "a01057" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01057: ldsflda int64 [rvastatic4]A::a01058 conv.i8 dup dup xor xor conv.i ldind.i8 ldc.i8 58 beq a01058 ldstr "a01058" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01058: ldsflda int64 [rvastatic4]A::a01059 conv.r8 ldc.r8 234.098 add conv.r8 ldc.r8 -234.098 add conv.i ldind.i8 ldc.i8 59 beq a01059 ldstr "a01059" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01059: ldsflda int16 [rvastatic4]A::a01060 conv.i8 conv.r8 conv.u8 conv.i conv.i8 conv.r8 conv.u8 conv.i ldind.i2 ldc.i4 60 beq a01060 ldstr "a01060" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01060: ldsflda int8 [rvastatic4]A::a01061 conv.i8 dup ldc.i8 0x0000000000ffffff and ldc.i4 32 shl conv.i8 ldc.i4 32 shr.un or conv.i ldind.i1 ldc.i4 61 beq a01061 ldstr "a01061" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01061: ldsflda int64 [rvastatic4]A::a01062 conv.i8 ldc.i8 2 mul ldc.i4 1 shr.un conv.i ldind.i8 ldc.i8 62 beq a01062 ldstr "a01062" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01062: ldsflda int16 [rvastatic4]A::a01063 conv.i8 ldc.i8 2 mul ldc.i4 1 shr.un conv.i ldind.i2 ldc.i4 63 beq a01063 ldstr "a01063" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01063: ldsflda int32 [rvastatic4]A::a01064 conv.i8 ldc.i8 2 mul ldc.i4 1 shr.un conv.i ldind.i4 ldc.i4 64 beq a01064 ldstr "a01064" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01064: ldsflda int16 [rvastatic4]A::a01065 conv.i8 ldc.i8 2 mul ldc.i4 1 shr.un conv.i ldind.i2 ldc.i4 65 beq a01065 ldstr "a01065" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01065: ldsflda int8 [rvastatic4]A::a01066 conv.i8 conv.r8 conv.u8 conv.i conv.i8 conv.r8 conv.u8 conv.i ldind.i1 ldc.i4 66 beq a01066 ldstr "a01066" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01066: ldsflda int16 [rvastatic4]A::a01067 conv.i8 dup ldc.i8 0xffffffff00000000 and ldc.i4 32 shr.un conv.i8 ldc.i4 32 shl or conv.i ldind.i2 ldc.i4 67 beq a01067 ldstr "a01067" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01067: ldsflda int32 [rvastatic4]A::a01068 conv.i8 conv.r8 conv.u8 conv.i conv.i8 conv.r8 conv.u8 conv.i ldind.i4 ldc.i4 68 beq a01068 ldstr "a01068" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01068: ldsflda float32 [rvastatic4]A::a01069 conv.i8 ldc.i8 2 mul ldc.i4 1 shr.un conv.i ldind.r4 ldc.r4 69.0 beq a01069 ldstr "a01069" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01069: ldsflda float32 [rvastatic4]A::a01070 conv.i8 ldc.i8 48606 add conv.i8 ldc.i8 48606 sub conv.i ldind.r4 ldc.r4 70.0 beq a01070 ldstr "a01070" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01070: ldsflda int16 [rvastatic4]A::a01071 conv.r8 ldc.r8 234.098 add conv.r8 ldc.r8 -234.098 add conv.i ldind.i2 ldc.i4 71 beq a01071 ldstr "a01071" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01071: ldsflda float32 [rvastatic4]A::a01072 conv.i8 conv.r8 conv.u8 conv.i conv.i8 conv.r8 conv.u8 conv.i ldind.r4 ldc.r4 72.0 beq a01072 ldstr "a01072" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01072: ldsflda int64 [rvastatic4]A::a01073 conv.i8 ldc.i8 5680 add conv.i8 ldc.i8 5680 sub conv.i ldind.i8 ldc.i8 73 beq a01073 ldstr "a01073" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01073: ldsflda int64 [rvastatic4]A::a01074 conv.i8 ldc.i8 2 mul ldc.i4 1 shr.un conv.i ldind.i8 ldc.i8 74 beq a01074 ldstr "a01074" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01074: ldsflda int32 [rvastatic4]A::a01075 conv.i8 ldc.i8 32361 add conv.i8 ldc.i8 32361 sub conv.i ldind.i4 ldc.i4 75 beq a01075 ldstr "a01075" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01075: ldsflda int8 [rvastatic4]A::a01076 conv.i8 dup ldc.i8 0x0000000000ffffff and ldc.i4 32 shl conv.i8 ldc.i4 32 shr.un or conv.i ldind.i1 ldc.i4 76 beq a01076 ldstr "a01076" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01076: ldsflda int32 [rvastatic4]A::a01077 conv.i8 conv.r8 conv.u8 conv.i conv.i8 conv.r8 conv.u8 conv.i ldind.i4 ldc.i4 77 beq a01077 ldstr "a01077" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01077: ldsflda int16 [rvastatic4]A::a01078 conv.i8 dup ldc.i8 0x0000000000ffffff and ldc.i4 32 shl conv.i8 ldc.i4 32 shr.un or conv.i ldind.i2 ldc.i4 78 beq a01078 ldstr "a01078" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01078: ldsflda float32 [rvastatic4]A::a01079 conv.r8 ldc.r8 234.098 add conv.r8 ldc.r8 -234.098 add conv.i ldind.r4 ldc.r4 79.0 beq a01079 ldstr "a01079" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01079: ldsflda float32 [rvastatic4]A::a01080 conv.i8 dup ldc.i8 0xffffffff00000000 and ldc.i4 32 shr.un conv.i8 ldc.i4 32 shl or conv.i ldind.r4 ldc.r4 80.0 beq a01080 ldstr "a01080" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01080: ldsflda float32 [rvastatic4]A::a01081 conv.i8 conv.r8 conv.u8 conv.i conv.i8 conv.r8 conv.u8 conv.i ldind.r4 ldc.r4 81.0 beq a01081 ldstr "a01081" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01081: ldsflda int32 [rvastatic4]A::a01082 conv.i8 ldc.i8 30180 add conv.i8 ldc.i8 30180 sub conv.i ldind.i4 ldc.i4 82 beq a01082 ldstr "a01082" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01082: ldsflda int8 [rvastatic4]A::a01083 conv.i8 conv.r8 conv.u8 conv.i conv.i8 conv.r8 conv.u8 conv.i ldind.i1 ldc.i4 83 beq a01083 ldstr "a01083" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01083: ldsflda int64 [rvastatic4]A::a01084 conv.i8 dup ldc.i8 0xffffffff00000000 and ldc.i4 32 shr.un conv.i8 ldc.i4 32 shl or conv.i ldind.i8 ldc.i8 84 beq a01084 ldstr "a01084" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01084: ldsflda int64 [rvastatic4]A::a01085 conv.i8 ldc.i8 18787 add conv.i8 ldc.i8 18787 sub conv.i ldind.i8 ldc.i8 85 beq a01085 ldstr "a01085" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01085: ldsflda int32 [rvastatic4]A::a01086 conv.i8 dup dup xor xor conv.i ldind.i4 ldc.i4 86 beq a01086 ldstr "a01086" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01086: ldsflda int32 [rvastatic4]A::a01087 conv.i8 ldc.i8 16913 add conv.i8 ldc.i8 16913 sub conv.i ldind.i4 ldc.i4 87 beq a01087 ldstr "a01087" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01087: ldsflda int8 [rvastatic4]A::a01088 conv.i8 dup ldc.i8 0x0000000000ffffff and ldc.i4 32 shl conv.i8 ldc.i4 32 shr.un or conv.i ldind.i1 ldc.i4 88 beq a01088 ldstr "a01088" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01088: ldsflda int64 [rvastatic4]A::a01089 conv.r8 ldc.r8 234.098 add conv.r8 ldc.r8 -234.098 add conv.i ldind.i8 ldc.i8 89 beq a01089 ldstr "a01089" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01089: ldsflda int8 [rvastatic4]A::a01090 conv.i8 ldc.i8 42807 add conv.i8 ldc.i8 42807 sub conv.i ldind.i1 ldc.i4 90 beq a01090 ldstr "a01090" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01090: ldsflda int16 [rvastatic4]A::a01091 conv.i8 dup ldc.i8 0xffffffff00000000 and ldc.i4 32 shr.un conv.i8 ldc.i4 32 shl or conv.i ldind.i2 ldc.i4 91 beq a01091 ldstr "a01091" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01091: ldsflda float32 [rvastatic4]A::a01092 conv.i8 conv.r8 conv.u8 conv.i conv.i8 conv.r8 conv.u8 conv.i ldind.r4 ldc.r4 92.0 beq a01092 ldstr "a01092" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01092: ldsflda int64 [rvastatic4]A::a01093 conv.i8 ldc.i8 37525 add conv.i8 ldc.i8 37525 sub conv.i ldind.i8 ldc.i8 93 beq a01093 ldstr "a01093" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01093: ldsflda int64 [rvastatic4]A::a01094 conv.r8 ldc.r8 234.098 add conv.r8 ldc.r8 -234.098 add conv.i ldind.i8 ldc.i8 94 beq a01094 ldstr "a01094" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01094: ldsflda int8 [rvastatic4]A::a01095 conv.i8 dup dup xor xor conv.i ldind.i1 ldc.i4 95 beq a01095 ldstr "a01095" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01095: ldsflda float32 [rvastatic4]A::a01096 conv.i8 conv.r8 conv.u8 conv.i conv.i8 conv.r8 conv.u8 conv.i ldind.r4 ldc.r4 96.0 beq a01096 ldstr "a01096" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01096: ldsflda int16 [rvastatic4]A::a01097 conv.i8 ldc.i8 41331 add conv.i8 ldc.i8 41331 sub conv.i ldind.i2 ldc.i4 97 beq a01097 ldstr "a01097" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01097: ldsflda float32 [rvastatic4]A::a01098 conv.i8 conv.r8 conv.u8 conv.i conv.i8 conv.r8 conv.u8 conv.i ldind.r4 ldc.r4 98.0 beq a01098 ldstr "a01098" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01098: ldsflda int32 [rvastatic4]A::a01099 conv.i8 ldc.i8 4072 add conv.i8 ldc.i8 4072 sub conv.i ldind.i4 ldc.i4 99 beq a01099 ldstr "a01099" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01099: ldsflda int64 [rvastatic4]A::a010100 conv.i8 conv.r8 conv.u8 conv.i conv.i8 conv.r8 conv.u8 conv.i ldind.i8 ldc.i8 100 beq a010100 ldstr "a010100" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010100: ldsflda int32 [rvastatic4]A::a010101 conv.i8 dup dup xor xor conv.i ldind.i4 ldc.i4 101 beq a010101 ldstr "a010101" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010101: ldsflda float32 [rvastatic4]A::a010102 conv.i8 conv.r8 conv.u8 conv.i conv.i8 conv.r8 conv.u8 conv.i ldind.r4 ldc.r4 102.0 beq a010102 ldstr "a010102" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010102: ldsflda int64 [rvastatic4]A::a010103 conv.i8 conv.r8 conv.u8 conv.i conv.i8 conv.r8 conv.u8 conv.i ldind.i8 ldc.i8 103 beq a010103 ldstr "a010103" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010103: ldsflda int32 [rvastatic4]A::a010104 conv.r8 ldc.r8 234.098 add conv.r8 ldc.r8 -234.098 add conv.i ldind.i4 ldc.i4 104 beq a010104 ldstr "a010104" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010104: ldsflda int16 [rvastatic4]A::a010105 conv.i8 dup ldc.i8 0x0000000000ffffff and ldc.i4 32 shl conv.i8 ldc.i4 32 shr.un or conv.i ldind.i2 ldc.i4 105 beq a010105 ldstr "a010105" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010105: ldsflda int16 [rvastatic4]A::a010106 conv.i8 ldc.i8 2 mul ldc.i4 1 shr.un conv.i ldind.i2 ldc.i4 106 beq a010106 ldstr "a010106" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010106: ldsflda float32 [rvastatic4]A::a010107 conv.i8 ldc.i8 61555 add conv.i8 ldc.i8 61555 sub conv.i ldind.r4 ldc.r4 107.0 beq a010107 ldstr "a010107" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010107: ldsflda int32 [rvastatic4]A::a010108 conv.i8 dup ldc.i8 0x0000000000ffffff and ldc.i4 32 shl conv.i8 ldc.i4 32 shr.un or conv.i ldind.i4 ldc.i4 108 beq a010108 ldstr "a010108" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010108: ldsflda int16 [rvastatic4]A::a010109 conv.i8 dup ldc.i8 0xffffffff00000000 and ldc.i4 32 shr.un conv.i8 ldc.i4 32 shl or conv.i ldind.i2 ldc.i4 109 beq a010109 ldstr "a010109" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010109: ldsflda int32 [rvastatic4]A::a010110 conv.i8 conv.r8 conv.u8 conv.i conv.i8 conv.r8 conv.u8 conv.i ldind.i4 ldc.i4 110 beq a010110 ldstr "a010110" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010110: ldsflda int32 [rvastatic4]A::a010111 conv.i8 dup dup xor xor conv.i ldind.i4 ldc.i4 111 beq a010111 ldstr "a010111" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010111: ldsflda int32 [rvastatic4]A::a010112 conv.i8 dup dup xor xor conv.i ldind.i4 ldc.i4 112 beq a010112 ldstr "a010112" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010112: ldsflda int64 [rvastatic4]A::a010113 conv.i8 ldc.i8 45274 add conv.i8 ldc.i8 45274 sub conv.i ldind.i8 ldc.i8 113 beq a010113 ldstr "a010113" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010113: ldsflda int64 [rvastatic4]A::a010114 conv.r8 ldc.r8 234.098 add conv.r8 ldc.r8 -234.098 add conv.i ldind.i8 ldc.i8 114 beq a010114 ldstr "a010114" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010114: ldsflda int16 [rvastatic4]A::a010115 conv.i8 dup ldc.i8 0xffffffff00000000 and ldc.i4 32 shr.un conv.i8 ldc.i4 32 shl or conv.i ldind.i2 ldc.i4 115 beq a010115 ldstr "a010115" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010115: ldsflda int64 [rvastatic4]A::a010116 conv.i8 ldc.i8 2 mul ldc.i4 1 shr.un conv.i ldind.i8 ldc.i8 116 beq a010116 ldstr "a010116" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010116: ldsflda int64 [rvastatic4]A::a010117 conv.i8 dup ldc.i8 0xffffffff00000000 and ldc.i4 32 shr.un conv.i8 ldc.i4 32 shl or conv.i ldind.i8 ldc.i8 117 beq a010117 ldstr "a010117" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010117: ldsflda int32 [rvastatic4]A::a010118 conv.i8 ldc.i8 9701 add conv.i8 ldc.i8 9701 sub conv.i ldind.i4 ldc.i4 118 beq a010118 ldstr "a010118" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010118: ldsflda int64 [rvastatic4]A::a010119 conv.r8 ldc.r8 234.098 add conv.r8 ldc.r8 -234.098 add conv.i ldind.i8 ldc.i8 119 beq a010119 ldstr "a010119" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010119: ldsflda int64 [rvastatic4]A::a010120 conv.i8 dup ldc.i8 0x0000000000ffffff and ldc.i4 32 shl conv.i8 ldc.i4 32 shr.un or conv.i ldind.i8 ldc.i8 120 beq a010120 ldstr "a010120" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010120: ldsflda int64 [rvastatic4]A::a010121 conv.i8 dup ldc.i8 0x0000000000ffffff and ldc.i4 32 shl conv.i8 ldc.i4 32 shr.un or conv.i ldind.i8 ldc.i8 121 beq a010121 ldstr "a010121" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010121: ldsflda int16 [rvastatic4]A::a010122 conv.r8 ldc.r8 234.098 add conv.r8 ldc.r8 -234.098 add conv.i ldind.i2 ldc.i4 122 beq a010122 ldstr "a010122" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010122: ldsflda int64 [rvastatic4]A::a010123 conv.i8 ldc.i8 2 mul ldc.i4 1 shr.un conv.i ldind.i8 ldc.i8 123 beq a010123 ldstr "a010123" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010123: ldsflda int64 [rvastatic4]A::a010124 conv.i8 conv.r8 conv.u8 conv.i conv.i8 conv.r8 conv.u8 conv.i ldind.i8 ldc.i8 124 beq a010124 ldstr "a010124" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010124: ldsflda int32 [rvastatic4]A::a010125 conv.i8 conv.r8 conv.u8 conv.i conv.i8 conv.r8 conv.u8 conv.i ldind.i4 ldc.i4 125 beq a010125 ldstr "a010125" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010125: ldsflda int16 [rvastatic4]A::a010126 conv.i8 dup dup xor xor conv.i ldind.i2 ldc.i4 126 beq a010126 ldstr "a010126" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010126: ldsflda int16 [rvastatic4]A::a010127 conv.i8 dup ldc.i8 0xffffffff00000000 and ldc.i4 32 shr.un conv.i8 ldc.i4 32 shl or conv.i ldind.i2 ldc.i4 127 beq a010127 ldstr "a010127" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010127: ret} .method static void V5() {.maxstack 50 ldsflda int32 [rvastatic4]A::a0100 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i4 ldc.i4 0 beq a0100 ldstr "a0100" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a0100: ldsflda int64 [rvastatic4]A::a0101 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i8 ldc.i8 1 beq a0101 ldstr "a0101" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a0101: ldsflda float32 [rvastatic4]A::a0102 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.r4 ldc.r4 2.0 beq a0102 ldstr "a0102" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a0102: ldsflda int16 [rvastatic4]A::a0103 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i2 ldc.i4 3 beq a0103 ldstr "a0103" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a0103: ldsflda int16 [rvastatic4]A::a0104 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i2 ldc.i4 4 beq a0104 ldstr "a0104" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a0104: ldsflda int64 [rvastatic4]A::a0105 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i8 ldc.i8 5 beq a0105 ldstr "a0105" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a0105: ldsflda int16 [rvastatic4]A::a0106 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.i2 ldc.i4 6 beq a0106 ldstr "a0106" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a0106: ldsflda int8 [rvastatic4]A::a0107 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i1 ldc.i4 7 beq a0107 ldstr "a0107" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a0107: ldsflda int64 [rvastatic4]A::a0108 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i8 ldc.i8 8 beq a0108 ldstr "a0108" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a0108: ldsflda int32 [rvastatic4]A::a0109 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i4 ldc.i4 9 beq a0109 ldstr "a0109" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a0109: ldsflda int16 [rvastatic4]A::a01010 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.i2 ldc.i4 10 beq a01010 ldstr "a01010" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01010: ldsflda float32 [rvastatic4]A::a01011 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.r4 ldc.r4 11.0 beq a01011 ldstr "a01011" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01011: ldsflda int16 [rvastatic4]A::a01012 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i2 ldc.i4 12 beq a01012 ldstr "a01012" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01012: ldsflda float32 [rvastatic4]A::a01013 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.r4 ldc.r4 13.0 beq a01013 ldstr "a01013" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01013: ldsflda float32 [rvastatic4]A::a01014 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.r4 ldc.r4 14.0 beq a01014 ldstr "a01014" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01014: ldsflda int8 [rvastatic4]A::a01015 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i1 ldc.i4 15 beq a01015 ldstr "a01015" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01015: ldsflda float32 [rvastatic4]A::a01016 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.r4 ldc.r4 16.0 beq a01016 ldstr "a01016" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01016: ldsflda int8 [rvastatic4]A::a01017 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i1 ldc.i4 17 beq a01017 ldstr "a01017" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01017: ldsflda float32 [rvastatic4]A::a01018 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.r4 ldc.r4 18.0 beq a01018 ldstr "a01018" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01018: ldsflda float32 [rvastatic4]A::a01019 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.r4 ldc.r4 19.0 beq a01019 ldstr "a01019" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01019: ldsflda int8 [rvastatic4]A::a01020 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i1 ldc.i4 20 beq a01020 ldstr "a01020" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01020: ldsflda float32 [rvastatic4]A::a01021 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.r4 ldc.r4 21.0 beq a01021 ldstr "a01021" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01021: ldsflda int64 [rvastatic4]A::a01022 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i8 ldc.i8 22 beq a01022 ldstr "a01022" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01022: ldsflda int8 [rvastatic4]A::a01023 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i1 ldc.i4 23 beq a01023 ldstr "a01023" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01023: ldsflda int32 [rvastatic4]A::a01024 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.i4 ldc.i4 24 beq a01024 ldstr "a01024" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01024: ldsflda int64 [rvastatic4]A::a01025 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.i8 ldc.i8 25 beq a01025 ldstr "a01025" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01025: ldsflda int16 [rvastatic4]A::a01026 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i2 ldc.i4 26 beq a01026 ldstr "a01026" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01026: ldsflda int8 [rvastatic4]A::a01027 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i1 ldc.i4 27 beq a01027 ldstr "a01027" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01027: ldsflda int16 [rvastatic4]A::a01028 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.i2 ldc.i4 28 beq a01028 ldstr "a01028" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01028: ldsflda int16 [rvastatic4]A::a01029 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i2 ldc.i4 29 beq a01029 ldstr "a01029" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01029: ldsflda int8 [rvastatic4]A::a01030 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i1 ldc.i4 30 beq a01030 ldstr "a01030" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01030: ldsflda int8 [rvastatic4]A::a01031 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.i1 ldc.i4 31 beq a01031 ldstr "a01031" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01031: ldsflda int64 [rvastatic4]A::a01032 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i8 ldc.i8 32 beq a01032 ldstr "a01032" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01032: ldsflda float32 [rvastatic4]A::a01033 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.r4 ldc.r4 33.0 beq a01033 ldstr "a01033" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01033: ldsflda int16 [rvastatic4]A::a01034 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i2 ldc.i4 34 beq a01034 ldstr "a01034" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01034: ldsflda int8 [rvastatic4]A::a01035 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i1 ldc.i4 35 beq a01035 ldstr "a01035" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01035: ldsflda int8 [rvastatic4]A::a01036 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i1 ldc.i4 36 beq a01036 ldstr "a01036" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01036: ldsflda int32 [rvastatic4]A::a01037 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.i4 ldc.i4 37 beq a01037 ldstr "a01037" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01037: ldsflda int16 [rvastatic4]A::a01038 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.i2 ldc.i4 38 beq a01038 ldstr "a01038" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01038: ldsflda int8 [rvastatic4]A::a01039 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i1 ldc.i4 39 beq a01039 ldstr "a01039" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01039: ldsflda int8 [rvastatic4]A::a01040 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.i1 ldc.i4 40 beq a01040 ldstr "a01040" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01040: ldsflda int32 [rvastatic4]A::a01041 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.i4 ldc.i4 41 beq a01041 ldstr "a01041" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01041: ldsflda int64 [rvastatic4]A::a01042 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i8 ldc.i8 42 beq a01042 ldstr "a01042" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01042: ldsflda int16 [rvastatic4]A::a01043 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i2 ldc.i4 43 beq a01043 ldstr "a01043" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01043: ldsflda int64 [rvastatic4]A::a01044 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i8 ldc.i8 44 beq a01044 ldstr "a01044" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01044: ldsflda int64 [rvastatic4]A::a01045 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i8 ldc.i8 45 beq a01045 ldstr "a01045" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01045: ldsflda float32 [rvastatic4]A::a01046 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.r4 ldc.r4 46.0 beq a01046 ldstr "a01046" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01046: ldsflda int16 [rvastatic4]A::a01047 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i2 ldc.i4 47 beq a01047 ldstr "a01047" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01047: ldsflda int64 [rvastatic4]A::a01048 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i8 ldc.i8 48 beq a01048 ldstr "a01048" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01048: ldsflda int16 [rvastatic4]A::a01049 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i2 ldc.i4 49 beq a01049 ldstr "a01049" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01049: ldsflda int32 [rvastatic4]A::a01050 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i4 ldc.i4 50 beq a01050 ldstr "a01050" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01050: ldsflda int16 [rvastatic4]A::a01051 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i2 ldc.i4 51 beq a01051 ldstr "a01051" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01051: ldsflda int32 [rvastatic4]A::a01052 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i4 ldc.i4 52 beq a01052 ldstr "a01052" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01052: ldsflda int16 [rvastatic4]A::a01053 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i2 ldc.i4 53 beq a01053 ldstr "a01053" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01053: ldsflda float32 [rvastatic4]A::a01054 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.r4 ldc.r4 54.0 beq a01054 ldstr "a01054" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01054: ldsflda int64 [rvastatic4]A::a01055 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i8 ldc.i8 55 beq a01055 ldstr "a01055" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01055: ldsflda float32 [rvastatic4]A::a01056 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.r4 ldc.r4 56.0 beq a01056 ldstr "a01056" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01056: ldsflda int64 [rvastatic4]A::a01057 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i8 ldc.i8 57 beq a01057 ldstr "a01057" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01057: ldsflda int64 [rvastatic4]A::a01058 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i8 ldc.i8 58 beq a01058 ldstr "a01058" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01058: ldsflda int64 [rvastatic4]A::a01059 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i8 ldc.i8 59 beq a01059 ldstr "a01059" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01059: ldsflda int16 [rvastatic4]A::a01060 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.i2 ldc.i4 60 beq a01060 ldstr "a01060" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01060: ldsflda int8 [rvastatic4]A::a01061 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i1 ldc.i4 61 beq a01061 ldstr "a01061" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01061: ldsflda int64 [rvastatic4]A::a01062 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i8 ldc.i8 62 beq a01062 ldstr "a01062" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01062: ldsflda int16 [rvastatic4]A::a01063 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i2 ldc.i4 63 beq a01063 ldstr "a01063" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01063: ldsflda int32 [rvastatic4]A::a01064 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.i4 ldc.i4 64 beq a01064 ldstr "a01064" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01064: ldsflda int16 [rvastatic4]A::a01065 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.i2 ldc.i4 65 beq a01065 ldstr "a01065" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01065: ldsflda int8 [rvastatic4]A::a01066 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.i1 ldc.i4 66 beq a01066 ldstr "a01066" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01066: ldsflda int16 [rvastatic4]A::a01067 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i2 ldc.i4 67 beq a01067 ldstr "a01067" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01067: ldsflda int32 [rvastatic4]A::a01068 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.i4 ldc.i4 68 beq a01068 ldstr "a01068" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01068: ldsflda float32 [rvastatic4]A::a01069 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.r4 ldc.r4 69.0 beq a01069 ldstr "a01069" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01069: ldsflda float32 [rvastatic4]A::a01070 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.r4 ldc.r4 70.0 beq a01070 ldstr "a01070" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01070: ldsflda int16 [rvastatic4]A::a01071 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i2 ldc.i4 71 beq a01071 ldstr "a01071" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01071: ldsflda float32 [rvastatic4]A::a01072 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.r4 ldc.r4 72.0 beq a01072 ldstr "a01072" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01072: ldsflda int64 [rvastatic4]A::a01073 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i8 ldc.i8 73 beq a01073 ldstr "a01073" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01073: ldsflda int64 [rvastatic4]A::a01074 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i8 ldc.i8 74 beq a01074 ldstr "a01074" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01074: ldsflda int32 [rvastatic4]A::a01075 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i4 ldc.i4 75 beq a01075 ldstr "a01075" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01075: ldsflda int8 [rvastatic4]A::a01076 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.i1 ldc.i4 76 beq a01076 ldstr "a01076" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01076: ldsflda int32 [rvastatic4]A::a01077 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i4 ldc.i4 77 beq a01077 ldstr "a01077" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01077: ldsflda int16 [rvastatic4]A::a01078 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i2 ldc.i4 78 beq a01078 ldstr "a01078" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01078: ldsflda float32 [rvastatic4]A::a01079 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.r4 ldc.r4 79.0 beq a01079 ldstr "a01079" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01079: ldsflda float32 [rvastatic4]A::a01080 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.r4 ldc.r4 80.0 beq a01080 ldstr "a01080" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01080: ldsflda float32 [rvastatic4]A::a01081 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.r4 ldc.r4 81.0 beq a01081 ldstr "a01081" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01081: ldsflda int32 [rvastatic4]A::a01082 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i4 ldc.i4 82 beq a01082 ldstr "a01082" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01082: ldsflda int8 [rvastatic4]A::a01083 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i1 ldc.i4 83 beq a01083 ldstr "a01083" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01083: ldsflda int64 [rvastatic4]A::a01084 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.i8 ldc.i8 84 beq a01084 ldstr "a01084" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01084: ldsflda int64 [rvastatic4]A::a01085 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i8 ldc.i8 85 beq a01085 ldstr "a01085" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01085: ldsflda int32 [rvastatic4]A::a01086 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.i4 ldc.i4 86 beq a01086 ldstr "a01086" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01086: ldsflda int32 [rvastatic4]A::a01087 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i4 ldc.i4 87 beq a01087 ldstr "a01087" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01087: ldsflda int8 [rvastatic4]A::a01088 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i1 ldc.i4 88 beq a01088 ldstr "a01088" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01088: ldsflda int64 [rvastatic4]A::a01089 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i8 ldc.i8 89 beq a01089 ldstr "a01089" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01089: ldsflda int8 [rvastatic4]A::a01090 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.i1 ldc.i4 90 beq a01090 ldstr "a01090" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01090: ldsflda int16 [rvastatic4]A::a01091 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i2 ldc.i4 91 beq a01091 ldstr "a01091" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01091: ldsflda float32 [rvastatic4]A::a01092 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.r4 ldc.r4 92.0 beq a01092 ldstr "a01092" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01092: ldsflda int64 [rvastatic4]A::a01093 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i8 ldc.i8 93 beq a01093 ldstr "a01093" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01093: ldsflda int64 [rvastatic4]A::a01094 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i8 ldc.i8 94 beq a01094 ldstr "a01094" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01094: ldsflda int8 [rvastatic4]A::a01095 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i1 ldc.i4 95 beq a01095 ldstr "a01095" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01095: ldsflda float32 [rvastatic4]A::a01096 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.r4 ldc.r4 96.0 beq a01096 ldstr "a01096" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01096: ldsflda int16 [rvastatic4]A::a01097 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i2 ldc.i4 97 beq a01097 ldstr "a01097" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01097: ldsflda float32 [rvastatic4]A::a01098 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.r4 ldc.r4 98.0 beq a01098 ldstr "a01098" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01098: ldsflda int32 [rvastatic4]A::a01099 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i4 ldc.i4 99 beq a01099 ldstr "a01099" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a01099: ldsflda int64 [rvastatic4]A::a010100 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i8 ldc.i8 100 beq a010100 ldstr "a010100" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010100: ldsflda int32 [rvastatic4]A::a010101 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i4 ldc.i4 101 beq a010101 ldstr "a010101" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010101: ldsflda float32 [rvastatic4]A::a010102 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.r4 ldc.r4 102.0 beq a010102 ldstr "a010102" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010102: ldsflda int64 [rvastatic4]A::a010103 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.i8 ldc.i8 103 beq a010103 ldstr "a010103" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010103: ldsflda int32 [rvastatic4]A::a010104 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i4 ldc.i4 104 beq a010104 ldstr "a010104" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010104: ldsflda int16 [rvastatic4]A::a010105 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.i2 ldc.i4 105 beq a010105 ldstr "a010105" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010105: ldsflda int16 [rvastatic4]A::a010106 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i2 ldc.i4 106 beq a010106 ldstr "a010106" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010106: ldsflda float32 [rvastatic4]A::a010107 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.r4 ldc.r4 107.0 beq a010107 ldstr "a010107" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010107: ldsflda int32 [rvastatic4]A::a010108 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i4 ldc.i4 108 beq a010108 ldstr "a010108" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010108: ldsflda int16 [rvastatic4]A::a010109 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i2 ldc.i4 109 beq a010109 ldstr "a010109" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010109: ldsflda int32 [rvastatic4]A::a010110 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i4 ldc.i4 110 beq a010110 ldstr "a010110" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010110: ldsflda int32 [rvastatic4]A::a010111 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i4 ldc.i4 111 beq a010111 ldstr "a010111" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010111: ldsflda int32 [rvastatic4]A::a010112 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i4 ldc.i4 112 beq a010112 ldstr "a010112" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010112: ldsflda int64 [rvastatic4]A::a010113 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i8 ldc.i8 113 beq a010113 ldstr "a010113" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010113: ldsflda int64 [rvastatic4]A::a010114 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i8 ldc.i8 114 beq a010114 ldstr "a010114" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010114: ldsflda int16 [rvastatic4]A::a010115 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i2 ldc.i4 115 beq a010115 ldstr "a010115" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010115: ldsflda int64 [rvastatic4]A::a010116 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i8 ldc.i8 116 beq a010116 ldstr "a010116" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010116: ldsflda int64 [rvastatic4]A::a010117 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.i8 ldc.i8 117 beq a010117 ldstr "a010117" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010117: ldsflda int32 [rvastatic4]A::a010118 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i4 ldc.i4 118 beq a010118 ldstr "a010118" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010118: ldsflda int64 [rvastatic4]A::a010119 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i8 ldc.i8 119 beq a010119 ldstr "a010119" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010119: ldsflda int64 [rvastatic4]A::a010120 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i8 ldc.i8 120 beq a010120 ldstr "a010120" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010120: ldsflda int64 [rvastatic4]A::a010121 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.i8 ldc.i8 121 beq a010121 ldstr "a010121" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010121: ldsflda int16 [rvastatic4]A::a010122 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.i2 ldc.i4 122 beq a010122 ldstr "a010122" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010122: ldsflda int64 [rvastatic4]A::a010123 conv.i8 call native int [rvastatic4]A::Call1(int64) ldind.i8 ldc.i8 123 beq a010123 ldstr "a010123" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010123: ldsflda int64 [rvastatic4]A::a010124 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i8 ldc.i8 124 beq a010124 ldstr "a010124" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010124: ldsflda int32 [rvastatic4]A::a010125 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i4 ldc.i4 125 beq a010125 ldstr "a010125" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010125: ldsflda int16 [rvastatic4]A::a010126 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i2 ldc.i4 126 beq a010126 ldstr "a010126" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010126: ldsflda int16 [rvastatic4]A::a010127 conv.r8 call native int [rvastatic4]A::Call2(float64) ldind.i2 ldc.i4 127 beq a010127 ldstr "a010127" newobj instance void [mscorlib]System.Exception::.ctor(string) throw a010127: ret} .method static void V6() {.maxstack 50 ldsfld int32 [rvastatic4]A::a0100 ldc.i4 1 add stsfld int32 [rvastatic4]A::a0100 ldsfld int32 [rvastatic4]A::a0100 ldc.i4 1 beq a0100 newobj instance void [mscorlib]System.Exception::.ctor() throw a0100: ldsfld int64 [rvastatic4]A::a0101 ldc.i8 1 add stsfld int64 [rvastatic4]A::a0101 ldsfld int64 [rvastatic4]A::a0101 ldc.i8 2 beq a0101 newobj instance void [mscorlib]System.Exception::.ctor() throw a0101: ldsfld float32 [rvastatic4]A::a0102 ldc.r4 1 add stsfld float32 [rvastatic4]A::a0102 ldsfld float32 [rvastatic4]A::a0102 ldc.r4 3.0 beq a0102 newobj instance void [mscorlib]System.Exception::.ctor() throw a0102: ldsfld int16 [rvastatic4]A::a0103 ldc.i4 1 add stsfld int16 [rvastatic4]A::a0103 ldsfld int16 [rvastatic4]A::a0103 ldc.i4 4 beq a0103 newobj instance void [mscorlib]System.Exception::.ctor() throw a0103: ldsfld int16 [rvastatic4]A::a0104 ldc.i4 1 add stsfld int16 [rvastatic4]A::a0104 ldsfld int16 [rvastatic4]A::a0104 ldc.i4 5 beq a0104 newobj instance void [mscorlib]System.Exception::.ctor() throw a0104: ldsfld int64 [rvastatic4]A::a0105 ldc.i8 1 add stsfld int64 [rvastatic4]A::a0105 ldsfld int64 [rvastatic4]A::a0105 ldc.i8 6 beq a0105 newobj instance void [mscorlib]System.Exception::.ctor() throw a0105: ldsfld int16 [rvastatic4]A::a0106 ldc.i4 1 add stsfld int16 [rvastatic4]A::a0106 ldsfld int16 [rvastatic4]A::a0106 ldc.i4 7 beq a0106 newobj instance void [mscorlib]System.Exception::.ctor() throw a0106: ldsfld int8 [rvastatic4]A::a0107 ldc.i4 1 add stsfld int8 [rvastatic4]A::a0107 ldsfld int8 [rvastatic4]A::a0107 ldc.i4 8 beq a0107 newobj instance void [mscorlib]System.Exception::.ctor() throw a0107: ldsfld int64 [rvastatic4]A::a0108 ldc.i8 1 add stsfld int64 [rvastatic4]A::a0108 ldsfld int64 [rvastatic4]A::a0108 ldc.i8 9 beq a0108 newobj instance void [mscorlib]System.Exception::.ctor() throw a0108: ldsfld int32 [rvastatic4]A::a0109 ldc.i4 1 add stsfld int32 [rvastatic4]A::a0109 ldsfld int32 [rvastatic4]A::a0109 ldc.i4 10 beq a0109 newobj instance void [mscorlib]System.Exception::.ctor() throw a0109: ldsfld int16 [rvastatic4]A::a01010 ldc.i4 1 add stsfld int16 [rvastatic4]A::a01010 ldsfld int16 [rvastatic4]A::a01010 ldc.i4 11 beq a01010 newobj instance void [mscorlib]System.Exception::.ctor() throw a01010: ldsfld float32 [rvastatic4]A::a01011 ldc.r4 1 add stsfld float32 [rvastatic4]A::a01011 ldsfld float32 [rvastatic4]A::a01011 ldc.r4 12.0 beq a01011 newobj instance void [mscorlib]System.Exception::.ctor() throw a01011: ldsfld int16 [rvastatic4]A::a01012 ldc.i4 1 add stsfld int16 [rvastatic4]A::a01012 ldsfld int16 [rvastatic4]A::a01012 ldc.i4 13 beq a01012 newobj instance void [mscorlib]System.Exception::.ctor() throw a01012: ldsfld float32 [rvastatic4]A::a01013 ldc.r4 1 add stsfld float32 [rvastatic4]A::a01013 ldsfld float32 [rvastatic4]A::a01013 ldc.r4 14.0 beq a01013 newobj instance void [mscorlib]System.Exception::.ctor() throw a01013: ldsfld float32 [rvastatic4]A::a01014 ldc.r4 1 add stsfld float32 [rvastatic4]A::a01014 ldsfld float32 [rvastatic4]A::a01014 ldc.r4 15.0 beq a01014 newobj instance void [mscorlib]System.Exception::.ctor() throw a01014: ldsfld int8 [rvastatic4]A::a01015 ldc.i4 1 add stsfld int8 [rvastatic4]A::a01015 ldsfld int8 [rvastatic4]A::a01015 ldc.i4 16 beq a01015 newobj instance void [mscorlib]System.Exception::.ctor() throw a01015: ldsfld float32 [rvastatic4]A::a01016 ldc.r4 1 add stsfld float32 [rvastatic4]A::a01016 ldsfld float32 [rvastatic4]A::a01016 ldc.r4 17.0 beq a01016 newobj instance void [mscorlib]System.Exception::.ctor() throw a01016: ldsfld int8 [rvastatic4]A::a01017 ldc.i4 1 add stsfld int8 [rvastatic4]A::a01017 ldsfld int8 [rvastatic4]A::a01017 ldc.i4 18 beq a01017 newobj instance void [mscorlib]System.Exception::.ctor() throw a01017: ldsfld float32 [rvastatic4]A::a01018 ldc.r4 1 add stsfld float32 [rvastatic4]A::a01018 ldsfld float32 [rvastatic4]A::a01018 ldc.r4 19.0 beq a01018 newobj instance void [mscorlib]System.Exception::.ctor() throw a01018: ldsfld float32 [rvastatic4]A::a01019 ldc.r4 1 add stsfld float32 [rvastatic4]A::a01019 ldsfld float32 [rvastatic4]A::a01019 ldc.r4 20.0 beq a01019 newobj instance void [mscorlib]System.Exception::.ctor() throw a01019: ldsfld int8 [rvastatic4]A::a01020 ldc.i4 1 add stsfld int8 [rvastatic4]A::a01020 ldsfld int8 [rvastatic4]A::a01020 ldc.i4 21 beq a01020 newobj instance void [mscorlib]System.Exception::.ctor() throw a01020: ldsfld float32 [rvastatic4]A::a01021 ldc.r4 1 add stsfld float32 [rvastatic4]A::a01021 ldsfld float32 [rvastatic4]A::a01021 ldc.r4 22.0 beq a01021 newobj instance void [mscorlib]System.Exception::.ctor() throw a01021: ldsfld int64 [rvastatic4]A::a01022 ldc.i8 1 add stsfld int64 [rvastatic4]A::a01022 ldsfld int64 [rvastatic4]A::a01022 ldc.i8 23 beq a01022 newobj instance void [mscorlib]System.Exception::.ctor() throw a01022: ldsfld int8 [rvastatic4]A::a01023 ldc.i4 1 add stsfld int8 [rvastatic4]A::a01023 ldsfld int8 [rvastatic4]A::a01023 ldc.i4 24 beq a01023 newobj instance void [mscorlib]System.Exception::.ctor() throw a01023: ldsfld int32 [rvastatic4]A::a01024 ldc.i4 1 add stsfld int32 [rvastatic4]A::a01024 ldsfld int32 [rvastatic4]A::a01024 ldc.i4 25 beq a01024 newobj instance void [mscorlib]System.Exception::.ctor() throw a01024: ldsfld int64 [rvastatic4]A::a01025 ldc.i8 1 add stsfld int64 [rvastatic4]A::a01025 ldsfld int64 [rvastatic4]A::a01025 ldc.i8 26 beq a01025 newobj instance void [mscorlib]System.Exception::.ctor() throw a01025: ldsfld int16 [rvastatic4]A::a01026 ldc.i4 1 add stsfld int16 [rvastatic4]A::a01026 ldsfld int16 [rvastatic4]A::a01026 ldc.i4 27 beq a01026 newobj instance void [mscorlib]System.Exception::.ctor() throw a01026: ldsfld int8 [rvastatic4]A::a01027 ldc.i4 1 add stsfld int8 [rvastatic4]A::a01027 ldsfld int8 [rvastatic4]A::a01027 ldc.i4 28 beq a01027 newobj instance void [mscorlib]System.Exception::.ctor() throw a01027: ldsfld int16 [rvastatic4]A::a01028 ldc.i4 1 add stsfld int16 [rvastatic4]A::a01028 ldsfld int16 [rvastatic4]A::a01028 ldc.i4 29 beq a01028 newobj instance void [mscorlib]System.Exception::.ctor() throw a01028: ldsfld int16 [rvastatic4]A::a01029 ldc.i4 1 add stsfld int16 [rvastatic4]A::a01029 ldsfld int16 [rvastatic4]A::a01029 ldc.i4 30 beq a01029 newobj instance void [mscorlib]System.Exception::.ctor() throw a01029: ldsfld int8 [rvastatic4]A::a01030 ldc.i4 1 add stsfld int8 [rvastatic4]A::a01030 ldsfld int8 [rvastatic4]A::a01030 ldc.i4 31 beq a01030 newobj instance void [mscorlib]System.Exception::.ctor() throw a01030: ldsfld int8 [rvastatic4]A::a01031 ldc.i4 1 add stsfld int8 [rvastatic4]A::a01031 ldsfld int8 [rvastatic4]A::a01031 ldc.i4 32 beq a01031 newobj instance void [mscorlib]System.Exception::.ctor() throw a01031: ldsfld int64 [rvastatic4]A::a01032 ldc.i8 1 add stsfld int64 [rvastatic4]A::a01032 ldsfld int64 [rvastatic4]A::a01032 ldc.i8 33 beq a01032 newobj instance void [mscorlib]System.Exception::.ctor() throw a01032: ldsfld float32 [rvastatic4]A::a01033 ldc.r4 1 add stsfld float32 [rvastatic4]A::a01033 ldsfld float32 [rvastatic4]A::a01033 ldc.r4 34.0 beq a01033 newobj instance void [mscorlib]System.Exception::.ctor() throw a01033: ldsfld int16 [rvastatic4]A::a01034 ldc.i4 1 add stsfld int16 [rvastatic4]A::a01034 ldsfld int16 [rvastatic4]A::a01034 ldc.i4 35 beq a01034 newobj instance void [mscorlib]System.Exception::.ctor() throw a01034: ldsfld int8 [rvastatic4]A::a01035 ldc.i4 1 add stsfld int8 [rvastatic4]A::a01035 ldsfld int8 [rvastatic4]A::a01035 ldc.i4 36 beq a01035 newobj instance void [mscorlib]System.Exception::.ctor() throw a01035: ldsfld int8 [rvastatic4]A::a01036 ldc.i4 1 add stsfld int8 [rvastatic4]A::a01036 ldsfld int8 [rvastatic4]A::a01036 ldc.i4 37 beq a01036 newobj instance void [mscorlib]System.Exception::.ctor() throw a01036: ldsfld int32 [rvastatic4]A::a01037 ldc.i4 1 add stsfld int32 [rvastatic4]A::a01037 ldsfld int32 [rvastatic4]A::a01037 ldc.i4 38 beq a01037 newobj instance void [mscorlib]System.Exception::.ctor() throw a01037: ldsfld int16 [rvastatic4]A::a01038 ldc.i4 1 add stsfld int16 [rvastatic4]A::a01038 ldsfld int16 [rvastatic4]A::a01038 ldc.i4 39 beq a01038 newobj instance void [mscorlib]System.Exception::.ctor() throw a01038: ldsfld int8 [rvastatic4]A::a01039 ldc.i4 1 add stsfld int8 [rvastatic4]A::a01039 ldsfld int8 [rvastatic4]A::a01039 ldc.i4 40 beq a01039 newobj instance void [mscorlib]System.Exception::.ctor() throw a01039: ldsfld int8 [rvastatic4]A::a01040 ldc.i4 1 add stsfld int8 [rvastatic4]A::a01040 ldsfld int8 [rvastatic4]A::a01040 ldc.i4 41 beq a01040 newobj instance void [mscorlib]System.Exception::.ctor() throw a01040: ldsfld int32 [rvastatic4]A::a01041 ldc.i4 1 add stsfld int32 [rvastatic4]A::a01041 ldsfld int32 [rvastatic4]A::a01041 ldc.i4 42 beq a01041 newobj instance void [mscorlib]System.Exception::.ctor() throw a01041: ldsfld int64 [rvastatic4]A::a01042 ldc.i8 1 add stsfld int64 [rvastatic4]A::a01042 ldsfld int64 [rvastatic4]A::a01042 ldc.i8 43 beq a01042 newobj instance void [mscorlib]System.Exception::.ctor() throw a01042: ldsfld int16 [rvastatic4]A::a01043 ldc.i4 1 add stsfld int16 [rvastatic4]A::a01043 ldsfld int16 [rvastatic4]A::a01043 ldc.i4 44 beq a01043 newobj instance void [mscorlib]System.Exception::.ctor() throw a01043: ldsfld int64 [rvastatic4]A::a01044 ldc.i8 1 add stsfld int64 [rvastatic4]A::a01044 ldsfld int64 [rvastatic4]A::a01044 ldc.i8 45 beq a01044 newobj instance void [mscorlib]System.Exception::.ctor() throw a01044: ldsfld int64 [rvastatic4]A::a01045 ldc.i8 1 add stsfld int64 [rvastatic4]A::a01045 ldsfld int64 [rvastatic4]A::a01045 ldc.i8 46 beq a01045 newobj instance void [mscorlib]System.Exception::.ctor() throw a01045: ldsfld float32 [rvastatic4]A::a01046 ldc.r4 1 add stsfld float32 [rvastatic4]A::a01046 ldsfld float32 [rvastatic4]A::a01046 ldc.r4 47.0 beq a01046 newobj instance void [mscorlib]System.Exception::.ctor() throw a01046: ldsfld int16 [rvastatic4]A::a01047 ldc.i4 1 add stsfld int16 [rvastatic4]A::a01047 ldsfld int16 [rvastatic4]A::a01047 ldc.i4 48 beq a01047 newobj instance void [mscorlib]System.Exception::.ctor() throw a01047: ldsfld int64 [rvastatic4]A::a01048 ldc.i8 1 add stsfld int64 [rvastatic4]A::a01048 ldsfld int64 [rvastatic4]A::a01048 ldc.i8 49 beq a01048 newobj instance void [mscorlib]System.Exception::.ctor() throw a01048: ldsfld int16 [rvastatic4]A::a01049 ldc.i4 1 add stsfld int16 [rvastatic4]A::a01049 ldsfld int16 [rvastatic4]A::a01049 ldc.i4 50 beq a01049 newobj instance void [mscorlib]System.Exception::.ctor() throw a01049: ldsfld int32 [rvastatic4]A::a01050 ldc.i4 1 add stsfld int32 [rvastatic4]A::a01050 ldsfld int32 [rvastatic4]A::a01050 ldc.i4 51 beq a01050 newobj instance void [mscorlib]System.Exception::.ctor() throw a01050: ldsfld int16 [rvastatic4]A::a01051 ldc.i4 1 add stsfld int16 [rvastatic4]A::a01051 ldsfld int16 [rvastatic4]A::a01051 ldc.i4 52 beq a01051 newobj instance void [mscorlib]System.Exception::.ctor() throw a01051: ldsfld int32 [rvastatic4]A::a01052 ldc.i4 1 add stsfld int32 [rvastatic4]A::a01052 ldsfld int32 [rvastatic4]A::a01052 ldc.i4 53 beq a01052 newobj instance void [mscorlib]System.Exception::.ctor() throw a01052: ldsfld int16 [rvastatic4]A::a01053 ldc.i4 1 add stsfld int16 [rvastatic4]A::a01053 ldsfld int16 [rvastatic4]A::a01053 ldc.i4 54 beq a01053 newobj instance void [mscorlib]System.Exception::.ctor() throw a01053: ldsfld float32 [rvastatic4]A::a01054 ldc.r4 1 add stsfld float32 [rvastatic4]A::a01054 ldsfld float32 [rvastatic4]A::a01054 ldc.r4 55.0 beq a01054 newobj instance void [mscorlib]System.Exception::.ctor() throw a01054: ldsfld int64 [rvastatic4]A::a01055 ldc.i8 1 add stsfld int64 [rvastatic4]A::a01055 ldsfld int64 [rvastatic4]A::a01055 ldc.i8 56 beq a01055 newobj instance void [mscorlib]System.Exception::.ctor() throw a01055: ldsfld float32 [rvastatic4]A::a01056 ldc.r4 1 add stsfld float32 [rvastatic4]A::a01056 ldsfld float32 [rvastatic4]A::a01056 ldc.r4 57.0 beq a01056 newobj instance void [mscorlib]System.Exception::.ctor() throw a01056: ldsfld int64 [rvastatic4]A::a01057 ldc.i8 1 add stsfld int64 [rvastatic4]A::a01057 ldsfld int64 [rvastatic4]A::a01057 ldc.i8 58 beq a01057 newobj instance void [mscorlib]System.Exception::.ctor() throw a01057: ldsfld int64 [rvastatic4]A::a01058 ldc.i8 1 add stsfld int64 [rvastatic4]A::a01058 ldsfld int64 [rvastatic4]A::a01058 ldc.i8 59 beq a01058 newobj instance void [mscorlib]System.Exception::.ctor() throw a01058: ldsfld int64 [rvastatic4]A::a01059 ldc.i8 1 add stsfld int64 [rvastatic4]A::a01059 ldsfld int64 [rvastatic4]A::a01059 ldc.i8 60 beq a01059 newobj instance void [mscorlib]System.Exception::.ctor() throw a01059: ldsfld int16 [rvastatic4]A::a01060 ldc.i4 1 add stsfld int16 [rvastatic4]A::a01060 ldsfld int16 [rvastatic4]A::a01060 ldc.i4 61 beq a01060 newobj instance void [mscorlib]System.Exception::.ctor() throw a01060: ldsfld int8 [rvastatic4]A::a01061 ldc.i4 1 add stsfld int8 [rvastatic4]A::a01061 ldsfld int8 [rvastatic4]A::a01061 ldc.i4 62 beq a01061 newobj instance void [mscorlib]System.Exception::.ctor() throw a01061: ldsfld int64 [rvastatic4]A::a01062 ldc.i8 1 add stsfld int64 [rvastatic4]A::a01062 ldsfld int64 [rvastatic4]A::a01062 ldc.i8 63 beq a01062 newobj instance void [mscorlib]System.Exception::.ctor() throw a01062: ldsfld int16 [rvastatic4]A::a01063 ldc.i4 1 add stsfld int16 [rvastatic4]A::a01063 ldsfld int16 [rvastatic4]A::a01063 ldc.i4 64 beq a01063 newobj instance void [mscorlib]System.Exception::.ctor() throw a01063: ldsfld int32 [rvastatic4]A::a01064 ldc.i4 1 add stsfld int32 [rvastatic4]A::a01064 ldsfld int32 [rvastatic4]A::a01064 ldc.i4 65 beq a01064 newobj instance void [mscorlib]System.Exception::.ctor() throw a01064: ldsfld int16 [rvastatic4]A::a01065 ldc.i4 1 add stsfld int16 [rvastatic4]A::a01065 ldsfld int16 [rvastatic4]A::a01065 ldc.i4 66 beq a01065 newobj instance void [mscorlib]System.Exception::.ctor() throw a01065: ldsfld int8 [rvastatic4]A::a01066 ldc.i4 1 add stsfld int8 [rvastatic4]A::a01066 ldsfld int8 [rvastatic4]A::a01066 ldc.i4 67 beq a01066 newobj instance void [mscorlib]System.Exception::.ctor() throw a01066: ldsfld int16 [rvastatic4]A::a01067 ldc.i4 1 add stsfld int16 [rvastatic4]A::a01067 ldsfld int16 [rvastatic4]A::a01067 ldc.i4 68 beq a01067 newobj instance void [mscorlib]System.Exception::.ctor() throw a01067: ldsfld int32 [rvastatic4]A::a01068 ldc.i4 1 add stsfld int32 [rvastatic4]A::a01068 ldsfld int32 [rvastatic4]A::a01068 ldc.i4 69 beq a01068 newobj instance void [mscorlib]System.Exception::.ctor() throw a01068: ldsfld float32 [rvastatic4]A::a01069 ldc.r4 1 add stsfld float32 [rvastatic4]A::a01069 ldsfld float32 [rvastatic4]A::a01069 ldc.r4 70.0 beq a01069 newobj instance void [mscorlib]System.Exception::.ctor() throw a01069: ldsfld float32 [rvastatic4]A::a01070 ldc.r4 1 add stsfld float32 [rvastatic4]A::a01070 ldsfld float32 [rvastatic4]A::a01070 ldc.r4 71.0 beq a01070 newobj instance void [mscorlib]System.Exception::.ctor() throw a01070: ldsfld int16 [rvastatic4]A::a01071 ldc.i4 1 add stsfld int16 [rvastatic4]A::a01071 ldsfld int16 [rvastatic4]A::a01071 ldc.i4 72 beq a01071 newobj instance void [mscorlib]System.Exception::.ctor() throw a01071: ldsfld float32 [rvastatic4]A::a01072 ldc.r4 1 add stsfld float32 [rvastatic4]A::a01072 ldsfld float32 [rvastatic4]A::a01072 ldc.r4 73.0 beq a01072 newobj instance void [mscorlib]System.Exception::.ctor() throw a01072: ldsfld int64 [rvastatic4]A::a01073 ldc.i8 1 add stsfld int64 [rvastatic4]A::a01073 ldsfld int64 [rvastatic4]A::a01073 ldc.i8 74 beq a01073 newobj instance void [mscorlib]System.Exception::.ctor() throw a01073: ldsfld int64 [rvastatic4]A::a01074 ldc.i8 1 add stsfld int64 [rvastatic4]A::a01074 ldsfld int64 [rvastatic4]A::a01074 ldc.i8 75 beq a01074 newobj instance void [mscorlib]System.Exception::.ctor() throw a01074: ldsfld int32 [rvastatic4]A::a01075 ldc.i4 1 add stsfld int32 [rvastatic4]A::a01075 ldsfld int32 [rvastatic4]A::a01075 ldc.i4 76 beq a01075 newobj instance void [mscorlib]System.Exception::.ctor() throw a01075: ldsfld int8 [rvastatic4]A::a01076 ldc.i4 1 add stsfld int8 [rvastatic4]A::a01076 ldsfld int8 [rvastatic4]A::a01076 ldc.i4 77 beq a01076 newobj instance void [mscorlib]System.Exception::.ctor() throw a01076: ldsfld int32 [rvastatic4]A::a01077 ldc.i4 1 add stsfld int32 [rvastatic4]A::a01077 ldsfld int32 [rvastatic4]A::a01077 ldc.i4 78 beq a01077 newobj instance void [mscorlib]System.Exception::.ctor() throw a01077: ldsfld int16 [rvastatic4]A::a01078 ldc.i4 1 add stsfld int16 [rvastatic4]A::a01078 ldsfld int16 [rvastatic4]A::a01078 ldc.i4 79 beq a01078 newobj instance void [mscorlib]System.Exception::.ctor() throw a01078: ldsfld float32 [rvastatic4]A::a01079 ldc.r4 1 add stsfld float32 [rvastatic4]A::a01079 ldsfld float32 [rvastatic4]A::a01079 ldc.r4 80.0 beq a01079 newobj instance void [mscorlib]System.Exception::.ctor() throw a01079: ldsfld float32 [rvastatic4]A::a01080 ldc.r4 1 add stsfld float32 [rvastatic4]A::a01080 ldsfld float32 [rvastatic4]A::a01080 ldc.r4 81.0 beq a01080 newobj instance void [mscorlib]System.Exception::.ctor() throw a01080: ldsfld float32 [rvastatic4]A::a01081 ldc.r4 1 add stsfld float32 [rvastatic4]A::a01081 ldsfld float32 [rvastatic4]A::a01081 ldc.r4 82.0 beq a01081 newobj instance void [mscorlib]System.Exception::.ctor() throw a01081: ldsfld int32 [rvastatic4]A::a01082 ldc.i4 1 add stsfld int32 [rvastatic4]A::a01082 ldsfld int32 [rvastatic4]A::a01082 ldc.i4 83 beq a01082 newobj instance void [mscorlib]System.Exception::.ctor() throw a01082: ldsfld int8 [rvastatic4]A::a01083 ldc.i4 1 add stsfld int8 [rvastatic4]A::a01083 ldsfld int8 [rvastatic4]A::a01083 ldc.i4 84 beq a01083 newobj instance void [mscorlib]System.Exception::.ctor() throw a01083: ldsfld int64 [rvastatic4]A::a01084 ldc.i8 1 add stsfld int64 [rvastatic4]A::a01084 ldsfld int64 [rvastatic4]A::a01084 ldc.i8 85 beq a01084 newobj instance void [mscorlib]System.Exception::.ctor() throw a01084: ldsfld int64 [rvastatic4]A::a01085 ldc.i8 1 add stsfld int64 [rvastatic4]A::a01085 ldsfld int64 [rvastatic4]A::a01085 ldc.i8 86 beq a01085 newobj instance void [mscorlib]System.Exception::.ctor() throw a01085: ldsfld int32 [rvastatic4]A::a01086 ldc.i4 1 add stsfld int32 [rvastatic4]A::a01086 ldsfld int32 [rvastatic4]A::a01086 ldc.i4 87 beq a01086 newobj instance void [mscorlib]System.Exception::.ctor() throw a01086: ldsfld int32 [rvastatic4]A::a01087 ldc.i4 1 add stsfld int32 [rvastatic4]A::a01087 ldsfld int32 [rvastatic4]A::a01087 ldc.i4 88 beq a01087 newobj instance void [mscorlib]System.Exception::.ctor() throw a01087: ldsfld int8 [rvastatic4]A::a01088 ldc.i4 1 add stsfld int8 [rvastatic4]A::a01088 ldsfld int8 [rvastatic4]A::a01088 ldc.i4 89 beq a01088 newobj instance void [mscorlib]System.Exception::.ctor() throw a01088: ldsfld int64 [rvastatic4]A::a01089 ldc.i8 1 add stsfld int64 [rvastatic4]A::a01089 ldsfld int64 [rvastatic4]A::a01089 ldc.i8 90 beq a01089 newobj instance void [mscorlib]System.Exception::.ctor() throw a01089: ldsfld int8 [rvastatic4]A::a01090 ldc.i4 1 add stsfld int8 [rvastatic4]A::a01090 ldsfld int8 [rvastatic4]A::a01090 ldc.i4 91 beq a01090 newobj instance void [mscorlib]System.Exception::.ctor() throw a01090: ldsfld int16 [rvastatic4]A::a01091 ldc.i4 1 add stsfld int16 [rvastatic4]A::a01091 ldsfld int16 [rvastatic4]A::a01091 ldc.i4 92 beq a01091 newobj instance void [mscorlib]System.Exception::.ctor() throw a01091: ldsfld float32 [rvastatic4]A::a01092 ldc.r4 1 add stsfld float32 [rvastatic4]A::a01092 ldsfld float32 [rvastatic4]A::a01092 ldc.r4 93.0 beq a01092 newobj instance void [mscorlib]System.Exception::.ctor() throw a01092: ldsfld int64 [rvastatic4]A::a01093 ldc.i8 1 add stsfld int64 [rvastatic4]A::a01093 ldsfld int64 [rvastatic4]A::a01093 ldc.i8 94 beq a01093 newobj instance void [mscorlib]System.Exception::.ctor() throw a01093: ldsfld int64 [rvastatic4]A::a01094 ldc.i8 1 add stsfld int64 [rvastatic4]A::a01094 ldsfld int64 [rvastatic4]A::a01094 ldc.i8 95 beq a01094 newobj instance void [mscorlib]System.Exception::.ctor() throw a01094: ldsfld int8 [rvastatic4]A::a01095 ldc.i4 1 add stsfld int8 [rvastatic4]A::a01095 ldsfld int8 [rvastatic4]A::a01095 ldc.i4 96 beq a01095 newobj instance void [mscorlib]System.Exception::.ctor() throw a01095: ldsfld float32 [rvastatic4]A::a01096 ldc.r4 1 add stsfld float32 [rvastatic4]A::a01096 ldsfld float32 [rvastatic4]A::a01096 ldc.r4 97.0 beq a01096 newobj instance void [mscorlib]System.Exception::.ctor() throw a01096: ldsfld int16 [rvastatic4]A::a01097 ldc.i4 1 add stsfld int16 [rvastatic4]A::a01097 ldsfld int16 [rvastatic4]A::a01097 ldc.i4 98 beq a01097 newobj instance void [mscorlib]System.Exception::.ctor() throw a01097: ldsfld float32 [rvastatic4]A::a01098 ldc.r4 1 add stsfld float32 [rvastatic4]A::a01098 ldsfld float32 [rvastatic4]A::a01098 ldc.r4 99.0 beq a01098 newobj instance void [mscorlib]System.Exception::.ctor() throw a01098: ldsfld int32 [rvastatic4]A::a01099 ldc.i4 1 add stsfld int32 [rvastatic4]A::a01099 ldsfld int32 [rvastatic4]A::a01099 ldc.i4 100 beq a01099 newobj instance void [mscorlib]System.Exception::.ctor() throw a01099: ldsfld int64 [rvastatic4]A::a010100 ldc.i8 1 add stsfld int64 [rvastatic4]A::a010100 ldsfld int64 [rvastatic4]A::a010100 ldc.i8 101 beq a010100 newobj instance void [mscorlib]System.Exception::.ctor() throw a010100: ldsfld int32 [rvastatic4]A::a010101 ldc.i4 1 add stsfld int32 [rvastatic4]A::a010101 ldsfld int32 [rvastatic4]A::a010101 ldc.i4 102 beq a010101 newobj instance void [mscorlib]System.Exception::.ctor() throw a010101: ldsfld float32 [rvastatic4]A::a010102 ldc.r4 1 add stsfld float32 [rvastatic4]A::a010102 ldsfld float32 [rvastatic4]A::a010102 ldc.r4 103.0 beq a010102 newobj instance void [mscorlib]System.Exception::.ctor() throw a010102: ldsfld int64 [rvastatic4]A::a010103 ldc.i8 1 add stsfld int64 [rvastatic4]A::a010103 ldsfld int64 [rvastatic4]A::a010103 ldc.i8 104 beq a010103 newobj instance void [mscorlib]System.Exception::.ctor() throw a010103: ldsfld int32 [rvastatic4]A::a010104 ldc.i4 1 add stsfld int32 [rvastatic4]A::a010104 ldsfld int32 [rvastatic4]A::a010104 ldc.i4 105 beq a010104 newobj instance void [mscorlib]System.Exception::.ctor() throw a010104: ldsfld int16 [rvastatic4]A::a010105 ldc.i4 1 add stsfld int16 [rvastatic4]A::a010105 ldsfld int16 [rvastatic4]A::a010105 ldc.i4 106 beq a010105 newobj instance void [mscorlib]System.Exception::.ctor() throw a010105: ldsfld int16 [rvastatic4]A::a010106 ldc.i4 1 add stsfld int16 [rvastatic4]A::a010106 ldsfld int16 [rvastatic4]A::a010106 ldc.i4 107 beq a010106 newobj instance void [mscorlib]System.Exception::.ctor() throw a010106: ldsfld float32 [rvastatic4]A::a010107 ldc.r4 1 add stsfld float32 [rvastatic4]A::a010107 ldsfld float32 [rvastatic4]A::a010107 ldc.r4 108.0 beq a010107 newobj instance void [mscorlib]System.Exception::.ctor() throw a010107: ldsfld int32 [rvastatic4]A::a010108 ldc.i4 1 add stsfld int32 [rvastatic4]A::a010108 ldsfld int32 [rvastatic4]A::a010108 ldc.i4 109 beq a010108 newobj instance void [mscorlib]System.Exception::.ctor() throw a010108: ldsfld int16 [rvastatic4]A::a010109 ldc.i4 1 add stsfld int16 [rvastatic4]A::a010109 ldsfld int16 [rvastatic4]A::a010109 ldc.i4 110 beq a010109 newobj instance void [mscorlib]System.Exception::.ctor() throw a010109: ldsfld int32 [rvastatic4]A::a010110 ldc.i4 1 add stsfld int32 [rvastatic4]A::a010110 ldsfld int32 [rvastatic4]A::a010110 ldc.i4 111 beq a010110 newobj instance void [mscorlib]System.Exception::.ctor() throw a010110: ldsfld int32 [rvastatic4]A::a010111 ldc.i4 1 add stsfld int32 [rvastatic4]A::a010111 ldsfld int32 [rvastatic4]A::a010111 ldc.i4 112 beq a010111 newobj instance void [mscorlib]System.Exception::.ctor() throw a010111: ldsfld int32 [rvastatic4]A::a010112 ldc.i4 1 add stsfld int32 [rvastatic4]A::a010112 ldsfld int32 [rvastatic4]A::a010112 ldc.i4 113 beq a010112 newobj instance void [mscorlib]System.Exception::.ctor() throw a010112: ldsfld int64 [rvastatic4]A::a010113 ldc.i8 1 add stsfld int64 [rvastatic4]A::a010113 ldsfld int64 [rvastatic4]A::a010113 ldc.i8 114 beq a010113 newobj instance void [mscorlib]System.Exception::.ctor() throw a010113: ldsfld int64 [rvastatic4]A::a010114 ldc.i8 1 add stsfld int64 [rvastatic4]A::a010114 ldsfld int64 [rvastatic4]A::a010114 ldc.i8 115 beq a010114 newobj instance void [mscorlib]System.Exception::.ctor() throw a010114: ldsfld int16 [rvastatic4]A::a010115 ldc.i4 1 add stsfld int16 [rvastatic4]A::a010115 ldsfld int16 [rvastatic4]A::a010115 ldc.i4 116 beq a010115 newobj instance void [mscorlib]System.Exception::.ctor() throw a010115: ldsfld int64 [rvastatic4]A::a010116 ldc.i8 1 add stsfld int64 [rvastatic4]A::a010116 ldsfld int64 [rvastatic4]A::a010116 ldc.i8 117 beq a010116 newobj instance void [mscorlib]System.Exception::.ctor() throw a010116: ldsfld int64 [rvastatic4]A::a010117 ldc.i8 1 add stsfld int64 [rvastatic4]A::a010117 ldsfld int64 [rvastatic4]A::a010117 ldc.i8 118 beq a010117 newobj instance void [mscorlib]System.Exception::.ctor() throw a010117: ldsfld int32 [rvastatic4]A::a010118 ldc.i4 1 add stsfld int32 [rvastatic4]A::a010118 ldsfld int32 [rvastatic4]A::a010118 ldc.i4 119 beq a010118 newobj instance void [mscorlib]System.Exception::.ctor() throw a010118: ldsfld int64 [rvastatic4]A::a010119 ldc.i8 1 add stsfld int64 [rvastatic4]A::a010119 ldsfld int64 [rvastatic4]A::a010119 ldc.i8 120 beq a010119 newobj instance void [mscorlib]System.Exception::.ctor() throw a010119: ldsfld int64 [rvastatic4]A::a010120 ldc.i8 1 add stsfld int64 [rvastatic4]A::a010120 ldsfld int64 [rvastatic4]A::a010120 ldc.i8 121 beq a010120 newobj instance void [mscorlib]System.Exception::.ctor() throw a010120: ldsfld int64 [rvastatic4]A::a010121 ldc.i8 1 add stsfld int64 [rvastatic4]A::a010121 ldsfld int64 [rvastatic4]A::a010121 ldc.i8 122 beq a010121 newobj instance void [mscorlib]System.Exception::.ctor() throw a010121: ldsfld int16 [rvastatic4]A::a010122 ldc.i4 1 add stsfld int16 [rvastatic4]A::a010122 ldsfld int16 [rvastatic4]A::a010122 ldc.i4 123 beq a010122 newobj instance void [mscorlib]System.Exception::.ctor() throw a010122: ldsfld int64 [rvastatic4]A::a010123 ldc.i8 1 add stsfld int64 [rvastatic4]A::a010123 ldsfld int64 [rvastatic4]A::a010123 ldc.i8 124 beq a010123 newobj instance void [mscorlib]System.Exception::.ctor() throw a010123: ldsfld int64 [rvastatic4]A::a010124 ldc.i8 1 add stsfld int64 [rvastatic4]A::a010124 ldsfld int64 [rvastatic4]A::a010124 ldc.i8 125 beq a010124 newobj instance void [mscorlib]System.Exception::.ctor() throw a010124: ldsfld int32 [rvastatic4]A::a010125 ldc.i4 1 add stsfld int32 [rvastatic4]A::a010125 ldsfld int32 [rvastatic4]A::a010125 ldc.i4 126 beq a010125 newobj instance void [mscorlib]System.Exception::.ctor() throw a010125: ldsfld int16 [rvastatic4]A::a010126 ldc.i4 1 add stsfld int16 [rvastatic4]A::a010126 ldsfld int16 [rvastatic4]A::a010126 ldc.i4 127 beq a010126 newobj instance void [mscorlib]System.Exception::.ctor() throw a010126: ldsfld int16 [rvastatic4]A::a010127 ldc.i4 1 add stsfld int16 [rvastatic4]A::a010127 ldsfld int16 [rvastatic4]A::a010127 ldc.i4 128 beq a010127 newobj instance void [mscorlib]System.Exception::.ctor() throw a010127: ret} .method static int32 Main(string[] args){.entrypoint .maxstack 5 .custom instance void [xunit.core]Xunit.FactAttribute::.ctor() = ( 01 00 00 00 ) call void [rvastatic4]A::V1() call void [rvastatic4]A::V2() call void [rvastatic4]A::V3() call void [rvastatic4]A::V4() call void [rvastatic4]A::V5() call void [rvastatic4]A::V6() ldc.i4 100 ret} .field public static int32 a0100 at b0100 .field private static int32 aALIGN10100 at bALIGN10100 .field public static int64 a0101 at b0101 .field public static float32 a0102 at b0102 .field private static int32 aALIGN10102 at bALIGN10102 .field public static int16 a0103 at b0103 .field private static int16 aALIGN10103 at bALIGN10103 .field private static int32 aALIGN20103 at bALIGN20103 .field public static int16 a0104 at b0104 .field private static int16 aALIGN10104 at bALIGN10104 .field private static int32 aALIGN20104 at bALIGN20104 .field public static int64 a0105 at b0105 .field public static int16 a0106 at b0106 .field private static int16 aALIGN10106 at bALIGN10106 .field private static int32 aALIGN20106 at bALIGN20106 .field public static int8 a0107 at b0107 .field private static int32 aALIGN10107 at bALIGN10107 .field private static int16 aALIGN20107 at bALIGN20107 .field private static int8 aALIGN20107 at bALIGN30107 .field public static int64 a0108 at b0108 .field public static int32 a0109 at b0109 .field private static int32 aALIGN10109 at bALIGN10109 .field public static int16 a01010 at b01010 .field private static int16 aALIGN101010 at bALIGN101010 .field private static int32 aALIGN201010 at bALIGN201010 .field public static float32 a01011 at b01011 .field private static int32 aALIGN101011 at bALIGN101011 .field public static int16 a01012 at b01012 .field private static int16 aALIGN101012 at bALIGN101012 .field private static int32 aALIGN201012 at bALIGN201012 .field public static float32 a01013 at b01013 .field private static int32 aALIGN101013 at bALIGN101013 .field public static float32 a01014 at b01014 .field private static int32 aALIGN101014 at bALIGN101014 .field public static int8 a01015 at b01015 .field private static int32 aALIGN101015 at bALIGN101015 .field private static int16 aALIGN201015 at bALIGN201015 .field private static int8 aALIGN201015 at bALIGN301015 .field public static float32 a01016 at b01016 .field private static int32 aALIGN101016 at bALIGN101016 .field public static int8 a01017 at b01017 .field private static int32 aALIGN101017 at bALIGN101017 .field private static int16 aALIGN201017 at bALIGN201017 .field private static int8 aALIGN201017 at bALIGN301017 .field public static float32 a01018 at b01018 .field private static int32 aALIGN101018 at bALIGN101018 .field public static float32 a01019 at b01019 .field private static int32 aALIGN101019 at bALIGN101019 .field public static int8 a01020 at b01020 .field private static int32 aALIGN101020 at bALIGN101020 .field private static int16 aALIGN201020 at bALIGN201020 .field private static int8 aALIGN201020 at bALIGN301020 .field public static float32 a01021 at b01021 .field private static int32 aALIGN101021 at bALIGN101021 .field public static int64 a01022 at b01022 .field public static int8 a01023 at b01023 .field private static int32 aALIGN101023 at bALIGN101023 .field private static int16 aALIGN201023 at bALIGN201023 .field private static int8 aALIGN201023 at bALIGN301023 .field public static int32 a01024 at b01024 .field private static int32 aALIGN101024 at bALIGN101024 .field public static int64 a01025 at b01025 .field public static int16 a01026 at b01026 .field private static int16 aALIGN101026 at bALIGN101026 .field private static int32 aALIGN201026 at bALIGN201026 .field public static int8 a01027 at b01027 .field private static int32 aALIGN101027 at bALIGN101027 .field private static int16 aALIGN201027 at bALIGN201027 .field private static int8 aALIGN201027 at bALIGN301027 .field public static int16 a01028 at b01028 .field private static int16 aALIGN101028 at bALIGN101028 .field private static int32 aALIGN201028 at bALIGN201028 .field public static int16 a01029 at b01029 .field private static int16 aALIGN101029 at bALIGN101029 .field private static int32 aALIGN201029 at bALIGN201029 .field public static int8 a01030 at b01030 .field private static int32 aALIGN101030 at bALIGN101030 .field private static int16 aALIGN201030 at bALIGN201030 .field private static int8 aALIGN201030 at bALIGN301030 .field public static int8 a01031 at b01031 .field private static int32 aALIGN101031 at bALIGN101031 .field private static int16 aALIGN201031 at bALIGN201031 .field private static int8 aALIGN201031 at bALIGN301031 .field public static int64 a01032 at b01032 .field public static float32 a01033 at b01033 .field private static int32 aALIGN101033 at bALIGN101033 .field public static int16 a01034 at b01034 .field private static int16 aALIGN101034 at bALIGN101034 .field private static int32 aALIGN201034 at bALIGN201034 .field public static int8 a01035 at b01035 .field private static int32 aALIGN101035 at bALIGN101035 .field private static int16 aALIGN201035 at bALIGN201035 .field private static int8 aALIGN201035 at bALIGN301035 .field public static int8 a01036 at b01036 .field private static int32 aALIGN101036 at bALIGN101036 .field private static int16 aALIGN201036 at bALIGN201036 .field private static int8 aALIGN201036 at bALIGN301036 .field public static int32 a01037 at b01037 .field private static int32 aALIGN101037 at bALIGN101037 .field public static int16 a01038 at b01038 .field private static int16 aALIGN101038 at bALIGN101038 .field private static int32 aALIGN201038 at bALIGN201038 .field public static int8 a01039 at b01039 .field private static int32 aALIGN101039 at bALIGN101039 .field private static int16 aALIGN201039 at bALIGN201039 .field private static int8 aALIGN201039 at bALIGN301039 .field public static int8 a01040 at b01040 .field private static int32 aALIGN101040 at bALIGN101040 .field private static int16 aALIGN201040 at bALIGN201040 .field private static int8 aALIGN201040 at bALIGN301040 .field public static int32 a01041 at b01041 .field private static int32 aALIGN101041 at bALIGN101041 .field public static int64 a01042 at b01042 .field public static int16 a01043 at b01043 .field private static int16 aALIGN101043 at bALIGN101043 .field private static int32 aALIGN201043 at bALIGN201043 .field public static int64 a01044 at b01044 .field public static int64 a01045 at b01045 .field public static float32 a01046 at b01046 .field private static int32 aALIGN101046 at bALIGN101046 .field public static int16 a01047 at b01047 .field private static int16 aALIGN101047 at bALIGN101047 .field private static int32 aALIGN201047 at bALIGN201047 .field public static int64 a01048 at b01048 .field public static int16 a01049 at b01049 .field private static int16 aALIGN101049 at bALIGN101049 .field private static int32 aALIGN201049 at bALIGN201049 .field public static int32 a01050 at b01050 .field private static int32 aALIGN101050 at bALIGN101050 .field public static int16 a01051 at b01051 .field private static int16 aALIGN101051 at bALIGN101051 .field private static int32 aALIGN201051 at bALIGN201051 .field public static int32 a01052 at b01052 .field private static int32 aALIGN101052 at bALIGN101052 .field public static int16 a01053 at b01053 .field private static int16 aALIGN101053 at bALIGN101053 .field private static int32 aALIGN201053 at bALIGN201053 .field public static float32 a01054 at b01054 .field private static int32 aALIGN101054 at bALIGN101054 .field public static int64 a01055 at b01055 .field public static float32 a01056 at b01056 .field private static int32 aALIGN101056 at bALIGN101056 .field public static int64 a01057 at b01057 .field public static int64 a01058 at b01058 .field public static int64 a01059 at b01059 .field public static int16 a01060 at b01060 .field private static int16 aALIGN101060 at bALIGN101060 .field private static int32 aALIGN201060 at bALIGN201060 .field public static int8 a01061 at b01061 .field private static int32 aALIGN101061 at bALIGN101061 .field private static int16 aALIGN201061 at bALIGN201061 .field private static int8 aALIGN201061 at bALIGN301061 .field public static int64 a01062 at b01062 .field public static int16 a01063 at b01063 .field private static int16 aALIGN101063 at bALIGN101063 .field private static int32 aALIGN201063 at bALIGN201063 .field public static int32 a01064 at b01064 .field private static int32 aALIGN101064 at bALIGN101064 .field public static int16 a01065 at b01065 .field private static int16 aALIGN101065 at bALIGN101065 .field private static int32 aALIGN201065 at bALIGN201065 .field public static int8 a01066 at b01066 .field private static int32 aALIGN101066 at bALIGN101066 .field private static int16 aALIGN201066 at bALIGN201066 .field private static int8 aALIGN201066 at bALIGN301066 .field public static int16 a01067 at b01067 .field private static int16 aALIGN101067 at bALIGN101067 .field private static int32 aALIGN201067 at bALIGN201067 .field public static int32 a01068 at b01068 .field private static int32 aALIGN101068 at bALIGN101068 .field public static float32 a01069 at b01069 .field private static int32 aALIGN101069 at bALIGN101069 .field public static float32 a01070 at b01070 .field private static int32 aALIGN101070 at bALIGN101070 .field public static int16 a01071 at b01071 .field private static int16 aALIGN101071 at bALIGN101071 .field private static int32 aALIGN201071 at bALIGN201071 .field public static float32 a01072 at b01072 .field private static int32 aALIGN101072 at bALIGN101072 .field public static int64 a01073 at b01073 .field public static int64 a01074 at b01074 .field public static int32 a01075 at b01075 .field private static int32 aALIGN101075 at bALIGN101075 .field public static int8 a01076 at b01076 .field private static int32 aALIGN101076 at bALIGN101076 .field private static int16 aALIGN201076 at bALIGN201076 .field private static int8 aALIGN201076 at bALIGN301076 .field public static int32 a01077 at b01077 .field private static int32 aALIGN101077 at bALIGN101077 .field public static int16 a01078 at b01078 .field private static int16 aALIGN101078 at bALIGN101078 .field private static int32 aALIGN201078 at bALIGN201078 .field public static float32 a01079 at b01079 .field private static int32 aALIGN101079 at bALIGN101079 .field public static float32 a01080 at b01080 .field private static int32 aALIGN101080 at bALIGN101080 .field public static float32 a01081 at b01081 .field private static int32 aALIGN101081 at bALIGN101081 .field public static int32 a01082 at b01082 .field private static int32 aALIGN101082 at bALIGN101082 .field public static int8 a01083 at b01083 .field private static int32 aALIGN101083 at bALIGN101083 .field private static int16 aALIGN201083 at bALIGN201083 .field private static int8 aALIGN201083 at bALIGN301083 .field public static int64 a01084 at b01084 .field public static int64 a01085 at b01085 .field public static int32 a01086 at b01086 .field private static int32 aALIGN101086 at bALIGN101086 .field public static int32 a01087 at b01087 .field private static int32 aALIGN101087 at bALIGN101087 .field public static int8 a01088 at b01088 .field private static int32 aALIGN101088 at bALIGN101088 .field private static int16 aALIGN201088 at bALIGN201088 .field private static int8 aALIGN201088 at bALIGN301088 .field public static int64 a01089 at b01089 .field public static int8 a01090 at b01090 .field private static int32 aALIGN101090 at bALIGN101090 .field private static int16 aALIGN201090 at bALIGN201090 .field private static int8 aALIGN201090 at bALIGN301090 .field public static int16 a01091 at b01091 .field private static int16 aALIGN101091 at bALIGN101091 .field private static int32 aALIGN201091 at bALIGN201091 .field public static float32 a01092 at b01092 .field private static int32 aALIGN101092 at bALIGN101092 .field public static int64 a01093 at b01093 .field public static int64 a01094 at b01094 .field public static int8 a01095 at b01095 .field private static int32 aALIGN101095 at bALIGN101095 .field private static int16 aALIGN201095 at bALIGN201095 .field private static int8 aALIGN201095 at bALIGN301095 .field public static float32 a01096 at b01096 .field private static int32 aALIGN101096 at bALIGN101096 .field public static int16 a01097 at b01097 .field private static int16 aALIGN101097 at bALIGN101097 .field private static int32 aALIGN201097 at bALIGN201097 .field public static float32 a01098 at b01098 .field private static int32 aALIGN101098 at bALIGN101098 .field public static int32 a01099 at b01099 .field private static int32 aALIGN101099 at bALIGN101099 .field public static int64 a010100 at b010100 .field public static int32 a010101 at b010101 .field private static int32 aALIGN1010101 at bALIGN1010101 .field public static float32 a010102 at b010102 .field private static int32 aALIGN1010102 at bALIGN1010102 .field public static int64 a010103 at b010103 .field public static int32 a010104 at b010104 .field private static int32 aALIGN1010104 at bALIGN1010104 .field public static int16 a010105 at b010105 .field private static int16 aALIGN1010105 at bALIGN1010105 .field private static int32 aALIGN2010105 at bALIGN2010105 .field public static int16 a010106 at b010106 .field private static int16 aALIGN1010106 at bALIGN1010106 .field private static int32 aALIGN2010106 at bALIGN2010106 .field public static float32 a010107 at b010107 .field private static int32 aALIGN1010107 at bALIGN1010107 .field public static int32 a010108 at b010108 .field private static int32 aALIGN1010108 at bALIGN1010108 .field public static int16 a010109 at b010109 .field private static int16 aALIGN1010109 at bALIGN1010109 .field private static int32 aALIGN2010109 at bALIGN2010109 .field public static int32 a010110 at b010110 .field private static int32 aALIGN1010110 at bALIGN1010110 .field public static int32 a010111 at b010111 .field private static int32 aALIGN1010111 at bALIGN1010111 .field public static int32 a010112 at b010112 .field private static int32 aALIGN1010112 at bALIGN1010112 .field public static int64 a010113 at b010113 .field public static int64 a010114 at b010114 .field public static int16 a010115 at b010115 .field private static int16 aALIGN1010115 at bALIGN1010115 .field private static int32 aALIGN2010115 at bALIGN2010115 .field public static int64 a010116 at b010116 .field public static int64 a010117 at b010117 .field public static int32 a010118 at b010118 .field private static int32 aALIGN1010118 at bALIGN1010118 .field public static int64 a010119 at b010119 .field public static int64 a010120 at b010120 .field public static int64 a010121 at b010121 .field public static int16 a010122 at b010122 .field private static int16 aALIGN1010122 at bALIGN1010122 .field private static int32 aALIGN2010122 at bALIGN2010122 .field public static int64 a010123 at b010123 .field public static int64 a010124 at b010124 .field public static int32 a010125 at b010125 .field private static int32 aALIGN1010125 at bALIGN1010125 .field public static int16 a010126 at b010126 .field private static int16 aALIGN1010126 at bALIGN1010126 .field private static int32 aALIGN2010126 at bALIGN2010126 .field public static int16 a010127 at b010127 .field private static int16 aALIGN1010127 at bALIGN1010127 .field private static int32 aALIGN2010127 at bALIGN2010127 } .data b0100 = int32(0) .data bALIGN10100 = int32(0) .data b0101 = int64(1) .data b0102 = float32(2.0) .data bALIGN10102 = int32(0) .data b0103 = int16(3) .data bALIGN10103 = int16(0) .data bALIGN20103 = int32(0) .data b0104 = int16(4) .data bALIGN10104 = int16(0) .data bALIGN20104 = int32(0) .data b0105 = int64(5) .data b0106 = int16(6) .data bALIGN10106 = int16(0) .data bALIGN20106 = int32(0) .data b0107 = int8(7) .data bALIGN10107 = int32(0) .data bALIGN20107 = int16(0) .data bALIGN30107 = int8(0) .data b0108 = int64(8) .data b0109 = int32(9) .data bALIGN10109 = int32(0) .data b01010 = int16(10) .data bALIGN101010 = int16(0) .data bALIGN201010 = int32(0) .data b01011 = float32(11.0) .data bALIGN101011 = int32(0) .data b01012 = int16(12) .data bALIGN101012 = int16(0) .data bALIGN201012 = int32(0) .data b01013 = float32(13.0) .data bALIGN101013 = int32(0) .data b01014 = float32(14.0) .data bALIGN101014 = int32(0) .data b01015 = int8(15) .data bALIGN101015 = int32(0) .data bALIGN201015 = int16(0) .data bALIGN301015 = int8(0) .data b01016 = float32(16.0) .data bALIGN101016 = int32(0) .data b01017 = int8(17) .data bALIGN101017 = int32(0) .data bALIGN201017 = int16(0) .data bALIGN301017 = int8(0) .data b01018 = float32(18.0) .data bALIGN101018 = int32(0) .data b01019 = float32(19.0) .data bALIGN101019 = int32(0) .data b01020 = int8(20) .data bALIGN101020 = int32(0) .data bALIGN201020 = int16(0) .data bALIGN301020 = int8(0) .data b01021 = float32(21.0) .data bALIGN101021 = int32(0) .data b01022 = int64(22) .data b01023 = int8(23) .data bALIGN101023 = int32(0) .data bALIGN201023 = int16(0) .data bALIGN301023 = int8(0) .data b01024 = int32(24) .data bALIGN101024 = int32(0) .data b01025 = int64(25) .data b01026 = int16(26) .data bALIGN101026 = int16(0) .data bALIGN201026 = int32(0) .data b01027 = int8(27) .data bALIGN101027 = int32(0) .data bALIGN201027 = int16(0) .data bALIGN301027 = int8(0) .data b01028 = int16(28) .data bALIGN101028 = int16(0) .data bALIGN201028 = int32(0) .data b01029 = int16(29) .data bALIGN101029 = int16(0) .data bALIGN201029 = int32(0) .data b01030 = int8(30) .data bALIGN101030 = int32(0) .data bALIGN201030 = int16(0) .data bALIGN301030 = int8(0) .data b01031 = int8(31) .data bALIGN101031 = int32(0) .data bALIGN201031 = int16(0) .data bALIGN301031 = int8(0) .data b01032 = int64(32) .data b01033 = float32(33.0) .data bALIGN101033 = int32(0) .data b01034 = int16(34) .data bALIGN101034 = int16(0) .data bALIGN201034 = int32(0) .data b01035 = int8(35) .data bALIGN101035 = int32(0) .data bALIGN201035 = int16(0) .data bALIGN301035 = int8(0) .data b01036 = int8(36) .data bALIGN101036 = int32(0) .data bALIGN201036 = int16(0) .data bALIGN301036 = int8(0) .data b01037 = int32(37) .data bALIGN101037 = int32(0) .data b01038 = int16(38) .data bALIGN101038 = int16(0) .data bALIGN201038 = int32(0) .data b01039 = int8(39) .data bALIGN101039 = int32(0) .data bALIGN201039 = int16(0) .data bALIGN301039 = int8(0) .data b01040 = int8(40) .data bALIGN101040 = int32(0) .data bALIGN201040 = int16(0) .data bALIGN301040 = int8(0) .data b01041 = int32(41) .data bALIGN101041 = int32(0) .data b01042 = int64(42) .data b01043 = int16(43) .data bALIGN101043 = int16(0) .data bALIGN201043 = int32(0) .data b01044 = int64(44) .data b01045 = int64(45) .data b01046 = float32(46.0) .data bALIGN101046 = int32(0) .data b01047 = int16(47) .data bALIGN101047 = int16(0) .data bALIGN201047 = int32(0) .data b01048 = int64(48) .data b01049 = int16(49) .data bALIGN101049 = int16(0) .data bALIGN201049 = int32(0) .data b01050 = int32(50) .data bALIGN101050 = int32(0) .data b01051 = int16(51) .data bALIGN101051 = int16(0) .data bALIGN201051 = int32(0) .data b01052 = int32(52) .data bALIGN101052 = int32(0) .data b01053 = int16(53) .data bALIGN101053 = int16(0) .data bALIGN201053 = int32(0) .data b01054 = float32(54.0) .data bALIGN101054 = int32(0) .data b01055 = int64(55) .data b01056 = float32(56.0) .data bALIGN101056 = int32(0) .data b01057 = int64(57) .data b01058 = int64(58) .data b01059 = int64(59) .data b01060 = int16(60) .data bALIGN101060 = int16(0) .data bALIGN201060 = int32(0) .data b01061 = int8(61) .data bALIGN101061 = int32(0) .data bALIGN201061 = int16(0) .data bALIGN301061 = int8(0) .data b01062 = int64(62) .data b01063 = int16(63) .data bALIGN101063 = int16(0) .data bALIGN201063 = int32(0) .data b01064 = int32(64) .data bALIGN101064 = int32(0) .data b01065 = int16(65) .data bALIGN101065 = int16(0) .data bALIGN201065 = int32(0) .data b01066 = int8(66) .data bALIGN101066 = int32(0) .data bALIGN201066 = int16(0) .data bALIGN301066 = int8(0) .data b01067 = int16(67) .data bALIGN101067 = int16(0) .data bALIGN201067 = int32(0) .data b01068 = int32(68) .data bALIGN101068 = int32(0) .data b01069 = float32(69.0) .data bALIGN101069 = int32(0) .data b01070 = float32(70.0) .data bALIGN101070 = int32(0) .data b01071 = int16(71) .data bALIGN101071 = int16(0) .data bALIGN201071 = int32(0) .data b01072 = float32(72.0) .data bALIGN101072 = int32(0) .data b01073 = int64(73) .data b01074 = int64(74) .data b01075 = int32(75) .data bALIGN101075 = int32(0) .data b01076 = int8(76) .data bALIGN101076 = int32(0) .data bALIGN201076 = int16(0) .data bALIGN301076 = int8(0) .data b01077 = int32(77) .data bALIGN101077 = int32(0) .data b01078 = int16(78) .data bALIGN101078 = int16(0) .data bALIGN201078 = int32(0) .data b01079 = float32(79.0) .data bALIGN101079 = int32(0) .data b01080 = float32(80.0) .data bALIGN101080 = int32(0) .data b01081 = float32(81.0) .data bALIGN101081 = int32(0) .data b01082 = int32(82) .data bALIGN101082 = int32(0) .data b01083 = int8(83) .data bALIGN101083 = int32(0) .data bALIGN201083 = int16(0) .data bALIGN301083 = int8(0) .data b01084 = int64(84) .data b01085 = int64(85) .data b01086 = int32(86) .data bALIGN101086 = int32(0) .data b01087 = int32(87) .data bALIGN101087 = int32(0) .data b01088 = int8(88) .data bALIGN101088 = int32(0) .data bALIGN201088 = int16(0) .data bALIGN301088 = int8(0) .data b01089 = int64(89) .data b01090 = int8(90) .data bALIGN101090 = int32(0) .data bALIGN201090 = int16(0) .data bALIGN301090 = int8(0) .data b01091 = int16(91) .data bALIGN101091 = int16(0) .data bALIGN201091 = int32(0) .data b01092 = float32(92.0) .data bALIGN101092 = int32(0) .data b01093 = int64(93) .data b01094 = int64(94) .data b01095 = int8(95) .data bALIGN101095 = int32(0) .data bALIGN201095 = int16(0) .data bALIGN301095 = int8(0) .data b01096 = float32(96.0) .data bALIGN101096 = int32(0) .data b01097 = int16(97) .data bALIGN101097 = int16(0) .data bALIGN201097 = int32(0) .data b01098 = float32(98.0) .data bALIGN101098 = int32(0) .data b01099 = int32(99) .data bALIGN101099 = int32(0) .data b010100 = int64(100) .data b010101 = int32(101) .data bALIGN1010101 = int32(0) .data b010102 = float32(102.0) .data bALIGN1010102 = int32(0) .data b010103 = int64(103) .data b010104 = int32(104) .data bALIGN1010104 = int32(0) .data b010105 = int16(105) .data bALIGN1010105 = int16(0) .data bALIGN2010105 = int32(0) .data b010106 = int16(106) .data bALIGN1010106 = int16(0) .data bALIGN2010106 = int32(0) .data b010107 = float32(107.0) .data bALIGN1010107 = int32(0) .data b010108 = int32(108) .data bALIGN1010108 = int32(0) .data b010109 = int16(109) .data bALIGN1010109 = int16(0) .data bALIGN2010109 = int32(0) .data b010110 = int32(110) .data bALIGN1010110 = int32(0) .data b010111 = int32(111) .data bALIGN1010111 = int32(0) .data b010112 = int32(112) .data bALIGN1010112 = int32(0) .data b010113 = int64(113) .data b010114 = int64(114) .data b010115 = int16(115) .data bALIGN1010115 = int16(0) .data bALIGN2010115 = int32(0) .data b010116 = int64(116) .data b010117 = int64(117) .data b010118 = int32(118) .data bALIGN1010118 = int32(0) .data b010119 = int64(119) .data b010120 = int64(120) .data b010121 = int64(121) .data b010122 = int16(122) .data bALIGN1010122 = int16(0) .data bALIGN2010122 = int32(0) .data b010123 = int64(123) .data b010124 = int64(124) .data b010125 = int32(125) .data bALIGN1010125 = int32(0) .data b010126 = int16(126) .data bALIGN1010126 = int16(0) .data bALIGN2010126 = int32(0) .data b010127 = int16(127) .data bALIGN1010127 = int16(0) .data bALIGN2010127 = int32(0)
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/tests/JIT/jit64/valuetypes/nullable/castclass/castclass/castclass004.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="castclass004.cs" /> <Compile Include="..\structdef.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="castclass004.cs" /> <Compile Include="..\structdef.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/libraries/System.Numerics.Tensors/ref/System.Numerics.Tensors.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.Numerics.Tensors { public static partial class ArrayTensorExtensions { public static System.Numerics.Tensors.CompressedSparseTensor<T> ToCompressedSparseTensor<T>(this System.Array array, bool reverseStride = false) { throw null; } public static System.Numerics.Tensors.CompressedSparseTensor<T> ToCompressedSparseTensor<T>(this T[,,] array, bool reverseStride = false) { throw null; } public static System.Numerics.Tensors.CompressedSparseTensor<T> ToCompressedSparseTensor<T>(this T[,] array, bool reverseStride = false) { throw null; } public static System.Numerics.Tensors.CompressedSparseTensor<T> ToCompressedSparseTensor<T>(this T[] array) { throw null; } public static System.Numerics.Tensors.SparseTensor<T> ToSparseTensor<T>(this System.Array array, bool reverseStride = false) { throw null; } public static System.Numerics.Tensors.SparseTensor<T> ToSparseTensor<T>(this T[,,] array, bool reverseStride = false) { throw null; } public static System.Numerics.Tensors.SparseTensor<T> ToSparseTensor<T>(this T[,] array, bool reverseStride = false) { throw null; } public static System.Numerics.Tensors.SparseTensor<T> ToSparseTensor<T>(this T[] array) { throw null; } public static System.Numerics.Tensors.DenseTensor<T> ToTensor<T>(this System.Array array, bool reverseStride = false) { throw null; } public static System.Numerics.Tensors.DenseTensor<T> ToTensor<T>(this T[,,] array, bool reverseStride = false) { throw null; } public static System.Numerics.Tensors.DenseTensor<T> ToTensor<T>(this T[,] array, bool reverseStride = false) { throw null; } public static System.Numerics.Tensors.DenseTensor<T> ToTensor<T>(this T[] array) { throw null; } } public partial class CompressedSparseTensor<T> : System.Numerics.Tensors.Tensor<T> { public CompressedSparseTensor(System.Memory<T> values, System.Memory<int> compressedCounts, System.Memory<int> indices, int nonZeroCount, System.ReadOnlySpan<int> dimensions, bool reverseStride = false) : base (default(System.Array), default(bool)) { } public CompressedSparseTensor(System.ReadOnlySpan<int> dimensions, bool reverseStride = false) : base (default(System.Array), default(bool)) { } public CompressedSparseTensor(System.ReadOnlySpan<int> dimensions, int capacity, bool reverseStride = false) : base (default(System.Array), default(bool)) { } public int Capacity { get { throw null; } } public System.Memory<int> CompressedCounts { get { throw null; } } public System.Memory<int> Indices { get { throw null; } } public override T this[System.ReadOnlySpan<int> indices] { get { throw null; } set { } } public int NonZeroCount { get { throw null; } } public System.Memory<T> Values { get { throw null; } } public override System.Numerics.Tensors.Tensor<T> Clone() { throw null; } public override System.Numerics.Tensors.Tensor<TResult> CloneEmpty<TResult>(System.ReadOnlySpan<int> dimensions) { throw null; } public override T GetValue(int index) { throw null; } public override System.Numerics.Tensors.Tensor<T> Reshape(System.ReadOnlySpan<int> dimensions) { throw null; } public override void SetValue(int index, T value) { } public override System.Numerics.Tensors.CompressedSparseTensor<T> ToCompressedSparseTensor() { throw null; } public override System.Numerics.Tensors.DenseTensor<T> ToDenseTensor() { throw null; } public override System.Numerics.Tensors.SparseTensor<T> ToSparseTensor() { throw null; } } public partial class DenseTensor<T> : System.Numerics.Tensors.Tensor<T> { public DenseTensor(int length) : base (default(System.Array), default(bool)) { } public DenseTensor(System.Memory<T> memory, System.ReadOnlySpan<int> dimensions, bool reverseStride = false) : base (default(System.Array), default(bool)) { } public DenseTensor(System.ReadOnlySpan<int> dimensions, bool reverseStride = false) : base (default(System.Array), default(bool)) { } public System.Memory<T> Buffer { get { throw null; } } public override System.Numerics.Tensors.Tensor<T> Clone() { throw null; } public override System.Numerics.Tensors.Tensor<TResult> CloneEmpty<TResult>(System.ReadOnlySpan<int> dimensions) { throw null; } protected override void CopyTo(T[] array, int arrayIndex) { } public override T GetValue(int index) { throw null; } protected override int IndexOf(T item) { throw null; } public override System.Numerics.Tensors.Tensor<T> Reshape(System.ReadOnlySpan<int> dimensions) { throw null; } public override void SetValue(int index, T value) { } } public partial class SparseTensor<T> : System.Numerics.Tensors.Tensor<T> { public SparseTensor(System.ReadOnlySpan<int> dimensions, bool reverseStride = false, int capacity = 0) : base (default(System.Array), default(bool)) { } public int NonZeroCount { get { throw null; } } public override System.Numerics.Tensors.Tensor<T> Clone() { throw null; } public override System.Numerics.Tensors.Tensor<TResult> CloneEmpty<TResult>(System.ReadOnlySpan<int> dimensions) { throw null; } public override T GetValue(int index) { throw null; } public override System.Numerics.Tensors.Tensor<T> Reshape(System.ReadOnlySpan<int> dimensions) { throw null; } public override void SetValue(int index, T value) { } public override System.Numerics.Tensors.CompressedSparseTensor<T> ToCompressedSparseTensor() { throw null; } public override System.Numerics.Tensors.DenseTensor<T> ToDenseTensor() { throw null; } public override System.Numerics.Tensors.SparseTensor<T> ToSparseTensor() { throw null; } } public static partial class Tensor { public static System.Numerics.Tensors.Tensor<T> CreateFromDiagonal<T>(System.Numerics.Tensors.Tensor<T> diagonal) { throw null; } public static System.Numerics.Tensors.Tensor<T> CreateFromDiagonal<T>(System.Numerics.Tensors.Tensor<T> diagonal, int offset) { throw null; } public static System.Numerics.Tensors.Tensor<T> CreateIdentity<T>(int size) { throw null; } public static System.Numerics.Tensors.Tensor<T> CreateIdentity<T>(int size, bool columMajor) { throw null; } public static System.Numerics.Tensors.Tensor<T> CreateIdentity<T>(int size, bool columMajor, T oneValue) { throw null; } } public abstract partial class Tensor<T> : System.Collections.Generic.ICollection<T>, System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IList<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.Generic.IReadOnlyList<T>, System.Collections.ICollection, System.Collections.IEnumerable, System.Collections.IList, System.Collections.IStructuralComparable, System.Collections.IStructuralEquatable { protected Tensor(System.Array fromArray, bool reverseStride) { } protected Tensor(int length) { } protected Tensor(System.ReadOnlySpan<int> dimensions, bool reverseStride) { } public System.ReadOnlySpan<int> Dimensions { get { throw null; } } public bool IsFixedSize { get { throw null; } } public bool IsReadOnly { get { throw null; } } public bool IsReversedStride { get { throw null; } } public virtual T this[params int[] indices] { get { throw null; } set { } } public virtual T this[System.ReadOnlySpan<int> indices] { get { throw null; } set { } } public long Length { get { throw null; } } public int Rank { get { throw null; } } public System.ReadOnlySpan<int> Strides { get { throw null; } } int System.Collections.Generic.ICollection<T>.Count { get { throw null; } } T System.Collections.Generic.IList<T>.this[int index] { get { throw null; } set { } } int System.Collections.Generic.IReadOnlyCollection<T>.Count { get { throw null; } } T System.Collections.Generic.IReadOnlyList<T>.this[int index] { get { throw null; } } int System.Collections.ICollection.Count { get { throw null; } } bool System.Collections.ICollection.IsSynchronized { get { throw null; } } object System.Collections.ICollection.SyncRoot { get { throw null; } } object? System.Collections.IList.this[int index] { get { throw null; } set { } } public abstract System.Numerics.Tensors.Tensor<T> Clone(); public virtual System.Numerics.Tensors.Tensor<T> CloneEmpty() { throw null; } public virtual System.Numerics.Tensors.Tensor<T> CloneEmpty(System.ReadOnlySpan<int> dimensions) { throw null; } public virtual System.Numerics.Tensors.Tensor<TResult> CloneEmpty<TResult>() { throw null; } public abstract System.Numerics.Tensors.Tensor<TResult> CloneEmpty<TResult>(System.ReadOnlySpan<int> dimensions); public static int Compare(System.Numerics.Tensors.Tensor<T> left, System.Numerics.Tensors.Tensor<T> right) { throw null; } protected virtual bool Contains(T item) { throw null; } protected virtual void CopyTo(T[] array, int arrayIndex) { } public static bool Equals(System.Numerics.Tensors.Tensor<T> left, System.Numerics.Tensors.Tensor<T> right) { throw null; } public virtual void Fill(T value) { } public string GetArrayString(bool includeWhitespace = true) { throw null; } public System.Numerics.Tensors.Tensor<T> GetDiagonal() { throw null; } public System.Numerics.Tensors.Tensor<T> GetDiagonal(int offset) { throw null; } public System.Numerics.Tensors.Tensor<T> GetTriangle() { throw null; } public System.Numerics.Tensors.Tensor<T> GetTriangle(int offset) { throw null; } public System.Numerics.Tensors.Tensor<T> GetUpperTriangle() { throw null; } public System.Numerics.Tensors.Tensor<T> GetUpperTriangle(int offset) { throw null; } public abstract T GetValue(int index); protected virtual int IndexOf(T item) { throw null; } public abstract System.Numerics.Tensors.Tensor<T> Reshape(System.ReadOnlySpan<int> dimensions); public abstract void SetValue(int index, T value); public struct Enumerator : System.Collections.Generic.IEnumerator<T> { public T Current { get; private set; } object? System.Collections.IEnumerator.Current => throw null; public bool MoveNext() => throw null; public void Reset() { } public void Dispose() { } } public Enumerator GetEnumerator() => throw null; void System.Collections.Generic.ICollection<T>.Add(T item) { } void System.Collections.Generic.ICollection<T>.Clear() { } bool System.Collections.Generic.ICollection<T>.Contains(T item) { throw null; } void System.Collections.Generic.ICollection<T>.CopyTo(T[] array, int arrayIndex) { } bool System.Collections.Generic.ICollection<T>.Remove(T item) { throw null; } System.Collections.Generic.IEnumerator<T> System.Collections.Generic.IEnumerable<T>.GetEnumerator() { throw null; } int System.Collections.Generic.IList<T>.IndexOf(T item) { throw null; } void System.Collections.Generic.IList<T>.Insert(int index, T item) { } void System.Collections.Generic.IList<T>.RemoveAt(int index) { } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } int System.Collections.IList.Add(object? value) { throw null; } void System.Collections.IList.Clear() { } bool System.Collections.IList.Contains(object? value) { throw null; } int System.Collections.IList.IndexOf(object? value) { throw null; } void System.Collections.IList.Insert(int index, object? value) { } void System.Collections.IList.Remove(object? value) { } void System.Collections.IList.RemoveAt(int index) { } int System.Collections.IStructuralComparable.CompareTo(object? other, System.Collections.IComparer comparer) { throw null; } bool System.Collections.IStructuralEquatable.Equals(object? other, System.Collections.IEqualityComparer comparer) { throw null; } int System.Collections.IStructuralEquatable.GetHashCode(System.Collections.IEqualityComparer comparer) { throw null; } public virtual System.Numerics.Tensors.CompressedSparseTensor<T> ToCompressedSparseTensor() { throw null; } public virtual System.Numerics.Tensors.DenseTensor<T> ToDenseTensor() { throw null; } public virtual System.Numerics.Tensors.SparseTensor<T> ToSparseTensor() { 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.Numerics.Tensors { public static partial class ArrayTensorExtensions { public static System.Numerics.Tensors.CompressedSparseTensor<T> ToCompressedSparseTensor<T>(this System.Array array, bool reverseStride = false) { throw null; } public static System.Numerics.Tensors.CompressedSparseTensor<T> ToCompressedSparseTensor<T>(this T[,,] array, bool reverseStride = false) { throw null; } public static System.Numerics.Tensors.CompressedSparseTensor<T> ToCompressedSparseTensor<T>(this T[,] array, bool reverseStride = false) { throw null; } public static System.Numerics.Tensors.CompressedSparseTensor<T> ToCompressedSparseTensor<T>(this T[] array) { throw null; } public static System.Numerics.Tensors.SparseTensor<T> ToSparseTensor<T>(this System.Array array, bool reverseStride = false) { throw null; } public static System.Numerics.Tensors.SparseTensor<T> ToSparseTensor<T>(this T[,,] array, bool reverseStride = false) { throw null; } public static System.Numerics.Tensors.SparseTensor<T> ToSparseTensor<T>(this T[,] array, bool reverseStride = false) { throw null; } public static System.Numerics.Tensors.SparseTensor<T> ToSparseTensor<T>(this T[] array) { throw null; } public static System.Numerics.Tensors.DenseTensor<T> ToTensor<T>(this System.Array array, bool reverseStride = false) { throw null; } public static System.Numerics.Tensors.DenseTensor<T> ToTensor<T>(this T[,,] array, bool reverseStride = false) { throw null; } public static System.Numerics.Tensors.DenseTensor<T> ToTensor<T>(this T[,] array, bool reverseStride = false) { throw null; } public static System.Numerics.Tensors.DenseTensor<T> ToTensor<T>(this T[] array) { throw null; } } public partial class CompressedSparseTensor<T> : System.Numerics.Tensors.Tensor<T> { public CompressedSparseTensor(System.Memory<T> values, System.Memory<int> compressedCounts, System.Memory<int> indices, int nonZeroCount, System.ReadOnlySpan<int> dimensions, bool reverseStride = false) : base (default(System.Array), default(bool)) { } public CompressedSparseTensor(System.ReadOnlySpan<int> dimensions, bool reverseStride = false) : base (default(System.Array), default(bool)) { } public CompressedSparseTensor(System.ReadOnlySpan<int> dimensions, int capacity, bool reverseStride = false) : base (default(System.Array), default(bool)) { } public int Capacity { get { throw null; } } public System.Memory<int> CompressedCounts { get { throw null; } } public System.Memory<int> Indices { get { throw null; } } public override T this[System.ReadOnlySpan<int> indices] { get { throw null; } set { } } public int NonZeroCount { get { throw null; } } public System.Memory<T> Values { get { throw null; } } public override System.Numerics.Tensors.Tensor<T> Clone() { throw null; } public override System.Numerics.Tensors.Tensor<TResult> CloneEmpty<TResult>(System.ReadOnlySpan<int> dimensions) { throw null; } public override T GetValue(int index) { throw null; } public override System.Numerics.Tensors.Tensor<T> Reshape(System.ReadOnlySpan<int> dimensions) { throw null; } public override void SetValue(int index, T value) { } public override System.Numerics.Tensors.CompressedSparseTensor<T> ToCompressedSparseTensor() { throw null; } public override System.Numerics.Tensors.DenseTensor<T> ToDenseTensor() { throw null; } public override System.Numerics.Tensors.SparseTensor<T> ToSparseTensor() { throw null; } } public partial class DenseTensor<T> : System.Numerics.Tensors.Tensor<T> { public DenseTensor(int length) : base (default(System.Array), default(bool)) { } public DenseTensor(System.Memory<T> memory, System.ReadOnlySpan<int> dimensions, bool reverseStride = false) : base (default(System.Array), default(bool)) { } public DenseTensor(System.ReadOnlySpan<int> dimensions, bool reverseStride = false) : base (default(System.Array), default(bool)) { } public System.Memory<T> Buffer { get { throw null; } } public override System.Numerics.Tensors.Tensor<T> Clone() { throw null; } public override System.Numerics.Tensors.Tensor<TResult> CloneEmpty<TResult>(System.ReadOnlySpan<int> dimensions) { throw null; } protected override void CopyTo(T[] array, int arrayIndex) { } public override T GetValue(int index) { throw null; } protected override int IndexOf(T item) { throw null; } public override System.Numerics.Tensors.Tensor<T> Reshape(System.ReadOnlySpan<int> dimensions) { throw null; } public override void SetValue(int index, T value) { } } public partial class SparseTensor<T> : System.Numerics.Tensors.Tensor<T> { public SparseTensor(System.ReadOnlySpan<int> dimensions, bool reverseStride = false, int capacity = 0) : base (default(System.Array), default(bool)) { } public int NonZeroCount { get { throw null; } } public override System.Numerics.Tensors.Tensor<T> Clone() { throw null; } public override System.Numerics.Tensors.Tensor<TResult> CloneEmpty<TResult>(System.ReadOnlySpan<int> dimensions) { throw null; } public override T GetValue(int index) { throw null; } public override System.Numerics.Tensors.Tensor<T> Reshape(System.ReadOnlySpan<int> dimensions) { throw null; } public override void SetValue(int index, T value) { } public override System.Numerics.Tensors.CompressedSparseTensor<T> ToCompressedSparseTensor() { throw null; } public override System.Numerics.Tensors.DenseTensor<T> ToDenseTensor() { throw null; } public override System.Numerics.Tensors.SparseTensor<T> ToSparseTensor() { throw null; } } public static partial class Tensor { public static System.Numerics.Tensors.Tensor<T> CreateFromDiagonal<T>(System.Numerics.Tensors.Tensor<T> diagonal) { throw null; } public static System.Numerics.Tensors.Tensor<T> CreateFromDiagonal<T>(System.Numerics.Tensors.Tensor<T> diagonal, int offset) { throw null; } public static System.Numerics.Tensors.Tensor<T> CreateIdentity<T>(int size) { throw null; } public static System.Numerics.Tensors.Tensor<T> CreateIdentity<T>(int size, bool columMajor) { throw null; } public static System.Numerics.Tensors.Tensor<T> CreateIdentity<T>(int size, bool columMajor, T oneValue) { throw null; } } public abstract partial class Tensor<T> : System.Collections.Generic.ICollection<T>, System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IList<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.Generic.IReadOnlyList<T>, System.Collections.ICollection, System.Collections.IEnumerable, System.Collections.IList, System.Collections.IStructuralComparable, System.Collections.IStructuralEquatable { protected Tensor(System.Array fromArray, bool reverseStride) { } protected Tensor(int length) { } protected Tensor(System.ReadOnlySpan<int> dimensions, bool reverseStride) { } public System.ReadOnlySpan<int> Dimensions { get { throw null; } } public bool IsFixedSize { get { throw null; } } public bool IsReadOnly { get { throw null; } } public bool IsReversedStride { get { throw null; } } public virtual T this[params int[] indices] { get { throw null; } set { } } public virtual T this[System.ReadOnlySpan<int> indices] { get { throw null; } set { } } public long Length { get { throw null; } } public int Rank { get { throw null; } } public System.ReadOnlySpan<int> Strides { get { throw null; } } int System.Collections.Generic.ICollection<T>.Count { get { throw null; } } T System.Collections.Generic.IList<T>.this[int index] { get { throw null; } set { } } int System.Collections.Generic.IReadOnlyCollection<T>.Count { get { throw null; } } T System.Collections.Generic.IReadOnlyList<T>.this[int index] { get { throw null; } } int System.Collections.ICollection.Count { get { throw null; } } bool System.Collections.ICollection.IsSynchronized { get { throw null; } } object System.Collections.ICollection.SyncRoot { get { throw null; } } object? System.Collections.IList.this[int index] { get { throw null; } set { } } public abstract System.Numerics.Tensors.Tensor<T> Clone(); public virtual System.Numerics.Tensors.Tensor<T> CloneEmpty() { throw null; } public virtual System.Numerics.Tensors.Tensor<T> CloneEmpty(System.ReadOnlySpan<int> dimensions) { throw null; } public virtual System.Numerics.Tensors.Tensor<TResult> CloneEmpty<TResult>() { throw null; } public abstract System.Numerics.Tensors.Tensor<TResult> CloneEmpty<TResult>(System.ReadOnlySpan<int> dimensions); public static int Compare(System.Numerics.Tensors.Tensor<T> left, System.Numerics.Tensors.Tensor<T> right) { throw null; } protected virtual bool Contains(T item) { throw null; } protected virtual void CopyTo(T[] array, int arrayIndex) { } public static bool Equals(System.Numerics.Tensors.Tensor<T> left, System.Numerics.Tensors.Tensor<T> right) { throw null; } public virtual void Fill(T value) { } public string GetArrayString(bool includeWhitespace = true) { throw null; } public System.Numerics.Tensors.Tensor<T> GetDiagonal() { throw null; } public System.Numerics.Tensors.Tensor<T> GetDiagonal(int offset) { throw null; } public System.Numerics.Tensors.Tensor<T> GetTriangle() { throw null; } public System.Numerics.Tensors.Tensor<T> GetTriangle(int offset) { throw null; } public System.Numerics.Tensors.Tensor<T> GetUpperTriangle() { throw null; } public System.Numerics.Tensors.Tensor<T> GetUpperTriangle(int offset) { throw null; } public abstract T GetValue(int index); protected virtual int IndexOf(T item) { throw null; } public abstract System.Numerics.Tensors.Tensor<T> Reshape(System.ReadOnlySpan<int> dimensions); public abstract void SetValue(int index, T value); public struct Enumerator : System.Collections.Generic.IEnumerator<T> { public T Current { get; private set; } object? System.Collections.IEnumerator.Current => throw null; public bool MoveNext() => throw null; public void Reset() { } public void Dispose() { } } public Enumerator GetEnumerator() => throw null; void System.Collections.Generic.ICollection<T>.Add(T item) { } void System.Collections.Generic.ICollection<T>.Clear() { } bool System.Collections.Generic.ICollection<T>.Contains(T item) { throw null; } void System.Collections.Generic.ICollection<T>.CopyTo(T[] array, int arrayIndex) { } bool System.Collections.Generic.ICollection<T>.Remove(T item) { throw null; } System.Collections.Generic.IEnumerator<T> System.Collections.Generic.IEnumerable<T>.GetEnumerator() { throw null; } int System.Collections.Generic.IList<T>.IndexOf(T item) { throw null; } void System.Collections.Generic.IList<T>.Insert(int index, T item) { } void System.Collections.Generic.IList<T>.RemoveAt(int index) { } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } int System.Collections.IList.Add(object? value) { throw null; } void System.Collections.IList.Clear() { } bool System.Collections.IList.Contains(object? value) { throw null; } int System.Collections.IList.IndexOf(object? value) { throw null; } void System.Collections.IList.Insert(int index, object? value) { } void System.Collections.IList.Remove(object? value) { } void System.Collections.IList.RemoveAt(int index) { } int System.Collections.IStructuralComparable.CompareTo(object? other, System.Collections.IComparer comparer) { throw null; } bool System.Collections.IStructuralEquatable.Equals(object? other, System.Collections.IEqualityComparer comparer) { throw null; } int System.Collections.IStructuralEquatable.GetHashCode(System.Collections.IEqualityComparer comparer) { throw null; } public virtual System.Numerics.Tensors.CompressedSparseTensor<T> ToCompressedSparseTensor() { throw null; } public virtual System.Numerics.Tensors.DenseTensor<T> ToDenseTensor() { throw null; } public virtual System.Numerics.Tensors.SparseTensor<T> ToSparseTensor() { throw null; } } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/tests/Loader/classloader/TypeGeneratorTests/TypeGeneratorTest1095/Generated1095.ilproj
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="Generated1095.il" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\TestFramework\TestFramework.csproj" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <ItemGroup> <Compile Include="Generated1095.il" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\TestFramework\TestFramework.csproj" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/tests/JIT/Methodical/MDArray/DataTypes/long.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 VT { public long[,] long2darr; public long[, ,] long3darr; public long[,] long2darr_b; public long[, ,] long3darr_b; public long[,] long2darr_c; public long[, ,] long3darr_c; } public class CL { public long[,] long2darr = { { 0, -1 }, { 0, 0 } }; public long[, ,] long3darr = { { { 0, 0 } }, { { 0, -1 } }, { { 0, 0 } } }; public long[,] long2darr_b = { { 0, 1 }, { 0, 0 } }; public long[, ,] long3darr_b = { { { 0, 0 } }, { { 0, 1 } }, { { 0, 0 } } }; public long[,] long2darr_c = { { 0, 49 }, { 0, 0 } }; public long[, ,] long3darr_c = { { { 0, 0 } }, { { 0, 49 } }, { { 0, 0 } } }; } public class longMDArrTest { static long[,] long2darr = { { 0, -1 }, { 0, 0 } }; static long[, ,] long3darr = { { { 0, 0 } }, { { 0, -1 } }, { { 0, 0 } } }; static long[,] long2darr_b = { { 0, 1 }, { 0, 0 } }; static long[, ,] long3darr_b = { { { 0, 0 } }, { { 0, 1 } }, { { 0, 0 } } }; static long[,] long2darr_c = { { 0, 49 }, { 0, 0 } }; static long[, ,] long3darr_c = { { { 0, 0 } }, { { 0, 49 } }, { { 0, 0 } } }; static long[][,] ja1 = new long[2][,]; static long[][, ,] ja2 = new long[2][, ,]; static long[][,] ja1_b = new long[2][,]; static long[][, ,] ja2_b = new long[2][, ,]; static long[][,] ja1_c = new long[2][,]; static long[][, ,] ja2_c = new long[2][, ,]; public static int Main() { bool pass = true; VT vt1; vt1.long2darr = new long[,] { { 0, -1 }, { 0, 0 } }; vt1.long3darr = new long[,,] { { { 0, 0 } }, { { 0, -1 } }, { { 0, 0 } } }; vt1.long2darr_b = new long[,] { { 0, 1 }, { 0, 0 } }; vt1.long3darr_b = new long[,,] { { { 0, 0 } }, { { 0, 1 } }, { { 0, 0 } } }; vt1.long2darr_c = new long[,] { { 0, 49 }, { 0, 0 } }; vt1.long3darr_c = new long[,,] { { { 0, 0 } }, { { 0, 49 } }, { { 0, 0 } } }; CL cl1 = new CL(); ja1[0] = new long[,] { { 0, -1 }, { 0, 0 } }; ja2[1] = new long[,,] { { { 0, 0 } }, { { 0, -1 } }, { { 0, 0 } } }; ja1_b[0] = new long[,] { { 0, 1 }, { 0, 0 } }; ja2_b[1] = new long[,,] { { { 0, 0 } }, { { 0, 1 } }, { { 0, 0 } } }; ja1_c[0] = new long[,] { { 0, 49 }, { 0, 0 } }; ja2_c[1] = new long[,,] { { { 0, 0 } }, { { 0, 49 } }, { { 0, 0 } } }; long result = -1; // 2D if (result != long2darr[0, 1]) { Console.WriteLine("ERROR:"); Console.WriteLine("result is: {0}", result); Console.WriteLine("2darr[0, 1] is: {0}", long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (result != vt1.long2darr[0, 1]) { Console.WriteLine("ERROR:"); Console.WriteLine("result is: {0}", result); Console.WriteLine("vt1.long2darr[0, 1] is: {0}", vt1.long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (result != cl1.long2darr[0, 1]) { Console.WriteLine("ERROR:"); Console.WriteLine("result is: {0}", result); Console.WriteLine("cl1.long2darr[0, 1] is: {0}", cl1.long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (result != ja1[0][0, 1]) { Console.WriteLine("ERROR:"); Console.WriteLine("result is: {0}", result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (result != long3darr[1, 0, 1]) { Console.WriteLine("ERROR:"); Console.WriteLine("result is: {0}", result); Console.WriteLine("long3darr[1,0,1] is: {0}", long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (result != vt1.long3darr[1, 0, 1]) { Console.WriteLine("ERROR:"); Console.WriteLine("result is: {0}", result); Console.WriteLine("vt1.long3darr[1,0,1] is: {0}", vt1.long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (result != cl1.long3darr[1, 0, 1]) { Console.WriteLine("ERROR:"); Console.WriteLine("result is: {0}", result); Console.WriteLine("cl1.long3darr[1,0,1] is: {0}", cl1.long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (result != ja2[1][1, 0, 1]) { Console.WriteLine("ERROR:"); Console.WriteLine("result is: {0}", result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //Int64ToBool bool Bool_result = true; // 2D if (Bool_result != Convert.ToBoolean(long2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Bool_result is: {0}", Bool_result); Console.WriteLine("2darr[0, 1] is: {0}", long2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Bool_result != Convert.ToBoolean(vt1.long2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Bool_result is: {0}", Bool_result); Console.WriteLine("vt1.long2darr_b[0, 1] is: {0}", vt1.long2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Bool_result != Convert.ToBoolean(cl1.long2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Bool_result is: {0}", Bool_result); Console.WriteLine("cl1.long2darr_b[0, 1] is: {0}", cl1.long2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Bool_result != Convert.ToBoolean(ja1_b[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Bool_result is: {0}", Bool_result); Console.WriteLine("ja1_b[0][0, 1] is: {0}", ja1_b[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (Bool_result != Convert.ToBoolean(long3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Bool_result is: {0}", Bool_result); Console.WriteLine("long3darr_b[1,0,1] is: {0}", long3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Bool_result != Convert.ToBoolean(vt1.long3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Bool_result is: {0}", Bool_result); Console.WriteLine("vt1.long3darr_b[1,0,1] is: {0}", vt1.long3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Bool_result != Convert.ToBoolean(cl1.long3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Bool_result is: {0}", Bool_result); Console.WriteLine("cl1.long3darr_b[1,0,1] is: {0}", cl1.long3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Bool_result != Convert.ToBoolean(ja2_b[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Bool_result is: {0}", Bool_result); Console.WriteLine("ja2_b[1][1,0,1] is: {0}", ja2_b[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //Int64ToByte tests byte Byte_result = 1; // 2D if (Byte_result != Convert.ToByte(long2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Byte_result is: {0}", Byte_result); Console.WriteLine("2darr[0, 1] is: {0}", long2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Byte_result != Convert.ToByte(vt1.long2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Byte_result is: {0}", Byte_result); Console.WriteLine("vt1.long2darr_b[0, 1] is: {0}", vt1.long2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Byte_result != Convert.ToByte(cl1.long2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Byte_result is: {0}", Byte_result); Console.WriteLine("cl1.long2darr_b[0, 1] is: {0}", cl1.long2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Byte_result != Convert.ToByte(ja1_b[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Byte_result is: {0}", Byte_result); Console.WriteLine("ja1_b[0][0, 1] is: {0}", ja1_b[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (Byte_result != Convert.ToByte(long3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Byte_result is: {0}", Byte_result); Console.WriteLine("long3darr_b[1,0,1] is: {0}", long3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Byte_result != Convert.ToByte(vt1.long3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Byte_result is: {0}", Byte_result); Console.WriteLine("vt1.long3darr_b[1,0,1] is: {0}", vt1.long3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Byte_result != Convert.ToByte(cl1.long3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Byte_result is: {0}", Byte_result); Console.WriteLine("cl1.long3darr_b[1,0,1] is: {0}", cl1.long3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Byte_result != Convert.ToByte(ja2_b[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Byte_result is: {0}", Byte_result); Console.WriteLine("ja2_b[1][1,0,1] is: {0}", ja2_b[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //Int64ToChar tests char Char_result = '1'; // 2D if (Char_result != Convert.ToChar(long2darr_c[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Char_result is: {0}", Char_result); Console.WriteLine("2darr[0, 1] is: {0}", long2darr_c[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Char_result != Convert.ToChar(vt1.long2darr_c[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Char_result is: {0}", Char_result); Console.WriteLine("vt1.long2darr_c[0, 1] is: {0}", vt1.long2darr_c[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Char_result != Convert.ToChar(cl1.long2darr_c[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Char_result is: {0}", Char_result); Console.WriteLine("cl1.long2darr_c[0, 1] is: {0}", cl1.long2darr_c[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Char_result != Convert.ToChar(ja1_c[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Char_result is: {0}", Char_result); Console.WriteLine("ja1_c[0][0, 1] is: {0}", ja1_c[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (Char_result != Convert.ToChar(long3darr_c[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Char_result is: {0}", Char_result); Console.WriteLine("long3darr_c[1,0,1] is: {0}", long3darr_c[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Char_result != Convert.ToChar(vt1.long3darr_c[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Char_result is: {0}", Char_result); Console.WriteLine("vt1.long3darr_c[1,0,1] is: {0}", vt1.long3darr_c[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Char_result != Convert.ToChar(cl1.long3darr_c[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Char_result is: {0}", Char_result); Console.WriteLine("cl1.long3darr_c[1,0,1] is: {0}", cl1.long3darr_c[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Char_result != Convert.ToChar(ja2_c[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Char_result is: {0}", Char_result); Console.WriteLine("ja2_c[1][1,0,1] is: {0}", ja2_c[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //Int64ToDecimal tests decimal Decimal_result = -1; // 2D if (Decimal_result != Convert.ToDecimal(long2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Decimal_result is: {0}", Decimal_result); Console.WriteLine("2darr[0, 1] is: {0}", long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Decimal_result != Convert.ToDecimal(vt1.long2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Decimal_result is: {0}", Decimal_result); Console.WriteLine("vt1.long2darr[0, 1] is: {0}", vt1.long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Decimal_result != Convert.ToDecimal(cl1.long2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Decimal_result is: {0}", Decimal_result); Console.WriteLine("cl1.long2darr[0, 1] is: {0}", cl1.long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Decimal_result != Convert.ToDecimal(ja1[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Decimal_result is: {0}", Decimal_result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (Decimal_result != Convert.ToDecimal(long3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Decimal_result is: {0}", Decimal_result); Console.WriteLine("long3darr[1,0,1] is: {0}", long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Decimal_result != Convert.ToDecimal(vt1.long3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Decimal_result is: {0}", Decimal_result); Console.WriteLine("vt1.long3darr[1,0,1] is: {0}", vt1.long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Decimal_result != Convert.ToDecimal(cl1.long3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Decimal_result is: {0}", Decimal_result); Console.WriteLine("cl1.long3darr[1,0,1] is: {0}", cl1.long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Decimal_result != Convert.ToDecimal(ja2[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Decimal_result is: {0}", Decimal_result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //Int64ToDouble double Double_result = -1; // 2D if (Double_result != Convert.ToDouble(long2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Double_result is: {0}", Double_result); Console.WriteLine("2darr[0, 1] is: {0}", long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Double_result != Convert.ToDouble(vt1.long2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Double_result is: {0}", Double_result); Console.WriteLine("vt1.long2darr[0, 1] is: {0}", vt1.long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Double_result != Convert.ToDouble(cl1.long2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Double_result is: {0}", Double_result); Console.WriteLine("cl1.long2darr[0, 1] is: {0}", cl1.long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Double_result != Convert.ToDouble(ja1[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Double_result is: {0}", Double_result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (Double_result != Convert.ToDouble(long3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Double_result is: {0}", Double_result); Console.WriteLine("long3darr[1,0,1] is: {0}", long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Double_result != Convert.ToDouble(vt1.long3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Double_result is: {0}", Double_result); Console.WriteLine("vt1.long3darr[1,0,1] is: {0}", vt1.long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Double_result != Convert.ToDouble(cl1.long3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Double_result is: {0}", Double_result); Console.WriteLine("cl1.long3darr[1,0,1] is: {0}", cl1.long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Double_result != Convert.ToDouble(ja2[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Double_result is: {0}", Double_result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //Int64ToSingle tests float Single_result = -1; // 2D if (Single_result != Convert.ToSingle(long2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Single_result is: {0}", Single_result); Console.WriteLine("2darr[0, 1] is: {0}", long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Single_result != Convert.ToSingle(vt1.long2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Single_result is: {0}", Single_result); Console.WriteLine("vt1.long2darr[0, 1] is: {0}", vt1.long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Single_result != Convert.ToSingle(cl1.long2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Single_result is: {0}", Single_result); Console.WriteLine("cl1.long2darr[0, 1] is: {0}", cl1.long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Single_result != Convert.ToSingle(ja1[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Single_result is: {0}", Single_result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (Single_result != Convert.ToSingle(long3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Single_result is: {0}", Single_result); Console.WriteLine("long3darr[1,0,1] is: {0}", long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Single_result != Convert.ToSingle(vt1.long3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Single_result is: {0}", Single_result); Console.WriteLine("vt1.long3darr[1,0,1] is: {0}", vt1.long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Single_result != Convert.ToSingle(cl1.long3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Single_result is: {0}", Single_result); Console.WriteLine("cl1.long3darr[1,0,1] is: {0}", cl1.long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Single_result != Convert.ToSingle(ja2[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Single_result is: {0}", Single_result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //Int64ToInt32 tests int Int32_result = -1; // 2D if (Int32_result != Convert.ToInt32(long2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int32_result is: {0}", Int32_result); Console.WriteLine("2darr[0, 1] is: {0}", long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int32_result != Convert.ToInt32(vt1.long2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int32_result is: {0}", Int32_result); Console.WriteLine("vt1.long2darr[0, 1] is: {0}", vt1.long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int32_result != Convert.ToInt32(cl1.long2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int32_result is: {0}", Int32_result); Console.WriteLine("cl1.long2darr[0, 1] is: {0}", cl1.long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int32_result != Convert.ToInt32(ja1[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int32_result is: {0}", Int32_result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (Int32_result != Convert.ToInt32(long3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int32_result is: {0}", Int32_result); Console.WriteLine("long3darr[1,0,1] is: {0}", long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int32_result != Convert.ToInt32(vt1.long3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int32_result is: {0}", Int32_result); Console.WriteLine("vt1.long3darr[1,0,1] is: {0}", vt1.long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int32_result != Convert.ToInt32(cl1.long3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int32_result is: {0}", Int32_result); Console.WriteLine("cl1.long3darr[1,0,1] is: {0}", cl1.long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int32_result != Convert.ToInt32(ja2[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int32_result is: {0}", Int32_result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //Int64ToSByte tests sbyte SByte_result = -1; // 2D if (SByte_result != Convert.ToSByte(long2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("SByte_result is: {0}", SByte_result); Console.WriteLine("2darr[0, 1] is: {0}", long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (SByte_result != Convert.ToSByte(vt1.long2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("SByte_result is: {0}", SByte_result); Console.WriteLine("vt1.long2darr[0, 1] is: {0}", vt1.long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (SByte_result != Convert.ToSByte(cl1.long2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("SByte_result is: {0}", SByte_result); Console.WriteLine("cl1.long2darr[0, 1] is: {0}", cl1.long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (SByte_result != Convert.ToSByte(ja1[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("SByte_result is: {0}", SByte_result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (SByte_result != Convert.ToSByte(long3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("SByte_result is: {0}", SByte_result); Console.WriteLine("long3darr[1,0,1] is: {0}", long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (SByte_result != Convert.ToSByte(vt1.long3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("SByte_result is: {0}", SByte_result); Console.WriteLine("vt1.long3darr[1,0,1] is: {0}", vt1.long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (SByte_result != Convert.ToSByte(cl1.long3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("SByte_result is: {0}", SByte_result); Console.WriteLine("cl1.long3darr[1,0,1] is: {0}", cl1.long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (SByte_result != Convert.ToSByte(ja2[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("SByte_result is: {0}", SByte_result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //Int64ToInt16 tests short Int16_result = -1; // 2D if (Int16_result != Convert.ToInt16(long2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int16_result is: {0}", Int16_result); Console.WriteLine("2darr[0, 1] is: {0}", long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int16_result != Convert.ToInt16(vt1.long2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int16_result is: {0}", Int16_result); Console.WriteLine("vt1.long2darr[0, 1] is: {0}", vt1.long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int16_result != Convert.ToInt16(cl1.long2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int16_result is: {0}", Int16_result); Console.WriteLine("cl1.long2darr[0, 1] is: {0}", cl1.long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int16_result != Convert.ToInt16(ja1[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int16_result is: {0}", Int16_result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (Int16_result != Convert.ToInt16(long3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int16_result is: {0}", Int16_result); Console.WriteLine("long3darr[1,0,1] is: {0}", long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int16_result != Convert.ToInt16(vt1.long3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int16_result is: {0}", Int16_result); Console.WriteLine("vt1.long3darr[1,0,1] is: {0}", vt1.long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int16_result != Convert.ToInt16(cl1.long3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int16_result is: {0}", Int16_result); Console.WriteLine("cl1.long3darr[1,0,1] is: {0}", cl1.long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int16_result != Convert.ToInt16(ja2[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int16_result is: {0}", Int16_result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //Int64ToUInt32 tests uint UInt32_result = 1; // 2D if (UInt32_result != Convert.ToUInt32(long2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt32_result is: {0}", UInt32_result); Console.WriteLine("2darr[0, 1] is: {0}", long2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt32_result != Convert.ToUInt32(vt1.long2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt32_result is: {0}", UInt32_result); Console.WriteLine("vt1.long2darr_b[0, 1] is: {0}", vt1.long2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt32_result != Convert.ToUInt32(cl1.long2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt32_result is: {0}", UInt32_result); Console.WriteLine("cl1.long2darr_b[0, 1] is: {0}", cl1.long2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt32_result != Convert.ToUInt32(ja1_b[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt32_result is: {0}", UInt32_result); Console.WriteLine("ja1_b[0][0, 1] is: {0}", ja1_b[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (UInt32_result != Convert.ToUInt32(long3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt32_result is: {0}", UInt32_result); Console.WriteLine("long3darr_b[1,0,1] is: {0}", long3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt32_result != Convert.ToUInt32(vt1.long3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt32_result is: {0}", UInt32_result); Console.WriteLine("vt1.long3darr_b[1,0,1] is: {0}", vt1.long3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt32_result != Convert.ToUInt32(cl1.long3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt32_result is: {0}", UInt32_result); Console.WriteLine("cl1.long3darr_b[1,0,1] is: {0}", cl1.long3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt32_result != Convert.ToUInt32(ja2_b[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt32_result is: {0}", UInt32_result); Console.WriteLine("ja2_b[1][1,0,1] is: {0}", ja2_b[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //Int64ToUInt64 tests ulong UInt64_result = 1; // 2D if (UInt64_result != Convert.ToUInt64(long2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt64_result is: {0}", UInt64_result); Console.WriteLine("2darr[0, 1] is: {0}", long2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt64_result != Convert.ToUInt64(vt1.long2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt64_result is: {0}", UInt64_result); Console.WriteLine("vt1.long2darr_b[0, 1] is: {0}", vt1.long2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt64_result != Convert.ToUInt64(cl1.long2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt64_result is: {0}", UInt64_result); Console.WriteLine("cl1.long2darr_b[0, 1] is: {0}", cl1.long2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt64_result != Convert.ToUInt64(ja1_b[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt64_result is: {0}", UInt64_result); Console.WriteLine("ja1_b[0][0, 1] is: {0}", ja1_b[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (UInt64_result != Convert.ToUInt64(long3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt64_result is: {0}", UInt64_result); Console.WriteLine("long3darr_b[1,0,1] is: {0}", long3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt64_result != Convert.ToUInt64(vt1.long3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt64_result is: {0}", UInt64_result); Console.WriteLine("vt1.long3darr_b[1,0,1] is: {0}", vt1.long3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt64_result != Convert.ToUInt64(cl1.long3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt64_result is: {0}", UInt64_result); Console.WriteLine("cl1.long3darr_b[1,0,1] is: {0}", cl1.long3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt64_result != Convert.ToUInt64(ja2_b[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt64_result is: {0}", UInt64_result); Console.WriteLine("ja2_b[1][1,0,1] is: {0}", ja2_b[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //Int64ToUInt16 tests ushort UInt16_result = 1; // 2D if (UInt16_result != Convert.ToUInt16(long2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt16_result is: {0}", UInt16_result); Console.WriteLine("2darr[0, 1] is: {0}", long2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt16_result != Convert.ToUInt16(vt1.long2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt16_result is: {0}", UInt16_result); Console.WriteLine("vt1.long2darr_b[0, 1] is: {0}", vt1.long2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt16_result != Convert.ToUInt16(cl1.long2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt16_result is: {0}", UInt16_result); Console.WriteLine("cl1.long2darr_b[0, 1] is: {0}", cl1.long2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt16_result != Convert.ToUInt16(ja1_b[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt16_result is: {0}", UInt16_result); Console.WriteLine("ja1_b[0][0, 1] is: {0}", ja1_b[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (UInt16_result != Convert.ToUInt16(long3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt16_result is: {0}", UInt16_result); Console.WriteLine("long3darr_b[1,0,1] is: {0}", long3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt16_result != Convert.ToUInt16(vt1.long3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt16_result is: {0}", UInt16_result); Console.WriteLine("vt1.long3darr_b[1,0,1] is: {0}", vt1.long3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt16_result != Convert.ToUInt16(cl1.long3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt16_result is: {0}", UInt16_result); Console.WriteLine("cl1.long3darr_b[1,0,1] is: {0}", cl1.long3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt16_result != Convert.ToUInt16(ja2_b[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt16_result is: {0}", UInt16_result); Console.WriteLine("ja2_b[1][1,0,1] is: {0}", ja2_b[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (!pass) { Console.WriteLine("FAILED"); return 1; } else { Console.WriteLine("PASSED"); return 100; } } };
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // using System; public struct VT { public long[,] long2darr; public long[, ,] long3darr; public long[,] long2darr_b; public long[, ,] long3darr_b; public long[,] long2darr_c; public long[, ,] long3darr_c; } public class CL { public long[,] long2darr = { { 0, -1 }, { 0, 0 } }; public long[, ,] long3darr = { { { 0, 0 } }, { { 0, -1 } }, { { 0, 0 } } }; public long[,] long2darr_b = { { 0, 1 }, { 0, 0 } }; public long[, ,] long3darr_b = { { { 0, 0 } }, { { 0, 1 } }, { { 0, 0 } } }; public long[,] long2darr_c = { { 0, 49 }, { 0, 0 } }; public long[, ,] long3darr_c = { { { 0, 0 } }, { { 0, 49 } }, { { 0, 0 } } }; } public class longMDArrTest { static long[,] long2darr = { { 0, -1 }, { 0, 0 } }; static long[, ,] long3darr = { { { 0, 0 } }, { { 0, -1 } }, { { 0, 0 } } }; static long[,] long2darr_b = { { 0, 1 }, { 0, 0 } }; static long[, ,] long3darr_b = { { { 0, 0 } }, { { 0, 1 } }, { { 0, 0 } } }; static long[,] long2darr_c = { { 0, 49 }, { 0, 0 } }; static long[, ,] long3darr_c = { { { 0, 0 } }, { { 0, 49 } }, { { 0, 0 } } }; static long[][,] ja1 = new long[2][,]; static long[][, ,] ja2 = new long[2][, ,]; static long[][,] ja1_b = new long[2][,]; static long[][, ,] ja2_b = new long[2][, ,]; static long[][,] ja1_c = new long[2][,]; static long[][, ,] ja2_c = new long[2][, ,]; public static int Main() { bool pass = true; VT vt1; vt1.long2darr = new long[,] { { 0, -1 }, { 0, 0 } }; vt1.long3darr = new long[,,] { { { 0, 0 } }, { { 0, -1 } }, { { 0, 0 } } }; vt1.long2darr_b = new long[,] { { 0, 1 }, { 0, 0 } }; vt1.long3darr_b = new long[,,] { { { 0, 0 } }, { { 0, 1 } }, { { 0, 0 } } }; vt1.long2darr_c = new long[,] { { 0, 49 }, { 0, 0 } }; vt1.long3darr_c = new long[,,] { { { 0, 0 } }, { { 0, 49 } }, { { 0, 0 } } }; CL cl1 = new CL(); ja1[0] = new long[,] { { 0, -1 }, { 0, 0 } }; ja2[1] = new long[,,] { { { 0, 0 } }, { { 0, -1 } }, { { 0, 0 } } }; ja1_b[0] = new long[,] { { 0, 1 }, { 0, 0 } }; ja2_b[1] = new long[,,] { { { 0, 0 } }, { { 0, 1 } }, { { 0, 0 } } }; ja1_c[0] = new long[,] { { 0, 49 }, { 0, 0 } }; ja2_c[1] = new long[,,] { { { 0, 0 } }, { { 0, 49 } }, { { 0, 0 } } }; long result = -1; // 2D if (result != long2darr[0, 1]) { Console.WriteLine("ERROR:"); Console.WriteLine("result is: {0}", result); Console.WriteLine("2darr[0, 1] is: {0}", long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (result != vt1.long2darr[0, 1]) { Console.WriteLine("ERROR:"); Console.WriteLine("result is: {0}", result); Console.WriteLine("vt1.long2darr[0, 1] is: {0}", vt1.long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (result != cl1.long2darr[0, 1]) { Console.WriteLine("ERROR:"); Console.WriteLine("result is: {0}", result); Console.WriteLine("cl1.long2darr[0, 1] is: {0}", cl1.long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (result != ja1[0][0, 1]) { Console.WriteLine("ERROR:"); Console.WriteLine("result is: {0}", result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (result != long3darr[1, 0, 1]) { Console.WriteLine("ERROR:"); Console.WriteLine("result is: {0}", result); Console.WriteLine("long3darr[1,0,1] is: {0}", long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (result != vt1.long3darr[1, 0, 1]) { Console.WriteLine("ERROR:"); Console.WriteLine("result is: {0}", result); Console.WriteLine("vt1.long3darr[1,0,1] is: {0}", vt1.long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (result != cl1.long3darr[1, 0, 1]) { Console.WriteLine("ERROR:"); Console.WriteLine("result is: {0}", result); Console.WriteLine("cl1.long3darr[1,0,1] is: {0}", cl1.long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (result != ja2[1][1, 0, 1]) { Console.WriteLine("ERROR:"); Console.WriteLine("result is: {0}", result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //Int64ToBool bool Bool_result = true; // 2D if (Bool_result != Convert.ToBoolean(long2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Bool_result is: {0}", Bool_result); Console.WriteLine("2darr[0, 1] is: {0}", long2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Bool_result != Convert.ToBoolean(vt1.long2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Bool_result is: {0}", Bool_result); Console.WriteLine("vt1.long2darr_b[0, 1] is: {0}", vt1.long2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Bool_result != Convert.ToBoolean(cl1.long2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Bool_result is: {0}", Bool_result); Console.WriteLine("cl1.long2darr_b[0, 1] is: {0}", cl1.long2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Bool_result != Convert.ToBoolean(ja1_b[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Bool_result is: {0}", Bool_result); Console.WriteLine("ja1_b[0][0, 1] is: {0}", ja1_b[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (Bool_result != Convert.ToBoolean(long3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Bool_result is: {0}", Bool_result); Console.WriteLine("long3darr_b[1,0,1] is: {0}", long3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Bool_result != Convert.ToBoolean(vt1.long3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Bool_result is: {0}", Bool_result); Console.WriteLine("vt1.long3darr_b[1,0,1] is: {0}", vt1.long3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Bool_result != Convert.ToBoolean(cl1.long3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Bool_result is: {0}", Bool_result); Console.WriteLine("cl1.long3darr_b[1,0,1] is: {0}", cl1.long3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Bool_result != Convert.ToBoolean(ja2_b[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Bool_result is: {0}", Bool_result); Console.WriteLine("ja2_b[1][1,0,1] is: {0}", ja2_b[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //Int64ToByte tests byte Byte_result = 1; // 2D if (Byte_result != Convert.ToByte(long2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Byte_result is: {0}", Byte_result); Console.WriteLine("2darr[0, 1] is: {0}", long2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Byte_result != Convert.ToByte(vt1.long2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Byte_result is: {0}", Byte_result); Console.WriteLine("vt1.long2darr_b[0, 1] is: {0}", vt1.long2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Byte_result != Convert.ToByte(cl1.long2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Byte_result is: {0}", Byte_result); Console.WriteLine("cl1.long2darr_b[0, 1] is: {0}", cl1.long2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Byte_result != Convert.ToByte(ja1_b[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Byte_result is: {0}", Byte_result); Console.WriteLine("ja1_b[0][0, 1] is: {0}", ja1_b[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (Byte_result != Convert.ToByte(long3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Byte_result is: {0}", Byte_result); Console.WriteLine("long3darr_b[1,0,1] is: {0}", long3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Byte_result != Convert.ToByte(vt1.long3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Byte_result is: {0}", Byte_result); Console.WriteLine("vt1.long3darr_b[1,0,1] is: {0}", vt1.long3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Byte_result != Convert.ToByte(cl1.long3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Byte_result is: {0}", Byte_result); Console.WriteLine("cl1.long3darr_b[1,0,1] is: {0}", cl1.long3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Byte_result != Convert.ToByte(ja2_b[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Byte_result is: {0}", Byte_result); Console.WriteLine("ja2_b[1][1,0,1] is: {0}", ja2_b[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //Int64ToChar tests char Char_result = '1'; // 2D if (Char_result != Convert.ToChar(long2darr_c[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Char_result is: {0}", Char_result); Console.WriteLine("2darr[0, 1] is: {0}", long2darr_c[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Char_result != Convert.ToChar(vt1.long2darr_c[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Char_result is: {0}", Char_result); Console.WriteLine("vt1.long2darr_c[0, 1] is: {0}", vt1.long2darr_c[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Char_result != Convert.ToChar(cl1.long2darr_c[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Char_result is: {0}", Char_result); Console.WriteLine("cl1.long2darr_c[0, 1] is: {0}", cl1.long2darr_c[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Char_result != Convert.ToChar(ja1_c[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Char_result is: {0}", Char_result); Console.WriteLine("ja1_c[0][0, 1] is: {0}", ja1_c[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (Char_result != Convert.ToChar(long3darr_c[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Char_result is: {0}", Char_result); Console.WriteLine("long3darr_c[1,0,1] is: {0}", long3darr_c[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Char_result != Convert.ToChar(vt1.long3darr_c[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Char_result is: {0}", Char_result); Console.WriteLine("vt1.long3darr_c[1,0,1] is: {0}", vt1.long3darr_c[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Char_result != Convert.ToChar(cl1.long3darr_c[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Char_result is: {0}", Char_result); Console.WriteLine("cl1.long3darr_c[1,0,1] is: {0}", cl1.long3darr_c[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Char_result != Convert.ToChar(ja2_c[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Char_result is: {0}", Char_result); Console.WriteLine("ja2_c[1][1,0,1] is: {0}", ja2_c[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //Int64ToDecimal tests decimal Decimal_result = -1; // 2D if (Decimal_result != Convert.ToDecimal(long2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Decimal_result is: {0}", Decimal_result); Console.WriteLine("2darr[0, 1] is: {0}", long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Decimal_result != Convert.ToDecimal(vt1.long2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Decimal_result is: {0}", Decimal_result); Console.WriteLine("vt1.long2darr[0, 1] is: {0}", vt1.long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Decimal_result != Convert.ToDecimal(cl1.long2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Decimal_result is: {0}", Decimal_result); Console.WriteLine("cl1.long2darr[0, 1] is: {0}", cl1.long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Decimal_result != Convert.ToDecimal(ja1[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Decimal_result is: {0}", Decimal_result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (Decimal_result != Convert.ToDecimal(long3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Decimal_result is: {0}", Decimal_result); Console.WriteLine("long3darr[1,0,1] is: {0}", long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Decimal_result != Convert.ToDecimal(vt1.long3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Decimal_result is: {0}", Decimal_result); Console.WriteLine("vt1.long3darr[1,0,1] is: {0}", vt1.long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Decimal_result != Convert.ToDecimal(cl1.long3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Decimal_result is: {0}", Decimal_result); Console.WriteLine("cl1.long3darr[1,0,1] is: {0}", cl1.long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Decimal_result != Convert.ToDecimal(ja2[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Decimal_result is: {0}", Decimal_result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //Int64ToDouble double Double_result = -1; // 2D if (Double_result != Convert.ToDouble(long2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Double_result is: {0}", Double_result); Console.WriteLine("2darr[0, 1] is: {0}", long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Double_result != Convert.ToDouble(vt1.long2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Double_result is: {0}", Double_result); Console.WriteLine("vt1.long2darr[0, 1] is: {0}", vt1.long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Double_result != Convert.ToDouble(cl1.long2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Double_result is: {0}", Double_result); Console.WriteLine("cl1.long2darr[0, 1] is: {0}", cl1.long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Double_result != Convert.ToDouble(ja1[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Double_result is: {0}", Double_result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (Double_result != Convert.ToDouble(long3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Double_result is: {0}", Double_result); Console.WriteLine("long3darr[1,0,1] is: {0}", long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Double_result != Convert.ToDouble(vt1.long3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Double_result is: {0}", Double_result); Console.WriteLine("vt1.long3darr[1,0,1] is: {0}", vt1.long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Double_result != Convert.ToDouble(cl1.long3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Double_result is: {0}", Double_result); Console.WriteLine("cl1.long3darr[1,0,1] is: {0}", cl1.long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Double_result != Convert.ToDouble(ja2[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Double_result is: {0}", Double_result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //Int64ToSingle tests float Single_result = -1; // 2D if (Single_result != Convert.ToSingle(long2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Single_result is: {0}", Single_result); Console.WriteLine("2darr[0, 1] is: {0}", long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Single_result != Convert.ToSingle(vt1.long2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Single_result is: {0}", Single_result); Console.WriteLine("vt1.long2darr[0, 1] is: {0}", vt1.long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Single_result != Convert.ToSingle(cl1.long2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Single_result is: {0}", Single_result); Console.WriteLine("cl1.long2darr[0, 1] is: {0}", cl1.long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Single_result != Convert.ToSingle(ja1[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Single_result is: {0}", Single_result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (Single_result != Convert.ToSingle(long3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Single_result is: {0}", Single_result); Console.WriteLine("long3darr[1,0,1] is: {0}", long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Single_result != Convert.ToSingle(vt1.long3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Single_result is: {0}", Single_result); Console.WriteLine("vt1.long3darr[1,0,1] is: {0}", vt1.long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Single_result != Convert.ToSingle(cl1.long3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Single_result is: {0}", Single_result); Console.WriteLine("cl1.long3darr[1,0,1] is: {0}", cl1.long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Single_result != Convert.ToSingle(ja2[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Single_result is: {0}", Single_result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //Int64ToInt32 tests int Int32_result = -1; // 2D if (Int32_result != Convert.ToInt32(long2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int32_result is: {0}", Int32_result); Console.WriteLine("2darr[0, 1] is: {0}", long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int32_result != Convert.ToInt32(vt1.long2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int32_result is: {0}", Int32_result); Console.WriteLine("vt1.long2darr[0, 1] is: {0}", vt1.long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int32_result != Convert.ToInt32(cl1.long2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int32_result is: {0}", Int32_result); Console.WriteLine("cl1.long2darr[0, 1] is: {0}", cl1.long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int32_result != Convert.ToInt32(ja1[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int32_result is: {0}", Int32_result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (Int32_result != Convert.ToInt32(long3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int32_result is: {0}", Int32_result); Console.WriteLine("long3darr[1,0,1] is: {0}", long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int32_result != Convert.ToInt32(vt1.long3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int32_result is: {0}", Int32_result); Console.WriteLine("vt1.long3darr[1,0,1] is: {0}", vt1.long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int32_result != Convert.ToInt32(cl1.long3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int32_result is: {0}", Int32_result); Console.WriteLine("cl1.long3darr[1,0,1] is: {0}", cl1.long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int32_result != Convert.ToInt32(ja2[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int32_result is: {0}", Int32_result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //Int64ToSByte tests sbyte SByte_result = -1; // 2D if (SByte_result != Convert.ToSByte(long2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("SByte_result is: {0}", SByte_result); Console.WriteLine("2darr[0, 1] is: {0}", long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (SByte_result != Convert.ToSByte(vt1.long2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("SByte_result is: {0}", SByte_result); Console.WriteLine("vt1.long2darr[0, 1] is: {0}", vt1.long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (SByte_result != Convert.ToSByte(cl1.long2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("SByte_result is: {0}", SByte_result); Console.WriteLine("cl1.long2darr[0, 1] is: {0}", cl1.long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (SByte_result != Convert.ToSByte(ja1[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("SByte_result is: {0}", SByte_result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (SByte_result != Convert.ToSByte(long3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("SByte_result is: {0}", SByte_result); Console.WriteLine("long3darr[1,0,1] is: {0}", long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (SByte_result != Convert.ToSByte(vt1.long3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("SByte_result is: {0}", SByte_result); Console.WriteLine("vt1.long3darr[1,0,1] is: {0}", vt1.long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (SByte_result != Convert.ToSByte(cl1.long3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("SByte_result is: {0}", SByte_result); Console.WriteLine("cl1.long3darr[1,0,1] is: {0}", cl1.long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (SByte_result != Convert.ToSByte(ja2[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("SByte_result is: {0}", SByte_result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //Int64ToInt16 tests short Int16_result = -1; // 2D if (Int16_result != Convert.ToInt16(long2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int16_result is: {0}", Int16_result); Console.WriteLine("2darr[0, 1] is: {0}", long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int16_result != Convert.ToInt16(vt1.long2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int16_result is: {0}", Int16_result); Console.WriteLine("vt1.long2darr[0, 1] is: {0}", vt1.long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int16_result != Convert.ToInt16(cl1.long2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int16_result is: {0}", Int16_result); Console.WriteLine("cl1.long2darr[0, 1] is: {0}", cl1.long2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int16_result != Convert.ToInt16(ja1[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int16_result is: {0}", Int16_result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (Int16_result != Convert.ToInt16(long3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int16_result is: {0}", Int16_result); Console.WriteLine("long3darr[1,0,1] is: {0}", long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int16_result != Convert.ToInt16(vt1.long3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int16_result is: {0}", Int16_result); Console.WriteLine("vt1.long3darr[1,0,1] is: {0}", vt1.long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int16_result != Convert.ToInt16(cl1.long3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int16_result is: {0}", Int16_result); Console.WriteLine("cl1.long3darr[1,0,1] is: {0}", cl1.long3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int16_result != Convert.ToInt16(ja2[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int16_result is: {0}", Int16_result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //Int64ToUInt32 tests uint UInt32_result = 1; // 2D if (UInt32_result != Convert.ToUInt32(long2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt32_result is: {0}", UInt32_result); Console.WriteLine("2darr[0, 1] is: {0}", long2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt32_result != Convert.ToUInt32(vt1.long2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt32_result is: {0}", UInt32_result); Console.WriteLine("vt1.long2darr_b[0, 1] is: {0}", vt1.long2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt32_result != Convert.ToUInt32(cl1.long2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt32_result is: {0}", UInt32_result); Console.WriteLine("cl1.long2darr_b[0, 1] is: {0}", cl1.long2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt32_result != Convert.ToUInt32(ja1_b[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt32_result is: {0}", UInt32_result); Console.WriteLine("ja1_b[0][0, 1] is: {0}", ja1_b[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (UInt32_result != Convert.ToUInt32(long3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt32_result is: {0}", UInt32_result); Console.WriteLine("long3darr_b[1,0,1] is: {0}", long3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt32_result != Convert.ToUInt32(vt1.long3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt32_result is: {0}", UInt32_result); Console.WriteLine("vt1.long3darr_b[1,0,1] is: {0}", vt1.long3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt32_result != Convert.ToUInt32(cl1.long3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt32_result is: {0}", UInt32_result); Console.WriteLine("cl1.long3darr_b[1,0,1] is: {0}", cl1.long3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt32_result != Convert.ToUInt32(ja2_b[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt32_result is: {0}", UInt32_result); Console.WriteLine("ja2_b[1][1,0,1] is: {0}", ja2_b[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //Int64ToUInt64 tests ulong UInt64_result = 1; // 2D if (UInt64_result != Convert.ToUInt64(long2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt64_result is: {0}", UInt64_result); Console.WriteLine("2darr[0, 1] is: {0}", long2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt64_result != Convert.ToUInt64(vt1.long2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt64_result is: {0}", UInt64_result); Console.WriteLine("vt1.long2darr_b[0, 1] is: {0}", vt1.long2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt64_result != Convert.ToUInt64(cl1.long2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt64_result is: {0}", UInt64_result); Console.WriteLine("cl1.long2darr_b[0, 1] is: {0}", cl1.long2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt64_result != Convert.ToUInt64(ja1_b[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt64_result is: {0}", UInt64_result); Console.WriteLine("ja1_b[0][0, 1] is: {0}", ja1_b[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (UInt64_result != Convert.ToUInt64(long3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt64_result is: {0}", UInt64_result); Console.WriteLine("long3darr_b[1,0,1] is: {0}", long3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt64_result != Convert.ToUInt64(vt1.long3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt64_result is: {0}", UInt64_result); Console.WriteLine("vt1.long3darr_b[1,0,1] is: {0}", vt1.long3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt64_result != Convert.ToUInt64(cl1.long3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt64_result is: {0}", UInt64_result); Console.WriteLine("cl1.long3darr_b[1,0,1] is: {0}", cl1.long3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt64_result != Convert.ToUInt64(ja2_b[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt64_result is: {0}", UInt64_result); Console.WriteLine("ja2_b[1][1,0,1] is: {0}", ja2_b[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //Int64ToUInt16 tests ushort UInt16_result = 1; // 2D if (UInt16_result != Convert.ToUInt16(long2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt16_result is: {0}", UInt16_result); Console.WriteLine("2darr[0, 1] is: {0}", long2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt16_result != Convert.ToUInt16(vt1.long2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt16_result is: {0}", UInt16_result); Console.WriteLine("vt1.long2darr_b[0, 1] is: {0}", vt1.long2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt16_result != Convert.ToUInt16(cl1.long2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt16_result is: {0}", UInt16_result); Console.WriteLine("cl1.long2darr_b[0, 1] is: {0}", cl1.long2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt16_result != Convert.ToUInt16(ja1_b[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt16_result is: {0}", UInt16_result); Console.WriteLine("ja1_b[0][0, 1] is: {0}", ja1_b[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (UInt16_result != Convert.ToUInt16(long3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt16_result is: {0}", UInt16_result); Console.WriteLine("long3darr_b[1,0,1] is: {0}", long3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt16_result != Convert.ToUInt16(vt1.long3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt16_result is: {0}", UInt16_result); Console.WriteLine("vt1.long3darr_b[1,0,1] is: {0}", vt1.long3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt16_result != Convert.ToUInt16(cl1.long3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt16_result is: {0}", UInt16_result); Console.WriteLine("cl1.long3darr_b[1,0,1] is: {0}", cl1.long3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt16_result != Convert.ToUInt16(ja2_b[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt16_result is: {0}", UInt16_result); Console.WriteLine("ja2_b[1][1,0,1] is: {0}", ja2_b[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (!pass) { Console.WriteLine("FAILED"); return 1; } else { Console.WriteLine("PASSED"); return 100; } } };
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/libraries/System.Net.NameResolution/tests/PalTests/Fakes/IPAddressFakeExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Net { internal static class IPAddressFakeExtensions { public static bool TryWriteBytes(this IPAddress address, Span<byte> destination, out int bytesWritten) { byte[] bytes = address.GetAddressBytes(); if (bytes.Length >= destination.Length) { new ReadOnlySpan<byte>(bytes).CopyTo(destination); bytesWritten = bytes.Length; return true; } else { bytesWritten = 0; return false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace System.Net { internal static class IPAddressFakeExtensions { public static bool TryWriteBytes(this IPAddress address, Span<byte> destination, out int bytesWritten) { byte[] bytes = address.GetAddressBytes(); if (bytes.Length >= destination.Length) { new ReadOnlySpan<byte>(bytes).CopyTo(destination); bytesWritten = bytes.Length; return true; } else { bytesWritten = 0; return false; } } } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/tests/JIT/Directed/debugging/debuginfo/tests_r.ilproj
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>library</OutputType> <IlasmFlags>$(IlasmFlags) -DEBUG=OPT</IlasmFlags> <CLRTestKind>BuildOnly</CLRTestKind> </PropertyGroup> <ItemGroup> <ProjectReference Include="attribute.csproj" /> <Compile Include="tests.il" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk.IL"> <PropertyGroup> <OutputType>library</OutputType> <IlasmFlags>$(IlasmFlags) -DEBUG=OPT</IlasmFlags> <CLRTestKind>BuildOnly</CLRTestKind> </PropertyGroup> <ItemGroup> <ProjectReference Include="attribute.csproj" /> <Compile Include="tests.il" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/tests/JIT/CodeGenBringUpTests/InstanceCalls_r.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="InstanceCalls.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> <Optimize>False</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="InstanceCalls.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/StructMarshallingDataNode.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 ILCompiler.DependencyAnalysisFramework; using Internal.TypeSystem; using Internal.TypeSystem.Interop; namespace ILCompiler.DependencyAnalysis { /// <summary> /// Represents an entry in the <see cref="StructMarshallingStubMapNode"/> table. /// </summary> public class StructMarshallingDataNode : DependencyNodeCore<NodeFactory> { private readonly DefType _type; public DefType Type => _type; public StructMarshallingDataNode(DefType type) { _type = type; } public override IEnumerable<DependencyListEntry> GetStaticDependencies(NodeFactory factory) { InteropStateManager stateManager = ((CompilerGeneratedInteropStubManager)factory.InteropStubManager)._interopStateManager; yield return new DependencyListEntry(factory.NecessaryTypeSymbol(_type), "Struct Marshalling Stub"); // Not all StructMarshalingDataNodes require marshalling - some are only present because we want to // generate field offset information for Marshal.OffsetOf. if (MarshalHelpers.IsStructMarshallingRequired(_type)) { yield return new DependencyListEntry(factory.MethodEntrypoint(stateManager.GetStructMarshallingManagedToNativeThunk(_type)), "Struct Marshalling stub"); yield return new DependencyListEntry(factory.MethodEntrypoint(stateManager.GetStructMarshallingNativeToManagedThunk(_type)), "Struct Marshalling stub"); yield return new DependencyListEntry(factory.MethodEntrypoint(stateManager.GetStructMarshallingCleanupThunk(_type)), "Struct Marshalling stub"); } } protected override string GetName(NodeFactory context) { return $"Struct marshaling data for {_type}"; } public override bool InterestingForDynamicDependencyAnalysis => false; public override bool HasDynamicDependencies => false; public override bool HasConditionalStaticDependencies => false; public override bool StaticDependenciesAreComputed => true; public override IEnumerable<CombinedDependencyListEntry> GetConditionalStaticDependencies(NodeFactory context) => null; public override IEnumerable<CombinedDependencyListEntry> SearchDynamicDependencies(List<DependencyNodeCore<NodeFactory>> markedNodes, int firstNode, NodeFactory context) => 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.Collections.Generic; using ILCompiler.DependencyAnalysisFramework; using Internal.TypeSystem; using Internal.TypeSystem.Interop; namespace ILCompiler.DependencyAnalysis { /// <summary> /// Represents an entry in the <see cref="StructMarshallingStubMapNode"/> table. /// </summary> public class StructMarshallingDataNode : DependencyNodeCore<NodeFactory> { private readonly DefType _type; public DefType Type => _type; public StructMarshallingDataNode(DefType type) { _type = type; } public override IEnumerable<DependencyListEntry> GetStaticDependencies(NodeFactory factory) { InteropStateManager stateManager = ((CompilerGeneratedInteropStubManager)factory.InteropStubManager)._interopStateManager; yield return new DependencyListEntry(factory.NecessaryTypeSymbol(_type), "Struct Marshalling Stub"); // Not all StructMarshalingDataNodes require marshalling - some are only present because we want to // generate field offset information for Marshal.OffsetOf. if (MarshalHelpers.IsStructMarshallingRequired(_type)) { yield return new DependencyListEntry(factory.MethodEntrypoint(stateManager.GetStructMarshallingManagedToNativeThunk(_type)), "Struct Marshalling stub"); yield return new DependencyListEntry(factory.MethodEntrypoint(stateManager.GetStructMarshallingNativeToManagedThunk(_type)), "Struct Marshalling stub"); yield return new DependencyListEntry(factory.MethodEntrypoint(stateManager.GetStructMarshallingCleanupThunk(_type)), "Struct Marshalling stub"); } } protected override string GetName(NodeFactory context) { return $"Struct marshaling data for {_type}"; } public override bool InterestingForDynamicDependencyAnalysis => false; public override bool HasDynamicDependencies => false; public override bool HasConditionalStaticDependencies => false; public override bool StaticDependenciesAreComputed => true; public override IEnumerable<CombinedDependencyListEntry> GetConditionalStaticDependencies(NodeFactory context) => null; public override IEnumerable<CombinedDependencyListEntry> SearchDynamicDependencies(List<DependencyNodeCore<NodeFactory>> markedNodes, int firstNode, NodeFactory context) => null; } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/libraries/System.Private.Xml/tests/XmlSchema/TestFiles/TestData/Bug430164.xsd
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" targetNamespace="ns-b" xmlns="ns-b"> <xsd:complexType name="ct-B"> <xsd:sequence minOccurs="1"> <xsd:element name="b1" type="xsd:boolean"/> <xsd:element name="b2" type="xsd:int"/> </xsd:sequence> </xsd:complexType> <xsd:element name="e2" type="ct-B"/> </xsd:schema>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" targetNamespace="ns-b" xmlns="ns-b"> <xsd:complexType name="ct-B"> <xsd:sequence minOccurs="1"> <xsd:element name="b1" type="xsd:boolean"/> <xsd:element name="b2" type="xsd:int"/> </xsd:sequence> </xsd:complexType> <xsd:element name="e2" type="ct-B"/> </xsd:schema>
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/tests/JIT/Regression/JitBlue/DevDiv_578217/DevDiv_578217.il
// Microsoft (R) .NET Framework IL Disassembler. Version 4.7.3108.0 // Copyright (c) Microsoft Corporation. All rights reserved. // This test originally triggered incorrect assert that fgGetPtrArgCntMax calculated during morph was lower // than maxStackLevel calculated during StackLevelSetter. It happens because long decomposition // is able to move PUTARG_STK. // Metadata version: v4.0.30319 .assembly extern System.Runtime { auto } .assembly 'DevDiv_578217' {} .assembly extern xunit.core {} .class private auto ansi beforefieldinit DevDiv_578217.Program extends [System.Runtime]System.Object { .method static int16 ILGEN_METHOD(unsigned int16, float32, native unsigned int, unsigned int16, unsigned int8, int16, unsigned int32) { .maxstack 142 .locals init (unsigned int64) IL_0000: ldc.i8 0x20fa631bf0010bd2 IL_0009: ldarg.s 0x00 IL_000b: conv.u8 IL_000c: ldarg 0x0001 IL_0010: pop IL_0011: ldc.i8 0x30cdeb7bedc062f5 IL_001a: conv.r4 IL_001b: conv.ovf.i1.un IL_001c: shr IL_001d: not IL_001e: ldc.i8 0x0881617fcdbacd3b IL_0027: ldloc.s 0x00 IL_0029: conv.ovf.u8 IL_002a: add.ovf IL_002b: ldloc.s 0x00 IL_002d: conv.i4 IL_002e: ldloc 0x0000 IL_0032: conv.ovf.u8 IL_0033: ldarg 0x0001 IL_0037: conv.ovf.i8.un IL_0038: cgt IL_003a: mul IL_003b: shr IL_003c: mul.ovf.un IL_003d: ldc.i8 0xfda22ae3eca9bad9 IL_0046: ldloc.s 0x00 IL_0048: cgt.un IL_004a: starg 0x0005 IL_004e: bgt IL_005d IL_0053: ldc.i8 0x601e3816def227ec IL_005c: pop IL_005d: ldarg.s 0x03 IL_005f: ldarg.s 0x02 IL_0061: not IL_0062: conv.u1 IL_0063: shr.un IL_0064: ldc.i8 0x8e78692b130a7a32 IL_006d: conv.r8 IL_006e: conv.r8 IL_006f: neg IL_0070: conv.ovf.i4 IL_0071: not IL_0072: ldarg.s 0x00 IL_0074: not IL_0075: shr IL_0076: shr IL_0077: ldarg.s 0x05 IL_0079: shr IL_007a: ldloc.s 0x00 IL_007c: ldloc 0x0000 IL_0080: or IL_0081: neg IL_0082: pop IL_0083: ldc.i4 0xf7cd9099 IL_0088: conv.ovf.u8 IL_0089: conv.u8 IL_008a: conv.ovf.u2.un IL_008b: starg.s 0x02 IL_008d: ret } // end of method Program::ILGEN_METHOD .method private hidebysig static int32 Main(string[] args) cil managed { .custom instance void [xunit.core]Xunit.FactAttribute::.ctor() = ( 01 00 00 00 ) .entrypoint // Code size 34 (0x22) .maxstack 7 .locals init (int32 V_0) IL_0000: nop .try { IL_0001: nop IL_0002: ldc.i4.0 IL_0003: ldc.r4 0.0 IL_0008: ldc.i4.0 IL_0009: ldc.i4.0 IL_000a: ldc.i4.0 IL_000b: ldc.i4.0 IL_000c: ldc.i4.0 IL_000d: call int16 DevDiv_578217.Program::ILGEN_METHOD(uint16, float32, native unsigned int, uint16, uint8, int16, uint32) IL_0012: pop IL_0013: nop IL_0014: leave.s IL_001b } // end .try catch [System.Runtime]System.Object { IL_0016: pop IL_0017: nop IL_0018: nop IL_0019: leave.s IL_001b } // end handler IL_001b: ldc.i4.s 100 IL_001d: stloc.0 IL_001e: br.s IL_0020 IL_0020: ldloc.0 IL_0021: ret } // end of method Program::Main .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method Program::.ctor } // end of class DevDiv_578217.Program
// Microsoft (R) .NET Framework IL Disassembler. Version 4.7.3108.0 // Copyright (c) Microsoft Corporation. All rights reserved. // This test originally triggered incorrect assert that fgGetPtrArgCntMax calculated during morph was lower // than maxStackLevel calculated during StackLevelSetter. It happens because long decomposition // is able to move PUTARG_STK. // Metadata version: v4.0.30319 .assembly extern System.Runtime { auto } .assembly 'DevDiv_578217' {} .assembly extern xunit.core {} .class private auto ansi beforefieldinit DevDiv_578217.Program extends [System.Runtime]System.Object { .method static int16 ILGEN_METHOD(unsigned int16, float32, native unsigned int, unsigned int16, unsigned int8, int16, unsigned int32) { .maxstack 142 .locals init (unsigned int64) IL_0000: ldc.i8 0x20fa631bf0010bd2 IL_0009: ldarg.s 0x00 IL_000b: conv.u8 IL_000c: ldarg 0x0001 IL_0010: pop IL_0011: ldc.i8 0x30cdeb7bedc062f5 IL_001a: conv.r4 IL_001b: conv.ovf.i1.un IL_001c: shr IL_001d: not IL_001e: ldc.i8 0x0881617fcdbacd3b IL_0027: ldloc.s 0x00 IL_0029: conv.ovf.u8 IL_002a: add.ovf IL_002b: ldloc.s 0x00 IL_002d: conv.i4 IL_002e: ldloc 0x0000 IL_0032: conv.ovf.u8 IL_0033: ldarg 0x0001 IL_0037: conv.ovf.i8.un IL_0038: cgt IL_003a: mul IL_003b: shr IL_003c: mul.ovf.un IL_003d: ldc.i8 0xfda22ae3eca9bad9 IL_0046: ldloc.s 0x00 IL_0048: cgt.un IL_004a: starg 0x0005 IL_004e: bgt IL_005d IL_0053: ldc.i8 0x601e3816def227ec IL_005c: pop IL_005d: ldarg.s 0x03 IL_005f: ldarg.s 0x02 IL_0061: not IL_0062: conv.u1 IL_0063: shr.un IL_0064: ldc.i8 0x8e78692b130a7a32 IL_006d: conv.r8 IL_006e: conv.r8 IL_006f: neg IL_0070: conv.ovf.i4 IL_0071: not IL_0072: ldarg.s 0x00 IL_0074: not IL_0075: shr IL_0076: shr IL_0077: ldarg.s 0x05 IL_0079: shr IL_007a: ldloc.s 0x00 IL_007c: ldloc 0x0000 IL_0080: or IL_0081: neg IL_0082: pop IL_0083: ldc.i4 0xf7cd9099 IL_0088: conv.ovf.u8 IL_0089: conv.u8 IL_008a: conv.ovf.u2.un IL_008b: starg.s 0x02 IL_008d: ret } // end of method Program::ILGEN_METHOD .method private hidebysig static int32 Main(string[] args) cil managed { .custom instance void [xunit.core]Xunit.FactAttribute::.ctor() = ( 01 00 00 00 ) .entrypoint // Code size 34 (0x22) .maxstack 7 .locals init (int32 V_0) IL_0000: nop .try { IL_0001: nop IL_0002: ldc.i4.0 IL_0003: ldc.r4 0.0 IL_0008: ldc.i4.0 IL_0009: ldc.i4.0 IL_000a: ldc.i4.0 IL_000b: ldc.i4.0 IL_000c: ldc.i4.0 IL_000d: call int16 DevDiv_578217.Program::ILGEN_METHOD(uint16, float32, native unsigned int, uint16, uint8, int16, uint32) IL_0012: pop IL_0013: nop IL_0014: leave.s IL_001b } // end .try catch [System.Runtime]System.Object { IL_0016: pop IL_0017: nop IL_0018: nop IL_0019: leave.s IL_001b } // end handler IL_001b: ldc.i4.s 100 IL_001d: stloc.0 IL_001e: br.s IL_0020 IL_0020: ldloc.0 IL_0021: ret } // end of method Program::Main .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [System.Runtime]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method Program::.ctor } // end of class DevDiv_578217.Program
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/libraries/Common/src/Interop/Windows/Crypt32/Interop.CertFindExtension.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, SetLastError = true)] internal static unsafe partial CERT_EXTENSION* CertFindExtension([MarshalAs(UnmanagedType.LPStr)] string pszObjId, int cExtensions, IntPtr rgExtensions); } }
// 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, SetLastError = true)] internal static unsafe partial CERT_EXTENSION* CertFindExtension([MarshalAs(UnmanagedType.LPStr)] string pszObjId, int cExtensions, IntPtr rgExtensions); } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/tests/GC/Stress/Tests/LargeObjectAlloc4.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // This test should need to allocated a maximum of 20 MB and so, should pass without // OOM Exception. On RTM as the largeobjects were never committed, this test would // fail after a few loops. using System; public class Test { public static int Main(string[] args) { Int32 basesize; Int32[] largeobjarr; int loop = 0; TestLibrary.Logging.WriteLine("Test should pass with ExitCode 100"); while (loop < 50) { TestLibrary.Logging.WriteLine("loop: {0}", loop); basesize = 4096; try { for (int i = 0; i < 1000; i++) { //TestLibrary.Logging.WriteLine("In loop {0}, Allocating array of {1} bytes\n",i,basesize*4); largeobjarr = new Int32[basesize]; basesize += 4096; } } catch (Exception e) { TestLibrary.Logging.WriteLine("Exception caught: {0}", e); return 1; } loop++; } TestLibrary.Logging.WriteLine("Test Passed"); return 100; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // This test should need to allocated a maximum of 20 MB and so, should pass without // OOM Exception. On RTM as the largeobjects were never committed, this test would // fail after a few loops. using System; public class Test { public static int Main(string[] args) { Int32 basesize; Int32[] largeobjarr; int loop = 0; TestLibrary.Logging.WriteLine("Test should pass with ExitCode 100"); while (loop < 50) { TestLibrary.Logging.WriteLine("loop: {0}", loop); basesize = 4096; try { for (int i = 0; i < 1000; i++) { //TestLibrary.Logging.WriteLine("In loop {0}, Allocating array of {1} bytes\n",i,basesize*4); largeobjarr = new Int32[basesize]; basesize += 4096; } } catch (Exception e) { TestLibrary.Logging.WriteLine("Exception caught: {0}", e); return 1; } loop++; } TestLibrary.Logging.WriteLine("Test Passed"); return 100; } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/libraries/System.Security.AccessControl/tests/RawAcl/RawAcl_AceCount.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.Security.Principal; using Xunit; namespace System.Security.AccessControl.Tests { public class RawAcl_AceCount { [Fact] public static void BasicValidationTestCases() { RawAcl rawAcl = null; GenericAce gAce = null; byte revision = 0; int capacity = 0; string sid = "BA"; //case 1, empty RawAcl revision = 0; capacity = 1; rawAcl = new RawAcl(revision, capacity); Assert.True(0 == rawAcl.Count); //case 2, RawAcl with one Ace revision = 0; capacity = 1; rawAcl = new RawAcl(revision, capacity); gAce = new CommonAce(AceFlags.SuccessfulAccess, AceQualifier.SystemAudit, 1, new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid(sid)), false, null); rawAcl.InsertAce(0, gAce); Assert.True(1 == rawAcl.Count); //case 3, RawAcl with two Aces revision = 0; capacity = 1; rawAcl = new RawAcl(revision, capacity); gAce = new CommonAce(AceFlags.SuccessfulAccess, AceQualifier.SystemAudit, 1, new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid(sid)), false, null); rawAcl.InsertAce(0, gAce); gAce = new CommonAce(AceFlags.SuccessfulAccess, AceQualifier.SystemAudit, 2, new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid(sid)), false, null); rawAcl.InsertAce(0, gAce); Assert.True(2 == rawAcl.Count); } [Fact] public static void AdditionalTestCases() { RawAcl rawAcl = null; GenericAce gAce = null; byte revision = 0; int capacity = 0; SecurityIdentifier sid = new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid("BA")); //case 1, RawAcl with huge number of Aces revision = 0; capacity = 1; rawAcl = new RawAcl(revision, capacity); for (int i = 0; i < 1820; i++) { //this ace binary length is 36, 1820 * 36 = 65520 gAce = new CommonAce(AceFlags.SuccessfulAccess, AceQualifier.SystemAudit, i + 1, sid, false, null); rawAcl.InsertAce(0, gAce); } Assert.True(1820 == rawAcl.Count); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Security.Principal; using Xunit; namespace System.Security.AccessControl.Tests { public class RawAcl_AceCount { [Fact] public static void BasicValidationTestCases() { RawAcl rawAcl = null; GenericAce gAce = null; byte revision = 0; int capacity = 0; string sid = "BA"; //case 1, empty RawAcl revision = 0; capacity = 1; rawAcl = new RawAcl(revision, capacity); Assert.True(0 == rawAcl.Count); //case 2, RawAcl with one Ace revision = 0; capacity = 1; rawAcl = new RawAcl(revision, capacity); gAce = new CommonAce(AceFlags.SuccessfulAccess, AceQualifier.SystemAudit, 1, new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid(sid)), false, null); rawAcl.InsertAce(0, gAce); Assert.True(1 == rawAcl.Count); //case 3, RawAcl with two Aces revision = 0; capacity = 1; rawAcl = new RawAcl(revision, capacity); gAce = new CommonAce(AceFlags.SuccessfulAccess, AceQualifier.SystemAudit, 1, new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid(sid)), false, null); rawAcl.InsertAce(0, gAce); gAce = new CommonAce(AceFlags.SuccessfulAccess, AceQualifier.SystemAudit, 2, new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid(sid)), false, null); rawAcl.InsertAce(0, gAce); Assert.True(2 == rawAcl.Count); } [Fact] public static void AdditionalTestCases() { RawAcl rawAcl = null; GenericAce gAce = null; byte revision = 0; int capacity = 0; SecurityIdentifier sid = new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid("BA")); //case 1, RawAcl with huge number of Aces revision = 0; capacity = 1; rawAcl = new RawAcl(revision, capacity); for (int i = 0; i < 1820; i++) { //this ace binary length is 36, 1820 * 36 = 65520 gAce = new CommonAce(AceFlags.SuccessfulAccess, AceQualifier.SystemAudit, i + 1, sid, false, null); rawAcl.InsertAce(0, gAce); } Assert.True(1820 == rawAcl.Count); } } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/tests/JIT/Regression/CLR-x86-JIT/V1-M13-RTM/b89506/b89506.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>PdbOnly</DebugType> </PropertyGroup> <ItemGroup> <Compile Include="$(MSBuildProjectName).cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/coreclr/tools/dotnet-pgo/R2RSignatureTypeProvider.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.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection.Metadata; using ILCompiler.Reflection.ReadyToRun; using Internal.ReadyToRunConstants; using Internal.TypeSystem; using Internal.TypeSystem.Ecma; namespace Microsoft.Diagnostics.Tools.Pgo { struct R2RSigProviderContext { } class R2RSignatureTypeProvider : IR2RSignatureTypeProvider<TypeDesc, MethodDesc, R2RSigProviderContext> { public R2RSignatureTypeProvider(TraceTypeSystemContext tsc) { _tsc = tsc; } TraceTypeSystemContext _tsc; TypeDesc IConstructedTypeProvider<TypeDesc>.GetArrayType(TypeDesc elementType, ArrayShape shape) { if (elementType == null) return null; return elementType.MakeArrayType(shape.Rank); } TypeDesc IConstructedTypeProvider<TypeDesc>.GetByReferenceType(TypeDesc elementType) { if (elementType == null) return null; return elementType.MakeByRefType(); } TypeDesc IR2RSignatureTypeProvider<TypeDesc, MethodDesc, R2RSigProviderContext>.GetCanonType() { return _tsc.CanonType; } MethodDesc IR2RSignatureTypeProvider<TypeDesc, MethodDesc, R2RSigProviderContext>.GetConstrainedMethod(MethodDesc method, TypeDesc constraint) { // Cannot exist in entrypoint definition throw new System.NotImplementedException(); } TypeDesc ISignatureTypeProvider<TypeDesc, R2RSigProviderContext>.GetFunctionPointerType(MethodSignature<TypeDesc> signature) { // Cannot exist in entrypoint definition throw new System.NotImplementedException(); } TypeDesc IConstructedTypeProvider<TypeDesc>.GetGenericInstantiation(TypeDesc genericType, ImmutableArray<TypeDesc> typeArguments) { if (genericType == null) return null; foreach (var type in typeArguments) { if (type == null) return null; } return _tsc.GetInstantiatedType((MetadataType)genericType, new Instantiation(typeArguments.ToArray())); } TypeDesc ISignatureTypeProvider<TypeDesc, R2RSigProviderContext>.GetGenericMethodParameter(R2RSigProviderContext genericContext, int index) { // Cannot exist in entrypoint definition throw new System.NotImplementedException(); } TypeDesc ISignatureTypeProvider<TypeDesc, R2RSigProviderContext>.GetGenericTypeParameter(R2RSigProviderContext genericContext, int index) { // Cannot exist in entrypoint definition throw new System.NotImplementedException(); } MethodDesc IR2RSignatureTypeProvider<TypeDesc, MethodDesc, R2RSigProviderContext>.GetInstantiatedMethod(MethodDesc uninstantiatedMethod, ImmutableArray<TypeDesc> instantiation) { if (uninstantiatedMethod == null) return null; foreach (var type in instantiation) { if (type == null) return null; } return uninstantiatedMethod.MakeInstantiatedMethod(instantiation.ToArray()); } MethodDesc IR2RSignatureTypeProvider<TypeDesc, MethodDesc, R2RSigProviderContext>.GetMethodFromMemberRef(MetadataReader reader, MemberReferenceHandle handle, TypeDesc owningTypeOverride) { var ecmaModule = (EcmaModule)_tsc.GetModuleForSimpleName(reader.GetString(reader.GetAssemblyDefinition().Name)); var method = (MethodDesc)ecmaModule.GetObject(handle, NotFoundBehavior.ReturnNull); if (method == null) { return null; } if (owningTypeOverride != null) { return _tsc.GetMethodForInstantiatedType(method.GetTypicalMethodDefinition(), (InstantiatedType)owningTypeOverride); } return method; } protected MethodDesc GetMethodFromMethodDef(MetadataReader reader, MethodDefinitionHandle handle, TypeDesc owningTypeOverride) { var ecmaModule = (EcmaModule)_tsc.GetModuleForSimpleName(reader.GetString(reader.GetAssemblyDefinition().Name)); var method = (MethodDesc)ecmaModule.GetObject(handle, NotFoundBehavior.ReturnNull); if (method == null) { return null; } if (owningTypeOverride != null) { if (owningTypeOverride != method.OwningType) { return _tsc.GetMethodForInstantiatedType(method.GetTypicalMethodDefinition(), (InstantiatedType)owningTypeOverride); } } return method; } MethodDesc IR2RSignatureTypeProvider<TypeDesc, MethodDesc, R2RSigProviderContext>.GetMethodFromMethodDef(MetadataReader reader, MethodDefinitionHandle handle, TypeDesc owningTypeOverride) { return GetMethodFromMethodDef(reader, handle, owningTypeOverride); } MethodDesc IR2RSignatureTypeProvider<TypeDesc, MethodDesc, R2RSigProviderContext>.GetMethodWithFlags(ReadyToRunMethodSigFlags flags, MethodDesc method) { return method; } TypeDesc ISignatureTypeProvider<TypeDesc, R2RSigProviderContext>.GetModifiedType(TypeDesc modifier, TypeDesc unmodifiedType, bool isRequired) { // Cannot exist in entrypoint definition throw new System.NotImplementedException(); } TypeDesc ISignatureTypeProvider<TypeDesc, R2RSigProviderContext>.GetPinnedType(TypeDesc elementType) { // Cannot exist in entrypoint definition throw new System.NotImplementedException(); } TypeDesc IConstructedTypeProvider<TypeDesc>.GetPointerType(TypeDesc elementType) { // Cannot exist in entrypoint definition throw new System.NotImplementedException(); } TypeDesc ISimpleTypeProvider<TypeDesc>.GetPrimitiveType(PrimitiveTypeCode typeCode) { WellKnownType wkt = 0; switch (typeCode) { case PrimitiveTypeCode.Void: wkt = WellKnownType.Void; break; case PrimitiveTypeCode.Boolean: wkt = WellKnownType.Boolean; break; case PrimitiveTypeCode.Char: wkt = WellKnownType.Char; break; case PrimitiveTypeCode.SByte: wkt = WellKnownType.SByte; break; case PrimitiveTypeCode.Byte: wkt = WellKnownType.Byte; break; case PrimitiveTypeCode.Int16: wkt = WellKnownType.Int16; break; case PrimitiveTypeCode.UInt16: wkt = WellKnownType.UInt16; break; case PrimitiveTypeCode.Int32: wkt = WellKnownType.Int32; break; case PrimitiveTypeCode.UInt32: wkt = WellKnownType.UInt32; break; case PrimitiveTypeCode.Int64: wkt = WellKnownType.Int64; break; case PrimitiveTypeCode.UInt64: wkt = WellKnownType.UInt64; break; case PrimitiveTypeCode.Single: wkt = WellKnownType.Single; break; case PrimitiveTypeCode.Double: wkt = WellKnownType.Double; break; case PrimitiveTypeCode.String: wkt = WellKnownType.String; break; case PrimitiveTypeCode.TypedReference: wkt = WellKnownType.TypedReference; break; case PrimitiveTypeCode.IntPtr: wkt = WellKnownType.IntPtr; break; case PrimitiveTypeCode.UIntPtr: wkt = WellKnownType.UIntPtr; break; case PrimitiveTypeCode.Object: wkt = WellKnownType.Object; break; } return _tsc.GetWellKnownType(wkt); } TypeDesc ISZArrayTypeProvider<TypeDesc>.GetSZArrayType(TypeDesc elementType) { if (elementType == null) return null; return elementType.MakeArrayType(); } TypeDesc ISimpleTypeProvider<TypeDesc>.GetTypeFromDefinition(MetadataReader reader, TypeDefinitionHandle handle, byte rawTypeKind) { var ecmaModule = (EcmaModule)_tsc.GetModuleForSimpleName(reader.GetString(reader.GetAssemblyDefinition().Name)); return (TypeDesc)ecmaModule.GetObject(handle, NotFoundBehavior.ReturnNull); } TypeDesc ISimpleTypeProvider<TypeDesc>.GetTypeFromReference(MetadataReader reader, TypeReferenceHandle handle, byte rawTypeKind) { var ecmaModule = (EcmaModule)_tsc.GetModuleForSimpleName(reader.GetString(reader.GetAssemblyDefinition().Name)); return (TypeDesc)ecmaModule.GetObject(handle, NotFoundBehavior.ReturnNull); } TypeDesc ISignatureTypeProvider<TypeDesc, R2RSigProviderContext>.GetTypeFromSpecification(MetadataReader reader, R2RSigProviderContext genericContext, TypeSpecificationHandle handle, byte rawTypeKind) { var ecmaModule = (EcmaModule)_tsc.GetModuleForSimpleName(reader.GetString(reader.GetAssemblyDefinition().Name)); return (TypeDesc)ecmaModule.GetObject(handle, NotFoundBehavior.ReturnNull); } } class R2RSignatureTypeProviderForGlobalTables : R2RSignatureTypeProvider, IR2RSignatureTypeProvider<TypeDesc, MethodDesc, R2RSigProviderContext> { public R2RSignatureTypeProviderForGlobalTables(TraceTypeSystemContext tsc) : base(tsc) { } MethodDesc IR2RSignatureTypeProvider<TypeDesc, MethodDesc, R2RSigProviderContext>.GetMethodFromMethodDef(MetadataReader reader, MethodDefinitionHandle handle, TypeDesc owningTypeOverride) { if (owningTypeOverride != null) { reader = ((EcmaModule)((MetadataType)owningTypeOverride.GetTypeDefinition()).Module).MetadataReader; } Debug.Assert(reader != null); return GetMethodFromMethodDef(reader, handle, owningTypeOverride); } MethodDesc IR2RSignatureTypeProvider<TypeDesc, MethodDesc, R2RSigProviderContext>.GetMethodFromMemberRef(MetadataReader reader, MemberReferenceHandle handle, TypeDesc owningTypeOverride) { // Global signature cannot have MemberRef entries in them as such things aren't uniquely identifiable throw new NotSupportedException(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection.Metadata; using ILCompiler.Reflection.ReadyToRun; using Internal.ReadyToRunConstants; using Internal.TypeSystem; using Internal.TypeSystem.Ecma; namespace Microsoft.Diagnostics.Tools.Pgo { struct R2RSigProviderContext { } class R2RSignatureTypeProvider : IR2RSignatureTypeProvider<TypeDesc, MethodDesc, R2RSigProviderContext> { public R2RSignatureTypeProvider(TraceTypeSystemContext tsc) { _tsc = tsc; } TraceTypeSystemContext _tsc; TypeDesc IConstructedTypeProvider<TypeDesc>.GetArrayType(TypeDesc elementType, ArrayShape shape) { if (elementType == null) return null; return elementType.MakeArrayType(shape.Rank); } TypeDesc IConstructedTypeProvider<TypeDesc>.GetByReferenceType(TypeDesc elementType) { if (elementType == null) return null; return elementType.MakeByRefType(); } TypeDesc IR2RSignatureTypeProvider<TypeDesc, MethodDesc, R2RSigProviderContext>.GetCanonType() { return _tsc.CanonType; } MethodDesc IR2RSignatureTypeProvider<TypeDesc, MethodDesc, R2RSigProviderContext>.GetConstrainedMethod(MethodDesc method, TypeDesc constraint) { // Cannot exist in entrypoint definition throw new System.NotImplementedException(); } TypeDesc ISignatureTypeProvider<TypeDesc, R2RSigProviderContext>.GetFunctionPointerType(MethodSignature<TypeDesc> signature) { // Cannot exist in entrypoint definition throw new System.NotImplementedException(); } TypeDesc IConstructedTypeProvider<TypeDesc>.GetGenericInstantiation(TypeDesc genericType, ImmutableArray<TypeDesc> typeArguments) { if (genericType == null) return null; foreach (var type in typeArguments) { if (type == null) return null; } return _tsc.GetInstantiatedType((MetadataType)genericType, new Instantiation(typeArguments.ToArray())); } TypeDesc ISignatureTypeProvider<TypeDesc, R2RSigProviderContext>.GetGenericMethodParameter(R2RSigProviderContext genericContext, int index) { // Cannot exist in entrypoint definition throw new System.NotImplementedException(); } TypeDesc ISignatureTypeProvider<TypeDesc, R2RSigProviderContext>.GetGenericTypeParameter(R2RSigProviderContext genericContext, int index) { // Cannot exist in entrypoint definition throw new System.NotImplementedException(); } MethodDesc IR2RSignatureTypeProvider<TypeDesc, MethodDesc, R2RSigProviderContext>.GetInstantiatedMethod(MethodDesc uninstantiatedMethod, ImmutableArray<TypeDesc> instantiation) { if (uninstantiatedMethod == null) return null; foreach (var type in instantiation) { if (type == null) return null; } return uninstantiatedMethod.MakeInstantiatedMethod(instantiation.ToArray()); } MethodDesc IR2RSignatureTypeProvider<TypeDesc, MethodDesc, R2RSigProviderContext>.GetMethodFromMemberRef(MetadataReader reader, MemberReferenceHandle handle, TypeDesc owningTypeOverride) { var ecmaModule = (EcmaModule)_tsc.GetModuleForSimpleName(reader.GetString(reader.GetAssemblyDefinition().Name)); var method = (MethodDesc)ecmaModule.GetObject(handle, NotFoundBehavior.ReturnNull); if (method == null) { return null; } if (owningTypeOverride != null) { return _tsc.GetMethodForInstantiatedType(method.GetTypicalMethodDefinition(), (InstantiatedType)owningTypeOverride); } return method; } protected MethodDesc GetMethodFromMethodDef(MetadataReader reader, MethodDefinitionHandle handle, TypeDesc owningTypeOverride) { var ecmaModule = (EcmaModule)_tsc.GetModuleForSimpleName(reader.GetString(reader.GetAssemblyDefinition().Name)); var method = (MethodDesc)ecmaModule.GetObject(handle, NotFoundBehavior.ReturnNull); if (method == null) { return null; } if (owningTypeOverride != null) { if (owningTypeOverride != method.OwningType) { return _tsc.GetMethodForInstantiatedType(method.GetTypicalMethodDefinition(), (InstantiatedType)owningTypeOverride); } } return method; } MethodDesc IR2RSignatureTypeProvider<TypeDesc, MethodDesc, R2RSigProviderContext>.GetMethodFromMethodDef(MetadataReader reader, MethodDefinitionHandle handle, TypeDesc owningTypeOverride) { return GetMethodFromMethodDef(reader, handle, owningTypeOverride); } MethodDesc IR2RSignatureTypeProvider<TypeDesc, MethodDesc, R2RSigProviderContext>.GetMethodWithFlags(ReadyToRunMethodSigFlags flags, MethodDesc method) { return method; } TypeDesc ISignatureTypeProvider<TypeDesc, R2RSigProviderContext>.GetModifiedType(TypeDesc modifier, TypeDesc unmodifiedType, bool isRequired) { // Cannot exist in entrypoint definition throw new System.NotImplementedException(); } TypeDesc ISignatureTypeProvider<TypeDesc, R2RSigProviderContext>.GetPinnedType(TypeDesc elementType) { // Cannot exist in entrypoint definition throw new System.NotImplementedException(); } TypeDesc IConstructedTypeProvider<TypeDesc>.GetPointerType(TypeDesc elementType) { // Cannot exist in entrypoint definition throw new System.NotImplementedException(); } TypeDesc ISimpleTypeProvider<TypeDesc>.GetPrimitiveType(PrimitiveTypeCode typeCode) { WellKnownType wkt = 0; switch (typeCode) { case PrimitiveTypeCode.Void: wkt = WellKnownType.Void; break; case PrimitiveTypeCode.Boolean: wkt = WellKnownType.Boolean; break; case PrimitiveTypeCode.Char: wkt = WellKnownType.Char; break; case PrimitiveTypeCode.SByte: wkt = WellKnownType.SByte; break; case PrimitiveTypeCode.Byte: wkt = WellKnownType.Byte; break; case PrimitiveTypeCode.Int16: wkt = WellKnownType.Int16; break; case PrimitiveTypeCode.UInt16: wkt = WellKnownType.UInt16; break; case PrimitiveTypeCode.Int32: wkt = WellKnownType.Int32; break; case PrimitiveTypeCode.UInt32: wkt = WellKnownType.UInt32; break; case PrimitiveTypeCode.Int64: wkt = WellKnownType.Int64; break; case PrimitiveTypeCode.UInt64: wkt = WellKnownType.UInt64; break; case PrimitiveTypeCode.Single: wkt = WellKnownType.Single; break; case PrimitiveTypeCode.Double: wkt = WellKnownType.Double; break; case PrimitiveTypeCode.String: wkt = WellKnownType.String; break; case PrimitiveTypeCode.TypedReference: wkt = WellKnownType.TypedReference; break; case PrimitiveTypeCode.IntPtr: wkt = WellKnownType.IntPtr; break; case PrimitiveTypeCode.UIntPtr: wkt = WellKnownType.UIntPtr; break; case PrimitiveTypeCode.Object: wkt = WellKnownType.Object; break; } return _tsc.GetWellKnownType(wkt); } TypeDesc ISZArrayTypeProvider<TypeDesc>.GetSZArrayType(TypeDesc elementType) { if (elementType == null) return null; return elementType.MakeArrayType(); } TypeDesc ISimpleTypeProvider<TypeDesc>.GetTypeFromDefinition(MetadataReader reader, TypeDefinitionHandle handle, byte rawTypeKind) { var ecmaModule = (EcmaModule)_tsc.GetModuleForSimpleName(reader.GetString(reader.GetAssemblyDefinition().Name)); return (TypeDesc)ecmaModule.GetObject(handle, NotFoundBehavior.ReturnNull); } TypeDesc ISimpleTypeProvider<TypeDesc>.GetTypeFromReference(MetadataReader reader, TypeReferenceHandle handle, byte rawTypeKind) { var ecmaModule = (EcmaModule)_tsc.GetModuleForSimpleName(reader.GetString(reader.GetAssemblyDefinition().Name)); return (TypeDesc)ecmaModule.GetObject(handle, NotFoundBehavior.ReturnNull); } TypeDesc ISignatureTypeProvider<TypeDesc, R2RSigProviderContext>.GetTypeFromSpecification(MetadataReader reader, R2RSigProviderContext genericContext, TypeSpecificationHandle handle, byte rawTypeKind) { var ecmaModule = (EcmaModule)_tsc.GetModuleForSimpleName(reader.GetString(reader.GetAssemblyDefinition().Name)); return (TypeDesc)ecmaModule.GetObject(handle, NotFoundBehavior.ReturnNull); } } class R2RSignatureTypeProviderForGlobalTables : R2RSignatureTypeProvider, IR2RSignatureTypeProvider<TypeDesc, MethodDesc, R2RSigProviderContext> { public R2RSignatureTypeProviderForGlobalTables(TraceTypeSystemContext tsc) : base(tsc) { } MethodDesc IR2RSignatureTypeProvider<TypeDesc, MethodDesc, R2RSigProviderContext>.GetMethodFromMethodDef(MetadataReader reader, MethodDefinitionHandle handle, TypeDesc owningTypeOverride) { if (owningTypeOverride != null) { reader = ((EcmaModule)((MetadataType)owningTypeOverride.GetTypeDefinition()).Module).MetadataReader; } Debug.Assert(reader != null); return GetMethodFromMethodDef(reader, handle, owningTypeOverride); } MethodDesc IR2RSignatureTypeProvider<TypeDesc, MethodDesc, R2RSigProviderContext>.GetMethodFromMemberRef(MetadataReader reader, MemberReferenceHandle handle, TypeDesc owningTypeOverride) { // Global signature cannot have MemberRef entries in them as such things aren't uniquely identifiable throw new NotSupportedException(); } } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/coreclr/vm/win32threadpool.cpp
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*++ Module Name: Win32ThreadPool.cpp Abstract: This module implements Threadpool support using Win32 APIs Revision History: December 1999 - Created --*/ #include "common.h" #include "log.h" #include "threadpoolrequest.h" #include "win32threadpool.h" #include "delegateinfo.h" #include "eeconfig.h" #include "dbginterface.h" #include "corhost.h" #include "eventtrace.h" #include "threads.h" #include "appdomain.inl" #include "nativeoverlapped.h" #include "hillclimbing.h" #include "configuration.h" #ifndef TARGET_UNIX #ifndef DACCESS_COMPILE // APIs that must be accessed through dynamic linking. typedef int (WINAPI *NtQueryInformationThreadProc) ( HANDLE ThreadHandle, THREADINFOCLASS ThreadInformationClass, PVOID ThreadInformation, ULONG ThreadInformationLength, PULONG ReturnLength); NtQueryInformationThreadProc g_pufnNtQueryInformationThread = NULL; typedef int (WINAPI *NtQuerySystemInformationProc) ( SYSTEM_INFORMATION_CLASS SystemInformationClass, PVOID SystemInformation, ULONG SystemInformationLength, PULONG ReturnLength OPTIONAL); NtQuerySystemInformationProc g_pufnNtQuerySystemInformation = NULL; typedef HANDLE (WINAPI * CreateWaitableTimerExProc) ( LPSECURITY_ATTRIBUTES lpTimerAttributes, LPCTSTR lpTimerName, DWORD dwFlags, DWORD dwDesiredAccess); CreateWaitableTimerExProc g_pufnCreateWaitableTimerEx = NULL; typedef BOOL (WINAPI * SetWaitableTimerExProc) ( HANDLE hTimer, const LARGE_INTEGER *lpDueTime, LONG lPeriod, PTIMERAPCROUTINE pfnCompletionRoutine, LPVOID lpArgToCompletionRoutine, void* WakeContext, //should be PREASON_CONTEXT, but it's not defined for us (and we don't use it) ULONG TolerableDelay); SetWaitableTimerExProc g_pufnSetWaitableTimerEx = NULL; #endif // !DACCESS_COMPILE #endif // !TARGET_UNIX BOOL ThreadpoolMgr::InitCompletionPortThreadpool = FALSE; HANDLE ThreadpoolMgr::GlobalCompletionPort; // used for binding io completions on file handles SVAL_IMPL(ThreadpoolMgr::ThreadCounter,ThreadpoolMgr,CPThreadCounter); SVAL_IMPL_INIT(LONG,ThreadpoolMgr,MaxLimitTotalCPThreads,1000); // = MaxLimitCPThreadsPerCPU * number of CPUS SVAL_IMPL(LONG,ThreadpoolMgr,MinLimitTotalCPThreads); SVAL_IMPL(LONG,ThreadpoolMgr,MaxFreeCPThreads); // = MaxFreeCPThreadsPerCPU * Number of CPUS // Cacheline aligned, hot variable DECLSPEC_ALIGN(MAX_CACHE_LINE_SIZE) SVAL_IMPL(ThreadpoolMgr::ThreadCounter, ThreadpoolMgr, WorkerCounter); SVAL_IMPL(LONG,ThreadpoolMgr,MinLimitTotalWorkerThreads); // = MaxLimitCPThreadsPerCPU * number of CPUS SVAL_IMPL(LONG,ThreadpoolMgr,MaxLimitTotalWorkerThreads); // = MaxLimitCPThreadsPerCPU * number of CPUS SVAL_IMPL(LONG,ThreadpoolMgr,cpuUtilization); HillClimbing ThreadpoolMgr::HillClimbingInstance; // Cacheline aligned, 3 hot variables updated in a group DECLSPEC_ALIGN(MAX_CACHE_LINE_SIZE) LONG ThreadpoolMgr::PriorCompletedWorkRequests = 0; DWORD ThreadpoolMgr::PriorCompletedWorkRequestsTime; DWORD ThreadpoolMgr::NextCompletedWorkRequestsTime; LARGE_INTEGER ThreadpoolMgr::CurrentSampleStartTime; unsigned int ThreadpoolMgr::WorkerThreadSpinLimit; bool ThreadpoolMgr::IsHillClimbingDisabled; int ThreadpoolMgr::ThreadAdjustmentInterval; #define INVALID_HANDLE ((HANDLE) -1) #define NEW_THREAD_THRESHOLD 7 // Number of requests outstanding before we start a new thread #define CP_THREAD_PENDINGIO_WAIT 5000 // polling interval when thread is retired but has a pending io #define GATE_THREAD_DELAY 500 /*milliseconds*/ #define GATE_THREAD_DELAY_TOLERANCE 50 /*milliseconds*/ #define DELAY_BETWEEN_SUSPENDS (5000 + GATE_THREAD_DELAY) // time to delay between suspensions Volatile<LONG> ThreadpoolMgr::Initialization = 0; // indicator of whether the threadpool is initialized. bool ThreadpoolMgr::s_usePortableThreadPool = false; bool ThreadpoolMgr::s_usePortableThreadPoolForIO = false; // Cacheline aligned, hot variable DECLSPEC_ALIGN(MAX_CACHE_LINE_SIZE) unsigned int ThreadpoolMgr::LastDequeueTime; // used to determine if work items are getting thread starved SPTR_IMPL(WorkRequest,ThreadpoolMgr,WorkRequestHead); // Head of work request queue SPTR_IMPL(WorkRequest,ThreadpoolMgr,WorkRequestTail); // Head of work request queue SVAL_IMPL(ThreadpoolMgr::LIST_ENTRY,ThreadpoolMgr,TimerQueue); // queue of timers //unsigned int ThreadpoolMgr::LastCpuSamplingTime=0; // last time cpu utilization was sampled by gate thread unsigned int ThreadpoolMgr::LastCPThreadCreation=0; // last time a completion port thread was created unsigned int ThreadpoolMgr::NumberOfProcessors; // = NumberOfWorkerThreads - no. of blocked threads CrstStatic ThreadpoolMgr::WorkerCriticalSection; CLREvent * ThreadpoolMgr::RetiredCPWakeupEvent; // wakeup event for completion port threads CrstStatic ThreadpoolMgr::WaitThreadsCriticalSection; ThreadpoolMgr::LIST_ENTRY ThreadpoolMgr::WaitThreadsHead; CLRLifoSemaphore* ThreadpoolMgr::WorkerSemaphore; CLRLifoSemaphore* ThreadpoolMgr::RetiredWorkerSemaphore; CrstStatic ThreadpoolMgr::TimerQueueCriticalSection; HANDLE ThreadpoolMgr::TimerThread=NULL; Thread *ThreadpoolMgr::pTimerThread=NULL; // Cacheline aligned, hot variable DECLSPEC_ALIGN(MAX_CACHE_LINE_SIZE) DWORD ThreadpoolMgr::LastTickCount; // Cacheline aligned, hot variable DECLSPEC_ALIGN(MAX_CACHE_LINE_SIZE) LONG ThreadpoolMgr::GateThreadStatus=GATE_THREAD_STATUS_NOT_RUNNING; // Move out of from preceeding variables' cache line DECLSPEC_ALIGN(MAX_CACHE_LINE_SIZE) ThreadpoolMgr::RecycledListsWrapper ThreadpoolMgr::RecycledLists; ThreadpoolMgr::TimerInfo *ThreadpoolMgr::TimerInfosToBeRecycled = NULL; BOOL ThreadpoolMgr::IsApcPendingOnWaitThread = FALSE; #ifndef DACCESS_COMPILE // Macros for inserting/deleting from doubly linked list #define InitializeListHead(ListHead) (\ (ListHead)->Flink = (ListHead)->Blink = (ListHead)) // // these are named the same as slightly different macros in the NT headers // #undef RemoveHeadList #undef RemoveEntryList #undef InsertTailList #undef InsertHeadList #define RemoveHeadList(ListHead,FirstEntry) \ {\ FirstEntry = (LIST_ENTRY*) (ListHead)->Flink;\ ((LIST_ENTRY*)FirstEntry->Flink)->Blink = (ListHead);\ (ListHead)->Flink = FirstEntry->Flink;\ } #define RemoveEntryList(Entry) {\ LIST_ENTRY* _EX_Entry;\ _EX_Entry = (Entry);\ ((LIST_ENTRY*) _EX_Entry->Blink)->Flink = _EX_Entry->Flink;\ ((LIST_ENTRY*) _EX_Entry->Flink)->Blink = _EX_Entry->Blink;\ } #define InsertTailList(ListHead,Entry) \ (Entry)->Flink = (ListHead);\ (Entry)->Blink = (ListHead)->Blink;\ ((LIST_ENTRY*)(ListHead)->Blink)->Flink = (Entry);\ (ListHead)->Blink = (Entry); #define InsertHeadList(ListHead,Entry) {\ LIST_ENTRY* _EX_Flink;\ LIST_ENTRY* _EX_ListHead;\ _EX_ListHead = (LIST_ENTRY*)(ListHead);\ _EX_Flink = (LIST_ENTRY*) _EX_ListHead->Flink;\ (Entry)->Flink = _EX_Flink;\ (Entry)->Blink = _EX_ListHead;\ _EX_Flink->Blink = (Entry);\ _EX_ListHead->Flink = (Entry);\ } #define IsListEmpty(ListHead) \ ((ListHead)->Flink == (ListHead)) #define SetLastHRError(hr) \ if (HRESULT_FACILITY(hr) == FACILITY_WIN32)\ SetLastError(HRESULT_CODE(hr));\ else \ SetLastError(ERROR_INVALID_DATA);\ /************************************************************************/ void ThreadpoolMgr::RecycledListsWrapper::Initialize( unsigned int numProcs ) { CONTRACTL { THROWS; MODE_ANY; GC_NOTRIGGER; } CONTRACTL_END; pRecycledListPerProcessor = new RecycledListInfo[numProcs][MEMTYPE_COUNT]; } //--// void ThreadpoolMgr::EnsureInitialized() { CONTRACTL { THROWS; // EnsureInitializedSlow can throw MODE_ANY; GC_NOTRIGGER; } CONTRACTL_END; if (IsInitialized()) return; EnsureInitializedSlow(); } NOINLINE void ThreadpoolMgr::EnsureInitializedSlow() { CONTRACTL { THROWS; // Initialize can throw MODE_ANY; GC_NOTRIGGER; } CONTRACTL_END; DWORD dwSwitchCount = 0; retry: if (InterlockedCompareExchange(&Initialization, 1, 0) == 0) { if (Initialize()) Initialization = -1; else { Initialization = 0; COMPlusThrowOM(); } } else // someone has already begun initializing. { // wait until it finishes while (Initialization != -1) { __SwitchToThread(0, ++dwSwitchCount); goto retry; } } } DWORD GetDefaultMaxLimitWorkerThreads(DWORD minLimit) { CONTRACTL { MODE_ANY; GC_NOTRIGGER; NOTHROW; } CONTRACTL_END; _ASSERTE(!ThreadpoolMgr::UsePortableThreadPool()); // // We determine the max limit for worker threads as follows: // // 1) It must be at least MinLimitTotalWorkerThreads // 2) It must be no greater than (half the virtual address space)/(thread stack size) // 3) It must be <= MaxPossibleWorkerThreads // // TODO: what about CP threads? Can they follow a similar plan? How do we allocate // thread counts between the two kinds of threads? // SIZE_T stackReserveSize = 0; Thread::GetProcessDefaultStackSize(&stackReserveSize, NULL); ULONGLONG halfVirtualAddressSpace; MEMORYSTATUSEX memStats; memStats.dwLength = sizeof(memStats); if (GlobalMemoryStatusEx(&memStats)) { halfVirtualAddressSpace = memStats.ullTotalVirtual / 2; } else { //assume the normal Win32 32-bit virtual address space halfVirtualAddressSpace = 0x000000007FFE0000ull / 2; } ULONGLONG limit = halfVirtualAddressSpace / stackReserveSize; limit = max(limit, (ULONGLONG)minLimit); limit = min(limit, (ULONGLONG)ThreadpoolMgr::ThreadCounter::MaxPossibleCount); _ASSERTE(FitsIn<DWORD>(limit)); return (DWORD)limit; } DWORD GetForceMinWorkerThreadsValue() { WRAPPER_NO_CONTRACT; _ASSERTE(!ThreadpoolMgr::UsePortableThreadPool()); return Configuration::GetKnobDWORDValue(W("System.Threading.ThreadPool.MinThreads"), CLRConfig::INTERNAL_ThreadPool_ForceMinWorkerThreads); } DWORD GetForceMaxWorkerThreadsValue() { WRAPPER_NO_CONTRACT; _ASSERTE(!ThreadpoolMgr::UsePortableThreadPool()); return Configuration::GetKnobDWORDValue(W("System.Threading.ThreadPool.MaxThreads"), CLRConfig::INTERNAL_ThreadPool_ForceMaxWorkerThreads); } BOOL ThreadpoolMgr::Initialize() { CONTRACTL { THROWS; MODE_ANY; GC_NOTRIGGER; INJECT_FAULT(COMPlusThrowOM()); } CONTRACTL_END; BOOL bRet = FALSE; BOOL bExceptionCaught = FALSE; NumberOfProcessors = GetCurrentProcessCpuCount(); InitPlatformVariables(); EX_TRY { if (!UsePortableThreadPool()) { WorkerThreadSpinLimit = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_ThreadPool_UnfairSemaphoreSpinLimit); IsHillClimbingDisabled = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_HillClimbing_Disable) != 0; ThreadAdjustmentInterval = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_HillClimbing_SampleIntervalLow); WaitThreadsCriticalSection.Init(CrstThreadpoolWaitThreads); } if (!UsePortableThreadPoolForIO()) { WorkerCriticalSection.Init(CrstThreadpoolWorker); } TimerQueueCriticalSection.Init(CrstThreadpoolTimerQueue); if (!UsePortableThreadPool()) { // initialize WaitThreadsHead InitializeListHead(&WaitThreadsHead); } // initialize TimerQueue InitializeListHead(&TimerQueue); if (!UsePortableThreadPoolForIO()) { RetiredCPWakeupEvent = new CLREvent(); RetiredCPWakeupEvent->CreateAutoEvent(FALSE); _ASSERTE(RetiredCPWakeupEvent->IsValid()); } if (!UsePortableThreadPool()) { WorkerSemaphore = new CLRLifoSemaphore(); WorkerSemaphore->Create(0, ThreadCounter::MaxPossibleCount); RetiredWorkerSemaphore = new CLRLifoSemaphore(); RetiredWorkerSemaphore->Create(0, ThreadCounter::MaxPossibleCount); } #ifndef TARGET_UNIX //ThreadPool_CPUGroup if (CPUGroupInfo::CanEnableThreadUseAllCpuGroups()) RecycledLists.Initialize( CPUGroupInfo::GetNumActiveProcessors() ); else RecycledLists.Initialize( g_SystemInfo.dwNumberOfProcessors ); #else // !TARGET_UNIX RecycledLists.Initialize( PAL_GetTotalCpuCount() ); #endif // !TARGET_UNIX } EX_CATCH { if (!UsePortableThreadPoolForIO() && RetiredCPWakeupEvent) { delete RetiredCPWakeupEvent; RetiredCPWakeupEvent = NULL; } // Note: It is fine to call Destroy on uninitialized critical sections if (!UsePortableThreadPool()) { WaitThreadsCriticalSection.Destroy(); } if (!UsePortableThreadPoolForIO()) { WorkerCriticalSection.Destroy(); } TimerQueueCriticalSection.Destroy(); bExceptionCaught = TRUE; } EX_END_CATCH(SwallowAllExceptions); if (bExceptionCaught) { goto end; } if (!UsePortableThreadPool()) { // initialize Worker thread settings DWORD forceMin; forceMin = GetForceMinWorkerThreadsValue(); MinLimitTotalWorkerThreads = forceMin > 0 ? (LONG)forceMin : (LONG)NumberOfProcessors; DWORD forceMax; forceMax = GetForceMaxWorkerThreadsValue(); MaxLimitTotalWorkerThreads = forceMax > 0 ? (LONG)forceMax : (LONG)GetDefaultMaxLimitWorkerThreads(MinLimitTotalWorkerThreads); ThreadCounter::Counts counts; counts.NumActive = 0; counts.NumWorking = 0; counts.NumRetired = 0; counts.MaxWorking = MinLimitTotalWorkerThreads; WorkerCounter.counts.AsLongLong = counts.AsLongLong; } if (!UsePortableThreadPoolForIO()) { // initialize CP thread settings MinLimitTotalCPThreads = NumberOfProcessors; // Use volatile store to guarantee make the value visible to the DAC (the store can be optimized out otherwise) VolatileStoreWithoutBarrier<LONG>(&MaxFreeCPThreads, NumberOfProcessors*MaxFreeCPThreadsPerCPU); ThreadCounter::Counts counts; counts.NumActive = 0; counts.NumWorking = 0; counts.NumRetired = 0; counts.MaxWorking = MinLimitTotalCPThreads; CPThreadCounter.counts.AsLongLong = counts.AsLongLong; #ifndef TARGET_UNIX { GlobalCompletionPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, /*ignored for invalid handle value*/ NumberOfProcessors); } #endif // !TARGET_UNIX } if (!UsePortableThreadPool()) { HillClimbingInstance.Initialize(); } bRet = TRUE; end: return bRet; } void ThreadpoolMgr::InitPlatformVariables() { CONTRACTL { NOTHROW; MODE_ANY; GC_NOTRIGGER; } CONTRACTL_END; #ifndef TARGET_UNIX HINSTANCE hNtDll; HINSTANCE hCoreSynch = nullptr; { CONTRACT_VIOLATION(GCViolation|FaultViolation); hNtDll = CLRLoadLibrary(W("ntdll.dll")); _ASSERTE(hNtDll); if (!UsePortableThreadPool()) { hCoreSynch = CLRLoadLibrary(W("api-ms-win-core-synch-l1-1-0.dll")); _ASSERTE(hCoreSynch); } } // These APIs must be accessed via dynamic binding since they may be removed in future // OS versions. g_pufnNtQueryInformationThread = (NtQueryInformationThreadProc)GetProcAddress(hNtDll,"NtQueryInformationThread"); g_pufnNtQuerySystemInformation = (NtQuerySystemInformationProc)GetProcAddress(hNtDll,"NtQuerySystemInformation"); if (!UsePortableThreadPool()) { // These APIs are only supported on newer Windows versions g_pufnCreateWaitableTimerEx = (CreateWaitableTimerExProc)GetProcAddress(hCoreSynch, "CreateWaitableTimerExW"); g_pufnSetWaitableTimerEx = (SetWaitableTimerExProc)GetProcAddress(hCoreSynch, "SetWaitableTimerEx"); } #endif } bool ThreadpoolMgr::CanSetMinIOCompletionThreads(DWORD ioCompletionThreads) { WRAPPER_NO_CONTRACT; _ASSERTE(UsePortableThreadPool()); _ASSERTE(!UsePortableThreadPoolForIO()); EnsureInitialized(); // The lock used by SetMinThreads() and SetMaxThreads() is not taken here, the caller is expected to synchronize between // them. The conditions here should be the same as in the corresponding Set function. return ioCompletionThreads <= (DWORD)MaxLimitTotalCPThreads; } bool ThreadpoolMgr::CanSetMaxIOCompletionThreads(DWORD ioCompletionThreads) { WRAPPER_NO_CONTRACT; _ASSERTE(UsePortableThreadPool()); _ASSERTE(!UsePortableThreadPoolForIO()); _ASSERTE(ioCompletionThreads != 0); EnsureInitialized(); // The lock used by SetMinThreads() and SetMaxThreads() is not taken here, the caller is expected to synchronize between // them. The conditions here should be the same as in the corresponding Set function. return ioCompletionThreads >= (DWORD)MinLimitTotalCPThreads; } BOOL ThreadpoolMgr::SetMaxThreadsHelper(DWORD MaxWorkerThreads, DWORD MaxIOCompletionThreads) { CONTRACTL { THROWS; // Crst can throw and toggle GC mode MODE_ANY; GC_TRIGGERS; } CONTRACTL_END; _ASSERTE(!UsePortableThreadPoolForIO()); BOOL result = FALSE; // doesn't need to be WorkerCS, but using it to avoid race condition between setting min and max, and didn't want to create a new CS. CrstHolder csh(&WorkerCriticalSection); bool usePortableThreadPool = UsePortableThreadPool(); if (( usePortableThreadPool || ( MaxWorkerThreads >= (DWORD)MinLimitTotalWorkerThreads && MaxWorkerThreads != 0 ) ) && MaxIOCompletionThreads >= (DWORD)MinLimitTotalCPThreads && MaxIOCompletionThreads != 0) { if (!usePortableThreadPool && GetForceMaxWorkerThreadsValue() == 0) { MaxLimitTotalWorkerThreads = min(MaxWorkerThreads, (DWORD)ThreadCounter::MaxPossibleCount); ThreadCounter::Counts counts = WorkerCounter.GetCleanCounts(); while (counts.MaxWorking > MaxLimitTotalWorkerThreads) { ThreadCounter::Counts newCounts = counts; newCounts.MaxWorking = MaxLimitTotalWorkerThreads; ThreadCounter::Counts oldCounts = WorkerCounter.CompareExchangeCounts(newCounts, counts); if (oldCounts == counts) counts = newCounts; else counts = oldCounts; } } MaxLimitTotalCPThreads = min(MaxIOCompletionThreads, (DWORD)ThreadCounter::MaxPossibleCount); result = TRUE; } return result; } /************************************************************************/ BOOL ThreadpoolMgr::SetMaxThreads(DWORD MaxWorkerThreads, DWORD MaxIOCompletionThreads) { CONTRACTL { THROWS; // SetMaxThreadsHelper can throw and toggle GC mode MODE_ANY; GC_TRIGGERS; } CONTRACTL_END; _ASSERTE(!UsePortableThreadPoolForIO()); EnsureInitialized(); return SetMaxThreadsHelper(MaxWorkerThreads, MaxIOCompletionThreads); } BOOL ThreadpoolMgr::GetMaxThreads(DWORD* MaxWorkerThreads, DWORD* MaxIOCompletionThreads) { LIMITED_METHOD_CONTRACT; _ASSERTE(!UsePortableThreadPoolForIO()); if (!MaxWorkerThreads || !MaxIOCompletionThreads) { SetLastHRError(ERROR_INVALID_DATA); return FALSE; } EnsureInitialized(); *MaxWorkerThreads = UsePortableThreadPool() ? 1 : (DWORD)MaxLimitTotalWorkerThreads; *MaxIOCompletionThreads = MaxLimitTotalCPThreads; return TRUE; } BOOL ThreadpoolMgr::SetMinThreads(DWORD MinWorkerThreads, DWORD MinIOCompletionThreads) { CONTRACTL { THROWS; // Crst can throw and toggle GC mode MODE_ANY; GC_TRIGGERS; } CONTRACTL_END; _ASSERTE(!UsePortableThreadPoolForIO()); EnsureInitialized(); // doesn't need to be WorkerCS, but using it to avoid race condition between setting min and max, and didn't want to create a new CS. CrstHolder csh(&WorkerCriticalSection); BOOL init_result = FALSE; bool usePortableThreadPool = UsePortableThreadPool(); if (( usePortableThreadPool || ( MinWorkerThreads >= 0 && MinWorkerThreads <= (DWORD) MaxLimitTotalWorkerThreads ) ) && MinIOCompletionThreads >= 0 && MinIOCompletionThreads <= (DWORD) MaxLimitTotalCPThreads) { if (!usePortableThreadPool && GetForceMinWorkerThreadsValue() == 0) { MinLimitTotalWorkerThreads = max(1, min(MinWorkerThreads, (DWORD)ThreadCounter::MaxPossibleCount)); ThreadCounter::Counts counts = WorkerCounter.GetCleanCounts(); while (counts.MaxWorking < MinLimitTotalWorkerThreads) { ThreadCounter::Counts newCounts = counts; newCounts.MaxWorking = MinLimitTotalWorkerThreads; ThreadCounter::Counts oldCounts = WorkerCounter.CompareExchangeCounts(newCounts, counts); if (oldCounts == counts) { counts = newCounts; // if we increased the limit, and there are pending workitems, we need // to dispatch a thread to process the work. if (newCounts.MaxWorking > oldCounts.MaxWorking && PerAppDomainTPCountList::AreRequestsPendingInAnyAppDomains()) { MaybeAddWorkingWorker(); } } else { counts = oldCounts; } } } MinLimitTotalCPThreads = max(1, min(MinIOCompletionThreads, (DWORD)ThreadCounter::MaxPossibleCount)); init_result = TRUE; } return init_result; } BOOL ThreadpoolMgr::GetMinThreads(DWORD* MinWorkerThreads, DWORD* MinIOCompletionThreads) { LIMITED_METHOD_CONTRACT; _ASSERTE(!UsePortableThreadPoolForIO()); if (!MinWorkerThreads || !MinIOCompletionThreads) { SetLastHRError(ERROR_INVALID_DATA); return FALSE; } EnsureInitialized(); *MinWorkerThreads = UsePortableThreadPool() ? 1 : (DWORD)MinLimitTotalWorkerThreads; *MinIOCompletionThreads = MinLimitTotalCPThreads; return TRUE; } BOOL ThreadpoolMgr::GetAvailableThreads(DWORD* AvailableWorkerThreads, DWORD* AvailableIOCompletionThreads) { LIMITED_METHOD_CONTRACT; _ASSERTE(!UsePortableThreadPoolForIO()); if (!AvailableWorkerThreads || !AvailableIOCompletionThreads) { SetLastHRError(ERROR_INVALID_DATA); return FALSE; } EnsureInitialized(); if (UsePortableThreadPool()) { *AvailableWorkerThreads = 0; } else { ThreadCounter::Counts counts = WorkerCounter.GetCleanCounts(); if (MaxLimitTotalWorkerThreads < counts.NumActive) *AvailableWorkerThreads = 0; else *AvailableWorkerThreads = MaxLimitTotalWorkerThreads - counts.NumWorking; } ThreadCounter::Counts counts = CPThreadCounter.GetCleanCounts(); if (MaxLimitTotalCPThreads < counts.NumActive) *AvailableIOCompletionThreads = counts.NumActive - counts.NumWorking; else *AvailableIOCompletionThreads = MaxLimitTotalCPThreads - counts.NumWorking; return TRUE; } INT32 ThreadpoolMgr::GetThreadCount() { WRAPPER_NO_CONTRACT; _ASSERTE(!UsePortableThreadPoolForIO()); if (!IsInitialized()) { return 0; } INT32 workerThreadCount = UsePortableThreadPool() ? 0 : WorkerCounter.DangerousGetDirtyCounts().NumActive; return workerThreadCount + CPThreadCounter.DangerousGetDirtyCounts().NumActive; } void QueueUserWorkItemHelp(LPTHREAD_START_ROUTINE Function, PVOID Context) { STATIC_CONTRACT_THROWS; STATIC_CONTRACT_GC_TRIGGERS; STATIC_CONTRACT_MODE_ANY; /* Cannot use contract here because of SEH CONTRACTL { THROWS; GC_TRIGGERS; MODE_ANY; } CONTRACTL_END;*/ _ASSERTE(!ThreadpoolMgr::UsePortableThreadPool()); Function(Context); Thread *pThread = GetThreadNULLOk(); if (pThread) { _ASSERTE(!pThread->IsAbortRequested()); pThread->InternalReset(); } } // // WorkingThreadCounts tracks the number of worker threads currently doing user work, and the maximum number of such threads // since the last time TakeMaxWorkingThreadCount was called. This information is for diagnostic purposes only, // and is tracked only if the CLR config value INTERNAL_ThreadPool_EnableWorkerTracking is non-zero (this feature is off // by default). // union WorkingThreadCounts { struct { int currentWorking : 16; int maxWorking : 16; }; LONG asLong; }; WorkingThreadCounts g_workingThreadCounts; // // If worker tracking is enabled (see above) then this is called immediately before and after a worker thread executes // each work item. // void ThreadpoolMgr::ReportThreadStatus(bool isWorking) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; _ASSERTE(IsInitialized()); // can't be here without requesting a thread first _ASSERTE(CLRConfig::GetConfigValue(CLRConfig::INTERNAL_ThreadPool_EnableWorkerTracking)); while (true) { WorkingThreadCounts currentCounts, newCounts; currentCounts.asLong = VolatileLoad(&g_workingThreadCounts.asLong); newCounts = currentCounts; if (isWorking) newCounts.currentWorking++; if (newCounts.currentWorking > newCounts.maxWorking) newCounts.maxWorking = newCounts.currentWorking; if (!isWorking) newCounts.currentWorking--; if (currentCounts.asLong == InterlockedCompareExchange(&g_workingThreadCounts.asLong, newCounts.asLong, currentCounts.asLong)) break; } } // // Returns the max working count since the previous call to TakeMaxWorkingThreadCount, and resets WorkingThreadCounts.maxWorking. // int TakeMaxWorkingThreadCount() { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; _ASSERTE(CLRConfig::GetConfigValue(CLRConfig::INTERNAL_ThreadPool_EnableWorkerTracking)); while (true) { WorkingThreadCounts currentCounts, newCounts; currentCounts.asLong = VolatileLoad(&g_workingThreadCounts.asLong); newCounts = currentCounts; newCounts.maxWorking = 0; if (currentCounts.asLong == InterlockedCompareExchange(&g_workingThreadCounts.asLong, newCounts.asLong, currentCounts.asLong)) { // If we haven't updated the counts since the last call to TakeMaxWorkingThreadCount, then we never updated maxWorking. // In that case, the number of working threads for the whole period since the last TakeMaxWorkingThreadCount is the // current number of working threads. return currentCounts.maxWorking == 0 ? currentCounts.currentWorking : currentCounts.maxWorking; } } } /************************************************************************/ BOOL ThreadpoolMgr::QueueUserWorkItem(LPTHREAD_START_ROUTINE Function, PVOID Context, DWORD Flags, BOOL UnmanagedTPRequest) { CONTRACTL { THROWS; // EnsureInitialized, EnqueueWorkRequest can throw OOM GC_TRIGGERS; MODE_ANY; } CONTRACTL_END; _ASSERTE_ALL_BUILDS(__FILE__, !UsePortableThreadPool()); EnsureInitialized(); if (Flags == CALL_OR_QUEUE) { // we've been asked to call this directly if the thread pressure is not too high int MinimumAvailableCPThreads = (NumberOfProcessors < 3) ? 3 : NumberOfProcessors; ThreadCounter::Counts counts = CPThreadCounter.GetCleanCounts(); if ((MaxLimitTotalCPThreads - counts.NumActive) >= MinimumAvailableCPThreads ) { QueueUserWorkItemHelp(Function, Context); return TRUE; } } if (UnmanagedTPRequest) { UnManagedPerAppDomainTPCount* pADTPCount; pADTPCount = PerAppDomainTPCountList::GetUnmanagedTPCount(); pADTPCount->QueueUnmanagedWorkRequest(Function, Context); } else { // caller has already registered its TPCount; this call is just to adjust the thread count } return TRUE; } bool ThreadpoolMgr::ShouldWorkerKeepRunning() { WRAPPER_NO_CONTRACT; _ASSERTE(!UsePortableThreadPool()); // // Maybe this thread should retire now. Let's see. // bool shouldThisThreadKeepRunning = true; // Dirty read is OK here; the worst that can happen is that we won't retire this time. In the // case where we might retire, we have to succeed a CompareExchange, which will have the effect // of validating this read. ThreadCounter::Counts counts = WorkerCounter.DangerousGetDirtyCounts(); while (true) { if (counts.NumActive <= counts.MaxWorking) { shouldThisThreadKeepRunning = true; break; } ThreadCounter::Counts newCounts = counts; newCounts.NumWorking--; newCounts.NumActive--; newCounts.NumRetired++; ThreadCounter::Counts oldCounts = WorkerCounter.CompareExchangeCounts(newCounts, counts); if (oldCounts == counts) { shouldThisThreadKeepRunning = false; break; } counts = oldCounts; } return shouldThisThreadKeepRunning; } DangerousNonHostedSpinLock ThreadpoolMgr::ThreadAdjustmentLock; // // This method must only be called if ShouldAdjustMaxWorkersActive has returned true, *and* // ThreadAdjustmentLock is held. // void ThreadpoolMgr::AdjustMaxWorkersActive() { CONTRACTL { NOTHROW; if (GetThreadNULLOk()) { GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);} MODE_ANY; } CONTRACTL_END; _ASSERTE(!UsePortableThreadPool()); _ASSERTE(ThreadAdjustmentLock.IsHeld()); LARGE_INTEGER startTime = CurrentSampleStartTime; LARGE_INTEGER endTime; QueryPerformanceCounter(&endTime); static LARGE_INTEGER freq; if (freq.QuadPart == 0) QueryPerformanceFrequency(&freq); double elapsed = (double)(endTime.QuadPart - startTime.QuadPart) / freq.QuadPart; // // It's possible for the current sample to be reset while we're holding // ThreadAdjustmentLock. This will result in a very short sample, possibly // with completely bogus counts. We'll try to detect this by checking the sample // interval; if it's very short, then we try again later. // if (elapsed*1000.0 >= (ThreadAdjustmentInterval/2)) { DWORD currentTicks = GetTickCount(); LONG totalNumCompletions = (LONG)Thread::GetTotalWorkerThreadPoolCompletionCount(); LONG numCompletions = totalNumCompletions - VolatileLoad(&PriorCompletedWorkRequests); ThreadCounter::Counts currentCounts = WorkerCounter.GetCleanCounts(); int newMax = HillClimbingInstance.Update( currentCounts.MaxWorking, elapsed, numCompletions, &ThreadAdjustmentInterval); while (newMax != currentCounts.MaxWorking) { ThreadCounter::Counts newCounts = currentCounts; newCounts.MaxWorking = newMax; ThreadCounter::Counts oldCounts = WorkerCounter.CompareExchangeCounts(newCounts, currentCounts); if (oldCounts == currentCounts) { // // If we're increasing the max, inject a thread. If that thread finds work, it will inject // another thread, etc., until nobody finds work or we reach the new maximum. // // If we're reducing the max, whichever threads notice this first will retire themselves. // if (newMax > oldCounts.MaxWorking) MaybeAddWorkingWorker(); break; } else { // we failed - maybe try again if (oldCounts.MaxWorking > currentCounts.MaxWorking && oldCounts.MaxWorking >= newMax) { // someone (probably the gate thread) increased the thread count more than // we are about to do. Don't interfere. break; } currentCounts = oldCounts; } } PriorCompletedWorkRequests = totalNumCompletions; NextCompletedWorkRequestsTime = currentTicks + ThreadAdjustmentInterval; MemoryBarrier(); // flush previous writes (especially NextCompletedWorkRequestsTime) PriorCompletedWorkRequestsTime = currentTicks; CurrentSampleStartTime = endTime;; } } void ThreadpoolMgr::MaybeAddWorkingWorker() { CONTRACTL { NOTHROW; if (GetThreadNULLOk()) { GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);} MODE_ANY; } CONTRACTL_END; _ASSERTE(!UsePortableThreadPool()); // counts volatile read paired with CompareExchangeCounts loop set ThreadCounter::Counts counts = WorkerCounter.DangerousGetDirtyCounts(); ThreadCounter::Counts newCounts; while (true) { newCounts = counts; newCounts.NumWorking = max(counts.NumWorking, min(counts.NumWorking + 1, counts.MaxWorking)); newCounts.NumActive = max(counts.NumActive, newCounts.NumWorking); newCounts.NumRetired = max(0, counts.NumRetired - (newCounts.NumActive - counts.NumActive)); if (newCounts == counts) return; ThreadCounter::Counts oldCounts = WorkerCounter.CompareExchangeCounts(newCounts, counts); if (oldCounts == counts) break; counts = oldCounts; } int toUnretire = counts.NumRetired - newCounts.NumRetired; int toCreate = (newCounts.NumActive - counts.NumActive) - toUnretire; int toRelease = (newCounts.NumWorking - counts.NumWorking) - (toUnretire + toCreate); _ASSERTE(toUnretire >= 0); _ASSERTE(toCreate >= 0); _ASSERTE(toRelease >= 0); _ASSERTE(toUnretire + toCreate + toRelease <= 1); if (toUnretire > 0) { RetiredWorkerSemaphore->Release(toUnretire); } if (toRelease > 0) WorkerSemaphore->Release(toRelease); while (toCreate > 0) { if (CreateWorkerThread()) { toCreate--; } else { // // Uh-oh, we promised to create a new thread, but the creation failed. We have to renege on our // promise. This may possibly result in no work getting done for a while, but the gate thread will // eventually notice that no completions are happening and force the creation of a new thread. // Of course, there's no guarantee *that* will work - but hopefully enough time will have passed // to allow whoever's using all the memory right now to release some. // // counts volatile read paired with CompareExchangeCounts loop set counts = WorkerCounter.DangerousGetDirtyCounts(); while (true) { // // If we said we would create a thread, we also said it would be working. So we need to // decrement both NumWorking and NumActive by the number of threads we will no longer be creating. // newCounts = counts; newCounts.NumWorking -= toCreate; newCounts.NumActive -= toCreate; ThreadCounter::Counts oldCounts = WorkerCounter.CompareExchangeCounts(newCounts, counts); if (oldCounts == counts) break; counts = oldCounts; } toCreate = 0; } } } BOOL ThreadpoolMgr::PostQueuedCompletionStatus(LPOVERLAPPED lpOverlapped, LPOVERLAPPED_COMPLETION_ROUTINE Function) { CONTRACTL { THROWS; // EnsureInitialized can throw OOM GC_TRIGGERS; MODE_ANY; } CONTRACTL_END; _ASSERTE(!UsePortableThreadPoolForIO()); #ifndef TARGET_UNIX EnsureInitialized(); _ASSERTE(GlobalCompletionPort != NULL); if (!InitCompletionPortThreadpool) InitCompletionPortThreadpool = TRUE; GrowCompletionPortThreadpoolIfNeeded(); // In order to allow external ETW listeners to correlate activities that use our IO completion port // as a dispatch mechanism, we have to ensure the runtime's calls to ::PostQueuedCompletionStatus // and ::GetQueuedCompletionStatus are "annotated" with ETW events representing to operations // performed. // There are currently 2 codepaths that post to the GlobalCompletionPort: // 1. the managed API ThreadPool.UnsafeQueueNativeOverlapped(), calling CorPostQueuedCompletionStatus() // which already fires the ETW event as needed // 2. the managed API ThreadPool.RegisterWaitForSingleObject which needs to fire the ETW event // at the time the managed API is called (on the orignial user thread), and not when the ::PQCS // is called (from the dedicated wait thread). // If additional codepaths appear they need to either fire the ETW event before calling this or ensure // we do not fire an unmatched "dequeue" event in ThreadpoolMgr::CompletionPortThreadStart // The current possible values for Function: // - BindIoCompletionCallbackStub for ThreadPool.UnsafeQueueNativeOverlapped // - WaitIOCompletionCallback for ThreadPool.RegisterWaitForSingleObject return ::PostQueuedCompletionStatus(GlobalCompletionPort, 0, (ULONG_PTR) Function, lpOverlapped); #else SetLastError(ERROR_CALL_NOT_IMPLEMENTED); return FALSE; #endif // !TARGET_UNIX } void ThreadpoolMgr::WaitIOCompletionCallback( DWORD dwErrorCode, DWORD numBytesTransferred, LPOVERLAPPED lpOverlapped) { CONTRACTL { THROWS; MODE_ANY; } CONTRACTL_END; if (dwErrorCode == ERROR_SUCCESS) DWORD ret = AsyncCallbackCompletion((PVOID)lpOverlapped); } extern void WINAPI BindIoCompletionCallbackStub(DWORD ErrorCode, DWORD numBytesTransferred, LPOVERLAPPED lpOverlapped); // This is either made by a worker thread or a CP thread // indicated by threadTypeStatus void ThreadpoolMgr::EnsureGateThreadRunning() { LIMITED_METHOD_CONTRACT; _ASSERTE(!UsePortableThreadPoolForIO()); if (UsePortableThreadPool()) { GCX_COOP(); MethodDescCallSite(METHOD__THREAD_POOL__ENSURE_GATE_THREAD_RUNNING).Call(NULL); return; } while (true) { switch (GateThreadStatus) { case GATE_THREAD_STATUS_REQUESTED: // // No action needed; the gate thread is running, and someone else has already registered a request // for it to stay. // return; case GATE_THREAD_STATUS_WAITING_FOR_REQUEST: // // Prevent the gate thread from exiting, if it hasn't already done so. If it has, we'll create it on the next iteration of // this loop. // FastInterlockCompareExchange(&GateThreadStatus, GATE_THREAD_STATUS_REQUESTED, GATE_THREAD_STATUS_WAITING_FOR_REQUEST); break; case GATE_THREAD_STATUS_NOT_RUNNING: // // We need to create a new gate thread // if (FastInterlockCompareExchange(&GateThreadStatus, GATE_THREAD_STATUS_REQUESTED, GATE_THREAD_STATUS_NOT_RUNNING) == GATE_THREAD_STATUS_NOT_RUNNING) { if (!CreateGateThread()) { // // If we failed to create the gate thread, someone else will need to try again later. // GateThreadStatus = GATE_THREAD_STATUS_NOT_RUNNING; } return; } break; default: _ASSERTE(!"Invalid value of ThreadpoolMgr::GateThreadStatus"); } } } bool ThreadpoolMgr::NeedGateThreadForIOCompletions() { LIMITED_METHOD_CONTRACT; _ASSERTE(!UsePortableThreadPoolForIO()); if (!InitCompletionPortThreadpool) { return false; } ThreadCounter::Counts counts = CPThreadCounter.GetCleanCounts(); return counts.NumActive <= counts.NumWorking; } bool ThreadpoolMgr::ShouldGateThreadKeepRunning() { LIMITED_METHOD_CONTRACT; _ASSERTE(!UsePortableThreadPool()); _ASSERTE(GateThreadStatus == GATE_THREAD_STATUS_WAITING_FOR_REQUEST || GateThreadStatus == GATE_THREAD_STATUS_REQUESTED); // // Switch to WAITING_FOR_REQUEST, and see if we had a request since the last check. // LONG previousStatus = FastInterlockExchange(&GateThreadStatus, GATE_THREAD_STATUS_WAITING_FOR_REQUEST); if (previousStatus == GATE_THREAD_STATUS_WAITING_FOR_REQUEST) { // // No recent requests for the gate thread. Check to see if we're still needed. // // // Are there any free threads in the I/O completion pool? If there are, we don't need a gate thread. // This implies that whenever we decrement NumFreeCPThreads to 0, we need to call EnsureGateThreadRunning(). // bool needGateThreadForCompletionPort = NeedGateThreadForIOCompletions(); // // Are there any work requests in any worker queue? If so, we need a gate thread. // This imples that whenever a work queue goes from empty to non-empty, we need to call EnsureGateThreadRunning(). // bool needGateThreadForWorkerThreads = PerAppDomainTPCountList::AreRequestsPendingInAnyAppDomains(); // // If worker tracking is enabled, we need to fire periodic ETW events with active worker counts. This is // done by the gate thread. // We don't have to do anything special with EnsureGateThreadRunning() here, because this is only needed // once work has been added to the queue for the first time (which is covered above). // bool needGateThreadForWorkerTracking = 0 != CLRConfig::GetConfigValue(CLRConfig::INTERNAL_ThreadPool_EnableWorkerTracking); if (!(needGateThreadForCompletionPort || needGateThreadForWorkerThreads || needGateThreadForWorkerTracking)) { // // It looks like we shouldn't be running. But another thread may now tell us to run. If so, they will set GateThreadStatus // back to GATE_THREAD_STATUS_REQUESTED. // previousStatus = FastInterlockCompareExchange(&GateThreadStatus, GATE_THREAD_STATUS_NOT_RUNNING, GATE_THREAD_STATUS_WAITING_FOR_REQUEST); if (previousStatus == GATE_THREAD_STATUS_WAITING_FOR_REQUEST) return false; } } _ASSERTE(GateThreadStatus == GATE_THREAD_STATUS_WAITING_FOR_REQUEST || GateThreadStatus == GATE_THREAD_STATUS_REQUESTED); return true; } //************************************************************************ void ThreadpoolMgr::EnqueueWorkRequest(WorkRequest* workRequest) { CONTRACTL { NOTHROW; MODE_ANY; GC_NOTRIGGER; } CONTRACTL_END; _ASSERTE(!UsePortableThreadPool()); AppendWorkRequest(workRequest); } WorkRequest* ThreadpoolMgr::DequeueWorkRequest() { WorkRequest* entry = NULL; CONTRACT(WorkRequest*) { NOTHROW; GC_NOTRIGGER; MODE_PREEMPTIVE; POSTCONDITION(CheckPointer(entry, NULL_OK)); } CONTRACT_END; _ASSERTE(!UsePortableThreadPool()); entry = RemoveWorkRequest(); RETURN entry; } void ThreadpoolMgr::ExecuteWorkRequest(bool* foundWork, bool* wasNotRecalled) { CONTRACTL { THROWS; // QueueUserWorkItem can throw GC_TRIGGERS; MODE_PREEMPTIVE; } CONTRACTL_END; _ASSERTE(!UsePortableThreadPool()); IPerAppDomainTPCount* pAdCount; LONG index = PerAppDomainTPCountList::GetAppDomainIndexForThreadpoolDispatch(); if (index == 0) { *foundWork = false; *wasNotRecalled = true; return; } if (index == -1) { pAdCount = PerAppDomainTPCountList::GetUnmanagedTPCount(); } else { pAdCount = PerAppDomainTPCountList::GetPerAppdomainCount(TPIndex((DWORD)index)); _ASSERTE(pAdCount); } pAdCount->DispatchWorkItem(foundWork, wasNotRecalled); } //-------------------------------------------------------------------------- //This function informs the thread scheduler that the first requests has been //queued on an appdomain, or it's the first unmanaged TP request. //Arguments: // UnmanagedTP: Indicates that the request arises from the unmanaged //part of Thread Pool. //Assumptions: // This function must be called under a per-appdomain lock or the //correct lock under unmanaged TP queue. // BOOL ThreadpoolMgr::SetAppDomainRequestsActive(BOOL UnmanagedTP) { CONTRACTL { NOTHROW; MODE_ANY; GC_TRIGGERS; } CONTRACTL_END; _ASSERTE(!UsePortableThreadPool()); BOOL fShouldSignalEvent = FALSE; IPerAppDomainTPCount* pAdCount; if(UnmanagedTP) { pAdCount = PerAppDomainTPCountList::GetUnmanagedTPCount(); _ASSERTE(pAdCount); } else { Thread* pCurThread = GetThread(); AppDomain* pAppDomain = pCurThread->GetDomain(); _ASSERTE(pAppDomain); TPIndex tpindex = pAppDomain->GetTPIndex(); pAdCount = PerAppDomainTPCountList::GetPerAppdomainCount(tpindex); _ASSERTE(pAdCount); } pAdCount->SetAppDomainRequestsActive(); return fShouldSignalEvent; } void ThreadpoolMgr::ClearAppDomainRequestsActive(BOOL UnmanagedTP, LONG id) //-------------------------------------------------------------------------- //This function informs the thread scheduler that the kast request has been //dequeued on an appdomain, or it's the last unmanaged TP request. //Arguments: // UnmanagedTP: Indicates that the request arises from the unmanaged //part of Thread Pool. // id: Indicates the id of the appdomain. The id is needed as this //function can be called (indirectly) from the appdomain unload thread from //unmanaged code to clear per-appdomain state during rude unload. //Assumptions: // This function must be called under a per-appdomain lock or the //correct lock under unmanaged TP queue. // { CONTRACTL { NOTHROW; MODE_ANY; GC_TRIGGERS; } CONTRACTL_END; _ASSERTE(!UsePortableThreadPool()); IPerAppDomainTPCount* pAdCount; if(UnmanagedTP) { pAdCount = PerAppDomainTPCountList::GetUnmanagedTPCount(); _ASSERTE(pAdCount); } else { Thread* pCurThread = GetThread(); AppDomain* pAppDomain = pCurThread->GetDomain(); _ASSERTE(pAppDomain); TPIndex tpindex = pAppDomain->GetTPIndex(); pAdCount = PerAppDomainTPCountList::GetPerAppdomainCount(tpindex); _ASSERTE(pAdCount); } pAdCount->ClearAppDomainRequestsActive(); } // Remove a block from the appropriate recycleList and return. // If recycleList is empty, fall back to new. LPVOID ThreadpoolMgr::GetRecycledMemory(enum MemType memType) { LPVOID result = NULL; CONTRACT(LPVOID) { THROWS; GC_NOTRIGGER; MODE_ANY; INJECT_FAULT(COMPlusThrowOM()); POSTCONDITION(CheckPointer(result)); } CONTRACT_END; if(RecycledLists.IsInitialized()) { RecycledListInfo& list = RecycledLists.GetRecycleMemoryInfo( memType ); result = list.Remove(); } if(result == NULL) { switch (memType) { case MEMTYPE_DelegateInfo: result = new DelegateInfo; break; case MEMTYPE_AsyncCallback: result = new AsyncCallback; break; case MEMTYPE_WorkRequest: result = new WorkRequest; break; default: _ASSERTE(!"Unknown Memtype"); result = NULL; break; } } RETURN result; } // Insert freed block in recycle list. If list is full, return to system heap void ThreadpoolMgr::RecycleMemory(LPVOID mem, enum MemType memType) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; if(RecycledLists.IsInitialized()) { RecycledListInfo& list = RecycledLists.GetRecycleMemoryInfo( memType ); if(list.CanInsert()) { list.Insert( mem ); return; } } switch (memType) { case MEMTYPE_DelegateInfo: delete (DelegateInfo*) mem; break; case MEMTYPE_AsyncCallback: delete (AsyncCallback*) mem; break; case MEMTYPE_WorkRequest: delete (WorkRequest*) mem; break; default: _ASSERTE(!"Unknown Memtype"); } } Thread* ThreadpoolMgr::CreateUnimpersonatedThread(LPTHREAD_START_ROUTINE lpStartAddress, LPVOID lpArgs, BOOL *pIsCLRThread) { STATIC_CONTRACT_NOTHROW; if (GetThreadNULLOk()) { STATIC_CONTRACT_GC_TRIGGERS;} else {DISABLED(STATIC_CONTRACT_GC_NOTRIGGER);} STATIC_CONTRACT_MODE_ANY; /* cannot use contract because of SEH CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END;*/ Thread* pThread = NULL; if (g_fEEStarted) { *pIsCLRThread = TRUE; } else *pIsCLRThread = FALSE; if (*pIsCLRThread) { EX_TRY { pThread = SetupUnstartedThread(); } EX_CATCH { pThread = NULL; } EX_END_CATCH(SwallowAllExceptions); if (pThread == NULL) { return NULL; } } DWORD threadId; BOOL bOK = FALSE; HANDLE threadHandle = NULL; if (*pIsCLRThread) { // CreateNewThread takes care of reverting any impersonation - so dont do anything here. bOK = pThread->CreateNewThread(0, // default stack size lpStartAddress, lpArgs, //arguments W(".NET ThreadPool Worker")); } else { #ifndef TARGET_UNIX HandleHolder token; BOOL bReverted = FALSE; bOK = RevertIfImpersonated(&bReverted, &token); if (bOK != TRUE) return NULL; #endif // !TARGET_UNIX threadHandle = CreateThread(NULL, // security descriptor 0, // default stack size lpStartAddress, lpArgs, CREATE_SUSPENDED, &threadId); SetThreadName(threadHandle, W(".NET ThreadPool Worker")); #ifndef TARGET_UNIX UndoRevert(bReverted, token); #endif // !TARGET_UNIX } if (*pIsCLRThread && !bOK) { pThread->DecExternalCount(FALSE); pThread = NULL; } if (*pIsCLRThread) { return pThread; } else return (Thread*)threadHandle; } BOOL ThreadpoolMgr::CreateWorkerThread() { CONTRACTL { if (GetThreadNULLOk()) { GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);} NOTHROW; MODE_ANY; // We may try to add a worker thread while queuing a work item thru an fcall } CONTRACTL_END; _ASSERTE(!UsePortableThreadPool()); Thread *pThread; BOOL fIsCLRThread; if ((pThread = CreateUnimpersonatedThread(WorkerThreadStart, NULL, &fIsCLRThread)) != NULL) { if (fIsCLRThread) { pThread->ChooseThreadCPUGroupAffinity(); pThread->StartThread(); } else { DWORD status; status = ResumeThread((HANDLE)pThread); _ASSERTE(status != (DWORD) (-1)); CloseHandle((HANDLE)pThread); // we don't need this anymore } return TRUE; } return FALSE; } DWORD WINAPI ThreadpoolMgr::WorkerThreadStart(LPVOID lpArgs) { ClrFlsSetThreadType (ThreadType_Threadpool_Worker); CONTRACTL { THROWS; GC_TRIGGERS; MODE_PREEMPTIVE; } CONTRACTL_END; _ASSERTE_ALL_BUILDS(__FILE__, !UsePortableThreadPool()); Thread *pThread = NULL; DWORD dwSwitchCount = 0; BOOL fThreadInit = FALSE; ThreadCounter::Counts counts, oldCounts, newCounts; bool foundWork = true, wasNotRecalled = true; counts = WorkerCounter.GetCleanCounts(); if (ETW_EVENT_ENABLED(MICROSOFT_WINDOWS_DOTNETRUNTIME_PROVIDER_DOTNET_Context, ThreadPoolWorkerThreadStart)) FireEtwThreadPoolWorkerThreadStart(counts.NumActive, counts.NumRetired, GetClrInstanceId()); #ifdef FEATURE_COMINTEROP BOOL fCoInited = FALSE; // Threadpool threads should be initialized as MTA. If we are unable to do so, // return failure. { fCoInited = SUCCEEDED(::CoInitializeEx(NULL, COINIT_MULTITHREADED)); if (!fCoInited) { goto Exit; } } #endif // FEATURE_COMINTEROP Work: if (!fThreadInit) { if (g_fEEStarted) { pThread = SetupThreadNoThrow(); if (pThread == NULL) { __SwitchToThread(0, ++dwSwitchCount); goto Work; } // converted to CLRThread and added to ThreadStore, pick an group affinity for this thread pThread->ChooseThreadCPUGroupAffinity(); #ifdef FEATURE_COMINTEROP if (pThread->SetApartment(Thread::AS_InMTA) != Thread::AS_InMTA) { // counts volatile read paired with CompareExchangeCounts loop set counts = WorkerCounter.DangerousGetDirtyCounts(); while (true) { newCounts = counts; newCounts.NumActive--; newCounts.NumWorking--; oldCounts = WorkerCounter.CompareExchangeCounts(newCounts, counts); if (oldCounts == counts) break; counts = oldCounts; } goto Exit; } #endif // FEATURE_COMINTEROP pThread->SetBackground(TRUE); fThreadInit = TRUE; } } GCX_PREEMP_NO_DTOR(); _ASSERTE(pThread == NULL || !pThread->PreemptiveGCDisabled()); // make sure there's really work. If not, go back to sleep // counts volatile read paired with CompareExchangeCounts loop set counts = WorkerCounter.DangerousGetDirtyCounts(); while (true) { _ASSERTE(counts.NumActive > 0); _ASSERTE(counts.NumWorking > 0); newCounts = counts; bool retired; if (counts.NumActive > counts.MaxWorking) { newCounts.NumActive--; newCounts.NumRetired++; retired = true; } else { retired = false; if (foundWork) break; } newCounts.NumWorking--; oldCounts = WorkerCounter.CompareExchangeCounts(newCounts, counts); if (oldCounts == counts) { if (retired) goto Retire; else goto WaitForWork; } counts = oldCounts; } if (GCHeapUtilities::IsGCInProgress(TRUE)) { // GC is imminent, so wait until GC is complete before executing next request. // this reduces in-flight objects allocated right before GC, easing the GC's work GCHeapUtilities::WaitForGCCompletion(TRUE); } { ThreadpoolMgr::UpdateLastDequeueTime(); ThreadpoolMgr::ExecuteWorkRequest(&foundWork, &wasNotRecalled); } if (foundWork) { // Reset TLS etc. for next WorkRequest. if (pThread == NULL) pThread = GetThreadNULLOk(); if (pThread) { _ASSERTE(!pThread->IsAbortRequested()); pThread->InternalReset(); } } if (wasNotRecalled) goto Work; Retire: counts = WorkerCounter.GetCleanCounts(); FireEtwThreadPoolWorkerThreadRetirementStart(counts.NumActive, counts.NumRetired, GetClrInstanceId()); // It's possible that some work came in just before we decremented the active thread count, in which // case whoever queued that work may be expecting us to pick it up - so they would not have signalled // the worker semaphore. If there are other threads waiting, they will never be woken up, because // whoever queued the work expects that it's already been picked up. The solution is to signal the semaphore // if there's any work available. if (PerAppDomainTPCountList::AreRequestsPendingInAnyAppDomains()) MaybeAddWorkingWorker(); while (true) { RetryRetire: if (RetiredWorkerSemaphore->Wait(WorkerTimeout)) { foundWork = true; counts = WorkerCounter.GetCleanCounts(); FireEtwThreadPoolWorkerThreadRetirementStop(counts.NumActive, counts.NumRetired, GetClrInstanceId()); goto Work; } if (!IsIoPending()) { // // We're going to exit. There's a nasty race here. We're about to decrement NumRetired, // since we're going to exit. Once we've done that, nobody will expect this thread // to be waiting for RetiredWorkerSemaphore. But between now and then, other threads still // think we're waiting on the semaphore, and they will happily do the following to try to // wake us up: // // 1) Decrement NumRetired // 2) Increment NumActive // 3) Increment NumWorking // 4) Signal RetiredWorkerSemaphore // // We will not receive that signal. If we don't do something special here, // we will decrement NumRetired an extra time, and leave the world thinking there // are fewer retired threads, and more working threads than reality. // // What can we do about this? First, we *need* to decrement NumRetired. If someone did it before us, // it might go negative. This is the easiest way to tell that we've encountered this race. In that case, // we will simply not commit the decrement, swallow the signal that was sent, and proceed as if we // got WAIT_OBJECT_0 in the wait above. // // If we don't hit zero while decrementing NumRetired, we still may have encountered this race. But // if we don't hit zero, then there's another retired thread that will pick up this signal. So it's ok // to exit. // // counts volatile read paired with CompareExchangeCounts loop set counts = WorkerCounter.DangerousGetDirtyCounts(); while (true) { if (counts.NumRetired == 0) goto RetryRetire; newCounts = counts; newCounts.NumRetired--; oldCounts = WorkerCounter.CompareExchangeCounts(newCounts, counts); if (oldCounts == counts) { counts = newCounts; break; } counts = oldCounts; } FireEtwThreadPoolWorkerThreadRetirementStop(counts.NumActive, counts.NumRetired, GetClrInstanceId()); goto Exit; } } WaitForWork: // It's possible that we decided we had no work just before some work came in, // but reduced the worker count *after* the work came in. In this case, we might // miss the notification of available work. So we make a sweep through the ADs here, // and wake up a thread (maybe this one!) if there is work to do. if (PerAppDomainTPCountList::AreRequestsPendingInAnyAppDomains()) { foundWork = true; MaybeAddWorkingWorker(); } if (ETW_EVENT_ENABLED(MICROSOFT_WINDOWS_DOTNETRUNTIME_PROVIDER_DOTNET_Context, ThreadPoolWorkerThreadWait)) FireEtwThreadPoolWorkerThreadWait(counts.NumActive, counts.NumRetired, GetClrInstanceId()); RetryWaitForWork: if (WorkerSemaphore->Wait(WorkerTimeout, WorkerThreadSpinLimit, NumberOfProcessors)) { foundWork = true; goto Work; } if (!IsIoPending()) { // // We timed out, and are about to exit. This puts us in a very similar situation to the // retirement case above - someone may think we're still waiting, and go ahead and: // // 1) Increment NumWorking // 2) Signal WorkerSemaphore // // The solution is much like retirement; when we're decrementing NumActive, we need to make // sure it doesn't drop below NumWorking. If it would, then we need to go back and wait // again. // DangerousNonHostedSpinLockHolder tal(&ThreadAdjustmentLock); // counts volatile read paired with CompareExchangeCounts loop set counts = WorkerCounter.DangerousGetDirtyCounts(); while (true) { if (counts.NumActive == counts.NumWorking) { goto RetryWaitForWork; } newCounts = counts; newCounts.NumActive--; // if we timed out while active, then Hill Climbing needs to be told that we need fewer threads newCounts.MaxWorking = max(MinLimitTotalWorkerThreads, min(newCounts.NumActive, newCounts.MaxWorking)); oldCounts = WorkerCounter.CompareExchangeCounts(newCounts, counts); if (oldCounts == counts) { HillClimbingInstance.ForceChange(newCounts.MaxWorking, ThreadTimedOut); goto Exit; } counts = oldCounts; } } else { goto RetryWaitForWork; } Exit: #ifdef FEATURE_COMINTEROP if (pThread) { pThread->SetApartment(Thread::AS_Unknown); pThread->CoUninitialize(); } // Couninit the worker thread if (fCoInited) { CoUninitialize(); } #endif if (pThread) { pThread->ClearThreadCPUGroupAffinity(); DestroyThread(pThread); } _ASSERTE(!IsIoPending()); counts = WorkerCounter.GetCleanCounts(); if (ETW_EVENT_ENABLED(MICROSOFT_WINDOWS_DOTNETRUNTIME_PROVIDER_DOTNET_Context, ThreadPoolWorkerThreadStop)) FireEtwThreadPoolWorkerThreadStop(counts.NumActive, counts.NumRetired, GetClrInstanceId()); return ERROR_SUCCESS; } // this should only be called by unmanaged thread (i.e. there should be no mgd // caller on the stack) since we are swallowing terminal exceptions DWORD ThreadpoolMgr::SafeWait(CLREvent * ev, DWORD sleepTime, BOOL alertable) { STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_MODE_PREEMPTIVE; /* cannot use contract because of SEH CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_PREEMPTIVE; } CONTRACTL_END;*/ DWORD status = WAIT_TIMEOUT; EX_TRY { status = ev->Wait(sleepTime,FALSE); } EX_CATCH { } EX_END_CATCH(SwallowAllExceptions) return status; } /************************************************************************/ BOOL ThreadpoolMgr::RegisterWaitForSingleObject(PHANDLE phNewWaitObject, HANDLE hWaitObject, WAITORTIMERCALLBACK Callback, PVOID Context, ULONG timeout, DWORD dwFlag ) { CONTRACTL { THROWS; MODE_ANY; if (GetThreadNULLOk()) { GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);} } CONTRACTL_END; _ASSERTE(!UsePortableThreadPool()); EnsureInitialized(); ThreadCB* threadCB; { CrstHolder csh(&WaitThreadsCriticalSection); threadCB = FindWaitThread(); } *phNewWaitObject = NULL; if (threadCB) { WaitInfo* waitInfo = new (nothrow) WaitInfo; if (waitInfo == NULL) return FALSE; waitInfo->waitHandle = hWaitObject; waitInfo->Callback = Callback; waitInfo->Context = Context; waitInfo->timeout = timeout; waitInfo->flag = dwFlag; waitInfo->threadCB = threadCB; waitInfo->state = 0; waitInfo->refCount = 1; // safe to do this since no wait has yet been queued, so no other thread could be modifying this waitInfo->ExternalCompletionEvent = INVALID_HANDLE; waitInfo->ExternalEventSafeHandle = NULL; waitInfo->timer.startTime = GetTickCount(); waitInfo->timer.remainingTime = timeout; *phNewWaitObject = waitInfo; // We fire the "enqueue" ETW event here, to "mark" the thread that had called the API, rather than the // thread that will PostQueuedCompletionStatus (the dedicated WaitThread). // This event correlates with ThreadPoolIODequeue in ThreadpoolMgr::AsyncCallbackCompletion if (ETW_EVENT_ENABLED(MICROSOFT_WINDOWS_DOTNETRUNTIME_PROVIDER_DOTNET_Context, ThreadPoolIOEnqueue)) FireEtwThreadPoolIOEnqueue((LPOVERLAPPED)waitInfo, reinterpret_cast<void*>(Callback), (dwFlag & WAIT_SINGLE_EXECUTION) == 0, GetClrInstanceId()); BOOL status = QueueUserAPC((PAPCFUNC)InsertNewWaitForSelf, threadCB->threadHandle, (size_t) waitInfo); if (status == FALSE) { *phNewWaitObject = NULL; delete waitInfo; } return status; } return FALSE; } // Returns a wait thread that can accomodate another wait request. The // caller is responsible for synchronizing access to the WaitThreadsHead ThreadpoolMgr::ThreadCB* ThreadpoolMgr::FindWaitThread() { CONTRACTL { THROWS; // CreateWaitThread can throw MODE_ANY; GC_TRIGGERS; } CONTRACTL_END; _ASSERTE(!UsePortableThreadPool()); do { for (LIST_ENTRY* Node = (LIST_ENTRY*) WaitThreadsHead.Flink ; Node != &WaitThreadsHead ; Node = (LIST_ENTRY*)Node->Flink) { _ASSERTE(offsetof(WaitThreadInfo,link) == 0); ThreadCB* threadCB = ((WaitThreadInfo*) Node)->threadCB; if (threadCB->NumWaitHandles < MAX_WAITHANDLES) // this test and following ... { InterlockedIncrement(&threadCB->NumWaitHandles); // ... increment are protected by WaitThreadsCriticalSection. // but there might be a concurrent decrement in DeactivateWait // or InsertNewWaitForSelf, hence the interlock return threadCB; } } // if reached here, there are no wait threads available, so need to create a new one if (!CreateWaitThread()) return NULL; // Now loop back } while (TRUE); } BOOL ThreadpoolMgr::CreateWaitThread() { CONTRACTL { THROWS; // CLREvent::CreateAutoEvent can throw OOM GC_TRIGGERS; MODE_ANY; INJECT_FAULT(COMPlusThrowOM()); } CONTRACTL_END; _ASSERTE(!UsePortableThreadPool()); DWORD threadId; if (g_fEEShutDown & ShutDown_Finalize2){ // The process is shutting down. Shutdown thread has ThreadStore lock, // wait thread is blocked on the lock. return FALSE; } NewHolder<WaitThreadInfo> waitThreadInfo(new (nothrow) WaitThreadInfo); if (waitThreadInfo == NULL) return FALSE; NewHolder<ThreadCB> threadCB(new (nothrow) ThreadCB); if (threadCB == NULL) { return FALSE; } threadCB->startEvent.CreateAutoEvent(FALSE); HANDLE threadHandle = Thread::CreateUtilityThread(Thread::StackSize_Small, WaitThreadStart, (LPVOID)threadCB, W(".NET ThreadPool Wait"), CREATE_SUSPENDED, &threadId); if (threadHandle == NULL) { threadCB->startEvent.CloseEvent(); return FALSE; } waitThreadInfo.SuppressRelease(); threadCB.SuppressRelease(); threadCB->threadHandle = threadHandle; threadCB->threadId = threadId; // may be useful for debugging otherwise not used threadCB->NumWaitHandles = 0; threadCB->NumActiveWaits = 0; for (int i=0; i< MAX_WAITHANDLES; i++) { InitializeListHead(&(threadCB->waitPointer[i])); } waitThreadInfo->threadCB = threadCB; DWORD status = ResumeThread(threadHandle); { // We will QueueUserAPC on the newly created thread. // Let us wait until the thread starts running. GCX_PREEMP(); DWORD timeout=500; while (TRUE) { if (g_fEEShutDown & ShutDown_Finalize2){ // The process is shutting down. Shutdown thread has ThreadStore lock, // wait thread is blocked on the lock. return FALSE; } DWORD wait_status = threadCB->startEvent.Wait(timeout, FALSE); if (wait_status == WAIT_OBJECT_0) { break; } } } threadCB->startEvent.CloseEvent(); // check to see if setup succeeded if (threadCB->threadHandle == NULL) return FALSE; InsertHeadList(&WaitThreadsHead,&waitThreadInfo->link); _ASSERTE(status != (DWORD) (-1)); return (status != (DWORD) (-1)); } // Executed as an APC on a WaitThread. Add the wait specified in pArg to the list of objects it is waiting on void ThreadpoolMgr::InsertNewWaitForSelf(WaitInfo* pArgs) { WRAPPER_NO_CONTRACT; _ASSERTE(!UsePortableThreadPool()); WaitInfo* waitInfo = pArgs; // the following is safe since only this thread is allowed to change the state if (!(waitInfo->state & WAIT_DELETE)) { waitInfo->state = (WAIT_REGISTERED | WAIT_ACTIVE); } else { // some thread unregistered the wait DeleteWait(waitInfo); return; } ThreadCB* threadCB = waitInfo->threadCB; _ASSERTE(threadCB->NumActiveWaits <= threadCB->NumWaitHandles); int index = FindWaitIndex(threadCB, waitInfo->waitHandle); _ASSERTE(index >= 0 && index <= threadCB->NumActiveWaits); if (index == threadCB->NumActiveWaits) { threadCB->waitHandle[threadCB->NumActiveWaits] = waitInfo->waitHandle; threadCB->NumActiveWaits++; } else { // this is a duplicate waithandle, so the increment in FindWaitThread // wasn't strictly necessary. This will avoid unnecessary thread creation. InterlockedDecrement(&threadCB->NumWaitHandles); } _ASSERTE(offsetof(WaitInfo, link) == 0); InsertTailList(&(threadCB->waitPointer[index]), (&waitInfo->link)); return; } // returns the index of the entry that matches waitHandle or next free entry if not found int ThreadpoolMgr::FindWaitIndex(const ThreadCB* threadCB, const HANDLE waitHandle) { LIMITED_METHOD_CONTRACT; _ASSERTE(!UsePortableThreadPool()); for (int i=0;i<threadCB->NumActiveWaits; i++) if (threadCB->waitHandle[i] == waitHandle) return i; // else not found return threadCB->NumActiveWaits; } // if no wraparound that the timer is expired if duetime is less than current time // if wraparound occurred, then the timer expired if dueTime was greater than last time or dueTime is less equal to current time #define TimeExpired(last,now,duetime) ((last) <= (now) ? \ ((duetime) <= (now) && (duetime) >= (last)): \ ((duetime) >= (last) || (duetime) <= (now))) #define TimeInterval(end,start) ((end) > (start) ? ((end) - (start)) : ((0xffffffff - (start)) + (end) + 1)) // Returns the minimum of the remaining time to reach a timeout among all the waits DWORD ThreadpoolMgr::MinimumRemainingWait(LIST_ENTRY* waitInfo, unsigned int numWaits) { LIMITED_METHOD_CONTRACT; _ASSERTE(!UsePortableThreadPool()); unsigned int min = (unsigned int) -1; DWORD currentTime = GetTickCount(); for (unsigned i=0; i < numWaits ; i++) { WaitInfo* waitInfoPtr = (WaitInfo*) (waitInfo[i].Flink); PVOID waitInfoHead = &(waitInfo[i]); do { if (waitInfoPtr->timeout != INFINITE) { // compute remaining time DWORD elapsedTime = TimeInterval(currentTime,waitInfoPtr->timer.startTime ); __int64 remainingTime = (__int64) (waitInfoPtr->timeout) - (__int64) elapsedTime; // update remaining time waitInfoPtr->timer.remainingTime = remainingTime > 0 ? (int) remainingTime : 0; // ... and min if (waitInfoPtr->timer.remainingTime < min) min = waitInfoPtr->timer.remainingTime; } waitInfoPtr = (WaitInfo*) (waitInfoPtr->link.Flink); } while ((PVOID) waitInfoPtr != waitInfoHead); } return min; } #ifdef _MSC_VER #ifdef HOST_64BIT #pragma warning (disable : 4716) #else #pragma warning (disable : 4715) #endif #endif #ifdef _PREFAST_ #pragma warning(push) #pragma warning(disable:22008) // "Prefast integer overflow check on (0 + lval) is bogus. Tried local disable without luck, doing whole method." #endif DWORD WINAPI ThreadpoolMgr::WaitThreadStart(LPVOID lpArgs) { CONTRACTL { THROWS; GC_TRIGGERS; MODE_PREEMPTIVE; } CONTRACTL_END; ClrFlsSetThreadType (ThreadType_Wait); _ASSERTE_ALL_BUILDS(__FILE__, !UsePortableThreadPool()); ThreadCB* threadCB = (ThreadCB*) lpArgs; Thread* pThread = SetupThreadNoThrow(); if (pThread == NULL) { _ASSERTE(threadCB->threadHandle != NULL); threadCB->threadHandle = NULL; } threadCB->startEvent.Set(); if (pThread == NULL) { return 0; } { // wait threads never die. (Why?) for (;;) { DWORD status; DWORD timeout = 0; if (threadCB->NumActiveWaits == 0) { #undef SleepEx // <TODO>@TODO Consider doing a sleep for an idle period and terminating the thread if no activity</TODO> //We use SleepEx instead of CLRSLeepEx because CLRSleepEx calls into SQL(or other hosts) in hosted //scenarios. SQL does not deliver APC's, and the waithread wait insertion/deletion logic depends on //APC's being delivered. status = SleepEx(INFINITE,TRUE); #define SleepEx(a,b) Dont_Use_SleepEx(a,b) _ASSERTE(status == WAIT_IO_COMPLETION); } else if (IsWaitThreadAPCPending()) { //Do a sleep if an APC is pending, This was done to solve the corner case where the wait is signaled, //and APC to deregiter the wait never fires. That scenario leads to an infinite loop. This check would //allow the thread to enter alertable wait and thus cause the APC to fire. ResetWaitThreadAPCPending(); //We use SleepEx instead of CLRSLeepEx because CLRSleepEx calls into SQL(or other hosts) in hosted //scenarios. SQL does not deliver APC's, and the waithread wait insertion/deletion logic depends on //APC's being delivered. #undef SleepEx status = SleepEx(0,TRUE); #define SleepEx(a,b) Dont_Use_SleepEx(a,b) continue; } else { // compute minimum timeout. this call also updates the remainingTime field for each wait timeout = MinimumRemainingWait(threadCB->waitPointer,threadCB->NumActiveWaits); status = WaitForMultipleObjectsEx( threadCB->NumActiveWaits, threadCB->waitHandle, FALSE, // waitall timeout, TRUE ); // alertable _ASSERTE( (status == WAIT_TIMEOUT) || (status == WAIT_IO_COMPLETION) || //It could be that there are no waiters at this point, //as the APC to deregister the wait may have run. (status == WAIT_OBJECT_0) || (status >= WAIT_OBJECT_0 && status < (DWORD)(WAIT_OBJECT_0 + threadCB->NumActiveWaits)) || (status == WAIT_FAILED)); //It could be that the last waiter also got deregistered. if (threadCB->NumActiveWaits == 0) { continue; } } if (status == WAIT_IO_COMPLETION) continue; if (status == WAIT_TIMEOUT) { for (int i=0; i< threadCB->NumActiveWaits; i++) { WaitInfo* waitInfo = (WaitInfo*) (threadCB->waitPointer[i]).Flink; PVOID waitInfoHead = &(threadCB->waitPointer[i]); do { _ASSERTE(waitInfo->timer.remainingTime >= timeout); WaitInfo* wTemp = (WaitInfo*) waitInfo->link.Flink; if (waitInfo->timer.remainingTime == timeout) { ProcessWaitCompletion(waitInfo,i,TRUE); } waitInfo = wTemp; } while ((PVOID) waitInfo != waitInfoHead); } } else if (status >= WAIT_OBJECT_0 && status < (DWORD)(WAIT_OBJECT_0 + threadCB->NumActiveWaits)) { unsigned index = status - WAIT_OBJECT_0; WaitInfo* waitInfo = (WaitInfo*) (threadCB->waitPointer[index]).Flink; PVOID waitInfoHead = &(threadCB->waitPointer[index]); BOOL isAutoReset; // Setting to unconditional TRUE is inefficient since we will re-enter the wait and release // the next waiter, but short of using undocumented NT apis is the only solution. // Querying the state with a WaitForSingleObject is not an option as it will reset an // auto reset event if it has been signalled since the previous wait. isAutoReset = TRUE; do { WaitInfo* wTemp = (WaitInfo*) waitInfo->link.Flink; ProcessWaitCompletion(waitInfo,index,FALSE); waitInfo = wTemp; } while (((PVOID) waitInfo != waitInfoHead) && !isAutoReset); // If an app registers a recurring wait for an event that is always signalled (!), // then no apc's will be executed since the thread never enters the alertable state. // This can be fixed by doing the following: // SleepEx(0,TRUE); // However, it causes an unnecessary context switch. It is not worth penalizing well // behaved apps to protect poorly written apps. } else { _ASSERTE(status == WAIT_FAILED); // wait failed: application error // find out which wait handle caused the wait to fail for (int i = 0; i < threadCB->NumActiveWaits; i++) { DWORD subRet = WaitForSingleObject(threadCB->waitHandle[i], 0); if (subRet != WAIT_FAILED) continue; // remove all waits associated with this wait handle WaitInfo* waitInfo = (WaitInfo*) (threadCB->waitPointer[i]).Flink; PVOID waitInfoHead = &(threadCB->waitPointer[i]); do { WaitInfo* temp = (WaitInfo*) waitInfo->link.Flink; DeactivateNthWait(waitInfo,i); // Note, we cannot cleanup here since there is no way to suppress finalization // we will just leak, and rely on the finalizer to clean up the memory //if (InterlockedDecrement(&waitInfo->refCount) == 0) // DeleteWait(waitInfo); waitInfo = temp; } while ((PVOID) waitInfo != waitInfoHead); break; } } } } //This is unreachable...so no return required. } #ifdef _PREFAST_ #pragma warning(pop) #endif #ifdef _MSC_VER #ifdef HOST_64BIT #pragma warning (default : 4716) #else #pragma warning (default : 4715) #endif #endif void ThreadpoolMgr::ProcessWaitCompletion(WaitInfo* waitInfo, unsigned index, BOOL waitTimedOut ) { STATIC_CONTRACT_THROWS; STATIC_CONTRACT_GC_TRIGGERS; STATIC_CONTRACT_MODE_PREEMPTIVE; /* cannot use contract because of SEH CONTRACTL { THROWS; GC_TRIGGERS; MODE_PREEMPTIVE; } CONTRACTL_END;*/ AsyncCallback* asyncCallback = NULL; EX_TRY{ if ( waitInfo->flag & WAIT_SINGLE_EXECUTION) { DeactivateNthWait (waitInfo,index) ; } else { // reactivate wait by resetting timer waitInfo->timer.startTime = GetTickCount(); } asyncCallback = MakeAsyncCallback(); if (asyncCallback) { asyncCallback->wait = waitInfo; asyncCallback->waitTimedOut = waitTimedOut; InterlockedIncrement(&waitInfo->refCount); #ifndef TARGET_UNIX if (FALSE == PostQueuedCompletionStatus((LPOVERLAPPED)asyncCallback, (LPOVERLAPPED_COMPLETION_ROUTINE)WaitIOCompletionCallback)) #else // TARGET_UNIX if (FALSE == QueueUserWorkItem(AsyncCallbackCompletion, asyncCallback, QUEUE_ONLY)) #endif // !TARGET_UNIX ReleaseAsyncCallback(asyncCallback); } } EX_CATCH { if (asyncCallback) ReleaseAsyncCallback(asyncCallback); EX_RETHROW; } EX_END_CATCH(SwallowAllExceptions); } DWORD WINAPI ThreadpoolMgr::AsyncCallbackCompletion(PVOID pArgs) { CONTRACTL { THROWS; MODE_PREEMPTIVE; GC_TRIGGERS; } CONTRACTL_END; Thread * pThread = GetThreadNULLOk(); if (pThread == NULL) { HRESULT hr = ERROR_SUCCESS; ClrFlsSetThreadType(ThreadType_Threadpool_Worker); pThread = SetupThreadNoThrow(&hr); if (pThread == NULL) { return hr; } } { AsyncCallback * asyncCallback = (AsyncCallback*) pArgs; WaitInfo * waitInfo = asyncCallback->wait; AsyncCallbackHolder asyncCBHolder; asyncCBHolder.Assign(asyncCallback); // We fire the "dequeue" ETW event here, before executing the user code, to enable correlation with // the ThreadPoolIOEnqueue fired in ThreadpoolMgr::RegisterWaitForSingleObject if (ETW_EVENT_ENABLED(MICROSOFT_WINDOWS_DOTNETRUNTIME_PROVIDER_DOTNET_Context, ThreadPoolIODequeue)) FireEtwThreadPoolIODequeue(waitInfo, reinterpret_cast<void*>(waitInfo->Callback), GetClrInstanceId()); // the user callback can throw, the host must be prepared to handle it. // SQL is ok, since they have a top-level SEH handler. However, there's // no easy way to verify it ((WAITORTIMERCALLBACKFUNC) waitInfo->Callback) ( waitInfo->Context, asyncCallback->waitTimedOut != FALSE); #ifndef TARGET_UNIX Thread::IncrementIOThreadPoolCompletionCount(pThread); #endif } return ERROR_SUCCESS; } void ThreadpoolMgr::DeactivateWait(WaitInfo* waitInfo) { LIMITED_METHOD_CONTRACT; ThreadCB* threadCB = waitInfo->threadCB; DWORD endIndex = threadCB->NumActiveWaits-1; DWORD index; for (index = 0; index <= endIndex; index++) { LIST_ENTRY* head = &(threadCB->waitPointer[index]); LIST_ENTRY* current = head; do { if (current->Flink == (PVOID) waitInfo) goto FOUND; current = (LIST_ENTRY*) current->Flink; } while (current != head); } FOUND: _ASSERTE(index <= endIndex); DeactivateNthWait(waitInfo, index); } void ThreadpoolMgr::DeactivateNthWait(WaitInfo* waitInfo, DWORD index) { LIMITED_METHOD_CONTRACT; _ASSERTE(!UsePortableThreadPool()); ThreadCB* threadCB = waitInfo->threadCB; if (waitInfo->link.Flink != waitInfo->link.Blink) { RemoveEntryList(&(waitInfo->link)); } else { ULONG EndIndex = threadCB->NumActiveWaits -1; // Move the remaining ActiveWaitArray left. ShiftWaitArray( threadCB, index+1, index,EndIndex - index ) ; // repair the blink and flink of the first and last elements in the list for (unsigned int i = 0; i< EndIndex-index; i++) { WaitInfo* firstWaitInfo = (WaitInfo*) threadCB->waitPointer[index+i].Flink; WaitInfo* lastWaitInfo = (WaitInfo*) threadCB->waitPointer[index+i].Blink; firstWaitInfo->link.Blink = &(threadCB->waitPointer[index+i]); lastWaitInfo->link.Flink = &(threadCB->waitPointer[index+i]); } // initialize the entry just freed InitializeListHead(&(threadCB->waitPointer[EndIndex])); threadCB->NumActiveWaits-- ; InterlockedDecrement(&threadCB->NumWaitHandles); } waitInfo->state &= ~WAIT_ACTIVE ; } void ThreadpoolMgr::DeleteWait(WaitInfo* waitInfo) { CONTRACTL { if (waitInfo->ExternalEventSafeHandle != NULL) { THROWS;} else { NOTHROW; } MODE_ANY; if (GetThreadNULLOk()) {GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);} } CONTRACTL_END; if(waitInfo->Context && (waitInfo->flag & WAIT_FREE_CONTEXT)) { DelegateInfo* pDelegate = (DelegateInfo*) waitInfo->Context; // Since the delegate release destroys a handle, we need to be in // co-operative mode { GCX_COOP(); pDelegate->Release(); } RecycleMemory( pDelegate, MEMTYPE_DelegateInfo ); } if (waitInfo->flag & WAIT_INTERNAL_COMPLETION) { waitInfo->InternalCompletionEvent.Set(); return; // waitInfo will be deleted by the thread that's waiting on this event } else if (waitInfo->ExternalCompletionEvent != INVALID_HANDLE) { SetEvent(waitInfo->ExternalCompletionEvent); } else if (waitInfo->ExternalEventSafeHandle != NULL) { // Release the safe handle and the GC handle holding it ReleaseWaitInfo(waitInfo); } delete waitInfo; } /************************************************************************/ BOOL ThreadpoolMgr::UnregisterWaitEx(HANDLE hWaitObject,HANDLE Event) { CONTRACTL { THROWS; //NOTHROW; if (GetThreadNULLOk()) {GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);} MODE_ANY; } CONTRACTL_END; _ASSERTE(!UsePortableThreadPool()); _ASSERTE(IsInitialized()); // cannot call unregister before first registering const BOOL Blocking = (Event == (HANDLE) -1); WaitInfo* waitInfo = (WaitInfo*) hWaitObject; if (!hWaitObject) { return FALSE; } // we do not allow callbacks to run in the wait thread, hence the assert _ASSERTE(GetCurrentThreadId() != waitInfo->threadCB->threadId); if (Blocking) { waitInfo->InternalCompletionEvent.CreateAutoEvent(FALSE); waitInfo->flag |= WAIT_INTERNAL_COMPLETION; } else { waitInfo->ExternalCompletionEvent = (Event ? Event : INVALID_HANDLE); _ASSERTE((waitInfo->flag & WAIT_INTERNAL_COMPLETION) == 0); // we still want to block until the wait has been deactivated waitInfo->PartialCompletionEvent.CreateAutoEvent(FALSE); } BOOL status = QueueDeregisterWait(waitInfo->threadCB->threadHandle, waitInfo); if (status == 0) { STRESS_LOG1(LF_THREADPOOL, LL_ERROR, "Queue APC failed in UnregisterWaitEx %x", status); if (Blocking) waitInfo->InternalCompletionEvent.CloseEvent(); else waitInfo->PartialCompletionEvent.CloseEvent(); return FALSE; } if (!Blocking) { waitInfo->PartialCompletionEvent.Wait(INFINITE,TRUE); waitInfo->PartialCompletionEvent.CloseEvent(); // we cannot do DeleteWait in DeregisterWait, since the DeleteWait could happen before // we close the event. So, the code has been moved here. if (InterlockedDecrement(&waitInfo->refCount) == 0) { DeleteWait(waitInfo); } } else // i.e. blocking { _ASSERTE(waitInfo->flag & WAIT_INTERNAL_COMPLETION); _ASSERTE(waitInfo->ExternalEventSafeHandle == NULL); waitInfo->InternalCompletionEvent.Wait(INFINITE,TRUE); waitInfo->InternalCompletionEvent.CloseEvent(); delete waitInfo; // if WAIT_INTERNAL_COMPLETION is not set, waitInfo will be deleted in DeleteWait } return TRUE; } void ThreadpoolMgr::DeregisterWait(WaitInfo* pArgs) { WRAPPER_NO_CONTRACT; WaitInfo* waitInfo = pArgs; if ( ! (waitInfo->state & WAIT_REGISTERED) ) { // set state to deleted, so that it does not get registered waitInfo->state |= WAIT_DELETE ; // since the wait has not even been registered, we dont need an interlock to decrease the RefCount waitInfo->refCount--; if (waitInfo->PartialCompletionEvent.IsValid()) { waitInfo->PartialCompletionEvent.Set(); } return; } if (waitInfo->state & WAIT_ACTIVE) { DeactivateWait(waitInfo); } if ( waitInfo->PartialCompletionEvent.IsValid()) { waitInfo->PartialCompletionEvent.Set(); return; // we cannot delete the wait here since the PartialCompletionEvent // may not have been closed yet. so, we return and rely on the waiter of PartialCompletionEvent // to do the close } if (InterlockedDecrement(&waitInfo->refCount) == 0) { DeleteWait(waitInfo); } return; } /* This gets called in a finalizer thread ONLY IF an app does not deregister the the wait. Note that just because the registeredWaitHandle is collected by GC does not mean it is safe to delete the wait. The refcount tells us when it is safe. */ void ThreadpoolMgr::WaitHandleCleanup(HANDLE hWaitObject) { LIMITED_METHOD_CONTRACT; _ASSERTE(!UsePortableThreadPool()); _ASSERTE(IsInitialized()); // cannot call cleanup before first registering WaitInfo* waitInfo = (WaitInfo*) hWaitObject; _ASSERTE(waitInfo->refCount > 0); DWORD result = QueueDeregisterWait(waitInfo->threadCB->threadHandle, waitInfo); if (result == 0) STRESS_LOG1(LF_THREADPOOL, LL_ERROR, "Queue APC failed in WaitHandleCleanup %x", result); } BOOL ThreadpoolMgr::CreateGateThread() { LIMITED_METHOD_CONTRACT; _ASSERTE(!UsePortableThreadPool()); HANDLE threadHandle = Thread::CreateUtilityThread(Thread::StackSize_Small, GateThreadStart, NULL, W(".NET ThreadPool Gate")); if (threadHandle) { CloseHandle(threadHandle); //we don't need this anymore return TRUE; } return FALSE; } /************************************************************************/ BOOL ThreadpoolMgr::BindIoCompletionCallback(HANDLE FileHandle, LPOVERLAPPED_COMPLETION_ROUTINE Function, ULONG Flags, DWORD& errCode) { CONTRACTL { THROWS; // EnsureInitialized can throw if (GetThreadNULLOk()) { GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);} MODE_ANY; } CONTRACTL_END; _ASSERTE(!UsePortableThreadPoolForIO()); #ifndef TARGET_UNIX errCode = S_OK; EnsureInitialized(); _ASSERTE(GlobalCompletionPort != NULL); if (!InitCompletionPortThreadpool) InitCompletionPortThreadpool = TRUE; GrowCompletionPortThreadpoolIfNeeded(); HANDLE h = CreateIoCompletionPort(FileHandle, GlobalCompletionPort, (ULONG_PTR) Function, NumberOfProcessors); if (h == NULL) { errCode = GetLastError(); return FALSE; } _ASSERTE(h == GlobalCompletionPort); return TRUE; #else // TARGET_UNIX SetLastError(ERROR_CALL_NOT_IMPLEMENTED); return FALSE; #endif // !TARGET_UNIX } #ifndef TARGET_UNIX BOOL ThreadpoolMgr::CreateCompletionPortThread(LPVOID lpArgs) { CONTRACTL { NOTHROW; if (GetThreadNULLOk()) { GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);} MODE_ANY; } CONTRACTL_END; _ASSERTE(!UsePortableThreadPoolForIO()); Thread *pThread; BOOL fIsCLRThread; if ((pThread = CreateUnimpersonatedThread(CompletionPortThreadStart, lpArgs, &fIsCLRThread)) != NULL) { LastCPThreadCreation = GetTickCount(); // record this for use by logic to spawn additional threads if (fIsCLRThread) { pThread->ChooseThreadCPUGroupAffinity(); pThread->StartThread(); } else { DWORD status; status = ResumeThread((HANDLE)pThread); _ASSERTE(status != (DWORD) (-1)); CloseHandle((HANDLE)pThread); // we don't need this anymore } ThreadCounter::Counts counts = CPThreadCounter.GetCleanCounts(); FireEtwIOThreadCreate_V1(counts.NumActive + counts.NumRetired, counts.NumRetired, GetClrInstanceId()); return TRUE; } return FALSE; } DWORD WINAPI ThreadpoolMgr::CompletionPortThreadStart(LPVOID lpArgs) { ClrFlsSetThreadType (ThreadType_Threadpool_IOCompletion); CONTRACTL { THROWS; if (GetThreadNULLOk()) { MODE_PREEMPTIVE;} else { DISABLED(MODE_ANY);} if (GetThreadNULLOk()) { GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);} } CONTRACTL_END; _ASSERTE_ALL_BUILDS(__FILE__, !UsePortableThreadPoolForIO()); DWORD numBytes=0; size_t key=0; LPOVERLAPPED pOverlapped = NULL; DWORD errorCode; PIOCompletionContext context; BOOL fIsCompletionContext; const DWORD CP_THREAD_WAIT = 15000; /* milliseconds */ _ASSERTE(GlobalCompletionPort != NULL); BOOL fThreadInit = FALSE; Thread *pThread = NULL; DWORD cpThreadWait = 0; if (g_fEEStarted) { pThread = SetupThreadNoThrow(); if (pThread == NULL) { return 0; } // converted to CLRThread and added to ThreadStore, pick an group affinity for this thread pThread->ChooseThreadCPUGroupAffinity(); fThreadInit = TRUE; } #ifdef FEATURE_COMINTEROP // Threadpool threads should be initialized as MTA. If we are unable to do so, // return failure. BOOL fCoInited = FALSE; { fCoInited = SUCCEEDED(::CoInitializeEx(NULL, COINIT_MULTITHREADED)); if (!fCoInited) { goto Exit; } } if (pThread && pThread->SetApartment(Thread::AS_InMTA) != Thread::AS_InMTA) { // @todo: should we log the failure goto Exit; } #endif // FEATURE_COMINTEROP ThreadCounter::Counts oldCounts; ThreadCounter::Counts newCounts; cpThreadWait = CP_THREAD_WAIT; for (;; ) { Top: if (!fThreadInit) { if (g_fEEStarted) { pThread = SetupThreadNoThrow(); if (pThread == NULL) { break; } // converted to CLRThread and added to ThreadStore, pick an group affinity for this thread pThread->ChooseThreadCPUGroupAffinity(); #ifdef FEATURE_COMINTEROP if (pThread->SetApartment(Thread::AS_InMTA) != Thread::AS_InMTA) { // @todo: should we log the failure goto Exit; } #endif // FEATURE_COMINTEROP fThreadInit = TRUE; } } GCX_PREEMP_NO_DTOR(); // // We're about to wait on the IOCP; mark ourselves as no longer "working." // while (true) { ThreadCounter::Counts oldCounts = CPThreadCounter.DangerousGetDirtyCounts(); ThreadCounter::Counts newCounts = oldCounts; newCounts.NumWorking--; // // If we've only got one thread left, it won't be allowed to exit, because we need to keep // one thread listening for completions. So there's no point in having a timeout; it will // only use power unnecessarily. // cpThreadWait = (newCounts.NumActive == 1) ? INFINITE : CP_THREAD_WAIT; if (oldCounts == CPThreadCounter.CompareExchangeCounts(newCounts, oldCounts)) break; } errorCode = S_OK; if (lpArgs == NULL) { CONTRACT_VIOLATION(ThrowsViolation); context = NULL; fIsCompletionContext = FALSE; if (pThread == NULL) { pThread = GetThreadNULLOk(); } if (pThread) { context = (PIOCompletionContext) pThread->GetIOCompletionContext(); if (context->lpOverlapped != NULL) { errorCode = context->ErrorCode; numBytes = context->numBytesTransferred; pOverlapped = context->lpOverlapped; key = context->key; context->lpOverlapped = NULL; fIsCompletionContext = TRUE; } } if((context == NULL) || (!fIsCompletionContext)) { _ASSERTE (context == NULL || context->lpOverlapped == NULL); BOOL status = GetQueuedCompletionStatus( GlobalCompletionPort, &numBytes, (PULONG_PTR)&key, &pOverlapped, cpThreadWait ); if (status == 0) errorCode = GetLastError(); } } else { QueuedStatus *CompletionStatus = (QueuedStatus*)lpArgs; numBytes = CompletionStatus->numBytes; key = (size_t)CompletionStatus->key; pOverlapped = CompletionStatus->pOverlapped; errorCode = CompletionStatus->errorCode; delete CompletionStatus; lpArgs = NULL; // one-time deal for initial CP packet } // We fire IODequeue events whether the IO completion was retrieved in the above call to // GetQueuedCompletionStatus or during an earlier call (e.g. in GateThreadStart, and passed here in lpArgs, // or in CompletionPortDispatchWorkWithinAppDomain, and passed here through StoreOverlappedInfoInThread) // For the purposes of activity correlation we only fire ETW events here, if needed OR if not fired at a higher // abstraction level (e.g. ThreadpoolMgr::RegisterWaitForSingleObject) // Note: we still fire the event for managed async IO, despite the fact we don't have a paired IOEnqueue event // for this case. We do this to "mark" the end of the previous workitem. When we provide full support at the higher // abstraction level for managed IO we can remove the IODequeues fired here if (ETW_EVENT_ENABLED(MICROSOFT_WINDOWS_DOTNETRUNTIME_PROVIDER_DOTNET_Context, ThreadPoolIODequeue) && !AreEtwIOQueueEventsSpeciallyHandled((LPOVERLAPPED_COMPLETION_ROUTINE)key) && pOverlapped != NULL) { FireEtwThreadPoolIODequeue(pOverlapped, OverlappedDataObject::GetOverlappedForTracing(pOverlapped), GetClrInstanceId()); } bool enterRetirement; while (true) { // // When we reach this point, this thread is "active" but not "working." Depending on the result of the call to GetQueuedCompletionStatus, // and the state of the rest of the IOCP threads, we need to figure out whether to de-activate (exit) this thread, retire this thread, // or transition to "working." // // counts volatile read paired with CompareExchangeCounts loop set oldCounts = CPThreadCounter.DangerousGetDirtyCounts(); newCounts = oldCounts; enterRetirement = false; if (errorCode == WAIT_TIMEOUT) { // // We timed out, and are going to try to exit or retire. // newCounts.NumActive--; // // We need at least one free thread, or we have no way of knowing if completions are being queued. // if (newCounts.NumWorking == newCounts.NumActive) { newCounts = oldCounts; newCounts.NumWorking++; //not really working, but we'll decremented it at the top if (oldCounts == CPThreadCounter.CompareExchangeCounts(newCounts, oldCounts)) goto Top; else continue; } // // We can't exit a thread that has pending I/O - we'll "retire" it instead. // if (IsIoPending()) { enterRetirement = true; newCounts.NumRetired++; } } else { // // We have work to do // newCounts.NumWorking++; } if (oldCounts == CPThreadCounter.CompareExchangeCounts(newCounts, oldCounts)) break; } if (errorCode == WAIT_TIMEOUT) { if (!enterRetirement) { goto Exit; } else { // now in "retired mode" waiting for pending io to complete FireEtwIOThreadRetire_V1(newCounts.NumActive + newCounts.NumRetired, newCounts.NumRetired, GetClrInstanceId()); for (;;) { DWORD status = SafeWait(RetiredCPWakeupEvent,CP_THREAD_PENDINGIO_WAIT,FALSE); _ASSERTE(status == WAIT_TIMEOUT || status == WAIT_OBJECT_0); if (status == WAIT_TIMEOUT) { if (IsIoPending()) { continue; } else { // We can now exit; decrement the retired count. while (true) { // counts volatile read paired with CompareExchangeCounts loop set oldCounts = CPThreadCounter.DangerousGetDirtyCounts(); newCounts = oldCounts; newCounts.NumRetired--; if (oldCounts == CPThreadCounter.CompareExchangeCounts(newCounts, oldCounts)) break; } goto Exit; } } else { // put back into rotation -- we need a thread while (true) { // counts volatile read paired with CompareExchangeCounts loop set oldCounts = CPThreadCounter.DangerousGetDirtyCounts(); newCounts = oldCounts; newCounts.NumRetired--; newCounts.NumActive++; newCounts.NumWorking++; //we're not really working, but we'll decrement this before waiting for work. if (oldCounts == CPThreadCounter.CompareExchangeCounts(newCounts, oldCounts)) break; } FireEtwIOThreadUnretire_V1(newCounts.NumActive + newCounts.NumRetired, newCounts.NumRetired, GetClrInstanceId()); goto Top; } } } } // we should not reach this point unless we have work to do _ASSERTE(errorCode != WAIT_TIMEOUT && !enterRetirement); // if we have no more free threads, start the gate thread if (newCounts.NumWorking >= newCounts.NumActive) EnsureGateThreadRunning(); // We can not assert here. If stdin/stdout/stderr of child process are redirected based on // async io, GetQueuedCompletionStatus returns when child process operates on its stdin/stdout/stderr. // Parent process does not issue any ReadFile/WriteFile, and hence pOverlapped is going to be NULL. //_ASSERTE(pOverlapped != NULL); if (pOverlapped != NULL) { _ASSERTE(key != 0); // should be a valid function address if (key != 0) { if (GCHeapUtilities::IsGCInProgress(TRUE)) { //Indicate that this thread is free, and waiting on GC, not doing any user work. //This helps in threads not getting injected when some threads have woken up from the //GC event, and some have not. while (true) { // counts volatile read paired with CompareExchangeCounts loop set oldCounts = CPThreadCounter.DangerousGetDirtyCounts(); newCounts = oldCounts; newCounts.NumWorking--; if (oldCounts == CPThreadCounter.CompareExchangeCounts(newCounts, oldCounts)) break; } // GC is imminent, so wait until GC is complete before executing next request. // this reduces in-flight objects allocated right before GC, easing the GC's work GCHeapUtilities::WaitForGCCompletion(TRUE); while (true) { // counts volatile read paired with CompareExchangeCounts loop set oldCounts = CPThreadCounter.DangerousGetDirtyCounts(); newCounts = oldCounts; newCounts.NumWorking++; if (oldCounts == CPThreadCounter.CompareExchangeCounts(newCounts, oldCounts)) break; } if (newCounts.NumWorking >= newCounts.NumActive) EnsureGateThreadRunning(); } else { GrowCompletionPortThreadpoolIfNeeded(); } { CONTRACT_VIOLATION(ThrowsViolation); ((LPOVERLAPPED_COMPLETION_ROUTINE) key)(errorCode, numBytes, pOverlapped); } Thread::IncrementIOThreadPoolCompletionCount(pThread); if (pThread == NULL) { pThread = GetThreadNULLOk(); } if (pThread) { _ASSERTE(!pThread->IsAbortRequested()); pThread->InternalReset(); } } else { // Application bug - can't do much, just ignore it } } } // for (;;) Exit: oldCounts = CPThreadCounter.GetCleanCounts(); // we should never destroy or retire all IOCP threads, because then we won't have any threads to notice incoming completions. _ASSERTE(oldCounts.NumActive > 0); FireEtwIOThreadTerminate_V1(oldCounts.NumActive + oldCounts.NumRetired, oldCounts.NumRetired, GetClrInstanceId()); #ifdef FEATURE_COMINTEROP if (pThread) { pThread->SetApartment(Thread::AS_Unknown); pThread->CoUninitialize(); } // Couninit the worker thread if (fCoInited) { CoUninitialize(); } #endif if (pThread) { pThread->ClearThreadCPUGroupAffinity(); DestroyThread(pThread); } return 0; } LPOVERLAPPED ThreadpoolMgr::CompletionPortDispatchWorkWithinAppDomain( Thread* pThread, DWORD* pErrorCode, DWORD* pNumBytes, size_t* pKey) // //This function is called just after dispatching the previous BindIO callback //to Managed code. This is a perf optimization to do a quick call to //GetQueuedCompletionStatus with a timeout of 0 ms. If there is work in the //same appdomain, dispatch it back immediately. If not stick it in a well known //place, and reenter the target domain. The timeout of zero is chosen so as to //not delay appdomain unloads. // { STATIC_CONTRACT_THROWS; STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_MODE_ANY; LPOVERLAPPED lpOverlapped=NULL; BOOL status=FALSE; OVERLAPPEDDATAREF overlapped=NULL; BOOL ManagedCallback=FALSE; *pErrorCode = S_OK; //Very Very Important! //Do not change the timeout for GetQueuedCompletionStatus to a non-zero value. //Selecting a non-zero value can cause the thread to block, and lead to expensive context switches. //In real life scenarios, we have noticed a packet to be not available immediately, but very shortly //(after few 100's of instructions), and falling back to the VM is good in that case as compared to //taking a context switch. Changing the timeout to non-zero can lead to perf degrades, that are very //hard to diagnose. status = ::GetQueuedCompletionStatus( GlobalCompletionPort, pNumBytes, (PULONG_PTR)pKey, &lpOverlapped, 0); DWORD lastError = GetLastError(); if (status == 0) { if (lpOverlapped != NULL) { *pErrorCode = lastError; } else { return NULL; } } if (((LPOVERLAPPED_COMPLETION_ROUTINE) *pKey) != BindIoCompletionCallbackStub) { //_ASSERTE(FALSE); } else { ManagedCallback = TRUE; overlapped = ObjectToOVERLAPPEDDATAREF(OverlappedDataObject::GetOverlapped(lpOverlapped)); } if (ManagedCallback) { _ASSERTE(*pKey != 0); // should be a valid function address if (*pKey ==0) { //Application Bug. return NULL; } } else { //Just retruned back from managed code, a Thread structure should exist. _ASSERTE (pThread); //Oops, this is an overlapped fom a different appdomain. STick it in //the thread. We will process it later. StoreOverlappedInfoInThread(pThread, *pErrorCode, *pNumBytes, *pKey, lpOverlapped); lpOverlapped = NULL; } #ifndef DACCESS_COMPILE return lpOverlapped; #endif } void ThreadpoolMgr::StoreOverlappedInfoInThread(Thread* pThread, DWORD dwErrorCode, DWORD dwNumBytes, size_t key, LPOVERLAPPED lpOverlapped) { STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_MODE_ANY; _ASSERTE(pThread); PIOCompletionContext context; context = (PIOCompletionContext) pThread->GetIOCompletionContext(); _ASSERTE(context); context->ErrorCode = dwErrorCode; context->numBytesTransferred = dwNumBytes; context->lpOverlapped = lpOverlapped; context->key = key; } BOOL ThreadpoolMgr::ShouldGrowCompletionPortThreadpool(ThreadCounter::Counts counts) { CONTRACTL { GC_NOTRIGGER; NOTHROW; MODE_ANY; } CONTRACTL_END; _ASSERTE(!UsePortableThreadPoolForIO()); if (counts.NumWorking >= counts.NumActive && (counts.NumActive == 0 || !GCHeapUtilities::IsGCInProgress(TRUE)) ) { // adjust limit if needed if (counts.NumRetired == 0) { if (counts.NumActive + counts.NumRetired < MaxLimitTotalCPThreads && (counts.NumActive < MinLimitTotalCPThreads || cpuUtilization < CpuUtilizationLow)) { // add one more check to make sure that we haven't fired off a new // thread since the last time time we checked the cpu utilization. // However, don't bother if we haven't reached the MinLimit (2*number of cpus) if ((counts.NumActive < MinLimitTotalCPThreads) || SufficientDelaySinceLastSample(LastCPThreadCreation,counts.NumActive)) { return TRUE; } } } if (counts.NumRetired > 0) return TRUE; } return FALSE; } void ThreadpoolMgr::GrowCompletionPortThreadpoolIfNeeded() { CONTRACTL { if (GetThreadNULLOk()) { GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);} NOTHROW; MODE_ANY; } CONTRACTL_END; _ASSERTE(!UsePortableThreadPoolForIO()); ThreadCounter::Counts oldCounts, newCounts; while (true) { oldCounts = CPThreadCounter.GetCleanCounts(); newCounts = oldCounts; if(!ShouldGrowCompletionPortThreadpool(oldCounts)) { break; } else { if (oldCounts.NumRetired > 0) { // wakeup retired thread instead RetiredCPWakeupEvent->Set(); return; } else { // create a new thread. New IOCP threads start as "active" and "working" newCounts.NumActive++; newCounts.NumWorking++; if (oldCounts == CPThreadCounter.CompareExchangeCounts(newCounts, oldCounts)) { if (!CreateCompletionPortThread(NULL)) { // if thread creation failed, we have to adjust the counts back down. while (true) { // counts volatile read paired with CompareExchangeCounts loop set oldCounts = CPThreadCounter.DangerousGetDirtyCounts(); newCounts = oldCounts; newCounts.NumActive--; newCounts.NumWorking--; if (oldCounts == CPThreadCounter.CompareExchangeCounts(newCounts, oldCounts)) break; } } return; } } } } } #endif // !TARGET_UNIX // Returns true if there is pending io on the thread. BOOL ThreadpoolMgr::IsIoPending() { CONTRACTL { NOTHROW; MODE_ANY; GC_NOTRIGGER; } CONTRACTL_END; #ifndef TARGET_UNIX int Status; ULONG IsIoPending; if (g_pufnNtQueryInformationThread) { Status =(int) (*g_pufnNtQueryInformationThread)(GetCurrentThread(), ThreadIsIoPending, &IsIoPending, sizeof(IsIoPending), NULL); if ((Status < 0) || IsIoPending) return TRUE; else return FALSE; } return TRUE; #else return FALSE; #endif // !TARGET_UNIX } #ifndef TARGET_UNIX #ifdef HOST_64BIT #pragma warning (disable : 4716) #else #pragma warning (disable : 4715) #endif int ThreadpoolMgr::GetCPUBusyTime_NT(PROCESS_CPU_INFORMATION* pOldInfo) { LIMITED_METHOD_CONTRACT; PROCESS_CPU_INFORMATION newUsage; newUsage.idleTime.QuadPart = 0; newUsage.kernelTime.QuadPart = 0; newUsage.userTime.QuadPart = 0; if (CPUGroupInfo::CanEnableThreadUseAllCpuGroups()) { #if !defined(FEATURE_REDHAWK) && !defined(TARGET_UNIX) FILETIME newIdleTime, newKernelTime, newUserTime; CPUGroupInfo::GetSystemTimes(&newIdleTime, &newKernelTime, &newUserTime); newUsage.idleTime.u.LowPart = newIdleTime.dwLowDateTime; newUsage.idleTime.u.HighPart = newIdleTime.dwHighDateTime; newUsage.kernelTime.u.LowPart = newKernelTime.dwLowDateTime; newUsage.kernelTime.u.HighPart = newKernelTime.dwHighDateTime; newUsage.userTime.u.LowPart = newUserTime.dwLowDateTime; newUsage.userTime.u.HighPart = newUserTime.dwHighDateTime; #endif } else { (*g_pufnNtQuerySystemInformation)(SystemProcessorPerformanceInformation, pOldInfo->usageBuffer, pOldInfo->usageBufferSize, NULL); SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION* pInfoArray = pOldInfo->usageBuffer; DWORD_PTR pmask = pOldInfo->affinityMask; int proc_no = 0; while (pmask) { if (pmask & 1) { //should be good: 1CPU 28823 years, 256CPUs 100+years newUsage.idleTime.QuadPart += pInfoArray[proc_no].IdleTime.QuadPart; newUsage.kernelTime.QuadPart += pInfoArray[proc_no].KernelTime.QuadPart; newUsage.userTime.QuadPart += pInfoArray[proc_no].UserTime.QuadPart; } pmask >>=1; proc_no++; } } __int64 cpuTotalTime, cpuBusyTime; cpuTotalTime = (newUsage.userTime.QuadPart - pOldInfo->userTime.QuadPart) + (newUsage.kernelTime.QuadPart - pOldInfo->kernelTime.QuadPart); cpuBusyTime = cpuTotalTime - (newUsage.idleTime.QuadPart - pOldInfo->idleTime.QuadPart); // Preserve reading pOldInfo->idleTime = newUsage.idleTime; pOldInfo->kernelTime = newUsage.kernelTime; pOldInfo->userTime = newUsage.userTime; __int64 reading = 0; if (cpuTotalTime > 0) reading = ((cpuBusyTime * 100) / cpuTotalTime); _ASSERTE(FitsIn<int>(reading)); return (int)reading; } #else // !TARGET_UNIX int ThreadpoolMgr::GetCPUBusyTime_NT(PAL_IOCP_CPU_INFORMATION* pOldInfo) { return PAL_GetCPUBusyTime(pOldInfo); } #endif // !TARGET_UNIX // // A timer that ticks every GATE_THREAD_DELAY milliseconds. // On platforms that support it, we use a coalescable waitable timer object. // For other platforms, we use Sleep, via __SwitchToThread. // class GateThreadTimer { #ifndef TARGET_UNIX HANDLE m_hTimer; public: GateThreadTimer() : m_hTimer(NULL) { CONTRACTL { NOTHROW; MODE_PREEMPTIVE; } CONTRACTL_END; if (g_pufnCreateWaitableTimerEx && g_pufnSetWaitableTimerEx) { m_hTimer = g_pufnCreateWaitableTimerEx(NULL, NULL, 0, TIMER_ALL_ACCESS); if (m_hTimer) { // // Set the timer to fire GATE_THREAD_DELAY milliseconds from now, then every GATE_THREAD_DELAY milliseconds thereafter. // We also set the tolerance to GET_THREAD_DELAY_TOLERANCE, allowing the OS to coalesce this timer. // LARGE_INTEGER dueTime; dueTime.QuadPart = MILLI_TO_100NANO(-(LONGLONG)GATE_THREAD_DELAY); //negative value indicates relative time if (!g_pufnSetWaitableTimerEx(m_hTimer, &dueTime, GATE_THREAD_DELAY, NULL, NULL, NULL, GATE_THREAD_DELAY_TOLERANCE)) { CloseHandle(m_hTimer); m_hTimer = NULL; } } } } ~GateThreadTimer() { CONTRACTL { NOTHROW; MODE_PREEMPTIVE; } CONTRACTL_END; if (m_hTimer) { CloseHandle(m_hTimer); m_hTimer = NULL; } } #endif // !TARGET_UNIX public: void Wait() { CONTRACTL { NOTHROW; MODE_PREEMPTIVE; } CONTRACTL_END; #ifndef TARGET_UNIX if (m_hTimer) WaitForSingleObject(m_hTimer, INFINITE); else #endif // !TARGET_UNIX __SwitchToThread(GATE_THREAD_DELAY, CALLER_LIMITS_SPINNING); } }; DWORD WINAPI ThreadpoolMgr::GateThreadStart(LPVOID lpArgs) { ClrFlsSetThreadType (ThreadType_Gate); CONTRACTL { NOTHROW; GC_TRIGGERS; MODE_PREEMPTIVE; } CONTRACTL_END; _ASSERTE(!UsePortableThreadPool()); _ASSERTE(GateThreadStatus == GATE_THREAD_STATUS_REQUESTED); GateThreadTimer timer; // TODO: do we need to do this? timer.Wait(); // delay getting initial CPU reading #ifndef TARGET_UNIX PROCESS_CPU_INFORMATION prevCPUInfo; if (!g_pufnNtQuerySystemInformation) { _ASSERT(!"NtQuerySystemInformation API not available!"); return 0; } #ifndef TARGET_UNIX //GateThread can start before EESetup, so ensure CPU group information is initialized; CPUGroupInfo::EnsureInitialized(); #endif // !TARGET_UNIX // initialize CPU usage information structure; prevCPUInfo.idleTime.QuadPart = 0; prevCPUInfo.kernelTime.QuadPart = 0; prevCPUInfo.userTime.QuadPart = 0; PREFIX_ASSUME(NumberOfProcessors < 65536); prevCPUInfo.numberOfProcessors = NumberOfProcessors; /* In following cases, affinity mask can be zero * 1. hosted, the hosted process already uses multiple cpu groups. * thus, during CLR initialization, GetCurrentProcessCpuCount() returns 64, and GC threads * are created to fill up the initial CPU group. ==> use g_SystemInfo.dwNumberOfProcessors * 2. GCCpuGroups=1, CLR creates GC threads for all processors in all CPU groups * thus, the threadpool thread would use a whole CPU group (if Thread_UseAllCpuGroups is not set). * ==> use g_SystemInfo.dwNumberOfProcessors. * 3. !defined(TARGET_UNIX), GetCurrentProcessCpuCount() * returns g_SystemInfo.dwNumberOfProcessors ==> use g_SystemInfo.dwNumberOfProcessors; * Other cases: * 1. Normal case: the mask is all or a subset of all processors in a CPU group; * 2. GCCpuGroups=1 && Thread_UseAllCpuGroups = 1, the mask is not used */ prevCPUInfo.affinityMask = GetCurrentProcessCpuMask(); if (prevCPUInfo.affinityMask == 0) { // create a mask that has g_SystemInfo.dwNumberOfProcessors; DWORD_PTR mask = 0, maskpos = 1; for (unsigned int i=0; i < g_SystemInfo.dwNumberOfProcessors; i++) { mask |= maskpos; maskpos <<= 1; } prevCPUInfo.affinityMask = mask; } // in some cases GetCurrentProcessCpuCount() returns a number larger than // g_SystemInfo.dwNumberOfProcessor when there are CPU groups, use the larger // one to create buffer. This buffer must be cleared with 0's to get correct // CPU usage statistics int elementsNeeded = NumberOfProcessors > g_SystemInfo.dwNumberOfProcessors ? NumberOfProcessors : g_SystemInfo.dwNumberOfProcessors; // // When CLR threads are not using all groups, GetCPUBusyTime_NT will read element X from // the "prevCPUInfo.usageBuffer" array if and only if "prevCPUInfo.affinityMask" contains a // set bit in bit position X. This implies that GetCPUBusyTime_NT would read past the end // of the "usageBuffer" array if the index of the highest set bit in "affinityMask" was // ever larger than the index of the last array element. // // If necessary, expand "elementsNeeded" to ensure that the index of the last array element // is always at least as large as the index of the highest set bit in the "affinityMask". // // This expansion is necessary in any case where the mask returned by GetCurrentProcessCpuMask // (which is just a wrapper around the Win32 GetProcessAffinityMask API) contains set bits // at indices greater than or equal to the larger of the basline CPU count values (i.e., // ThreadpoolMgr::NumberOfProcessors and g_SystemInfo.dwNumberOfProcessors) that were // captured earlier on (during ThreadpoolMgr::Initialize and during EEStartupHelper, // respectively). Note that in the relevant scenario (i.e., when CLR threads are not using // all groups) the mask and CPU counts are all collected via "group-unaware" APIs and are // all "group-local" values as a result. // // Expansion is necessary in at least the following cases: // // - If the baseline CPU counts were captured while running in groups that contain fewer // CPUs (in a multi-group system with heterogenous CPU counts across groups), but this code // is now running in a group that contains a larger number of CPUs. // // - If CPUs were hot-added to the system and then added to the current process affinity // mask at some point after the baseline CPU counts were captured. // if (!CPUGroupInfo::CanEnableThreadUseAllCpuGroups()) { int elementsNeededToCoverMask = 0; DWORD_PTR remainingMask = prevCPUInfo.affinityMask; while (remainingMask != 0) { elementsNeededToCoverMask++; remainingMask >>= 1; } if (elementsNeeded < elementsNeededToCoverMask) { elementsNeeded = elementsNeededToCoverMask; } } if (!ClrSafeInt<int>::multiply(elementsNeeded, sizeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION), prevCPUInfo.usageBufferSize)) return 0; prevCPUInfo.usageBuffer = (SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION *)alloca(prevCPUInfo.usageBufferSize); if (prevCPUInfo.usageBuffer == NULL) return 0; memset((void *)prevCPUInfo.usageBuffer, 0, prevCPUInfo.usageBufferSize); //must clear it with 0s GetCPUBusyTime_NT(&prevCPUInfo); #else // !TARGET_UNIX PAL_IOCP_CPU_INFORMATION prevCPUInfo; memset(&prevCPUInfo, 0, sizeof(prevCPUInfo)); GetCPUBusyTime_NT(&prevCPUInfo); // ignore return value the first time #endif // !TARGET_UNIX BOOL IgnoreNextSample = FALSE; do { timer.Wait(); if(CLRConfig::GetConfigValue(CLRConfig::INTERNAL_ThreadPool_EnableWorkerTracking)) FireEtwThreadPoolWorkingThreadCount(TakeMaxWorkingThreadCount(), GetClrInstanceId()); #ifdef DEBUGGING_SUPPORTED // if we are stopped at a debug breakpoint, go back to sleep if (CORDebuggerAttached() && g_pDebugInterface->IsStopped()) continue; #endif // DEBUGGING_SUPPORTED if (!GCHeapUtilities::IsGCInProgress(FALSE) ) { if (IgnoreNextSample) { IgnoreNextSample = FALSE; int cpuUtilizationTemp = GetCPUBusyTime_NT(&prevCPUInfo); // updates prevCPUInfo as side effect // don't artificially drive down average if cpu is high if (cpuUtilizationTemp <= CpuUtilizationLow) cpuUtilization = CpuUtilizationLow + 1; else cpuUtilization = cpuUtilizationTemp; } else { cpuUtilization = GetCPUBusyTime_NT(&prevCPUInfo); // updates prevCPUInfo as side effect } } else { int cpuUtilizationTemp = GetCPUBusyTime_NT(&prevCPUInfo); // updates prevCPUInfo as side effect // don't artificially drive down average if cpu is high if (cpuUtilizationTemp <= CpuUtilizationLow) cpuUtilization = CpuUtilizationLow + 1; else cpuUtilization = cpuUtilizationTemp; IgnoreNextSample = TRUE; } PerformGateActivities(cpuUtilization); } while (ShouldGateThreadKeepRunning()); return 0; } void ThreadpoolMgr::PerformGateActivities(int cpuUtilization) { CONTRACTL { NOTHROW; GC_TRIGGERS; MODE_PREEMPTIVE; } CONTRACTL_END; _ASSERTE(!UsePortableThreadPoolForIO()); ThreadpoolMgr::cpuUtilization = cpuUtilization; #ifndef TARGET_UNIX // don't mess with CP thread pool settings if not initialized yet if (InitCompletionPortThreadpool) { ThreadCounter::Counts oldCounts, newCounts; oldCounts = CPThreadCounter.GetCleanCounts(); if (oldCounts.NumActive == oldCounts.NumWorking && oldCounts.NumRetired == 0 && oldCounts.NumActive < MaxLimitTotalCPThreads && !GCHeapUtilities::IsGCInProgress(TRUE)) { BOOL status; DWORD numBytes; size_t key; LPOVERLAPPED pOverlapped; DWORD errorCode; errorCode = S_OK; status = GetQueuedCompletionStatus( GlobalCompletionPort, &numBytes, (PULONG_PTR)&key, &pOverlapped, 0 // immediate return ); if (status == 0) { errorCode = GetLastError(); } if (errorCode != WAIT_TIMEOUT) { QueuedStatus *CompletionStatus = NULL; // loop, retrying until memory is allocated. Under such conditions the gate // thread is not useful anyway, so I feel comfortable with this behavior do { // make sure to free mem later in thread CompletionStatus = new (nothrow) QueuedStatus; if (CompletionStatus == NULL) { __SwitchToThread(GATE_THREAD_DELAY, CALLER_LIMITS_SPINNING); } } while (CompletionStatus == NULL); CompletionStatus->numBytes = numBytes; CompletionStatus->key = (PULONG_PTR)key; CompletionStatus->pOverlapped = pOverlapped; CompletionStatus->errorCode = errorCode; // IOCP threads are created as "active" and "working" while (true) { // counts volatile read paired with CompareExchangeCounts loop set oldCounts = CPThreadCounter.DangerousGetDirtyCounts(); newCounts = oldCounts; newCounts.NumActive++; newCounts.NumWorking++; if (oldCounts == CPThreadCounter.CompareExchangeCounts(newCounts, oldCounts)) break; } // loop, retrying until thread is created. while (!CreateCompletionPortThread((LPVOID)CompletionStatus)) { __SwitchToThread(GATE_THREAD_DELAY, CALLER_LIMITS_SPINNING); } } } else if (cpuUtilization < CpuUtilizationLow) { // this could be an indication that threads might be getting blocked or there is no work if (oldCounts.NumWorking == oldCounts.NumActive && // don't bump the limit if there are already free threads oldCounts.NumRetired > 0) { RetiredCPWakeupEvent->Set(); } } } #endif // !TARGET_UNIX if (!UsePortableThreadPool() && 0 == CLRConfig::GetConfigValue(CLRConfig::INTERNAL_ThreadPool_DisableStarvationDetection)) { if (PerAppDomainTPCountList::AreRequestsPendingInAnyAppDomains() && SufficientDelaySinceLastDequeue()) { DangerousNonHostedSpinLockHolder tal(&ThreadAdjustmentLock); ThreadCounter::Counts counts = WorkerCounter.GetCleanCounts(); while (counts.NumActive < MaxLimitTotalWorkerThreads && //don't add a thread if we're at the max counts.NumActive >= counts.MaxWorking) //don't add a thread if we're already in the process of adding threads { bool breakIntoDebugger = (0 != CLRConfig::GetConfigValue(CLRConfig::INTERNAL_ThreadPool_DebugBreakOnWorkerStarvation)); if (breakIntoDebugger) { OutputDebugStringW(W("The CLR ThreadPool detected work queue starvation!")); DebugBreak(); } ThreadCounter::Counts newCounts = counts; newCounts.MaxWorking = newCounts.NumActive + 1; ThreadCounter::Counts oldCounts = WorkerCounter.CompareExchangeCounts(newCounts, counts); if (oldCounts == counts) { HillClimbingInstance.ForceChange(newCounts.MaxWorking, Starvation); MaybeAddWorkingWorker(); break; } else { counts = oldCounts; } } } } } // called by logic to spawn a new completion port thread. // return false if not enough time has elapsed since the last // time we sampled the cpu utilization. BOOL ThreadpoolMgr::SufficientDelaySinceLastSample(unsigned int LastThreadCreationTime, unsigned NumThreads, // total number of threads of that type (worker or CP) double throttleRate // the delay is increased by this percentage for each extra thread ) { LIMITED_METHOD_CONTRACT; unsigned dwCurrentTickCount = GetTickCount(); unsigned delaySinceLastThreadCreation = dwCurrentTickCount - LastThreadCreationTime; unsigned minWaitBetweenThreadCreation = GATE_THREAD_DELAY; if (throttleRate > 0.0) { _ASSERTE(throttleRate <= 1.0); unsigned adjustedThreadCount = NumThreads > NumberOfProcessors ? (NumThreads - NumberOfProcessors) : 0; minWaitBetweenThreadCreation = (unsigned) (GATE_THREAD_DELAY * pow((1.0 + throttleRate),(double)adjustedThreadCount)); } // the amount of time to wait should grow up as the number of threads is increased return (delaySinceLastThreadCreation > minWaitBetweenThreadCreation); } // called by logic to spawn new worker threads, return true if it's been too long // since the last dequeue operation - takes number of worker threads into account // in deciding "too long" BOOL ThreadpoolMgr::SufficientDelaySinceLastDequeue() { LIMITED_METHOD_CONTRACT; _ASSERTE(!UsePortableThreadPool()); #define DEQUEUE_DELAY_THRESHOLD (GATE_THREAD_DELAY * 2) unsigned delay = GetTickCount() - VolatileLoad(&LastDequeueTime); unsigned tooLong; if(cpuUtilization < CpuUtilizationLow) { tooLong = GATE_THREAD_DELAY; } else { ThreadCounter::Counts counts = WorkerCounter.GetCleanCounts(); unsigned numThreads = counts.MaxWorking; tooLong = numThreads * DEQUEUE_DELAY_THRESHOLD; } return (delay > tooLong); } #ifdef _MSC_VER #ifdef HOST_64BIT #pragma warning (default : 4716) #else #pragma warning (default : 4715) #endif #endif /************************************************************************/ struct CreateTimerThreadParams { CLREvent event; BOOL setupSucceeded; }; BOOL ThreadpoolMgr::CreateTimerQueueTimer(PHANDLE phNewTimer, WAITORTIMERCALLBACK Callback, PVOID Parameter, DWORD DueTime, DWORD Period, ULONG Flag) { CONTRACTL { THROWS; // EnsureInitialized, CreateAutoEvent can throw if (GetThreadNULLOk()) {GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);} // There can be calls thru ICorThreadpool MODE_ANY; INJECT_FAULT(COMPlusThrowOM()); } CONTRACTL_END; EnsureInitialized(); // For now we use just one timer thread. Consider using multiple timer threads if // number of timers in the queue exceeds a certain threshold. The logic and code // would be similar to the one for creating wait threads. if (NULL == TimerThread) { CrstHolder csh(&TimerQueueCriticalSection); // check again if (NULL == TimerThread) { CreateTimerThreadParams params; params.event.CreateAutoEvent(FALSE); params.setupSucceeded = FALSE; HANDLE TimerThreadHandle = Thread::CreateUtilityThread(Thread::StackSize_Small, TimerThreadStart, &params, W(".NET Timer")); if (TimerThreadHandle == NULL) { params.event.CloseEvent(); ThrowOutOfMemory(); } { GCX_PREEMP(); for(;;) { // if a host throws because it couldnt allocate another thread, // just retry the wait. if (SafeWait(&params.event,INFINITE, FALSE) != WAIT_TIMEOUT) break; } } params.event.CloseEvent(); if (!params.setupSucceeded) { CloseHandle(TimerThreadHandle); *phNewTimer = NULL; return FALSE; } TimerThread = TimerThreadHandle; } } NewHolder<TimerInfo> timerInfoHolder; TimerInfo * timerInfo = new (nothrow) TimerInfo; if (NULL == timerInfo) ThrowOutOfMemory(); timerInfoHolder.Assign(timerInfo); timerInfo->FiringTime = DueTime; timerInfo->Function = Callback; timerInfo->Context = Parameter; timerInfo->Period = Period; timerInfo->state = 0; timerInfo->flag = Flag; timerInfo->ExternalCompletionEvent = INVALID_HANDLE; timerInfo->ExternalEventSafeHandle = NULL; *phNewTimer = (HANDLE)timerInfo; BOOL status = QueueUserAPC((PAPCFUNC)InsertNewTimer,TimerThread,(size_t)timerInfo); if (FALSE == status) { *phNewTimer = NULL; return FALSE; } timerInfoHolder.SuppressRelease(); return TRUE; } #ifdef _MSC_VER #ifdef HOST_64BIT #pragma warning (disable : 4716) #else #pragma warning (disable : 4715) #endif #endif DWORD WINAPI ThreadpoolMgr::TimerThreadStart(LPVOID p) { ClrFlsSetThreadType (ThreadType_Timer); STATIC_CONTRACT_THROWS; STATIC_CONTRACT_GC_TRIGGERS; // due to SetApartment STATIC_CONTRACT_MODE_PREEMPTIVE; /* cannot use contract because of SEH CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_PREEMPTIVE; } CONTRACTL_END;*/ CreateTimerThreadParams* params = (CreateTimerThreadParams*)p; Thread* pThread = SetupThreadNoThrow(); params->setupSucceeded = (pThread == NULL) ? 0 : 1; params->event.Set(); if (pThread == NULL) return 0; pTimerThread = pThread; // Timer threads never die LastTickCount = GetTickCount(); #ifdef FEATURE_COMINTEROP if (pThread->SetApartment(Thread::AS_InMTA) != Thread::AS_InMTA) { // @todo: should we log the failure return 0; } #endif // FEATURE_COMINTEROP for (;;) { // moved to its own function since EX_TRY consumes stack #ifdef _MSC_VER #pragma inline_depth (0) // the function containing EX_TRY can't be inlined here #endif TimerThreadFire(); #ifdef _MSC_VER #pragma inline_depth (20) #endif } // unreachable } void ThreadpoolMgr::TimerThreadFire() { CONTRACTL { THROWS; GC_TRIGGERS; MODE_PREEMPTIVE; } CONTRACTL_END; EX_TRY { DWORD timeout = FireTimers(); #undef SleepEx SleepEx(timeout, TRUE); #define SleepEx(a,b) Dont_Use_SleepEx(a,b) // the thread could wake up either because an APC completed or the sleep timeout // in both case, we need to sweep the timer queue, firing timers, and readjusting // the next firing time } EX_CATCH { // Assert on debug builds since a dead timer thread is a fatal error _ASSERTE(FALSE); EX_RETHROW; } EX_END_CATCH(SwallowAllExceptions); } #ifdef _MSC_VER #ifdef HOST_64BIT #pragma warning (default : 4716) #else #pragma warning (default : 4715) #endif #endif // Executed as an APC in timer thread void ThreadpoolMgr::InsertNewTimer(TimerInfo* pArg) { CONTRACTL { NOTHROW; GC_TRIGGERS; MODE_ANY; } CONTRACTL_END; _ASSERTE(pArg); TimerInfo * timerInfo = pArg; if (timerInfo->state & TIMER_DELETE) { // timer was deleted before it could be registered DeleteTimer(timerInfo); return; } // set the firing time = current time + due time (note initially firing time = due time) DWORD currentTime = GetTickCount(); if (timerInfo->FiringTime == (ULONG) -1) { timerInfo->state = TIMER_REGISTERED; timerInfo->refCount = 1; } else { timerInfo->FiringTime += currentTime; timerInfo->state = (TIMER_REGISTERED | TIMER_ACTIVE); timerInfo->refCount = 1; // insert the timer in the queue InsertTailList(&TimerQueue,(&timerInfo->link)); } return; } // executed by the Timer thread // sweeps through the list of timers, readjusting the firing times, queueing APCs for // those that have expired, and returns the next firing time interval DWORD ThreadpoolMgr::FireTimers() { CONTRACTL { THROWS; // QueueUserWorkItem can throw if (GetThreadNULLOk()) { GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);} if (GetThreadNULLOk()) { MODE_PREEMPTIVE;} else { DISABLED(MODE_ANY);} } CONTRACTL_END; DWORD currentTime = GetTickCount(); DWORD nextFiringInterval = (DWORD) -1; TimerInfo* timerInfo = NULL; EX_TRY { for (LIST_ENTRY* node = (LIST_ENTRY*) TimerQueue.Flink; node != &TimerQueue; ) { timerInfo = (TimerInfo*) node; node = (LIST_ENTRY*) node->Flink; if (TimeExpired(LastTickCount, currentTime, timerInfo->FiringTime)) { if (timerInfo->Period == 0 || timerInfo->Period == (ULONG) -1) { DeactivateTimer(timerInfo); } InterlockedIncrement(&timerInfo->refCount); if (UsePortableThreadPool()) { GCX_COOP(); ARG_SLOT args[] = { PtrToArgSlot(AsyncTimerCallbackCompletion), PtrToArgSlot(timerInfo) }; MethodDescCallSite(METHOD__THREAD_POOL__UNSAFE_QUEUE_UNMANAGED_WORK_ITEM).Call(args); } else { QueueUserWorkItem(AsyncTimerCallbackCompletion, timerInfo, QUEUE_ONLY /* TimerInfo take care of deleting*/); } if (timerInfo->Period != 0 && timerInfo->Period != (ULONG)-1) { ULONG nextFiringTime = timerInfo->FiringTime + timerInfo->Period; DWORD firingInterval; if (TimeExpired(timerInfo->FiringTime, currentTime, nextFiringTime)) { // Enough time has elapsed to fire the timer yet again. The timer is not able to keep up with the short // period, have it fire 1 ms from now to avoid spinning without a delay. timerInfo->FiringTime = currentTime + 1; firingInterval = 1; } else { timerInfo->FiringTime = nextFiringTime; firingInterval = TimeInterval(nextFiringTime, currentTime); } if (firingInterval < nextFiringInterval) nextFiringInterval = firingInterval; } } else { DWORD firingInterval = TimeInterval(timerInfo->FiringTime, currentTime); if (firingInterval < nextFiringInterval) nextFiringInterval = firingInterval; } } } EX_CATCH { // If QueueUserWorkItem throws OOM, swallow the exception and retry on // the next call to FireTimers(), otherwise retrhow. Exception *ex = GET_EXCEPTION(); // undo the call to DeactivateTimer() InterlockedDecrement(&timerInfo->refCount); timerInfo->state = timerInfo->state & TIMER_ACTIVE; InsertTailList(&TimerQueue, (&timerInfo->link)); if (ex->GetHR() != E_OUTOFMEMORY) { EX_RETHROW; } } EX_END_CATCH(RethrowTerminalExceptions); LastTickCount = currentTime; return nextFiringInterval; } DWORD WINAPI ThreadpoolMgr::AsyncTimerCallbackCompletion(PVOID pArgs) { CONTRACTL { THROWS; GC_TRIGGERS; MODE_PREEMPTIVE; } CONTRACTL_END; Thread* pThread = GetThreadNULLOk(); if (pThread == NULL) { HRESULT hr = ERROR_SUCCESS; ClrFlsSetThreadType(ThreadType_Threadpool_Worker); pThread = SetupThreadNoThrow(&hr); if (pThread == NULL) { return hr; } } { TimerInfo* timerInfo = (TimerInfo*) pArgs; ((WAITORTIMERCALLBACKFUNC) timerInfo->Function) (timerInfo->Context, TRUE) ; if (InterlockedDecrement(&timerInfo->refCount) == 0) { DeleteTimer(timerInfo); } } return ERROR_SUCCESS; } // removes the timer from the timer queue, thereby cancelling it // there may still be pending callbacks that haven't completed void ThreadpoolMgr::DeactivateTimer(TimerInfo* timerInfo) { LIMITED_METHOD_CONTRACT; RemoveEntryList((LIST_ENTRY*) timerInfo); // This timer info could go into another linked list of timer infos // waiting to be released. Reinitialize the list pointers InitializeListHead(&timerInfo->link); timerInfo->state = timerInfo->state & ~TIMER_ACTIVE; } DWORD WINAPI ThreadpoolMgr::AsyncDeleteTimer(PVOID pArgs) { CONTRACTL { THROWS; MODE_PREEMPTIVE; GC_TRIGGERS; } CONTRACTL_END; Thread * pThread = GetThreadNULLOk(); if (pThread == NULL) { HRESULT hr = ERROR_SUCCESS; ClrFlsSetThreadType(ThreadType_Threadpool_Worker); pThread = SetupThreadNoThrow(&hr); if (pThread == NULL) { return hr; } } DeleteTimer((TimerInfo*) pArgs); return ERROR_SUCCESS; } void ThreadpoolMgr::DeleteTimer(TimerInfo* timerInfo) { CONTRACTL { if (GetThreadNULLOk() == pTimerThread) { NOTHROW; } else { THROWS; } GC_TRIGGERS; MODE_ANY; } CONTRACTL_END; _ASSERTE((timerInfo->state & TIMER_ACTIVE) == 0); _ASSERTE(!(timerInfo->flag & WAIT_FREE_CONTEXT)); if (timerInfo->flag & WAIT_INTERNAL_COMPLETION) { timerInfo->InternalCompletionEvent.Set(); return; // the timerInfo will be deleted by the thread that's waiting on InternalCompletionEvent } // ExternalCompletionEvent comes from Host, ExternalEventSafeHandle from managed code. // They are mutually exclusive. _ASSERTE(!(timerInfo->ExternalCompletionEvent != INVALID_HANDLE && timerInfo->ExternalEventSafeHandle != NULL)); if (timerInfo->ExternalCompletionEvent != INVALID_HANDLE) { SetEvent(timerInfo->ExternalCompletionEvent); timerInfo->ExternalCompletionEvent = INVALID_HANDLE; } // We cannot block the timer thread, so some cleanup is deferred to other threads. if (GetThreadNULLOk() == pTimerThread) { // Notify the ExternalEventSafeHandle with an user work item if (timerInfo->ExternalEventSafeHandle != NULL) { BOOL success = FALSE; EX_TRY { if (QueueUserWorkItem(AsyncDeleteTimer, timerInfo, QUEUE_ONLY) != FALSE) { success = TRUE; } } EX_CATCH { } EX_END_CATCH(SwallowAllExceptions); // If unable to queue a user work item, fall back to queueing timer for release // which will happen *sometime* in the future. if (success == FALSE) { QueueTimerInfoForRelease(timerInfo); } return; } // Releasing GC handles can block. So we wont do this on the timer thread. // We'll put it in a list which will be processed by a worker thread if (timerInfo->Context != NULL) { QueueTimerInfoForRelease(timerInfo); return; } } // To get here we are either not the Timer thread or there is no blocking work to be done if (timerInfo->Context != NULL) { GCX_COOP(); delete (ThreadpoolMgr::TimerInfoContext*)timerInfo->Context; } if (timerInfo->ExternalEventSafeHandle != NULL) { ReleaseTimerInfo(timerInfo); } delete timerInfo; } // We add TimerInfos from deleted timers into a linked list. // A worker thread will later release the handles held by the TimerInfo // and recycle them if possible. void ThreadpoolMgr::QueueTimerInfoForRelease(TimerInfo *pTimerInfo) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; // The synchronization in this method depends on the fact that // - There is only one timer thread // - The one and only timer thread is executing this method. // - This function wont go into an alertable state. That could trigger another APC. // Else two threads can be queueing timerinfos and a race could // lead to leaked memory and handles _ASSERTE(pTimerThread == GetThread()); TimerInfo *pHead = NULL; // Make sure this timer info has been deactivated and removed from any other lists _ASSERTE((pTimerInfo->state & TIMER_ACTIVE) == 0); //_ASSERTE(pTimerInfo->link.Blink == &(pTimerInfo->link) && // pTimerInfo->link.Flink == &(pTimerInfo->link)); // Make sure "link" is the first field in TimerInfo _ASSERTE(pTimerInfo == (PVOID)&pTimerInfo->link); // Grab any previously published list if ((pHead = InterlockedExchangeT(&TimerInfosToBeRecycled, NULL)) != NULL) { // If there already is a list, just append InsertTailList((LIST_ENTRY *)pHead, &pTimerInfo->link); pTimerInfo = pHead; } else // If this is the head, make its next and previous ptrs point to itself InitializeListHead((LIST_ENTRY*)&pTimerInfo->link); // Publish the list (void) InterlockedExchangeT(&TimerInfosToBeRecycled, pTimerInfo); } void ThreadpoolMgr::FlushQueueOfTimerInfos() { CONTRACTL { THROWS; GC_TRIGGERS; MODE_ANY; } CONTRACTL_END; TimerInfo *pHeadTimerInfo = NULL, *pCurrTimerInfo = NULL; LIST_ENTRY *pNextInfo = NULL; if ((pHeadTimerInfo = InterlockedExchangeT(&TimerInfosToBeRecycled, NULL)) == NULL) return; do { RemoveHeadList((LIST_ENTRY *)pHeadTimerInfo, pNextInfo); _ASSERTE(pNextInfo != NULL); pCurrTimerInfo = (TimerInfo *) pNextInfo; GCX_COOP(); if (pCurrTimerInfo->Context != NULL) { delete (ThreadpoolMgr::TimerInfoContext*)pCurrTimerInfo->Context; } if (pCurrTimerInfo->ExternalEventSafeHandle != NULL) { ReleaseTimerInfo(pCurrTimerInfo); } delete pCurrTimerInfo; } while ((TimerInfo *)pNextInfo != pHeadTimerInfo); } /************************************************************************/ BOOL ThreadpoolMgr::ChangeTimerQueueTimer( HANDLE Timer, ULONG DueTime, ULONG Period) { CONTRACTL { THROWS; MODE_ANY; GC_NOTRIGGER; INJECT_FAULT(COMPlusThrowOM()); } CONTRACTL_END; _ASSERTE(IsInitialized()); _ASSERTE(Timer); // not possible to give invalid handle in managed code NewHolder<TimerUpdateInfo> updateInfoHolder; TimerUpdateInfo *updateInfo = new TimerUpdateInfo; updateInfoHolder.Assign(updateInfo); updateInfo->Timer = (TimerInfo*) Timer; updateInfo->DueTime = DueTime; updateInfo->Period = Period; BOOL status = QueueUserAPC((PAPCFUNC)UpdateTimer, TimerThread, (size_t) updateInfo); if (status) updateInfoHolder.SuppressRelease(); return(status); } void ThreadpoolMgr::UpdateTimer(TimerUpdateInfo* pArgs) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; TimerUpdateInfo* updateInfo = (TimerUpdateInfo*) pArgs; TimerInfo* timerInfo = updateInfo->Timer; timerInfo->Period = updateInfo->Period; if (updateInfo->DueTime == (ULONG) -1) { if (timerInfo->state & TIMER_ACTIVE) { DeactivateTimer(timerInfo); } // else, noop (the timer was already inactive) _ASSERTE((timerInfo->state & TIMER_ACTIVE) == 0); delete updateInfo; return; } DWORD currentTime = GetTickCount(); timerInfo->FiringTime = currentTime + updateInfo->DueTime; delete updateInfo; if (! (timerInfo->state & TIMER_ACTIVE)) { // timer not active (probably a one shot timer that has expired), so activate it timerInfo->state |= TIMER_ACTIVE; _ASSERTE(timerInfo->refCount >= 1); // insert the timer in the queue InsertTailList(&TimerQueue,(&timerInfo->link)); } return; } /************************************************************************/ BOOL ThreadpoolMgr::DeleteTimerQueueTimer( HANDLE Timer, HANDLE Event) { CONTRACTL { THROWS; MODE_ANY; GC_TRIGGERS; } CONTRACTL_END; _ASSERTE(IsInitialized()); // cannot call delete before creating timer _ASSERTE(Timer); // not possible to give invalid handle in managed code // make volatile to avoid compiler reordering check after async call. // otherwise, DeregisterTimer could delete timerInfo before the comparison. VolatilePtr<TimerInfo> timerInfo = (TimerInfo*) Timer; if (Event == (HANDLE) -1) { //CONTRACT_VIOLATION(ThrowsViolation); timerInfo->InternalCompletionEvent.CreateAutoEvent(FALSE); timerInfo->flag |= WAIT_INTERNAL_COMPLETION; } else if (Event) { timerInfo->ExternalCompletionEvent = Event; } #ifdef _DEBUG else /* Event == NULL */ { _ASSERTE(timerInfo->ExternalCompletionEvent == INVALID_HANDLE); } #endif BOOL isBlocking = timerInfo->flag & WAIT_INTERNAL_COMPLETION; BOOL status = QueueUserAPC((PAPCFUNC)DeregisterTimer, TimerThread, (size_t)(TimerInfo*)timerInfo); if (FALSE == status) { if (isBlocking) timerInfo->InternalCompletionEvent.CloseEvent(); return FALSE; } if (isBlocking) { _ASSERTE(timerInfo->ExternalEventSafeHandle == NULL); _ASSERTE(timerInfo->ExternalCompletionEvent == INVALID_HANDLE); _ASSERTE(GetThreadNULLOk() != pTimerThread); timerInfo->InternalCompletionEvent.Wait(INFINITE,TRUE /*alertable*/); timerInfo->InternalCompletionEvent.CloseEvent(); // Release handles and delete TimerInfo _ASSERTE(timerInfo->refCount == 0); // if WAIT_INTERNAL_COMPLETION flag is not set, timerInfo will be deleted in DeleteTimer. timerInfo->flag &= ~WAIT_INTERNAL_COMPLETION; DeleteTimer(timerInfo); } return status; } void ThreadpoolMgr::DeregisterTimer(TimerInfo* pArgs) { CONTRACTL { NOTHROW; GC_TRIGGERS; MODE_PREEMPTIVE; } CONTRACTL_END; TimerInfo* timerInfo = (TimerInfo*) pArgs; if (! (timerInfo->state & TIMER_REGISTERED) ) { // set state to deleted, so that it does not get registered timerInfo->state |= TIMER_DELETE ; // since the timer has not even been registered, we dont need an interlock to decrease the RefCount timerInfo->refCount--; return; } if (timerInfo->state & TIMER_ACTIVE) { DeactivateTimer(timerInfo); } if (InterlockedDecrement(&timerInfo->refCount) == 0 ) { DeleteTimer(timerInfo); } return; } #endif // !DACCESS_COMPILE
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*++ Module Name: Win32ThreadPool.cpp Abstract: This module implements Threadpool support using Win32 APIs Revision History: December 1999 - Created --*/ #include "common.h" #include "log.h" #include "threadpoolrequest.h" #include "win32threadpool.h" #include "delegateinfo.h" #include "eeconfig.h" #include "dbginterface.h" #include "corhost.h" #include "eventtrace.h" #include "threads.h" #include "appdomain.inl" #include "nativeoverlapped.h" #include "hillclimbing.h" #include "configuration.h" #ifndef TARGET_UNIX #ifndef DACCESS_COMPILE // APIs that must be accessed through dynamic linking. typedef int (WINAPI *NtQueryInformationThreadProc) ( HANDLE ThreadHandle, THREADINFOCLASS ThreadInformationClass, PVOID ThreadInformation, ULONG ThreadInformationLength, PULONG ReturnLength); NtQueryInformationThreadProc g_pufnNtQueryInformationThread = NULL; typedef int (WINAPI *NtQuerySystemInformationProc) ( SYSTEM_INFORMATION_CLASS SystemInformationClass, PVOID SystemInformation, ULONG SystemInformationLength, PULONG ReturnLength OPTIONAL); NtQuerySystemInformationProc g_pufnNtQuerySystemInformation = NULL; typedef HANDLE (WINAPI * CreateWaitableTimerExProc) ( LPSECURITY_ATTRIBUTES lpTimerAttributes, LPCTSTR lpTimerName, DWORD dwFlags, DWORD dwDesiredAccess); CreateWaitableTimerExProc g_pufnCreateWaitableTimerEx = NULL; typedef BOOL (WINAPI * SetWaitableTimerExProc) ( HANDLE hTimer, const LARGE_INTEGER *lpDueTime, LONG lPeriod, PTIMERAPCROUTINE pfnCompletionRoutine, LPVOID lpArgToCompletionRoutine, void* WakeContext, //should be PREASON_CONTEXT, but it's not defined for us (and we don't use it) ULONG TolerableDelay); SetWaitableTimerExProc g_pufnSetWaitableTimerEx = NULL; #endif // !DACCESS_COMPILE #endif // !TARGET_UNIX BOOL ThreadpoolMgr::InitCompletionPortThreadpool = FALSE; HANDLE ThreadpoolMgr::GlobalCompletionPort; // used for binding io completions on file handles SVAL_IMPL(ThreadpoolMgr::ThreadCounter,ThreadpoolMgr,CPThreadCounter); SVAL_IMPL_INIT(LONG,ThreadpoolMgr,MaxLimitTotalCPThreads,1000); // = MaxLimitCPThreadsPerCPU * number of CPUS SVAL_IMPL(LONG,ThreadpoolMgr,MinLimitTotalCPThreads); SVAL_IMPL(LONG,ThreadpoolMgr,MaxFreeCPThreads); // = MaxFreeCPThreadsPerCPU * Number of CPUS // Cacheline aligned, hot variable DECLSPEC_ALIGN(MAX_CACHE_LINE_SIZE) SVAL_IMPL(ThreadpoolMgr::ThreadCounter, ThreadpoolMgr, WorkerCounter); SVAL_IMPL(LONG,ThreadpoolMgr,MinLimitTotalWorkerThreads); // = MaxLimitCPThreadsPerCPU * number of CPUS SVAL_IMPL(LONG,ThreadpoolMgr,MaxLimitTotalWorkerThreads); // = MaxLimitCPThreadsPerCPU * number of CPUS SVAL_IMPL(LONG,ThreadpoolMgr,cpuUtilization); HillClimbing ThreadpoolMgr::HillClimbingInstance; // Cacheline aligned, 3 hot variables updated in a group DECLSPEC_ALIGN(MAX_CACHE_LINE_SIZE) LONG ThreadpoolMgr::PriorCompletedWorkRequests = 0; DWORD ThreadpoolMgr::PriorCompletedWorkRequestsTime; DWORD ThreadpoolMgr::NextCompletedWorkRequestsTime; LARGE_INTEGER ThreadpoolMgr::CurrentSampleStartTime; unsigned int ThreadpoolMgr::WorkerThreadSpinLimit; bool ThreadpoolMgr::IsHillClimbingDisabled; int ThreadpoolMgr::ThreadAdjustmentInterval; #define INVALID_HANDLE ((HANDLE) -1) #define NEW_THREAD_THRESHOLD 7 // Number of requests outstanding before we start a new thread #define CP_THREAD_PENDINGIO_WAIT 5000 // polling interval when thread is retired but has a pending io #define GATE_THREAD_DELAY 500 /*milliseconds*/ #define GATE_THREAD_DELAY_TOLERANCE 50 /*milliseconds*/ #define DELAY_BETWEEN_SUSPENDS (5000 + GATE_THREAD_DELAY) // time to delay between suspensions Volatile<LONG> ThreadpoolMgr::Initialization = 0; // indicator of whether the threadpool is initialized. bool ThreadpoolMgr::s_usePortableThreadPool = false; bool ThreadpoolMgr::s_usePortableThreadPoolForIO = false; // Cacheline aligned, hot variable DECLSPEC_ALIGN(MAX_CACHE_LINE_SIZE) unsigned int ThreadpoolMgr::LastDequeueTime; // used to determine if work items are getting thread starved SPTR_IMPL(WorkRequest,ThreadpoolMgr,WorkRequestHead); // Head of work request queue SPTR_IMPL(WorkRequest,ThreadpoolMgr,WorkRequestTail); // Head of work request queue SVAL_IMPL(ThreadpoolMgr::LIST_ENTRY,ThreadpoolMgr,TimerQueue); // queue of timers //unsigned int ThreadpoolMgr::LastCpuSamplingTime=0; // last time cpu utilization was sampled by gate thread unsigned int ThreadpoolMgr::LastCPThreadCreation=0; // last time a completion port thread was created unsigned int ThreadpoolMgr::NumberOfProcessors; // = NumberOfWorkerThreads - no. of blocked threads CrstStatic ThreadpoolMgr::WorkerCriticalSection; CLREvent * ThreadpoolMgr::RetiredCPWakeupEvent; // wakeup event for completion port threads CrstStatic ThreadpoolMgr::WaitThreadsCriticalSection; ThreadpoolMgr::LIST_ENTRY ThreadpoolMgr::WaitThreadsHead; CLRLifoSemaphore* ThreadpoolMgr::WorkerSemaphore; CLRLifoSemaphore* ThreadpoolMgr::RetiredWorkerSemaphore; CrstStatic ThreadpoolMgr::TimerQueueCriticalSection; HANDLE ThreadpoolMgr::TimerThread=NULL; Thread *ThreadpoolMgr::pTimerThread=NULL; // Cacheline aligned, hot variable DECLSPEC_ALIGN(MAX_CACHE_LINE_SIZE) DWORD ThreadpoolMgr::LastTickCount; // Cacheline aligned, hot variable DECLSPEC_ALIGN(MAX_CACHE_LINE_SIZE) LONG ThreadpoolMgr::GateThreadStatus=GATE_THREAD_STATUS_NOT_RUNNING; // Move out of from preceeding variables' cache line DECLSPEC_ALIGN(MAX_CACHE_LINE_SIZE) ThreadpoolMgr::RecycledListsWrapper ThreadpoolMgr::RecycledLists; ThreadpoolMgr::TimerInfo *ThreadpoolMgr::TimerInfosToBeRecycled = NULL; BOOL ThreadpoolMgr::IsApcPendingOnWaitThread = FALSE; #ifndef DACCESS_COMPILE // Macros for inserting/deleting from doubly linked list #define InitializeListHead(ListHead) (\ (ListHead)->Flink = (ListHead)->Blink = (ListHead)) // // these are named the same as slightly different macros in the NT headers // #undef RemoveHeadList #undef RemoveEntryList #undef InsertTailList #undef InsertHeadList #define RemoveHeadList(ListHead,FirstEntry) \ {\ FirstEntry = (LIST_ENTRY*) (ListHead)->Flink;\ ((LIST_ENTRY*)FirstEntry->Flink)->Blink = (ListHead);\ (ListHead)->Flink = FirstEntry->Flink;\ } #define RemoveEntryList(Entry) {\ LIST_ENTRY* _EX_Entry;\ _EX_Entry = (Entry);\ ((LIST_ENTRY*) _EX_Entry->Blink)->Flink = _EX_Entry->Flink;\ ((LIST_ENTRY*) _EX_Entry->Flink)->Blink = _EX_Entry->Blink;\ } #define InsertTailList(ListHead,Entry) \ (Entry)->Flink = (ListHead);\ (Entry)->Blink = (ListHead)->Blink;\ ((LIST_ENTRY*)(ListHead)->Blink)->Flink = (Entry);\ (ListHead)->Blink = (Entry); #define InsertHeadList(ListHead,Entry) {\ LIST_ENTRY* _EX_Flink;\ LIST_ENTRY* _EX_ListHead;\ _EX_ListHead = (LIST_ENTRY*)(ListHead);\ _EX_Flink = (LIST_ENTRY*) _EX_ListHead->Flink;\ (Entry)->Flink = _EX_Flink;\ (Entry)->Blink = _EX_ListHead;\ _EX_Flink->Blink = (Entry);\ _EX_ListHead->Flink = (Entry);\ } #define IsListEmpty(ListHead) \ ((ListHead)->Flink == (ListHead)) #define SetLastHRError(hr) \ if (HRESULT_FACILITY(hr) == FACILITY_WIN32)\ SetLastError(HRESULT_CODE(hr));\ else \ SetLastError(ERROR_INVALID_DATA);\ /************************************************************************/ void ThreadpoolMgr::RecycledListsWrapper::Initialize( unsigned int numProcs ) { CONTRACTL { THROWS; MODE_ANY; GC_NOTRIGGER; } CONTRACTL_END; pRecycledListPerProcessor = new RecycledListInfo[numProcs][MEMTYPE_COUNT]; } //--// void ThreadpoolMgr::EnsureInitialized() { CONTRACTL { THROWS; // EnsureInitializedSlow can throw MODE_ANY; GC_NOTRIGGER; } CONTRACTL_END; if (IsInitialized()) return; EnsureInitializedSlow(); } NOINLINE void ThreadpoolMgr::EnsureInitializedSlow() { CONTRACTL { THROWS; // Initialize can throw MODE_ANY; GC_NOTRIGGER; } CONTRACTL_END; DWORD dwSwitchCount = 0; retry: if (InterlockedCompareExchange(&Initialization, 1, 0) == 0) { if (Initialize()) Initialization = -1; else { Initialization = 0; COMPlusThrowOM(); } } else // someone has already begun initializing. { // wait until it finishes while (Initialization != -1) { __SwitchToThread(0, ++dwSwitchCount); goto retry; } } } DWORD GetDefaultMaxLimitWorkerThreads(DWORD minLimit) { CONTRACTL { MODE_ANY; GC_NOTRIGGER; NOTHROW; } CONTRACTL_END; _ASSERTE(!ThreadpoolMgr::UsePortableThreadPool()); // // We determine the max limit for worker threads as follows: // // 1) It must be at least MinLimitTotalWorkerThreads // 2) It must be no greater than (half the virtual address space)/(thread stack size) // 3) It must be <= MaxPossibleWorkerThreads // // TODO: what about CP threads? Can they follow a similar plan? How do we allocate // thread counts between the two kinds of threads? // SIZE_T stackReserveSize = 0; Thread::GetProcessDefaultStackSize(&stackReserveSize, NULL); ULONGLONG halfVirtualAddressSpace; MEMORYSTATUSEX memStats; memStats.dwLength = sizeof(memStats); if (GlobalMemoryStatusEx(&memStats)) { halfVirtualAddressSpace = memStats.ullTotalVirtual / 2; } else { //assume the normal Win32 32-bit virtual address space halfVirtualAddressSpace = 0x000000007FFE0000ull / 2; } ULONGLONG limit = halfVirtualAddressSpace / stackReserveSize; limit = max(limit, (ULONGLONG)minLimit); limit = min(limit, (ULONGLONG)ThreadpoolMgr::ThreadCounter::MaxPossibleCount); _ASSERTE(FitsIn<DWORD>(limit)); return (DWORD)limit; } DWORD GetForceMinWorkerThreadsValue() { WRAPPER_NO_CONTRACT; _ASSERTE(!ThreadpoolMgr::UsePortableThreadPool()); return Configuration::GetKnobDWORDValue(W("System.Threading.ThreadPool.MinThreads"), CLRConfig::INTERNAL_ThreadPool_ForceMinWorkerThreads); } DWORD GetForceMaxWorkerThreadsValue() { WRAPPER_NO_CONTRACT; _ASSERTE(!ThreadpoolMgr::UsePortableThreadPool()); return Configuration::GetKnobDWORDValue(W("System.Threading.ThreadPool.MaxThreads"), CLRConfig::INTERNAL_ThreadPool_ForceMaxWorkerThreads); } BOOL ThreadpoolMgr::Initialize() { CONTRACTL { THROWS; MODE_ANY; GC_NOTRIGGER; INJECT_FAULT(COMPlusThrowOM()); } CONTRACTL_END; BOOL bRet = FALSE; BOOL bExceptionCaught = FALSE; NumberOfProcessors = GetCurrentProcessCpuCount(); InitPlatformVariables(); EX_TRY { if (!UsePortableThreadPool()) { WorkerThreadSpinLimit = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_ThreadPool_UnfairSemaphoreSpinLimit); IsHillClimbingDisabled = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_HillClimbing_Disable) != 0; ThreadAdjustmentInterval = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_HillClimbing_SampleIntervalLow); WaitThreadsCriticalSection.Init(CrstThreadpoolWaitThreads); } if (!UsePortableThreadPoolForIO()) { WorkerCriticalSection.Init(CrstThreadpoolWorker); } TimerQueueCriticalSection.Init(CrstThreadpoolTimerQueue); if (!UsePortableThreadPool()) { // initialize WaitThreadsHead InitializeListHead(&WaitThreadsHead); } // initialize TimerQueue InitializeListHead(&TimerQueue); if (!UsePortableThreadPoolForIO()) { RetiredCPWakeupEvent = new CLREvent(); RetiredCPWakeupEvent->CreateAutoEvent(FALSE); _ASSERTE(RetiredCPWakeupEvent->IsValid()); } if (!UsePortableThreadPool()) { WorkerSemaphore = new CLRLifoSemaphore(); WorkerSemaphore->Create(0, ThreadCounter::MaxPossibleCount); RetiredWorkerSemaphore = new CLRLifoSemaphore(); RetiredWorkerSemaphore->Create(0, ThreadCounter::MaxPossibleCount); } #ifndef TARGET_UNIX //ThreadPool_CPUGroup if (CPUGroupInfo::CanEnableThreadUseAllCpuGroups()) RecycledLists.Initialize( CPUGroupInfo::GetNumActiveProcessors() ); else RecycledLists.Initialize( g_SystemInfo.dwNumberOfProcessors ); #else // !TARGET_UNIX RecycledLists.Initialize( PAL_GetTotalCpuCount() ); #endif // !TARGET_UNIX } EX_CATCH { if (!UsePortableThreadPoolForIO() && RetiredCPWakeupEvent) { delete RetiredCPWakeupEvent; RetiredCPWakeupEvent = NULL; } // Note: It is fine to call Destroy on uninitialized critical sections if (!UsePortableThreadPool()) { WaitThreadsCriticalSection.Destroy(); } if (!UsePortableThreadPoolForIO()) { WorkerCriticalSection.Destroy(); } TimerQueueCriticalSection.Destroy(); bExceptionCaught = TRUE; } EX_END_CATCH(SwallowAllExceptions); if (bExceptionCaught) { goto end; } if (!UsePortableThreadPool()) { // initialize Worker thread settings DWORD forceMin; forceMin = GetForceMinWorkerThreadsValue(); MinLimitTotalWorkerThreads = forceMin > 0 ? (LONG)forceMin : (LONG)NumberOfProcessors; DWORD forceMax; forceMax = GetForceMaxWorkerThreadsValue(); MaxLimitTotalWorkerThreads = forceMax > 0 ? (LONG)forceMax : (LONG)GetDefaultMaxLimitWorkerThreads(MinLimitTotalWorkerThreads); ThreadCounter::Counts counts; counts.NumActive = 0; counts.NumWorking = 0; counts.NumRetired = 0; counts.MaxWorking = MinLimitTotalWorkerThreads; WorkerCounter.counts.AsLongLong = counts.AsLongLong; } if (!UsePortableThreadPoolForIO()) { // initialize CP thread settings MinLimitTotalCPThreads = NumberOfProcessors; // Use volatile store to guarantee make the value visible to the DAC (the store can be optimized out otherwise) VolatileStoreWithoutBarrier<LONG>(&MaxFreeCPThreads, NumberOfProcessors*MaxFreeCPThreadsPerCPU); ThreadCounter::Counts counts; counts.NumActive = 0; counts.NumWorking = 0; counts.NumRetired = 0; counts.MaxWorking = MinLimitTotalCPThreads; CPThreadCounter.counts.AsLongLong = counts.AsLongLong; #ifndef TARGET_UNIX { GlobalCompletionPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, /*ignored for invalid handle value*/ NumberOfProcessors); } #endif // !TARGET_UNIX } if (!UsePortableThreadPool()) { HillClimbingInstance.Initialize(); } bRet = TRUE; end: return bRet; } void ThreadpoolMgr::InitPlatformVariables() { CONTRACTL { NOTHROW; MODE_ANY; GC_NOTRIGGER; } CONTRACTL_END; #ifndef TARGET_UNIX HINSTANCE hNtDll; HINSTANCE hCoreSynch = nullptr; { CONTRACT_VIOLATION(GCViolation|FaultViolation); hNtDll = CLRLoadLibrary(W("ntdll.dll")); _ASSERTE(hNtDll); if (!UsePortableThreadPool()) { hCoreSynch = CLRLoadLibrary(W("api-ms-win-core-synch-l1-1-0.dll")); _ASSERTE(hCoreSynch); } } // These APIs must be accessed via dynamic binding since they may be removed in future // OS versions. g_pufnNtQueryInformationThread = (NtQueryInformationThreadProc)GetProcAddress(hNtDll,"NtQueryInformationThread"); g_pufnNtQuerySystemInformation = (NtQuerySystemInformationProc)GetProcAddress(hNtDll,"NtQuerySystemInformation"); if (!UsePortableThreadPool()) { // These APIs are only supported on newer Windows versions g_pufnCreateWaitableTimerEx = (CreateWaitableTimerExProc)GetProcAddress(hCoreSynch, "CreateWaitableTimerExW"); g_pufnSetWaitableTimerEx = (SetWaitableTimerExProc)GetProcAddress(hCoreSynch, "SetWaitableTimerEx"); } #endif } bool ThreadpoolMgr::CanSetMinIOCompletionThreads(DWORD ioCompletionThreads) { WRAPPER_NO_CONTRACT; _ASSERTE(UsePortableThreadPool()); _ASSERTE(!UsePortableThreadPoolForIO()); EnsureInitialized(); // The lock used by SetMinThreads() and SetMaxThreads() is not taken here, the caller is expected to synchronize between // them. The conditions here should be the same as in the corresponding Set function. return ioCompletionThreads <= (DWORD)MaxLimitTotalCPThreads; } bool ThreadpoolMgr::CanSetMaxIOCompletionThreads(DWORD ioCompletionThreads) { WRAPPER_NO_CONTRACT; _ASSERTE(UsePortableThreadPool()); _ASSERTE(!UsePortableThreadPoolForIO()); _ASSERTE(ioCompletionThreads != 0); EnsureInitialized(); // The lock used by SetMinThreads() and SetMaxThreads() is not taken here, the caller is expected to synchronize between // them. The conditions here should be the same as in the corresponding Set function. return ioCompletionThreads >= (DWORD)MinLimitTotalCPThreads; } BOOL ThreadpoolMgr::SetMaxThreadsHelper(DWORD MaxWorkerThreads, DWORD MaxIOCompletionThreads) { CONTRACTL { THROWS; // Crst can throw and toggle GC mode MODE_ANY; GC_TRIGGERS; } CONTRACTL_END; _ASSERTE(!UsePortableThreadPoolForIO()); BOOL result = FALSE; // doesn't need to be WorkerCS, but using it to avoid race condition between setting min and max, and didn't want to create a new CS. CrstHolder csh(&WorkerCriticalSection); bool usePortableThreadPool = UsePortableThreadPool(); if (( usePortableThreadPool || ( MaxWorkerThreads >= (DWORD)MinLimitTotalWorkerThreads && MaxWorkerThreads != 0 ) ) && MaxIOCompletionThreads >= (DWORD)MinLimitTotalCPThreads && MaxIOCompletionThreads != 0) { if (!usePortableThreadPool && GetForceMaxWorkerThreadsValue() == 0) { MaxLimitTotalWorkerThreads = min(MaxWorkerThreads, (DWORD)ThreadCounter::MaxPossibleCount); ThreadCounter::Counts counts = WorkerCounter.GetCleanCounts(); while (counts.MaxWorking > MaxLimitTotalWorkerThreads) { ThreadCounter::Counts newCounts = counts; newCounts.MaxWorking = MaxLimitTotalWorkerThreads; ThreadCounter::Counts oldCounts = WorkerCounter.CompareExchangeCounts(newCounts, counts); if (oldCounts == counts) counts = newCounts; else counts = oldCounts; } } MaxLimitTotalCPThreads = min(MaxIOCompletionThreads, (DWORD)ThreadCounter::MaxPossibleCount); result = TRUE; } return result; } /************************************************************************/ BOOL ThreadpoolMgr::SetMaxThreads(DWORD MaxWorkerThreads, DWORD MaxIOCompletionThreads) { CONTRACTL { THROWS; // SetMaxThreadsHelper can throw and toggle GC mode MODE_ANY; GC_TRIGGERS; } CONTRACTL_END; _ASSERTE(!UsePortableThreadPoolForIO()); EnsureInitialized(); return SetMaxThreadsHelper(MaxWorkerThreads, MaxIOCompletionThreads); } BOOL ThreadpoolMgr::GetMaxThreads(DWORD* MaxWorkerThreads, DWORD* MaxIOCompletionThreads) { LIMITED_METHOD_CONTRACT; _ASSERTE(!UsePortableThreadPoolForIO()); if (!MaxWorkerThreads || !MaxIOCompletionThreads) { SetLastHRError(ERROR_INVALID_DATA); return FALSE; } EnsureInitialized(); *MaxWorkerThreads = UsePortableThreadPool() ? 1 : (DWORD)MaxLimitTotalWorkerThreads; *MaxIOCompletionThreads = MaxLimitTotalCPThreads; return TRUE; } BOOL ThreadpoolMgr::SetMinThreads(DWORD MinWorkerThreads, DWORD MinIOCompletionThreads) { CONTRACTL { THROWS; // Crst can throw and toggle GC mode MODE_ANY; GC_TRIGGERS; } CONTRACTL_END; _ASSERTE(!UsePortableThreadPoolForIO()); EnsureInitialized(); // doesn't need to be WorkerCS, but using it to avoid race condition between setting min and max, and didn't want to create a new CS. CrstHolder csh(&WorkerCriticalSection); BOOL init_result = FALSE; bool usePortableThreadPool = UsePortableThreadPool(); if (( usePortableThreadPool || ( MinWorkerThreads >= 0 && MinWorkerThreads <= (DWORD) MaxLimitTotalWorkerThreads ) ) && MinIOCompletionThreads >= 0 && MinIOCompletionThreads <= (DWORD) MaxLimitTotalCPThreads) { if (!usePortableThreadPool && GetForceMinWorkerThreadsValue() == 0) { MinLimitTotalWorkerThreads = max(1, min(MinWorkerThreads, (DWORD)ThreadCounter::MaxPossibleCount)); ThreadCounter::Counts counts = WorkerCounter.GetCleanCounts(); while (counts.MaxWorking < MinLimitTotalWorkerThreads) { ThreadCounter::Counts newCounts = counts; newCounts.MaxWorking = MinLimitTotalWorkerThreads; ThreadCounter::Counts oldCounts = WorkerCounter.CompareExchangeCounts(newCounts, counts); if (oldCounts == counts) { counts = newCounts; // if we increased the limit, and there are pending workitems, we need // to dispatch a thread to process the work. if (newCounts.MaxWorking > oldCounts.MaxWorking && PerAppDomainTPCountList::AreRequestsPendingInAnyAppDomains()) { MaybeAddWorkingWorker(); } } else { counts = oldCounts; } } } MinLimitTotalCPThreads = max(1, min(MinIOCompletionThreads, (DWORD)ThreadCounter::MaxPossibleCount)); init_result = TRUE; } return init_result; } BOOL ThreadpoolMgr::GetMinThreads(DWORD* MinWorkerThreads, DWORD* MinIOCompletionThreads) { LIMITED_METHOD_CONTRACT; _ASSERTE(!UsePortableThreadPoolForIO()); if (!MinWorkerThreads || !MinIOCompletionThreads) { SetLastHRError(ERROR_INVALID_DATA); return FALSE; } EnsureInitialized(); *MinWorkerThreads = UsePortableThreadPool() ? 1 : (DWORD)MinLimitTotalWorkerThreads; *MinIOCompletionThreads = MinLimitTotalCPThreads; return TRUE; } BOOL ThreadpoolMgr::GetAvailableThreads(DWORD* AvailableWorkerThreads, DWORD* AvailableIOCompletionThreads) { LIMITED_METHOD_CONTRACT; _ASSERTE(!UsePortableThreadPoolForIO()); if (!AvailableWorkerThreads || !AvailableIOCompletionThreads) { SetLastHRError(ERROR_INVALID_DATA); return FALSE; } EnsureInitialized(); if (UsePortableThreadPool()) { *AvailableWorkerThreads = 0; } else { ThreadCounter::Counts counts = WorkerCounter.GetCleanCounts(); if (MaxLimitTotalWorkerThreads < counts.NumActive) *AvailableWorkerThreads = 0; else *AvailableWorkerThreads = MaxLimitTotalWorkerThreads - counts.NumWorking; } ThreadCounter::Counts counts = CPThreadCounter.GetCleanCounts(); if (MaxLimitTotalCPThreads < counts.NumActive) *AvailableIOCompletionThreads = counts.NumActive - counts.NumWorking; else *AvailableIOCompletionThreads = MaxLimitTotalCPThreads - counts.NumWorking; return TRUE; } INT32 ThreadpoolMgr::GetThreadCount() { WRAPPER_NO_CONTRACT; _ASSERTE(!UsePortableThreadPoolForIO()); if (!IsInitialized()) { return 0; } INT32 workerThreadCount = UsePortableThreadPool() ? 0 : WorkerCounter.DangerousGetDirtyCounts().NumActive; return workerThreadCount + CPThreadCounter.DangerousGetDirtyCounts().NumActive; } void QueueUserWorkItemHelp(LPTHREAD_START_ROUTINE Function, PVOID Context) { STATIC_CONTRACT_THROWS; STATIC_CONTRACT_GC_TRIGGERS; STATIC_CONTRACT_MODE_ANY; /* Cannot use contract here because of SEH CONTRACTL { THROWS; GC_TRIGGERS; MODE_ANY; } CONTRACTL_END;*/ _ASSERTE(!ThreadpoolMgr::UsePortableThreadPool()); Function(Context); Thread *pThread = GetThreadNULLOk(); if (pThread) { _ASSERTE(!pThread->IsAbortRequested()); pThread->InternalReset(); } } // // WorkingThreadCounts tracks the number of worker threads currently doing user work, and the maximum number of such threads // since the last time TakeMaxWorkingThreadCount was called. This information is for diagnostic purposes only, // and is tracked only if the CLR config value INTERNAL_ThreadPool_EnableWorkerTracking is non-zero (this feature is off // by default). // union WorkingThreadCounts { struct { int currentWorking : 16; int maxWorking : 16; }; LONG asLong; }; WorkingThreadCounts g_workingThreadCounts; // // If worker tracking is enabled (see above) then this is called immediately before and after a worker thread executes // each work item. // void ThreadpoolMgr::ReportThreadStatus(bool isWorking) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; _ASSERTE(IsInitialized()); // can't be here without requesting a thread first _ASSERTE(CLRConfig::GetConfigValue(CLRConfig::INTERNAL_ThreadPool_EnableWorkerTracking)); while (true) { WorkingThreadCounts currentCounts, newCounts; currentCounts.asLong = VolatileLoad(&g_workingThreadCounts.asLong); newCounts = currentCounts; if (isWorking) newCounts.currentWorking++; if (newCounts.currentWorking > newCounts.maxWorking) newCounts.maxWorking = newCounts.currentWorking; if (!isWorking) newCounts.currentWorking--; if (currentCounts.asLong == InterlockedCompareExchange(&g_workingThreadCounts.asLong, newCounts.asLong, currentCounts.asLong)) break; } } // // Returns the max working count since the previous call to TakeMaxWorkingThreadCount, and resets WorkingThreadCounts.maxWorking. // int TakeMaxWorkingThreadCount() { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; _ASSERTE(CLRConfig::GetConfigValue(CLRConfig::INTERNAL_ThreadPool_EnableWorkerTracking)); while (true) { WorkingThreadCounts currentCounts, newCounts; currentCounts.asLong = VolatileLoad(&g_workingThreadCounts.asLong); newCounts = currentCounts; newCounts.maxWorking = 0; if (currentCounts.asLong == InterlockedCompareExchange(&g_workingThreadCounts.asLong, newCounts.asLong, currentCounts.asLong)) { // If we haven't updated the counts since the last call to TakeMaxWorkingThreadCount, then we never updated maxWorking. // In that case, the number of working threads for the whole period since the last TakeMaxWorkingThreadCount is the // current number of working threads. return currentCounts.maxWorking == 0 ? currentCounts.currentWorking : currentCounts.maxWorking; } } } /************************************************************************/ BOOL ThreadpoolMgr::QueueUserWorkItem(LPTHREAD_START_ROUTINE Function, PVOID Context, DWORD Flags, BOOL UnmanagedTPRequest) { CONTRACTL { THROWS; // EnsureInitialized, EnqueueWorkRequest can throw OOM GC_TRIGGERS; MODE_ANY; } CONTRACTL_END; _ASSERTE_ALL_BUILDS(__FILE__, !UsePortableThreadPool()); EnsureInitialized(); if (Flags == CALL_OR_QUEUE) { // we've been asked to call this directly if the thread pressure is not too high int MinimumAvailableCPThreads = (NumberOfProcessors < 3) ? 3 : NumberOfProcessors; ThreadCounter::Counts counts = CPThreadCounter.GetCleanCounts(); if ((MaxLimitTotalCPThreads - counts.NumActive) >= MinimumAvailableCPThreads ) { QueueUserWorkItemHelp(Function, Context); return TRUE; } } if (UnmanagedTPRequest) { UnManagedPerAppDomainTPCount* pADTPCount; pADTPCount = PerAppDomainTPCountList::GetUnmanagedTPCount(); pADTPCount->QueueUnmanagedWorkRequest(Function, Context); } else { // caller has already registered its TPCount; this call is just to adjust the thread count } return TRUE; } bool ThreadpoolMgr::ShouldWorkerKeepRunning() { WRAPPER_NO_CONTRACT; _ASSERTE(!UsePortableThreadPool()); // // Maybe this thread should retire now. Let's see. // bool shouldThisThreadKeepRunning = true; // Dirty read is OK here; the worst that can happen is that we won't retire this time. In the // case where we might retire, we have to succeed a CompareExchange, which will have the effect // of validating this read. ThreadCounter::Counts counts = WorkerCounter.DangerousGetDirtyCounts(); while (true) { if (counts.NumActive <= counts.MaxWorking) { shouldThisThreadKeepRunning = true; break; } ThreadCounter::Counts newCounts = counts; newCounts.NumWorking--; newCounts.NumActive--; newCounts.NumRetired++; ThreadCounter::Counts oldCounts = WorkerCounter.CompareExchangeCounts(newCounts, counts); if (oldCounts == counts) { shouldThisThreadKeepRunning = false; break; } counts = oldCounts; } return shouldThisThreadKeepRunning; } DangerousNonHostedSpinLock ThreadpoolMgr::ThreadAdjustmentLock; // // This method must only be called if ShouldAdjustMaxWorkersActive has returned true, *and* // ThreadAdjustmentLock is held. // void ThreadpoolMgr::AdjustMaxWorkersActive() { CONTRACTL { NOTHROW; if (GetThreadNULLOk()) { GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);} MODE_ANY; } CONTRACTL_END; _ASSERTE(!UsePortableThreadPool()); _ASSERTE(ThreadAdjustmentLock.IsHeld()); LARGE_INTEGER startTime = CurrentSampleStartTime; LARGE_INTEGER endTime; QueryPerformanceCounter(&endTime); static LARGE_INTEGER freq; if (freq.QuadPart == 0) QueryPerformanceFrequency(&freq); double elapsed = (double)(endTime.QuadPart - startTime.QuadPart) / freq.QuadPart; // // It's possible for the current sample to be reset while we're holding // ThreadAdjustmentLock. This will result in a very short sample, possibly // with completely bogus counts. We'll try to detect this by checking the sample // interval; if it's very short, then we try again later. // if (elapsed*1000.0 >= (ThreadAdjustmentInterval/2)) { DWORD currentTicks = GetTickCount(); LONG totalNumCompletions = (LONG)Thread::GetTotalWorkerThreadPoolCompletionCount(); LONG numCompletions = totalNumCompletions - VolatileLoad(&PriorCompletedWorkRequests); ThreadCounter::Counts currentCounts = WorkerCounter.GetCleanCounts(); int newMax = HillClimbingInstance.Update( currentCounts.MaxWorking, elapsed, numCompletions, &ThreadAdjustmentInterval); while (newMax != currentCounts.MaxWorking) { ThreadCounter::Counts newCounts = currentCounts; newCounts.MaxWorking = newMax; ThreadCounter::Counts oldCounts = WorkerCounter.CompareExchangeCounts(newCounts, currentCounts); if (oldCounts == currentCounts) { // // If we're increasing the max, inject a thread. If that thread finds work, it will inject // another thread, etc., until nobody finds work or we reach the new maximum. // // If we're reducing the max, whichever threads notice this first will retire themselves. // if (newMax > oldCounts.MaxWorking) MaybeAddWorkingWorker(); break; } else { // we failed - maybe try again if (oldCounts.MaxWorking > currentCounts.MaxWorking && oldCounts.MaxWorking >= newMax) { // someone (probably the gate thread) increased the thread count more than // we are about to do. Don't interfere. break; } currentCounts = oldCounts; } } PriorCompletedWorkRequests = totalNumCompletions; NextCompletedWorkRequestsTime = currentTicks + ThreadAdjustmentInterval; MemoryBarrier(); // flush previous writes (especially NextCompletedWorkRequestsTime) PriorCompletedWorkRequestsTime = currentTicks; CurrentSampleStartTime = endTime;; } } void ThreadpoolMgr::MaybeAddWorkingWorker() { CONTRACTL { NOTHROW; if (GetThreadNULLOk()) { GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);} MODE_ANY; } CONTRACTL_END; _ASSERTE(!UsePortableThreadPool()); // counts volatile read paired with CompareExchangeCounts loop set ThreadCounter::Counts counts = WorkerCounter.DangerousGetDirtyCounts(); ThreadCounter::Counts newCounts; while (true) { newCounts = counts; newCounts.NumWorking = max(counts.NumWorking, min(counts.NumWorking + 1, counts.MaxWorking)); newCounts.NumActive = max(counts.NumActive, newCounts.NumWorking); newCounts.NumRetired = max(0, counts.NumRetired - (newCounts.NumActive - counts.NumActive)); if (newCounts == counts) return; ThreadCounter::Counts oldCounts = WorkerCounter.CompareExchangeCounts(newCounts, counts); if (oldCounts == counts) break; counts = oldCounts; } int toUnretire = counts.NumRetired - newCounts.NumRetired; int toCreate = (newCounts.NumActive - counts.NumActive) - toUnretire; int toRelease = (newCounts.NumWorking - counts.NumWorking) - (toUnretire + toCreate); _ASSERTE(toUnretire >= 0); _ASSERTE(toCreate >= 0); _ASSERTE(toRelease >= 0); _ASSERTE(toUnretire + toCreate + toRelease <= 1); if (toUnretire > 0) { RetiredWorkerSemaphore->Release(toUnretire); } if (toRelease > 0) WorkerSemaphore->Release(toRelease); while (toCreate > 0) { if (CreateWorkerThread()) { toCreate--; } else { // // Uh-oh, we promised to create a new thread, but the creation failed. We have to renege on our // promise. This may possibly result in no work getting done for a while, but the gate thread will // eventually notice that no completions are happening and force the creation of a new thread. // Of course, there's no guarantee *that* will work - but hopefully enough time will have passed // to allow whoever's using all the memory right now to release some. // // counts volatile read paired with CompareExchangeCounts loop set counts = WorkerCounter.DangerousGetDirtyCounts(); while (true) { // // If we said we would create a thread, we also said it would be working. So we need to // decrement both NumWorking and NumActive by the number of threads we will no longer be creating. // newCounts = counts; newCounts.NumWorking -= toCreate; newCounts.NumActive -= toCreate; ThreadCounter::Counts oldCounts = WorkerCounter.CompareExchangeCounts(newCounts, counts); if (oldCounts == counts) break; counts = oldCounts; } toCreate = 0; } } } BOOL ThreadpoolMgr::PostQueuedCompletionStatus(LPOVERLAPPED lpOverlapped, LPOVERLAPPED_COMPLETION_ROUTINE Function) { CONTRACTL { THROWS; // EnsureInitialized can throw OOM GC_TRIGGERS; MODE_ANY; } CONTRACTL_END; _ASSERTE(!UsePortableThreadPoolForIO()); #ifndef TARGET_UNIX EnsureInitialized(); _ASSERTE(GlobalCompletionPort != NULL); if (!InitCompletionPortThreadpool) InitCompletionPortThreadpool = TRUE; GrowCompletionPortThreadpoolIfNeeded(); // In order to allow external ETW listeners to correlate activities that use our IO completion port // as a dispatch mechanism, we have to ensure the runtime's calls to ::PostQueuedCompletionStatus // and ::GetQueuedCompletionStatus are "annotated" with ETW events representing to operations // performed. // There are currently 2 codepaths that post to the GlobalCompletionPort: // 1. the managed API ThreadPool.UnsafeQueueNativeOverlapped(), calling CorPostQueuedCompletionStatus() // which already fires the ETW event as needed // 2. the managed API ThreadPool.RegisterWaitForSingleObject which needs to fire the ETW event // at the time the managed API is called (on the orignial user thread), and not when the ::PQCS // is called (from the dedicated wait thread). // If additional codepaths appear they need to either fire the ETW event before calling this or ensure // we do not fire an unmatched "dequeue" event in ThreadpoolMgr::CompletionPortThreadStart // The current possible values for Function: // - BindIoCompletionCallbackStub for ThreadPool.UnsafeQueueNativeOverlapped // - WaitIOCompletionCallback for ThreadPool.RegisterWaitForSingleObject return ::PostQueuedCompletionStatus(GlobalCompletionPort, 0, (ULONG_PTR) Function, lpOverlapped); #else SetLastError(ERROR_CALL_NOT_IMPLEMENTED); return FALSE; #endif // !TARGET_UNIX } void ThreadpoolMgr::WaitIOCompletionCallback( DWORD dwErrorCode, DWORD numBytesTransferred, LPOVERLAPPED lpOverlapped) { CONTRACTL { THROWS; MODE_ANY; } CONTRACTL_END; if (dwErrorCode == ERROR_SUCCESS) DWORD ret = AsyncCallbackCompletion((PVOID)lpOverlapped); } extern void WINAPI BindIoCompletionCallbackStub(DWORD ErrorCode, DWORD numBytesTransferred, LPOVERLAPPED lpOverlapped); // This is either made by a worker thread or a CP thread // indicated by threadTypeStatus void ThreadpoolMgr::EnsureGateThreadRunning() { LIMITED_METHOD_CONTRACT; _ASSERTE(!UsePortableThreadPoolForIO()); if (UsePortableThreadPool()) { GCX_COOP(); MethodDescCallSite(METHOD__THREAD_POOL__ENSURE_GATE_THREAD_RUNNING).Call(NULL); return; } while (true) { switch (GateThreadStatus) { case GATE_THREAD_STATUS_REQUESTED: // // No action needed; the gate thread is running, and someone else has already registered a request // for it to stay. // return; case GATE_THREAD_STATUS_WAITING_FOR_REQUEST: // // Prevent the gate thread from exiting, if it hasn't already done so. If it has, we'll create it on the next iteration of // this loop. // FastInterlockCompareExchange(&GateThreadStatus, GATE_THREAD_STATUS_REQUESTED, GATE_THREAD_STATUS_WAITING_FOR_REQUEST); break; case GATE_THREAD_STATUS_NOT_RUNNING: // // We need to create a new gate thread // if (FastInterlockCompareExchange(&GateThreadStatus, GATE_THREAD_STATUS_REQUESTED, GATE_THREAD_STATUS_NOT_RUNNING) == GATE_THREAD_STATUS_NOT_RUNNING) { if (!CreateGateThread()) { // // If we failed to create the gate thread, someone else will need to try again later. // GateThreadStatus = GATE_THREAD_STATUS_NOT_RUNNING; } return; } break; default: _ASSERTE(!"Invalid value of ThreadpoolMgr::GateThreadStatus"); } } } bool ThreadpoolMgr::NeedGateThreadForIOCompletions() { LIMITED_METHOD_CONTRACT; _ASSERTE(!UsePortableThreadPoolForIO()); if (!InitCompletionPortThreadpool) { return false; } ThreadCounter::Counts counts = CPThreadCounter.GetCleanCounts(); return counts.NumActive <= counts.NumWorking; } bool ThreadpoolMgr::ShouldGateThreadKeepRunning() { LIMITED_METHOD_CONTRACT; _ASSERTE(!UsePortableThreadPool()); _ASSERTE(GateThreadStatus == GATE_THREAD_STATUS_WAITING_FOR_REQUEST || GateThreadStatus == GATE_THREAD_STATUS_REQUESTED); // // Switch to WAITING_FOR_REQUEST, and see if we had a request since the last check. // LONG previousStatus = FastInterlockExchange(&GateThreadStatus, GATE_THREAD_STATUS_WAITING_FOR_REQUEST); if (previousStatus == GATE_THREAD_STATUS_WAITING_FOR_REQUEST) { // // No recent requests for the gate thread. Check to see if we're still needed. // // // Are there any free threads in the I/O completion pool? If there are, we don't need a gate thread. // This implies that whenever we decrement NumFreeCPThreads to 0, we need to call EnsureGateThreadRunning(). // bool needGateThreadForCompletionPort = NeedGateThreadForIOCompletions(); // // Are there any work requests in any worker queue? If so, we need a gate thread. // This imples that whenever a work queue goes from empty to non-empty, we need to call EnsureGateThreadRunning(). // bool needGateThreadForWorkerThreads = PerAppDomainTPCountList::AreRequestsPendingInAnyAppDomains(); // // If worker tracking is enabled, we need to fire periodic ETW events with active worker counts. This is // done by the gate thread. // We don't have to do anything special with EnsureGateThreadRunning() here, because this is only needed // once work has been added to the queue for the first time (which is covered above). // bool needGateThreadForWorkerTracking = 0 != CLRConfig::GetConfigValue(CLRConfig::INTERNAL_ThreadPool_EnableWorkerTracking); if (!(needGateThreadForCompletionPort || needGateThreadForWorkerThreads || needGateThreadForWorkerTracking)) { // // It looks like we shouldn't be running. But another thread may now tell us to run. If so, they will set GateThreadStatus // back to GATE_THREAD_STATUS_REQUESTED. // previousStatus = FastInterlockCompareExchange(&GateThreadStatus, GATE_THREAD_STATUS_NOT_RUNNING, GATE_THREAD_STATUS_WAITING_FOR_REQUEST); if (previousStatus == GATE_THREAD_STATUS_WAITING_FOR_REQUEST) return false; } } _ASSERTE(GateThreadStatus == GATE_THREAD_STATUS_WAITING_FOR_REQUEST || GateThreadStatus == GATE_THREAD_STATUS_REQUESTED); return true; } //************************************************************************ void ThreadpoolMgr::EnqueueWorkRequest(WorkRequest* workRequest) { CONTRACTL { NOTHROW; MODE_ANY; GC_NOTRIGGER; } CONTRACTL_END; _ASSERTE(!UsePortableThreadPool()); AppendWorkRequest(workRequest); } WorkRequest* ThreadpoolMgr::DequeueWorkRequest() { WorkRequest* entry = NULL; CONTRACT(WorkRequest*) { NOTHROW; GC_NOTRIGGER; MODE_PREEMPTIVE; POSTCONDITION(CheckPointer(entry, NULL_OK)); } CONTRACT_END; _ASSERTE(!UsePortableThreadPool()); entry = RemoveWorkRequest(); RETURN entry; } void ThreadpoolMgr::ExecuteWorkRequest(bool* foundWork, bool* wasNotRecalled) { CONTRACTL { THROWS; // QueueUserWorkItem can throw GC_TRIGGERS; MODE_PREEMPTIVE; } CONTRACTL_END; _ASSERTE(!UsePortableThreadPool()); IPerAppDomainTPCount* pAdCount; LONG index = PerAppDomainTPCountList::GetAppDomainIndexForThreadpoolDispatch(); if (index == 0) { *foundWork = false; *wasNotRecalled = true; return; } if (index == -1) { pAdCount = PerAppDomainTPCountList::GetUnmanagedTPCount(); } else { pAdCount = PerAppDomainTPCountList::GetPerAppdomainCount(TPIndex((DWORD)index)); _ASSERTE(pAdCount); } pAdCount->DispatchWorkItem(foundWork, wasNotRecalled); } //-------------------------------------------------------------------------- //This function informs the thread scheduler that the first requests has been //queued on an appdomain, or it's the first unmanaged TP request. //Arguments: // UnmanagedTP: Indicates that the request arises from the unmanaged //part of Thread Pool. //Assumptions: // This function must be called under a per-appdomain lock or the //correct lock under unmanaged TP queue. // BOOL ThreadpoolMgr::SetAppDomainRequestsActive(BOOL UnmanagedTP) { CONTRACTL { NOTHROW; MODE_ANY; GC_TRIGGERS; } CONTRACTL_END; _ASSERTE(!UsePortableThreadPool()); BOOL fShouldSignalEvent = FALSE; IPerAppDomainTPCount* pAdCount; if(UnmanagedTP) { pAdCount = PerAppDomainTPCountList::GetUnmanagedTPCount(); _ASSERTE(pAdCount); } else { Thread* pCurThread = GetThread(); AppDomain* pAppDomain = pCurThread->GetDomain(); _ASSERTE(pAppDomain); TPIndex tpindex = pAppDomain->GetTPIndex(); pAdCount = PerAppDomainTPCountList::GetPerAppdomainCount(tpindex); _ASSERTE(pAdCount); } pAdCount->SetAppDomainRequestsActive(); return fShouldSignalEvent; } void ThreadpoolMgr::ClearAppDomainRequestsActive(BOOL UnmanagedTP, LONG id) //-------------------------------------------------------------------------- //This function informs the thread scheduler that the kast request has been //dequeued on an appdomain, or it's the last unmanaged TP request. //Arguments: // UnmanagedTP: Indicates that the request arises from the unmanaged //part of Thread Pool. // id: Indicates the id of the appdomain. The id is needed as this //function can be called (indirectly) from the appdomain unload thread from //unmanaged code to clear per-appdomain state during rude unload. //Assumptions: // This function must be called under a per-appdomain lock or the //correct lock under unmanaged TP queue. // { CONTRACTL { NOTHROW; MODE_ANY; GC_TRIGGERS; } CONTRACTL_END; _ASSERTE(!UsePortableThreadPool()); IPerAppDomainTPCount* pAdCount; if(UnmanagedTP) { pAdCount = PerAppDomainTPCountList::GetUnmanagedTPCount(); _ASSERTE(pAdCount); } else { Thread* pCurThread = GetThread(); AppDomain* pAppDomain = pCurThread->GetDomain(); _ASSERTE(pAppDomain); TPIndex tpindex = pAppDomain->GetTPIndex(); pAdCount = PerAppDomainTPCountList::GetPerAppdomainCount(tpindex); _ASSERTE(pAdCount); } pAdCount->ClearAppDomainRequestsActive(); } // Remove a block from the appropriate recycleList and return. // If recycleList is empty, fall back to new. LPVOID ThreadpoolMgr::GetRecycledMemory(enum MemType memType) { LPVOID result = NULL; CONTRACT(LPVOID) { THROWS; GC_NOTRIGGER; MODE_ANY; INJECT_FAULT(COMPlusThrowOM()); POSTCONDITION(CheckPointer(result)); } CONTRACT_END; if(RecycledLists.IsInitialized()) { RecycledListInfo& list = RecycledLists.GetRecycleMemoryInfo( memType ); result = list.Remove(); } if(result == NULL) { switch (memType) { case MEMTYPE_DelegateInfo: result = new DelegateInfo; break; case MEMTYPE_AsyncCallback: result = new AsyncCallback; break; case MEMTYPE_WorkRequest: result = new WorkRequest; break; default: _ASSERTE(!"Unknown Memtype"); result = NULL; break; } } RETURN result; } // Insert freed block in recycle list. If list is full, return to system heap void ThreadpoolMgr::RecycleMemory(LPVOID mem, enum MemType memType) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; if(RecycledLists.IsInitialized()) { RecycledListInfo& list = RecycledLists.GetRecycleMemoryInfo( memType ); if(list.CanInsert()) { list.Insert( mem ); return; } } switch (memType) { case MEMTYPE_DelegateInfo: delete (DelegateInfo*) mem; break; case MEMTYPE_AsyncCallback: delete (AsyncCallback*) mem; break; case MEMTYPE_WorkRequest: delete (WorkRequest*) mem; break; default: _ASSERTE(!"Unknown Memtype"); } } Thread* ThreadpoolMgr::CreateUnimpersonatedThread(LPTHREAD_START_ROUTINE lpStartAddress, LPVOID lpArgs, BOOL *pIsCLRThread) { STATIC_CONTRACT_NOTHROW; if (GetThreadNULLOk()) { STATIC_CONTRACT_GC_TRIGGERS;} else {DISABLED(STATIC_CONTRACT_GC_NOTRIGGER);} STATIC_CONTRACT_MODE_ANY; /* cannot use contract because of SEH CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END;*/ Thread* pThread = NULL; if (g_fEEStarted) { *pIsCLRThread = TRUE; } else *pIsCLRThread = FALSE; if (*pIsCLRThread) { EX_TRY { pThread = SetupUnstartedThread(); } EX_CATCH { pThread = NULL; } EX_END_CATCH(SwallowAllExceptions); if (pThread == NULL) { return NULL; } } DWORD threadId; BOOL bOK = FALSE; HANDLE threadHandle = NULL; if (*pIsCLRThread) { // CreateNewThread takes care of reverting any impersonation - so dont do anything here. bOK = pThread->CreateNewThread(0, // default stack size lpStartAddress, lpArgs, //arguments W(".NET ThreadPool Worker")); } else { #ifndef TARGET_UNIX HandleHolder token; BOOL bReverted = FALSE; bOK = RevertIfImpersonated(&bReverted, &token); if (bOK != TRUE) return NULL; #endif // !TARGET_UNIX threadHandle = CreateThread(NULL, // security descriptor 0, // default stack size lpStartAddress, lpArgs, CREATE_SUSPENDED, &threadId); SetThreadName(threadHandle, W(".NET ThreadPool Worker")); #ifndef TARGET_UNIX UndoRevert(bReverted, token); #endif // !TARGET_UNIX } if (*pIsCLRThread && !bOK) { pThread->DecExternalCount(FALSE); pThread = NULL; } if (*pIsCLRThread) { return pThread; } else return (Thread*)threadHandle; } BOOL ThreadpoolMgr::CreateWorkerThread() { CONTRACTL { if (GetThreadNULLOk()) { GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);} NOTHROW; MODE_ANY; // We may try to add a worker thread while queuing a work item thru an fcall } CONTRACTL_END; _ASSERTE(!UsePortableThreadPool()); Thread *pThread; BOOL fIsCLRThread; if ((pThread = CreateUnimpersonatedThread(WorkerThreadStart, NULL, &fIsCLRThread)) != NULL) { if (fIsCLRThread) { pThread->ChooseThreadCPUGroupAffinity(); pThread->StartThread(); } else { DWORD status; status = ResumeThread((HANDLE)pThread); _ASSERTE(status != (DWORD) (-1)); CloseHandle((HANDLE)pThread); // we don't need this anymore } return TRUE; } return FALSE; } DWORD WINAPI ThreadpoolMgr::WorkerThreadStart(LPVOID lpArgs) { ClrFlsSetThreadType (ThreadType_Threadpool_Worker); CONTRACTL { THROWS; GC_TRIGGERS; MODE_PREEMPTIVE; } CONTRACTL_END; _ASSERTE_ALL_BUILDS(__FILE__, !UsePortableThreadPool()); Thread *pThread = NULL; DWORD dwSwitchCount = 0; BOOL fThreadInit = FALSE; ThreadCounter::Counts counts, oldCounts, newCounts; bool foundWork = true, wasNotRecalled = true; counts = WorkerCounter.GetCleanCounts(); if (ETW_EVENT_ENABLED(MICROSOFT_WINDOWS_DOTNETRUNTIME_PROVIDER_DOTNET_Context, ThreadPoolWorkerThreadStart)) FireEtwThreadPoolWorkerThreadStart(counts.NumActive, counts.NumRetired, GetClrInstanceId()); #ifdef FEATURE_COMINTEROP BOOL fCoInited = FALSE; // Threadpool threads should be initialized as MTA. If we are unable to do so, // return failure. { fCoInited = SUCCEEDED(::CoInitializeEx(NULL, COINIT_MULTITHREADED)); if (!fCoInited) { goto Exit; } } #endif // FEATURE_COMINTEROP Work: if (!fThreadInit) { if (g_fEEStarted) { pThread = SetupThreadNoThrow(); if (pThread == NULL) { __SwitchToThread(0, ++dwSwitchCount); goto Work; } // converted to CLRThread and added to ThreadStore, pick an group affinity for this thread pThread->ChooseThreadCPUGroupAffinity(); #ifdef FEATURE_COMINTEROP if (pThread->SetApartment(Thread::AS_InMTA) != Thread::AS_InMTA) { // counts volatile read paired with CompareExchangeCounts loop set counts = WorkerCounter.DangerousGetDirtyCounts(); while (true) { newCounts = counts; newCounts.NumActive--; newCounts.NumWorking--; oldCounts = WorkerCounter.CompareExchangeCounts(newCounts, counts); if (oldCounts == counts) break; counts = oldCounts; } goto Exit; } #endif // FEATURE_COMINTEROP pThread->SetBackground(TRUE); fThreadInit = TRUE; } } GCX_PREEMP_NO_DTOR(); _ASSERTE(pThread == NULL || !pThread->PreemptiveGCDisabled()); // make sure there's really work. If not, go back to sleep // counts volatile read paired with CompareExchangeCounts loop set counts = WorkerCounter.DangerousGetDirtyCounts(); while (true) { _ASSERTE(counts.NumActive > 0); _ASSERTE(counts.NumWorking > 0); newCounts = counts; bool retired; if (counts.NumActive > counts.MaxWorking) { newCounts.NumActive--; newCounts.NumRetired++; retired = true; } else { retired = false; if (foundWork) break; } newCounts.NumWorking--; oldCounts = WorkerCounter.CompareExchangeCounts(newCounts, counts); if (oldCounts == counts) { if (retired) goto Retire; else goto WaitForWork; } counts = oldCounts; } if (GCHeapUtilities::IsGCInProgress(TRUE)) { // GC is imminent, so wait until GC is complete before executing next request. // this reduces in-flight objects allocated right before GC, easing the GC's work GCHeapUtilities::WaitForGCCompletion(TRUE); } { ThreadpoolMgr::UpdateLastDequeueTime(); ThreadpoolMgr::ExecuteWorkRequest(&foundWork, &wasNotRecalled); } if (foundWork) { // Reset TLS etc. for next WorkRequest. if (pThread == NULL) pThread = GetThreadNULLOk(); if (pThread) { _ASSERTE(!pThread->IsAbortRequested()); pThread->InternalReset(); } } if (wasNotRecalled) goto Work; Retire: counts = WorkerCounter.GetCleanCounts(); FireEtwThreadPoolWorkerThreadRetirementStart(counts.NumActive, counts.NumRetired, GetClrInstanceId()); // It's possible that some work came in just before we decremented the active thread count, in which // case whoever queued that work may be expecting us to pick it up - so they would not have signalled // the worker semaphore. If there are other threads waiting, they will never be woken up, because // whoever queued the work expects that it's already been picked up. The solution is to signal the semaphore // if there's any work available. if (PerAppDomainTPCountList::AreRequestsPendingInAnyAppDomains()) MaybeAddWorkingWorker(); while (true) { RetryRetire: if (RetiredWorkerSemaphore->Wait(WorkerTimeout)) { foundWork = true; counts = WorkerCounter.GetCleanCounts(); FireEtwThreadPoolWorkerThreadRetirementStop(counts.NumActive, counts.NumRetired, GetClrInstanceId()); goto Work; } if (!IsIoPending()) { // // We're going to exit. There's a nasty race here. We're about to decrement NumRetired, // since we're going to exit. Once we've done that, nobody will expect this thread // to be waiting for RetiredWorkerSemaphore. But between now and then, other threads still // think we're waiting on the semaphore, and they will happily do the following to try to // wake us up: // // 1) Decrement NumRetired // 2) Increment NumActive // 3) Increment NumWorking // 4) Signal RetiredWorkerSemaphore // // We will not receive that signal. If we don't do something special here, // we will decrement NumRetired an extra time, and leave the world thinking there // are fewer retired threads, and more working threads than reality. // // What can we do about this? First, we *need* to decrement NumRetired. If someone did it before us, // it might go negative. This is the easiest way to tell that we've encountered this race. In that case, // we will simply not commit the decrement, swallow the signal that was sent, and proceed as if we // got WAIT_OBJECT_0 in the wait above. // // If we don't hit zero while decrementing NumRetired, we still may have encountered this race. But // if we don't hit zero, then there's another retired thread that will pick up this signal. So it's ok // to exit. // // counts volatile read paired with CompareExchangeCounts loop set counts = WorkerCounter.DangerousGetDirtyCounts(); while (true) { if (counts.NumRetired == 0) goto RetryRetire; newCounts = counts; newCounts.NumRetired--; oldCounts = WorkerCounter.CompareExchangeCounts(newCounts, counts); if (oldCounts == counts) { counts = newCounts; break; } counts = oldCounts; } FireEtwThreadPoolWorkerThreadRetirementStop(counts.NumActive, counts.NumRetired, GetClrInstanceId()); goto Exit; } } WaitForWork: // It's possible that we decided we had no work just before some work came in, // but reduced the worker count *after* the work came in. In this case, we might // miss the notification of available work. So we make a sweep through the ADs here, // and wake up a thread (maybe this one!) if there is work to do. if (PerAppDomainTPCountList::AreRequestsPendingInAnyAppDomains()) { foundWork = true; MaybeAddWorkingWorker(); } if (ETW_EVENT_ENABLED(MICROSOFT_WINDOWS_DOTNETRUNTIME_PROVIDER_DOTNET_Context, ThreadPoolWorkerThreadWait)) FireEtwThreadPoolWorkerThreadWait(counts.NumActive, counts.NumRetired, GetClrInstanceId()); RetryWaitForWork: if (WorkerSemaphore->Wait(WorkerTimeout, WorkerThreadSpinLimit, NumberOfProcessors)) { foundWork = true; goto Work; } if (!IsIoPending()) { // // We timed out, and are about to exit. This puts us in a very similar situation to the // retirement case above - someone may think we're still waiting, and go ahead and: // // 1) Increment NumWorking // 2) Signal WorkerSemaphore // // The solution is much like retirement; when we're decrementing NumActive, we need to make // sure it doesn't drop below NumWorking. If it would, then we need to go back and wait // again. // DangerousNonHostedSpinLockHolder tal(&ThreadAdjustmentLock); // counts volatile read paired with CompareExchangeCounts loop set counts = WorkerCounter.DangerousGetDirtyCounts(); while (true) { if (counts.NumActive == counts.NumWorking) { goto RetryWaitForWork; } newCounts = counts; newCounts.NumActive--; // if we timed out while active, then Hill Climbing needs to be told that we need fewer threads newCounts.MaxWorking = max(MinLimitTotalWorkerThreads, min(newCounts.NumActive, newCounts.MaxWorking)); oldCounts = WorkerCounter.CompareExchangeCounts(newCounts, counts); if (oldCounts == counts) { HillClimbingInstance.ForceChange(newCounts.MaxWorking, ThreadTimedOut); goto Exit; } counts = oldCounts; } } else { goto RetryWaitForWork; } Exit: #ifdef FEATURE_COMINTEROP if (pThread) { pThread->SetApartment(Thread::AS_Unknown); pThread->CoUninitialize(); } // Couninit the worker thread if (fCoInited) { CoUninitialize(); } #endif if (pThread) { pThread->ClearThreadCPUGroupAffinity(); DestroyThread(pThread); } _ASSERTE(!IsIoPending()); counts = WorkerCounter.GetCleanCounts(); if (ETW_EVENT_ENABLED(MICROSOFT_WINDOWS_DOTNETRUNTIME_PROVIDER_DOTNET_Context, ThreadPoolWorkerThreadStop)) FireEtwThreadPoolWorkerThreadStop(counts.NumActive, counts.NumRetired, GetClrInstanceId()); return ERROR_SUCCESS; } // this should only be called by unmanaged thread (i.e. there should be no mgd // caller on the stack) since we are swallowing terminal exceptions DWORD ThreadpoolMgr::SafeWait(CLREvent * ev, DWORD sleepTime, BOOL alertable) { STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_MODE_PREEMPTIVE; /* cannot use contract because of SEH CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_PREEMPTIVE; } CONTRACTL_END;*/ DWORD status = WAIT_TIMEOUT; EX_TRY { status = ev->Wait(sleepTime,FALSE); } EX_CATCH { } EX_END_CATCH(SwallowAllExceptions) return status; } /************************************************************************/ BOOL ThreadpoolMgr::RegisterWaitForSingleObject(PHANDLE phNewWaitObject, HANDLE hWaitObject, WAITORTIMERCALLBACK Callback, PVOID Context, ULONG timeout, DWORD dwFlag ) { CONTRACTL { THROWS; MODE_ANY; if (GetThreadNULLOk()) { GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);} } CONTRACTL_END; _ASSERTE(!UsePortableThreadPool()); EnsureInitialized(); ThreadCB* threadCB; { CrstHolder csh(&WaitThreadsCriticalSection); threadCB = FindWaitThread(); } *phNewWaitObject = NULL; if (threadCB) { WaitInfo* waitInfo = new (nothrow) WaitInfo; if (waitInfo == NULL) return FALSE; waitInfo->waitHandle = hWaitObject; waitInfo->Callback = Callback; waitInfo->Context = Context; waitInfo->timeout = timeout; waitInfo->flag = dwFlag; waitInfo->threadCB = threadCB; waitInfo->state = 0; waitInfo->refCount = 1; // safe to do this since no wait has yet been queued, so no other thread could be modifying this waitInfo->ExternalCompletionEvent = INVALID_HANDLE; waitInfo->ExternalEventSafeHandle = NULL; waitInfo->timer.startTime = GetTickCount(); waitInfo->timer.remainingTime = timeout; *phNewWaitObject = waitInfo; // We fire the "enqueue" ETW event here, to "mark" the thread that had called the API, rather than the // thread that will PostQueuedCompletionStatus (the dedicated WaitThread). // This event correlates with ThreadPoolIODequeue in ThreadpoolMgr::AsyncCallbackCompletion if (ETW_EVENT_ENABLED(MICROSOFT_WINDOWS_DOTNETRUNTIME_PROVIDER_DOTNET_Context, ThreadPoolIOEnqueue)) FireEtwThreadPoolIOEnqueue((LPOVERLAPPED)waitInfo, reinterpret_cast<void*>(Callback), (dwFlag & WAIT_SINGLE_EXECUTION) == 0, GetClrInstanceId()); BOOL status = QueueUserAPC((PAPCFUNC)InsertNewWaitForSelf, threadCB->threadHandle, (size_t) waitInfo); if (status == FALSE) { *phNewWaitObject = NULL; delete waitInfo; } return status; } return FALSE; } // Returns a wait thread that can accomodate another wait request. The // caller is responsible for synchronizing access to the WaitThreadsHead ThreadpoolMgr::ThreadCB* ThreadpoolMgr::FindWaitThread() { CONTRACTL { THROWS; // CreateWaitThread can throw MODE_ANY; GC_TRIGGERS; } CONTRACTL_END; _ASSERTE(!UsePortableThreadPool()); do { for (LIST_ENTRY* Node = (LIST_ENTRY*) WaitThreadsHead.Flink ; Node != &WaitThreadsHead ; Node = (LIST_ENTRY*)Node->Flink) { _ASSERTE(offsetof(WaitThreadInfo,link) == 0); ThreadCB* threadCB = ((WaitThreadInfo*) Node)->threadCB; if (threadCB->NumWaitHandles < MAX_WAITHANDLES) // this test and following ... { InterlockedIncrement(&threadCB->NumWaitHandles); // ... increment are protected by WaitThreadsCriticalSection. // but there might be a concurrent decrement in DeactivateWait // or InsertNewWaitForSelf, hence the interlock return threadCB; } } // if reached here, there are no wait threads available, so need to create a new one if (!CreateWaitThread()) return NULL; // Now loop back } while (TRUE); } BOOL ThreadpoolMgr::CreateWaitThread() { CONTRACTL { THROWS; // CLREvent::CreateAutoEvent can throw OOM GC_TRIGGERS; MODE_ANY; INJECT_FAULT(COMPlusThrowOM()); } CONTRACTL_END; _ASSERTE(!UsePortableThreadPool()); DWORD threadId; if (g_fEEShutDown & ShutDown_Finalize2){ // The process is shutting down. Shutdown thread has ThreadStore lock, // wait thread is blocked on the lock. return FALSE; } NewHolder<WaitThreadInfo> waitThreadInfo(new (nothrow) WaitThreadInfo); if (waitThreadInfo == NULL) return FALSE; NewHolder<ThreadCB> threadCB(new (nothrow) ThreadCB); if (threadCB == NULL) { return FALSE; } threadCB->startEvent.CreateAutoEvent(FALSE); HANDLE threadHandle = Thread::CreateUtilityThread(Thread::StackSize_Small, WaitThreadStart, (LPVOID)threadCB, W(".NET ThreadPool Wait"), CREATE_SUSPENDED, &threadId); if (threadHandle == NULL) { threadCB->startEvent.CloseEvent(); return FALSE; } waitThreadInfo.SuppressRelease(); threadCB.SuppressRelease(); threadCB->threadHandle = threadHandle; threadCB->threadId = threadId; // may be useful for debugging otherwise not used threadCB->NumWaitHandles = 0; threadCB->NumActiveWaits = 0; for (int i=0; i< MAX_WAITHANDLES; i++) { InitializeListHead(&(threadCB->waitPointer[i])); } waitThreadInfo->threadCB = threadCB; DWORD status = ResumeThread(threadHandle); { // We will QueueUserAPC on the newly created thread. // Let us wait until the thread starts running. GCX_PREEMP(); DWORD timeout=500; while (TRUE) { if (g_fEEShutDown & ShutDown_Finalize2){ // The process is shutting down. Shutdown thread has ThreadStore lock, // wait thread is blocked on the lock. return FALSE; } DWORD wait_status = threadCB->startEvent.Wait(timeout, FALSE); if (wait_status == WAIT_OBJECT_0) { break; } } } threadCB->startEvent.CloseEvent(); // check to see if setup succeeded if (threadCB->threadHandle == NULL) return FALSE; InsertHeadList(&WaitThreadsHead,&waitThreadInfo->link); _ASSERTE(status != (DWORD) (-1)); return (status != (DWORD) (-1)); } // Executed as an APC on a WaitThread. Add the wait specified in pArg to the list of objects it is waiting on void ThreadpoolMgr::InsertNewWaitForSelf(WaitInfo* pArgs) { WRAPPER_NO_CONTRACT; _ASSERTE(!UsePortableThreadPool()); WaitInfo* waitInfo = pArgs; // the following is safe since only this thread is allowed to change the state if (!(waitInfo->state & WAIT_DELETE)) { waitInfo->state = (WAIT_REGISTERED | WAIT_ACTIVE); } else { // some thread unregistered the wait DeleteWait(waitInfo); return; } ThreadCB* threadCB = waitInfo->threadCB; _ASSERTE(threadCB->NumActiveWaits <= threadCB->NumWaitHandles); int index = FindWaitIndex(threadCB, waitInfo->waitHandle); _ASSERTE(index >= 0 && index <= threadCB->NumActiveWaits); if (index == threadCB->NumActiveWaits) { threadCB->waitHandle[threadCB->NumActiveWaits] = waitInfo->waitHandle; threadCB->NumActiveWaits++; } else { // this is a duplicate waithandle, so the increment in FindWaitThread // wasn't strictly necessary. This will avoid unnecessary thread creation. InterlockedDecrement(&threadCB->NumWaitHandles); } _ASSERTE(offsetof(WaitInfo, link) == 0); InsertTailList(&(threadCB->waitPointer[index]), (&waitInfo->link)); return; } // returns the index of the entry that matches waitHandle or next free entry if not found int ThreadpoolMgr::FindWaitIndex(const ThreadCB* threadCB, const HANDLE waitHandle) { LIMITED_METHOD_CONTRACT; _ASSERTE(!UsePortableThreadPool()); for (int i=0;i<threadCB->NumActiveWaits; i++) if (threadCB->waitHandle[i] == waitHandle) return i; // else not found return threadCB->NumActiveWaits; } // if no wraparound that the timer is expired if duetime is less than current time // if wraparound occurred, then the timer expired if dueTime was greater than last time or dueTime is less equal to current time #define TimeExpired(last,now,duetime) ((last) <= (now) ? \ ((duetime) <= (now) && (duetime) >= (last)): \ ((duetime) >= (last) || (duetime) <= (now))) #define TimeInterval(end,start) ((end) > (start) ? ((end) - (start)) : ((0xffffffff - (start)) + (end) + 1)) // Returns the minimum of the remaining time to reach a timeout among all the waits DWORD ThreadpoolMgr::MinimumRemainingWait(LIST_ENTRY* waitInfo, unsigned int numWaits) { LIMITED_METHOD_CONTRACT; _ASSERTE(!UsePortableThreadPool()); unsigned int min = (unsigned int) -1; DWORD currentTime = GetTickCount(); for (unsigned i=0; i < numWaits ; i++) { WaitInfo* waitInfoPtr = (WaitInfo*) (waitInfo[i].Flink); PVOID waitInfoHead = &(waitInfo[i]); do { if (waitInfoPtr->timeout != INFINITE) { // compute remaining time DWORD elapsedTime = TimeInterval(currentTime,waitInfoPtr->timer.startTime ); __int64 remainingTime = (__int64) (waitInfoPtr->timeout) - (__int64) elapsedTime; // update remaining time waitInfoPtr->timer.remainingTime = remainingTime > 0 ? (int) remainingTime : 0; // ... and min if (waitInfoPtr->timer.remainingTime < min) min = waitInfoPtr->timer.remainingTime; } waitInfoPtr = (WaitInfo*) (waitInfoPtr->link.Flink); } while ((PVOID) waitInfoPtr != waitInfoHead); } return min; } #ifdef _MSC_VER #ifdef HOST_64BIT #pragma warning (disable : 4716) #else #pragma warning (disable : 4715) #endif #endif #ifdef _PREFAST_ #pragma warning(push) #pragma warning(disable:22008) // "Prefast integer overflow check on (0 + lval) is bogus. Tried local disable without luck, doing whole method." #endif DWORD WINAPI ThreadpoolMgr::WaitThreadStart(LPVOID lpArgs) { CONTRACTL { THROWS; GC_TRIGGERS; MODE_PREEMPTIVE; } CONTRACTL_END; ClrFlsSetThreadType (ThreadType_Wait); _ASSERTE_ALL_BUILDS(__FILE__, !UsePortableThreadPool()); ThreadCB* threadCB = (ThreadCB*) lpArgs; Thread* pThread = SetupThreadNoThrow(); if (pThread == NULL) { _ASSERTE(threadCB->threadHandle != NULL); threadCB->threadHandle = NULL; } threadCB->startEvent.Set(); if (pThread == NULL) { return 0; } { // wait threads never die. (Why?) for (;;) { DWORD status; DWORD timeout = 0; if (threadCB->NumActiveWaits == 0) { #undef SleepEx // <TODO>@TODO Consider doing a sleep for an idle period and terminating the thread if no activity</TODO> //We use SleepEx instead of CLRSLeepEx because CLRSleepEx calls into SQL(or other hosts) in hosted //scenarios. SQL does not deliver APC's, and the waithread wait insertion/deletion logic depends on //APC's being delivered. status = SleepEx(INFINITE,TRUE); #define SleepEx(a,b) Dont_Use_SleepEx(a,b) _ASSERTE(status == WAIT_IO_COMPLETION); } else if (IsWaitThreadAPCPending()) { //Do a sleep if an APC is pending, This was done to solve the corner case where the wait is signaled, //and APC to deregiter the wait never fires. That scenario leads to an infinite loop. This check would //allow the thread to enter alertable wait and thus cause the APC to fire. ResetWaitThreadAPCPending(); //We use SleepEx instead of CLRSLeepEx because CLRSleepEx calls into SQL(or other hosts) in hosted //scenarios. SQL does not deliver APC's, and the waithread wait insertion/deletion logic depends on //APC's being delivered. #undef SleepEx status = SleepEx(0,TRUE); #define SleepEx(a,b) Dont_Use_SleepEx(a,b) continue; } else { // compute minimum timeout. this call also updates the remainingTime field for each wait timeout = MinimumRemainingWait(threadCB->waitPointer,threadCB->NumActiveWaits); status = WaitForMultipleObjectsEx( threadCB->NumActiveWaits, threadCB->waitHandle, FALSE, // waitall timeout, TRUE ); // alertable _ASSERTE( (status == WAIT_TIMEOUT) || (status == WAIT_IO_COMPLETION) || //It could be that there are no waiters at this point, //as the APC to deregister the wait may have run. (status == WAIT_OBJECT_0) || (status >= WAIT_OBJECT_0 && status < (DWORD)(WAIT_OBJECT_0 + threadCB->NumActiveWaits)) || (status == WAIT_FAILED)); //It could be that the last waiter also got deregistered. if (threadCB->NumActiveWaits == 0) { continue; } } if (status == WAIT_IO_COMPLETION) continue; if (status == WAIT_TIMEOUT) { for (int i=0; i< threadCB->NumActiveWaits; i++) { WaitInfo* waitInfo = (WaitInfo*) (threadCB->waitPointer[i]).Flink; PVOID waitInfoHead = &(threadCB->waitPointer[i]); do { _ASSERTE(waitInfo->timer.remainingTime >= timeout); WaitInfo* wTemp = (WaitInfo*) waitInfo->link.Flink; if (waitInfo->timer.remainingTime == timeout) { ProcessWaitCompletion(waitInfo,i,TRUE); } waitInfo = wTemp; } while ((PVOID) waitInfo != waitInfoHead); } } else if (status >= WAIT_OBJECT_0 && status < (DWORD)(WAIT_OBJECT_0 + threadCB->NumActiveWaits)) { unsigned index = status - WAIT_OBJECT_0; WaitInfo* waitInfo = (WaitInfo*) (threadCB->waitPointer[index]).Flink; PVOID waitInfoHead = &(threadCB->waitPointer[index]); BOOL isAutoReset; // Setting to unconditional TRUE is inefficient since we will re-enter the wait and release // the next waiter, but short of using undocumented NT apis is the only solution. // Querying the state with a WaitForSingleObject is not an option as it will reset an // auto reset event if it has been signalled since the previous wait. isAutoReset = TRUE; do { WaitInfo* wTemp = (WaitInfo*) waitInfo->link.Flink; ProcessWaitCompletion(waitInfo,index,FALSE); waitInfo = wTemp; } while (((PVOID) waitInfo != waitInfoHead) && !isAutoReset); // If an app registers a recurring wait for an event that is always signalled (!), // then no apc's will be executed since the thread never enters the alertable state. // This can be fixed by doing the following: // SleepEx(0,TRUE); // However, it causes an unnecessary context switch. It is not worth penalizing well // behaved apps to protect poorly written apps. } else { _ASSERTE(status == WAIT_FAILED); // wait failed: application error // find out which wait handle caused the wait to fail for (int i = 0; i < threadCB->NumActiveWaits; i++) { DWORD subRet = WaitForSingleObject(threadCB->waitHandle[i], 0); if (subRet != WAIT_FAILED) continue; // remove all waits associated with this wait handle WaitInfo* waitInfo = (WaitInfo*) (threadCB->waitPointer[i]).Flink; PVOID waitInfoHead = &(threadCB->waitPointer[i]); do { WaitInfo* temp = (WaitInfo*) waitInfo->link.Flink; DeactivateNthWait(waitInfo,i); // Note, we cannot cleanup here since there is no way to suppress finalization // we will just leak, and rely on the finalizer to clean up the memory //if (InterlockedDecrement(&waitInfo->refCount) == 0) // DeleteWait(waitInfo); waitInfo = temp; } while ((PVOID) waitInfo != waitInfoHead); break; } } } } //This is unreachable...so no return required. } #ifdef _PREFAST_ #pragma warning(pop) #endif #ifdef _MSC_VER #ifdef HOST_64BIT #pragma warning (default : 4716) #else #pragma warning (default : 4715) #endif #endif void ThreadpoolMgr::ProcessWaitCompletion(WaitInfo* waitInfo, unsigned index, BOOL waitTimedOut ) { STATIC_CONTRACT_THROWS; STATIC_CONTRACT_GC_TRIGGERS; STATIC_CONTRACT_MODE_PREEMPTIVE; /* cannot use contract because of SEH CONTRACTL { THROWS; GC_TRIGGERS; MODE_PREEMPTIVE; } CONTRACTL_END;*/ AsyncCallback* asyncCallback = NULL; EX_TRY{ if ( waitInfo->flag & WAIT_SINGLE_EXECUTION) { DeactivateNthWait (waitInfo,index) ; } else { // reactivate wait by resetting timer waitInfo->timer.startTime = GetTickCount(); } asyncCallback = MakeAsyncCallback(); if (asyncCallback) { asyncCallback->wait = waitInfo; asyncCallback->waitTimedOut = waitTimedOut; InterlockedIncrement(&waitInfo->refCount); #ifndef TARGET_UNIX if (FALSE == PostQueuedCompletionStatus((LPOVERLAPPED)asyncCallback, (LPOVERLAPPED_COMPLETION_ROUTINE)WaitIOCompletionCallback)) #else // TARGET_UNIX if (FALSE == QueueUserWorkItem(AsyncCallbackCompletion, asyncCallback, QUEUE_ONLY)) #endif // !TARGET_UNIX ReleaseAsyncCallback(asyncCallback); } } EX_CATCH { if (asyncCallback) ReleaseAsyncCallback(asyncCallback); EX_RETHROW; } EX_END_CATCH(SwallowAllExceptions); } DWORD WINAPI ThreadpoolMgr::AsyncCallbackCompletion(PVOID pArgs) { CONTRACTL { THROWS; MODE_PREEMPTIVE; GC_TRIGGERS; } CONTRACTL_END; Thread * pThread = GetThreadNULLOk(); if (pThread == NULL) { HRESULT hr = ERROR_SUCCESS; ClrFlsSetThreadType(ThreadType_Threadpool_Worker); pThread = SetupThreadNoThrow(&hr); if (pThread == NULL) { return hr; } } { AsyncCallback * asyncCallback = (AsyncCallback*) pArgs; WaitInfo * waitInfo = asyncCallback->wait; AsyncCallbackHolder asyncCBHolder; asyncCBHolder.Assign(asyncCallback); // We fire the "dequeue" ETW event here, before executing the user code, to enable correlation with // the ThreadPoolIOEnqueue fired in ThreadpoolMgr::RegisterWaitForSingleObject if (ETW_EVENT_ENABLED(MICROSOFT_WINDOWS_DOTNETRUNTIME_PROVIDER_DOTNET_Context, ThreadPoolIODequeue)) FireEtwThreadPoolIODequeue(waitInfo, reinterpret_cast<void*>(waitInfo->Callback), GetClrInstanceId()); // the user callback can throw, the host must be prepared to handle it. // SQL is ok, since they have a top-level SEH handler. However, there's // no easy way to verify it ((WAITORTIMERCALLBACKFUNC) waitInfo->Callback) ( waitInfo->Context, asyncCallback->waitTimedOut != FALSE); #ifndef TARGET_UNIX Thread::IncrementIOThreadPoolCompletionCount(pThread); #endif } return ERROR_SUCCESS; } void ThreadpoolMgr::DeactivateWait(WaitInfo* waitInfo) { LIMITED_METHOD_CONTRACT; ThreadCB* threadCB = waitInfo->threadCB; DWORD endIndex = threadCB->NumActiveWaits-1; DWORD index; for (index = 0; index <= endIndex; index++) { LIST_ENTRY* head = &(threadCB->waitPointer[index]); LIST_ENTRY* current = head; do { if (current->Flink == (PVOID) waitInfo) goto FOUND; current = (LIST_ENTRY*) current->Flink; } while (current != head); } FOUND: _ASSERTE(index <= endIndex); DeactivateNthWait(waitInfo, index); } void ThreadpoolMgr::DeactivateNthWait(WaitInfo* waitInfo, DWORD index) { LIMITED_METHOD_CONTRACT; _ASSERTE(!UsePortableThreadPool()); ThreadCB* threadCB = waitInfo->threadCB; if (waitInfo->link.Flink != waitInfo->link.Blink) { RemoveEntryList(&(waitInfo->link)); } else { ULONG EndIndex = threadCB->NumActiveWaits -1; // Move the remaining ActiveWaitArray left. ShiftWaitArray( threadCB, index+1, index,EndIndex - index ) ; // repair the blink and flink of the first and last elements in the list for (unsigned int i = 0; i< EndIndex-index; i++) { WaitInfo* firstWaitInfo = (WaitInfo*) threadCB->waitPointer[index+i].Flink; WaitInfo* lastWaitInfo = (WaitInfo*) threadCB->waitPointer[index+i].Blink; firstWaitInfo->link.Blink = &(threadCB->waitPointer[index+i]); lastWaitInfo->link.Flink = &(threadCB->waitPointer[index+i]); } // initialize the entry just freed InitializeListHead(&(threadCB->waitPointer[EndIndex])); threadCB->NumActiveWaits-- ; InterlockedDecrement(&threadCB->NumWaitHandles); } waitInfo->state &= ~WAIT_ACTIVE ; } void ThreadpoolMgr::DeleteWait(WaitInfo* waitInfo) { CONTRACTL { if (waitInfo->ExternalEventSafeHandle != NULL) { THROWS;} else { NOTHROW; } MODE_ANY; if (GetThreadNULLOk()) {GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);} } CONTRACTL_END; if(waitInfo->Context && (waitInfo->flag & WAIT_FREE_CONTEXT)) { DelegateInfo* pDelegate = (DelegateInfo*) waitInfo->Context; // Since the delegate release destroys a handle, we need to be in // co-operative mode { GCX_COOP(); pDelegate->Release(); } RecycleMemory( pDelegate, MEMTYPE_DelegateInfo ); } if (waitInfo->flag & WAIT_INTERNAL_COMPLETION) { waitInfo->InternalCompletionEvent.Set(); return; // waitInfo will be deleted by the thread that's waiting on this event } else if (waitInfo->ExternalCompletionEvent != INVALID_HANDLE) { SetEvent(waitInfo->ExternalCompletionEvent); } else if (waitInfo->ExternalEventSafeHandle != NULL) { // Release the safe handle and the GC handle holding it ReleaseWaitInfo(waitInfo); } delete waitInfo; } /************************************************************************/ BOOL ThreadpoolMgr::UnregisterWaitEx(HANDLE hWaitObject,HANDLE Event) { CONTRACTL { THROWS; //NOTHROW; if (GetThreadNULLOk()) {GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);} MODE_ANY; } CONTRACTL_END; _ASSERTE(!UsePortableThreadPool()); _ASSERTE(IsInitialized()); // cannot call unregister before first registering const BOOL Blocking = (Event == (HANDLE) -1); WaitInfo* waitInfo = (WaitInfo*) hWaitObject; if (!hWaitObject) { return FALSE; } // we do not allow callbacks to run in the wait thread, hence the assert _ASSERTE(GetCurrentThreadId() != waitInfo->threadCB->threadId); if (Blocking) { waitInfo->InternalCompletionEvent.CreateAutoEvent(FALSE); waitInfo->flag |= WAIT_INTERNAL_COMPLETION; } else { waitInfo->ExternalCompletionEvent = (Event ? Event : INVALID_HANDLE); _ASSERTE((waitInfo->flag & WAIT_INTERNAL_COMPLETION) == 0); // we still want to block until the wait has been deactivated waitInfo->PartialCompletionEvent.CreateAutoEvent(FALSE); } BOOL status = QueueDeregisterWait(waitInfo->threadCB->threadHandle, waitInfo); if (status == 0) { STRESS_LOG1(LF_THREADPOOL, LL_ERROR, "Queue APC failed in UnregisterWaitEx %x", status); if (Blocking) waitInfo->InternalCompletionEvent.CloseEvent(); else waitInfo->PartialCompletionEvent.CloseEvent(); return FALSE; } if (!Blocking) { waitInfo->PartialCompletionEvent.Wait(INFINITE,TRUE); waitInfo->PartialCompletionEvent.CloseEvent(); // we cannot do DeleteWait in DeregisterWait, since the DeleteWait could happen before // we close the event. So, the code has been moved here. if (InterlockedDecrement(&waitInfo->refCount) == 0) { DeleteWait(waitInfo); } } else // i.e. blocking { _ASSERTE(waitInfo->flag & WAIT_INTERNAL_COMPLETION); _ASSERTE(waitInfo->ExternalEventSafeHandle == NULL); waitInfo->InternalCompletionEvent.Wait(INFINITE,TRUE); waitInfo->InternalCompletionEvent.CloseEvent(); delete waitInfo; // if WAIT_INTERNAL_COMPLETION is not set, waitInfo will be deleted in DeleteWait } return TRUE; } void ThreadpoolMgr::DeregisterWait(WaitInfo* pArgs) { WRAPPER_NO_CONTRACT; WaitInfo* waitInfo = pArgs; if ( ! (waitInfo->state & WAIT_REGISTERED) ) { // set state to deleted, so that it does not get registered waitInfo->state |= WAIT_DELETE ; // since the wait has not even been registered, we dont need an interlock to decrease the RefCount waitInfo->refCount--; if (waitInfo->PartialCompletionEvent.IsValid()) { waitInfo->PartialCompletionEvent.Set(); } return; } if (waitInfo->state & WAIT_ACTIVE) { DeactivateWait(waitInfo); } if ( waitInfo->PartialCompletionEvent.IsValid()) { waitInfo->PartialCompletionEvent.Set(); return; // we cannot delete the wait here since the PartialCompletionEvent // may not have been closed yet. so, we return and rely on the waiter of PartialCompletionEvent // to do the close } if (InterlockedDecrement(&waitInfo->refCount) == 0) { DeleteWait(waitInfo); } return; } /* This gets called in a finalizer thread ONLY IF an app does not deregister the the wait. Note that just because the registeredWaitHandle is collected by GC does not mean it is safe to delete the wait. The refcount tells us when it is safe. */ void ThreadpoolMgr::WaitHandleCleanup(HANDLE hWaitObject) { LIMITED_METHOD_CONTRACT; _ASSERTE(!UsePortableThreadPool()); _ASSERTE(IsInitialized()); // cannot call cleanup before first registering WaitInfo* waitInfo = (WaitInfo*) hWaitObject; _ASSERTE(waitInfo->refCount > 0); DWORD result = QueueDeregisterWait(waitInfo->threadCB->threadHandle, waitInfo); if (result == 0) STRESS_LOG1(LF_THREADPOOL, LL_ERROR, "Queue APC failed in WaitHandleCleanup %x", result); } BOOL ThreadpoolMgr::CreateGateThread() { LIMITED_METHOD_CONTRACT; _ASSERTE(!UsePortableThreadPool()); HANDLE threadHandle = Thread::CreateUtilityThread(Thread::StackSize_Small, GateThreadStart, NULL, W(".NET ThreadPool Gate")); if (threadHandle) { CloseHandle(threadHandle); //we don't need this anymore return TRUE; } return FALSE; } /************************************************************************/ BOOL ThreadpoolMgr::BindIoCompletionCallback(HANDLE FileHandle, LPOVERLAPPED_COMPLETION_ROUTINE Function, ULONG Flags, DWORD& errCode) { CONTRACTL { THROWS; // EnsureInitialized can throw if (GetThreadNULLOk()) { GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);} MODE_ANY; } CONTRACTL_END; _ASSERTE(!UsePortableThreadPoolForIO()); #ifndef TARGET_UNIX errCode = S_OK; EnsureInitialized(); _ASSERTE(GlobalCompletionPort != NULL); if (!InitCompletionPortThreadpool) InitCompletionPortThreadpool = TRUE; GrowCompletionPortThreadpoolIfNeeded(); HANDLE h = CreateIoCompletionPort(FileHandle, GlobalCompletionPort, (ULONG_PTR) Function, NumberOfProcessors); if (h == NULL) { errCode = GetLastError(); return FALSE; } _ASSERTE(h == GlobalCompletionPort); return TRUE; #else // TARGET_UNIX SetLastError(ERROR_CALL_NOT_IMPLEMENTED); return FALSE; #endif // !TARGET_UNIX } #ifndef TARGET_UNIX BOOL ThreadpoolMgr::CreateCompletionPortThread(LPVOID lpArgs) { CONTRACTL { NOTHROW; if (GetThreadNULLOk()) { GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);} MODE_ANY; } CONTRACTL_END; _ASSERTE(!UsePortableThreadPoolForIO()); Thread *pThread; BOOL fIsCLRThread; if ((pThread = CreateUnimpersonatedThread(CompletionPortThreadStart, lpArgs, &fIsCLRThread)) != NULL) { LastCPThreadCreation = GetTickCount(); // record this for use by logic to spawn additional threads if (fIsCLRThread) { pThread->ChooseThreadCPUGroupAffinity(); pThread->StartThread(); } else { DWORD status; status = ResumeThread((HANDLE)pThread); _ASSERTE(status != (DWORD) (-1)); CloseHandle((HANDLE)pThread); // we don't need this anymore } ThreadCounter::Counts counts = CPThreadCounter.GetCleanCounts(); FireEtwIOThreadCreate_V1(counts.NumActive + counts.NumRetired, counts.NumRetired, GetClrInstanceId()); return TRUE; } return FALSE; } DWORD WINAPI ThreadpoolMgr::CompletionPortThreadStart(LPVOID lpArgs) { ClrFlsSetThreadType (ThreadType_Threadpool_IOCompletion); CONTRACTL { THROWS; if (GetThreadNULLOk()) { MODE_PREEMPTIVE;} else { DISABLED(MODE_ANY);} if (GetThreadNULLOk()) { GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);} } CONTRACTL_END; _ASSERTE_ALL_BUILDS(__FILE__, !UsePortableThreadPoolForIO()); DWORD numBytes=0; size_t key=0; LPOVERLAPPED pOverlapped = NULL; DWORD errorCode; PIOCompletionContext context; BOOL fIsCompletionContext; const DWORD CP_THREAD_WAIT = 15000; /* milliseconds */ _ASSERTE(GlobalCompletionPort != NULL); BOOL fThreadInit = FALSE; Thread *pThread = NULL; DWORD cpThreadWait = 0; if (g_fEEStarted) { pThread = SetupThreadNoThrow(); if (pThread == NULL) { return 0; } // converted to CLRThread and added to ThreadStore, pick an group affinity for this thread pThread->ChooseThreadCPUGroupAffinity(); fThreadInit = TRUE; } #ifdef FEATURE_COMINTEROP // Threadpool threads should be initialized as MTA. If we are unable to do so, // return failure. BOOL fCoInited = FALSE; { fCoInited = SUCCEEDED(::CoInitializeEx(NULL, COINIT_MULTITHREADED)); if (!fCoInited) { goto Exit; } } if (pThread && pThread->SetApartment(Thread::AS_InMTA) != Thread::AS_InMTA) { // @todo: should we log the failure goto Exit; } #endif // FEATURE_COMINTEROP ThreadCounter::Counts oldCounts; ThreadCounter::Counts newCounts; cpThreadWait = CP_THREAD_WAIT; for (;; ) { Top: if (!fThreadInit) { if (g_fEEStarted) { pThread = SetupThreadNoThrow(); if (pThread == NULL) { break; } // converted to CLRThread and added to ThreadStore, pick an group affinity for this thread pThread->ChooseThreadCPUGroupAffinity(); #ifdef FEATURE_COMINTEROP if (pThread->SetApartment(Thread::AS_InMTA) != Thread::AS_InMTA) { // @todo: should we log the failure goto Exit; } #endif // FEATURE_COMINTEROP fThreadInit = TRUE; } } GCX_PREEMP_NO_DTOR(); // // We're about to wait on the IOCP; mark ourselves as no longer "working." // while (true) { ThreadCounter::Counts oldCounts = CPThreadCounter.DangerousGetDirtyCounts(); ThreadCounter::Counts newCounts = oldCounts; newCounts.NumWorking--; // // If we've only got one thread left, it won't be allowed to exit, because we need to keep // one thread listening for completions. So there's no point in having a timeout; it will // only use power unnecessarily. // cpThreadWait = (newCounts.NumActive == 1) ? INFINITE : CP_THREAD_WAIT; if (oldCounts == CPThreadCounter.CompareExchangeCounts(newCounts, oldCounts)) break; } errorCode = S_OK; if (lpArgs == NULL) { CONTRACT_VIOLATION(ThrowsViolation); context = NULL; fIsCompletionContext = FALSE; if (pThread == NULL) { pThread = GetThreadNULLOk(); } if (pThread) { context = (PIOCompletionContext) pThread->GetIOCompletionContext(); if (context->lpOverlapped != NULL) { errorCode = context->ErrorCode; numBytes = context->numBytesTransferred; pOverlapped = context->lpOverlapped; key = context->key; context->lpOverlapped = NULL; fIsCompletionContext = TRUE; } } if((context == NULL) || (!fIsCompletionContext)) { _ASSERTE (context == NULL || context->lpOverlapped == NULL); BOOL status = GetQueuedCompletionStatus( GlobalCompletionPort, &numBytes, (PULONG_PTR)&key, &pOverlapped, cpThreadWait ); if (status == 0) errorCode = GetLastError(); } } else { QueuedStatus *CompletionStatus = (QueuedStatus*)lpArgs; numBytes = CompletionStatus->numBytes; key = (size_t)CompletionStatus->key; pOverlapped = CompletionStatus->pOverlapped; errorCode = CompletionStatus->errorCode; delete CompletionStatus; lpArgs = NULL; // one-time deal for initial CP packet } // We fire IODequeue events whether the IO completion was retrieved in the above call to // GetQueuedCompletionStatus or during an earlier call (e.g. in GateThreadStart, and passed here in lpArgs, // or in CompletionPortDispatchWorkWithinAppDomain, and passed here through StoreOverlappedInfoInThread) // For the purposes of activity correlation we only fire ETW events here, if needed OR if not fired at a higher // abstraction level (e.g. ThreadpoolMgr::RegisterWaitForSingleObject) // Note: we still fire the event for managed async IO, despite the fact we don't have a paired IOEnqueue event // for this case. We do this to "mark" the end of the previous workitem. When we provide full support at the higher // abstraction level for managed IO we can remove the IODequeues fired here if (ETW_EVENT_ENABLED(MICROSOFT_WINDOWS_DOTNETRUNTIME_PROVIDER_DOTNET_Context, ThreadPoolIODequeue) && !AreEtwIOQueueEventsSpeciallyHandled((LPOVERLAPPED_COMPLETION_ROUTINE)key) && pOverlapped != NULL) { FireEtwThreadPoolIODequeue(pOverlapped, OverlappedDataObject::GetOverlappedForTracing(pOverlapped), GetClrInstanceId()); } bool enterRetirement; while (true) { // // When we reach this point, this thread is "active" but not "working." Depending on the result of the call to GetQueuedCompletionStatus, // and the state of the rest of the IOCP threads, we need to figure out whether to de-activate (exit) this thread, retire this thread, // or transition to "working." // // counts volatile read paired with CompareExchangeCounts loop set oldCounts = CPThreadCounter.DangerousGetDirtyCounts(); newCounts = oldCounts; enterRetirement = false; if (errorCode == WAIT_TIMEOUT) { // // We timed out, and are going to try to exit or retire. // newCounts.NumActive--; // // We need at least one free thread, or we have no way of knowing if completions are being queued. // if (newCounts.NumWorking == newCounts.NumActive) { newCounts = oldCounts; newCounts.NumWorking++; //not really working, but we'll decremented it at the top if (oldCounts == CPThreadCounter.CompareExchangeCounts(newCounts, oldCounts)) goto Top; else continue; } // // We can't exit a thread that has pending I/O - we'll "retire" it instead. // if (IsIoPending()) { enterRetirement = true; newCounts.NumRetired++; } } else { // // We have work to do // newCounts.NumWorking++; } if (oldCounts == CPThreadCounter.CompareExchangeCounts(newCounts, oldCounts)) break; } if (errorCode == WAIT_TIMEOUT) { if (!enterRetirement) { goto Exit; } else { // now in "retired mode" waiting for pending io to complete FireEtwIOThreadRetire_V1(newCounts.NumActive + newCounts.NumRetired, newCounts.NumRetired, GetClrInstanceId()); for (;;) { DWORD status = SafeWait(RetiredCPWakeupEvent,CP_THREAD_PENDINGIO_WAIT,FALSE); _ASSERTE(status == WAIT_TIMEOUT || status == WAIT_OBJECT_0); if (status == WAIT_TIMEOUT) { if (IsIoPending()) { continue; } else { // We can now exit; decrement the retired count. while (true) { // counts volatile read paired with CompareExchangeCounts loop set oldCounts = CPThreadCounter.DangerousGetDirtyCounts(); newCounts = oldCounts; newCounts.NumRetired--; if (oldCounts == CPThreadCounter.CompareExchangeCounts(newCounts, oldCounts)) break; } goto Exit; } } else { // put back into rotation -- we need a thread while (true) { // counts volatile read paired with CompareExchangeCounts loop set oldCounts = CPThreadCounter.DangerousGetDirtyCounts(); newCounts = oldCounts; newCounts.NumRetired--; newCounts.NumActive++; newCounts.NumWorking++; //we're not really working, but we'll decrement this before waiting for work. if (oldCounts == CPThreadCounter.CompareExchangeCounts(newCounts, oldCounts)) break; } FireEtwIOThreadUnretire_V1(newCounts.NumActive + newCounts.NumRetired, newCounts.NumRetired, GetClrInstanceId()); goto Top; } } } } // we should not reach this point unless we have work to do _ASSERTE(errorCode != WAIT_TIMEOUT && !enterRetirement); // if we have no more free threads, start the gate thread if (newCounts.NumWorking >= newCounts.NumActive) EnsureGateThreadRunning(); // We can not assert here. If stdin/stdout/stderr of child process are redirected based on // async io, GetQueuedCompletionStatus returns when child process operates on its stdin/stdout/stderr. // Parent process does not issue any ReadFile/WriteFile, and hence pOverlapped is going to be NULL. //_ASSERTE(pOverlapped != NULL); if (pOverlapped != NULL) { _ASSERTE(key != 0); // should be a valid function address if (key != 0) { if (GCHeapUtilities::IsGCInProgress(TRUE)) { //Indicate that this thread is free, and waiting on GC, not doing any user work. //This helps in threads not getting injected when some threads have woken up from the //GC event, and some have not. while (true) { // counts volatile read paired with CompareExchangeCounts loop set oldCounts = CPThreadCounter.DangerousGetDirtyCounts(); newCounts = oldCounts; newCounts.NumWorking--; if (oldCounts == CPThreadCounter.CompareExchangeCounts(newCounts, oldCounts)) break; } // GC is imminent, so wait until GC is complete before executing next request. // this reduces in-flight objects allocated right before GC, easing the GC's work GCHeapUtilities::WaitForGCCompletion(TRUE); while (true) { // counts volatile read paired with CompareExchangeCounts loop set oldCounts = CPThreadCounter.DangerousGetDirtyCounts(); newCounts = oldCounts; newCounts.NumWorking++; if (oldCounts == CPThreadCounter.CompareExchangeCounts(newCounts, oldCounts)) break; } if (newCounts.NumWorking >= newCounts.NumActive) EnsureGateThreadRunning(); } else { GrowCompletionPortThreadpoolIfNeeded(); } { CONTRACT_VIOLATION(ThrowsViolation); ((LPOVERLAPPED_COMPLETION_ROUTINE) key)(errorCode, numBytes, pOverlapped); } Thread::IncrementIOThreadPoolCompletionCount(pThread); if (pThread == NULL) { pThread = GetThreadNULLOk(); } if (pThread) { _ASSERTE(!pThread->IsAbortRequested()); pThread->InternalReset(); } } else { // Application bug - can't do much, just ignore it } } } // for (;;) Exit: oldCounts = CPThreadCounter.GetCleanCounts(); // we should never destroy or retire all IOCP threads, because then we won't have any threads to notice incoming completions. _ASSERTE(oldCounts.NumActive > 0); FireEtwIOThreadTerminate_V1(oldCounts.NumActive + oldCounts.NumRetired, oldCounts.NumRetired, GetClrInstanceId()); #ifdef FEATURE_COMINTEROP if (pThread) { pThread->SetApartment(Thread::AS_Unknown); pThread->CoUninitialize(); } // Couninit the worker thread if (fCoInited) { CoUninitialize(); } #endif if (pThread) { pThread->ClearThreadCPUGroupAffinity(); DestroyThread(pThread); } return 0; } LPOVERLAPPED ThreadpoolMgr::CompletionPortDispatchWorkWithinAppDomain( Thread* pThread, DWORD* pErrorCode, DWORD* pNumBytes, size_t* pKey) // //This function is called just after dispatching the previous BindIO callback //to Managed code. This is a perf optimization to do a quick call to //GetQueuedCompletionStatus with a timeout of 0 ms. If there is work in the //same appdomain, dispatch it back immediately. If not stick it in a well known //place, and reenter the target domain. The timeout of zero is chosen so as to //not delay appdomain unloads. // { STATIC_CONTRACT_THROWS; STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_MODE_ANY; LPOVERLAPPED lpOverlapped=NULL; BOOL status=FALSE; OVERLAPPEDDATAREF overlapped=NULL; BOOL ManagedCallback=FALSE; *pErrorCode = S_OK; //Very Very Important! //Do not change the timeout for GetQueuedCompletionStatus to a non-zero value. //Selecting a non-zero value can cause the thread to block, and lead to expensive context switches. //In real life scenarios, we have noticed a packet to be not available immediately, but very shortly //(after few 100's of instructions), and falling back to the VM is good in that case as compared to //taking a context switch. Changing the timeout to non-zero can lead to perf degrades, that are very //hard to diagnose. status = ::GetQueuedCompletionStatus( GlobalCompletionPort, pNumBytes, (PULONG_PTR)pKey, &lpOverlapped, 0); DWORD lastError = GetLastError(); if (status == 0) { if (lpOverlapped != NULL) { *pErrorCode = lastError; } else { return NULL; } } if (((LPOVERLAPPED_COMPLETION_ROUTINE) *pKey) != BindIoCompletionCallbackStub) { //_ASSERTE(FALSE); } else { ManagedCallback = TRUE; overlapped = ObjectToOVERLAPPEDDATAREF(OverlappedDataObject::GetOverlapped(lpOverlapped)); } if (ManagedCallback) { _ASSERTE(*pKey != 0); // should be a valid function address if (*pKey ==0) { //Application Bug. return NULL; } } else { //Just retruned back from managed code, a Thread structure should exist. _ASSERTE (pThread); //Oops, this is an overlapped fom a different appdomain. STick it in //the thread. We will process it later. StoreOverlappedInfoInThread(pThread, *pErrorCode, *pNumBytes, *pKey, lpOverlapped); lpOverlapped = NULL; } #ifndef DACCESS_COMPILE return lpOverlapped; #endif } void ThreadpoolMgr::StoreOverlappedInfoInThread(Thread* pThread, DWORD dwErrorCode, DWORD dwNumBytes, size_t key, LPOVERLAPPED lpOverlapped) { STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_MODE_ANY; _ASSERTE(pThread); PIOCompletionContext context; context = (PIOCompletionContext) pThread->GetIOCompletionContext(); _ASSERTE(context); context->ErrorCode = dwErrorCode; context->numBytesTransferred = dwNumBytes; context->lpOverlapped = lpOverlapped; context->key = key; } BOOL ThreadpoolMgr::ShouldGrowCompletionPortThreadpool(ThreadCounter::Counts counts) { CONTRACTL { GC_NOTRIGGER; NOTHROW; MODE_ANY; } CONTRACTL_END; _ASSERTE(!UsePortableThreadPoolForIO()); if (counts.NumWorking >= counts.NumActive && (counts.NumActive == 0 || !GCHeapUtilities::IsGCInProgress(TRUE)) ) { // adjust limit if needed if (counts.NumRetired == 0) { if (counts.NumActive + counts.NumRetired < MaxLimitTotalCPThreads && (counts.NumActive < MinLimitTotalCPThreads || cpuUtilization < CpuUtilizationLow)) { // add one more check to make sure that we haven't fired off a new // thread since the last time time we checked the cpu utilization. // However, don't bother if we haven't reached the MinLimit (2*number of cpus) if ((counts.NumActive < MinLimitTotalCPThreads) || SufficientDelaySinceLastSample(LastCPThreadCreation,counts.NumActive)) { return TRUE; } } } if (counts.NumRetired > 0) return TRUE; } return FALSE; } void ThreadpoolMgr::GrowCompletionPortThreadpoolIfNeeded() { CONTRACTL { if (GetThreadNULLOk()) { GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);} NOTHROW; MODE_ANY; } CONTRACTL_END; _ASSERTE(!UsePortableThreadPoolForIO()); ThreadCounter::Counts oldCounts, newCounts; while (true) { oldCounts = CPThreadCounter.GetCleanCounts(); newCounts = oldCounts; if(!ShouldGrowCompletionPortThreadpool(oldCounts)) { break; } else { if (oldCounts.NumRetired > 0) { // wakeup retired thread instead RetiredCPWakeupEvent->Set(); return; } else { // create a new thread. New IOCP threads start as "active" and "working" newCounts.NumActive++; newCounts.NumWorking++; if (oldCounts == CPThreadCounter.CompareExchangeCounts(newCounts, oldCounts)) { if (!CreateCompletionPortThread(NULL)) { // if thread creation failed, we have to adjust the counts back down. while (true) { // counts volatile read paired with CompareExchangeCounts loop set oldCounts = CPThreadCounter.DangerousGetDirtyCounts(); newCounts = oldCounts; newCounts.NumActive--; newCounts.NumWorking--; if (oldCounts == CPThreadCounter.CompareExchangeCounts(newCounts, oldCounts)) break; } } return; } } } } } #endif // !TARGET_UNIX // Returns true if there is pending io on the thread. BOOL ThreadpoolMgr::IsIoPending() { CONTRACTL { NOTHROW; MODE_ANY; GC_NOTRIGGER; } CONTRACTL_END; #ifndef TARGET_UNIX int Status; ULONG IsIoPending; if (g_pufnNtQueryInformationThread) { Status =(int) (*g_pufnNtQueryInformationThread)(GetCurrentThread(), ThreadIsIoPending, &IsIoPending, sizeof(IsIoPending), NULL); if ((Status < 0) || IsIoPending) return TRUE; else return FALSE; } return TRUE; #else return FALSE; #endif // !TARGET_UNIX } #ifndef TARGET_UNIX #ifdef HOST_64BIT #pragma warning (disable : 4716) #else #pragma warning (disable : 4715) #endif int ThreadpoolMgr::GetCPUBusyTime_NT(PROCESS_CPU_INFORMATION* pOldInfo) { LIMITED_METHOD_CONTRACT; PROCESS_CPU_INFORMATION newUsage; newUsage.idleTime.QuadPart = 0; newUsage.kernelTime.QuadPart = 0; newUsage.userTime.QuadPart = 0; if (CPUGroupInfo::CanEnableThreadUseAllCpuGroups()) { #if !defined(FEATURE_REDHAWK) && !defined(TARGET_UNIX) FILETIME newIdleTime, newKernelTime, newUserTime; CPUGroupInfo::GetSystemTimes(&newIdleTime, &newKernelTime, &newUserTime); newUsage.idleTime.u.LowPart = newIdleTime.dwLowDateTime; newUsage.idleTime.u.HighPart = newIdleTime.dwHighDateTime; newUsage.kernelTime.u.LowPart = newKernelTime.dwLowDateTime; newUsage.kernelTime.u.HighPart = newKernelTime.dwHighDateTime; newUsage.userTime.u.LowPart = newUserTime.dwLowDateTime; newUsage.userTime.u.HighPart = newUserTime.dwHighDateTime; #endif } else { (*g_pufnNtQuerySystemInformation)(SystemProcessorPerformanceInformation, pOldInfo->usageBuffer, pOldInfo->usageBufferSize, NULL); SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION* pInfoArray = pOldInfo->usageBuffer; DWORD_PTR pmask = pOldInfo->affinityMask; int proc_no = 0; while (pmask) { if (pmask & 1) { //should be good: 1CPU 28823 years, 256CPUs 100+years newUsage.idleTime.QuadPart += pInfoArray[proc_no].IdleTime.QuadPart; newUsage.kernelTime.QuadPart += pInfoArray[proc_no].KernelTime.QuadPart; newUsage.userTime.QuadPart += pInfoArray[proc_no].UserTime.QuadPart; } pmask >>=1; proc_no++; } } __int64 cpuTotalTime, cpuBusyTime; cpuTotalTime = (newUsage.userTime.QuadPart - pOldInfo->userTime.QuadPart) + (newUsage.kernelTime.QuadPart - pOldInfo->kernelTime.QuadPart); cpuBusyTime = cpuTotalTime - (newUsage.idleTime.QuadPart - pOldInfo->idleTime.QuadPart); // Preserve reading pOldInfo->idleTime = newUsage.idleTime; pOldInfo->kernelTime = newUsage.kernelTime; pOldInfo->userTime = newUsage.userTime; __int64 reading = 0; if (cpuTotalTime > 0) reading = ((cpuBusyTime * 100) / cpuTotalTime); _ASSERTE(FitsIn<int>(reading)); return (int)reading; } #else // !TARGET_UNIX int ThreadpoolMgr::GetCPUBusyTime_NT(PAL_IOCP_CPU_INFORMATION* pOldInfo) { return PAL_GetCPUBusyTime(pOldInfo); } #endif // !TARGET_UNIX // // A timer that ticks every GATE_THREAD_DELAY milliseconds. // On platforms that support it, we use a coalescable waitable timer object. // For other platforms, we use Sleep, via __SwitchToThread. // class GateThreadTimer { #ifndef TARGET_UNIX HANDLE m_hTimer; public: GateThreadTimer() : m_hTimer(NULL) { CONTRACTL { NOTHROW; MODE_PREEMPTIVE; } CONTRACTL_END; if (g_pufnCreateWaitableTimerEx && g_pufnSetWaitableTimerEx) { m_hTimer = g_pufnCreateWaitableTimerEx(NULL, NULL, 0, TIMER_ALL_ACCESS); if (m_hTimer) { // // Set the timer to fire GATE_THREAD_DELAY milliseconds from now, then every GATE_THREAD_DELAY milliseconds thereafter. // We also set the tolerance to GET_THREAD_DELAY_TOLERANCE, allowing the OS to coalesce this timer. // LARGE_INTEGER dueTime; dueTime.QuadPart = MILLI_TO_100NANO(-(LONGLONG)GATE_THREAD_DELAY); //negative value indicates relative time if (!g_pufnSetWaitableTimerEx(m_hTimer, &dueTime, GATE_THREAD_DELAY, NULL, NULL, NULL, GATE_THREAD_DELAY_TOLERANCE)) { CloseHandle(m_hTimer); m_hTimer = NULL; } } } } ~GateThreadTimer() { CONTRACTL { NOTHROW; MODE_PREEMPTIVE; } CONTRACTL_END; if (m_hTimer) { CloseHandle(m_hTimer); m_hTimer = NULL; } } #endif // !TARGET_UNIX public: void Wait() { CONTRACTL { NOTHROW; MODE_PREEMPTIVE; } CONTRACTL_END; #ifndef TARGET_UNIX if (m_hTimer) WaitForSingleObject(m_hTimer, INFINITE); else #endif // !TARGET_UNIX __SwitchToThread(GATE_THREAD_DELAY, CALLER_LIMITS_SPINNING); } }; DWORD WINAPI ThreadpoolMgr::GateThreadStart(LPVOID lpArgs) { ClrFlsSetThreadType (ThreadType_Gate); CONTRACTL { NOTHROW; GC_TRIGGERS; MODE_PREEMPTIVE; } CONTRACTL_END; _ASSERTE(!UsePortableThreadPool()); _ASSERTE(GateThreadStatus == GATE_THREAD_STATUS_REQUESTED); GateThreadTimer timer; // TODO: do we need to do this? timer.Wait(); // delay getting initial CPU reading #ifndef TARGET_UNIX PROCESS_CPU_INFORMATION prevCPUInfo; if (!g_pufnNtQuerySystemInformation) { _ASSERT(!"NtQuerySystemInformation API not available!"); return 0; } #ifndef TARGET_UNIX //GateThread can start before EESetup, so ensure CPU group information is initialized; CPUGroupInfo::EnsureInitialized(); #endif // !TARGET_UNIX // initialize CPU usage information structure; prevCPUInfo.idleTime.QuadPart = 0; prevCPUInfo.kernelTime.QuadPart = 0; prevCPUInfo.userTime.QuadPart = 0; PREFIX_ASSUME(NumberOfProcessors < 65536); prevCPUInfo.numberOfProcessors = NumberOfProcessors; /* In following cases, affinity mask can be zero * 1. hosted, the hosted process already uses multiple cpu groups. * thus, during CLR initialization, GetCurrentProcessCpuCount() returns 64, and GC threads * are created to fill up the initial CPU group. ==> use g_SystemInfo.dwNumberOfProcessors * 2. GCCpuGroups=1, CLR creates GC threads for all processors in all CPU groups * thus, the threadpool thread would use a whole CPU group (if Thread_UseAllCpuGroups is not set). * ==> use g_SystemInfo.dwNumberOfProcessors. * 3. !defined(TARGET_UNIX), GetCurrentProcessCpuCount() * returns g_SystemInfo.dwNumberOfProcessors ==> use g_SystemInfo.dwNumberOfProcessors; * Other cases: * 1. Normal case: the mask is all or a subset of all processors in a CPU group; * 2. GCCpuGroups=1 && Thread_UseAllCpuGroups = 1, the mask is not used */ prevCPUInfo.affinityMask = GetCurrentProcessCpuMask(); if (prevCPUInfo.affinityMask == 0) { // create a mask that has g_SystemInfo.dwNumberOfProcessors; DWORD_PTR mask = 0, maskpos = 1; for (unsigned int i=0; i < g_SystemInfo.dwNumberOfProcessors; i++) { mask |= maskpos; maskpos <<= 1; } prevCPUInfo.affinityMask = mask; } // in some cases GetCurrentProcessCpuCount() returns a number larger than // g_SystemInfo.dwNumberOfProcessor when there are CPU groups, use the larger // one to create buffer. This buffer must be cleared with 0's to get correct // CPU usage statistics int elementsNeeded = NumberOfProcessors > g_SystemInfo.dwNumberOfProcessors ? NumberOfProcessors : g_SystemInfo.dwNumberOfProcessors; // // When CLR threads are not using all groups, GetCPUBusyTime_NT will read element X from // the "prevCPUInfo.usageBuffer" array if and only if "prevCPUInfo.affinityMask" contains a // set bit in bit position X. This implies that GetCPUBusyTime_NT would read past the end // of the "usageBuffer" array if the index of the highest set bit in "affinityMask" was // ever larger than the index of the last array element. // // If necessary, expand "elementsNeeded" to ensure that the index of the last array element // is always at least as large as the index of the highest set bit in the "affinityMask". // // This expansion is necessary in any case where the mask returned by GetCurrentProcessCpuMask // (which is just a wrapper around the Win32 GetProcessAffinityMask API) contains set bits // at indices greater than or equal to the larger of the basline CPU count values (i.e., // ThreadpoolMgr::NumberOfProcessors and g_SystemInfo.dwNumberOfProcessors) that were // captured earlier on (during ThreadpoolMgr::Initialize and during EEStartupHelper, // respectively). Note that in the relevant scenario (i.e., when CLR threads are not using // all groups) the mask and CPU counts are all collected via "group-unaware" APIs and are // all "group-local" values as a result. // // Expansion is necessary in at least the following cases: // // - If the baseline CPU counts were captured while running in groups that contain fewer // CPUs (in a multi-group system with heterogenous CPU counts across groups), but this code // is now running in a group that contains a larger number of CPUs. // // - If CPUs were hot-added to the system and then added to the current process affinity // mask at some point after the baseline CPU counts were captured. // if (!CPUGroupInfo::CanEnableThreadUseAllCpuGroups()) { int elementsNeededToCoverMask = 0; DWORD_PTR remainingMask = prevCPUInfo.affinityMask; while (remainingMask != 0) { elementsNeededToCoverMask++; remainingMask >>= 1; } if (elementsNeeded < elementsNeededToCoverMask) { elementsNeeded = elementsNeededToCoverMask; } } if (!ClrSafeInt<int>::multiply(elementsNeeded, sizeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION), prevCPUInfo.usageBufferSize)) return 0; prevCPUInfo.usageBuffer = (SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION *)alloca(prevCPUInfo.usageBufferSize); if (prevCPUInfo.usageBuffer == NULL) return 0; memset((void *)prevCPUInfo.usageBuffer, 0, prevCPUInfo.usageBufferSize); //must clear it with 0s GetCPUBusyTime_NT(&prevCPUInfo); #else // !TARGET_UNIX PAL_IOCP_CPU_INFORMATION prevCPUInfo; memset(&prevCPUInfo, 0, sizeof(prevCPUInfo)); GetCPUBusyTime_NT(&prevCPUInfo); // ignore return value the first time #endif // !TARGET_UNIX BOOL IgnoreNextSample = FALSE; do { timer.Wait(); if(CLRConfig::GetConfigValue(CLRConfig::INTERNAL_ThreadPool_EnableWorkerTracking)) FireEtwThreadPoolWorkingThreadCount(TakeMaxWorkingThreadCount(), GetClrInstanceId()); #ifdef DEBUGGING_SUPPORTED // if we are stopped at a debug breakpoint, go back to sleep if (CORDebuggerAttached() && g_pDebugInterface->IsStopped()) continue; #endif // DEBUGGING_SUPPORTED if (!GCHeapUtilities::IsGCInProgress(FALSE) ) { if (IgnoreNextSample) { IgnoreNextSample = FALSE; int cpuUtilizationTemp = GetCPUBusyTime_NT(&prevCPUInfo); // updates prevCPUInfo as side effect // don't artificially drive down average if cpu is high if (cpuUtilizationTemp <= CpuUtilizationLow) cpuUtilization = CpuUtilizationLow + 1; else cpuUtilization = cpuUtilizationTemp; } else { cpuUtilization = GetCPUBusyTime_NT(&prevCPUInfo); // updates prevCPUInfo as side effect } } else { int cpuUtilizationTemp = GetCPUBusyTime_NT(&prevCPUInfo); // updates prevCPUInfo as side effect // don't artificially drive down average if cpu is high if (cpuUtilizationTemp <= CpuUtilizationLow) cpuUtilization = CpuUtilizationLow + 1; else cpuUtilization = cpuUtilizationTemp; IgnoreNextSample = TRUE; } PerformGateActivities(cpuUtilization); } while (ShouldGateThreadKeepRunning()); return 0; } void ThreadpoolMgr::PerformGateActivities(int cpuUtilization) { CONTRACTL { NOTHROW; GC_TRIGGERS; MODE_PREEMPTIVE; } CONTRACTL_END; _ASSERTE(!UsePortableThreadPoolForIO()); ThreadpoolMgr::cpuUtilization = cpuUtilization; #ifndef TARGET_UNIX // don't mess with CP thread pool settings if not initialized yet if (InitCompletionPortThreadpool) { ThreadCounter::Counts oldCounts, newCounts; oldCounts = CPThreadCounter.GetCleanCounts(); if (oldCounts.NumActive == oldCounts.NumWorking && oldCounts.NumRetired == 0 && oldCounts.NumActive < MaxLimitTotalCPThreads && !GCHeapUtilities::IsGCInProgress(TRUE)) { BOOL status; DWORD numBytes; size_t key; LPOVERLAPPED pOverlapped; DWORD errorCode; errorCode = S_OK; status = GetQueuedCompletionStatus( GlobalCompletionPort, &numBytes, (PULONG_PTR)&key, &pOverlapped, 0 // immediate return ); if (status == 0) { errorCode = GetLastError(); } if (errorCode != WAIT_TIMEOUT) { QueuedStatus *CompletionStatus = NULL; // loop, retrying until memory is allocated. Under such conditions the gate // thread is not useful anyway, so I feel comfortable with this behavior do { // make sure to free mem later in thread CompletionStatus = new (nothrow) QueuedStatus; if (CompletionStatus == NULL) { __SwitchToThread(GATE_THREAD_DELAY, CALLER_LIMITS_SPINNING); } } while (CompletionStatus == NULL); CompletionStatus->numBytes = numBytes; CompletionStatus->key = (PULONG_PTR)key; CompletionStatus->pOverlapped = pOverlapped; CompletionStatus->errorCode = errorCode; // IOCP threads are created as "active" and "working" while (true) { // counts volatile read paired with CompareExchangeCounts loop set oldCounts = CPThreadCounter.DangerousGetDirtyCounts(); newCounts = oldCounts; newCounts.NumActive++; newCounts.NumWorking++; if (oldCounts == CPThreadCounter.CompareExchangeCounts(newCounts, oldCounts)) break; } // loop, retrying until thread is created. while (!CreateCompletionPortThread((LPVOID)CompletionStatus)) { __SwitchToThread(GATE_THREAD_DELAY, CALLER_LIMITS_SPINNING); } } } else if (cpuUtilization < CpuUtilizationLow) { // this could be an indication that threads might be getting blocked or there is no work if (oldCounts.NumWorking == oldCounts.NumActive && // don't bump the limit if there are already free threads oldCounts.NumRetired > 0) { RetiredCPWakeupEvent->Set(); } } } #endif // !TARGET_UNIX if (!UsePortableThreadPool() && 0 == CLRConfig::GetConfigValue(CLRConfig::INTERNAL_ThreadPool_DisableStarvationDetection)) { if (PerAppDomainTPCountList::AreRequestsPendingInAnyAppDomains() && SufficientDelaySinceLastDequeue()) { DangerousNonHostedSpinLockHolder tal(&ThreadAdjustmentLock); ThreadCounter::Counts counts = WorkerCounter.GetCleanCounts(); while (counts.NumActive < MaxLimitTotalWorkerThreads && //don't add a thread if we're at the max counts.NumActive >= counts.MaxWorking) //don't add a thread if we're already in the process of adding threads { bool breakIntoDebugger = (0 != CLRConfig::GetConfigValue(CLRConfig::INTERNAL_ThreadPool_DebugBreakOnWorkerStarvation)); if (breakIntoDebugger) { OutputDebugStringW(W("The CLR ThreadPool detected work queue starvation!")); DebugBreak(); } ThreadCounter::Counts newCounts = counts; newCounts.MaxWorking = newCounts.NumActive + 1; ThreadCounter::Counts oldCounts = WorkerCounter.CompareExchangeCounts(newCounts, counts); if (oldCounts == counts) { HillClimbingInstance.ForceChange(newCounts.MaxWorking, Starvation); MaybeAddWorkingWorker(); break; } else { counts = oldCounts; } } } } } // called by logic to spawn a new completion port thread. // return false if not enough time has elapsed since the last // time we sampled the cpu utilization. BOOL ThreadpoolMgr::SufficientDelaySinceLastSample(unsigned int LastThreadCreationTime, unsigned NumThreads, // total number of threads of that type (worker or CP) double throttleRate // the delay is increased by this percentage for each extra thread ) { LIMITED_METHOD_CONTRACT; unsigned dwCurrentTickCount = GetTickCount(); unsigned delaySinceLastThreadCreation = dwCurrentTickCount - LastThreadCreationTime; unsigned minWaitBetweenThreadCreation = GATE_THREAD_DELAY; if (throttleRate > 0.0) { _ASSERTE(throttleRate <= 1.0); unsigned adjustedThreadCount = NumThreads > NumberOfProcessors ? (NumThreads - NumberOfProcessors) : 0; minWaitBetweenThreadCreation = (unsigned) (GATE_THREAD_DELAY * pow((1.0 + throttleRate),(double)adjustedThreadCount)); } // the amount of time to wait should grow up as the number of threads is increased return (delaySinceLastThreadCreation > minWaitBetweenThreadCreation); } // called by logic to spawn new worker threads, return true if it's been too long // since the last dequeue operation - takes number of worker threads into account // in deciding "too long" BOOL ThreadpoolMgr::SufficientDelaySinceLastDequeue() { LIMITED_METHOD_CONTRACT; _ASSERTE(!UsePortableThreadPool()); #define DEQUEUE_DELAY_THRESHOLD (GATE_THREAD_DELAY * 2) unsigned delay = GetTickCount() - VolatileLoad(&LastDequeueTime); unsigned tooLong; if(cpuUtilization < CpuUtilizationLow) { tooLong = GATE_THREAD_DELAY; } else { ThreadCounter::Counts counts = WorkerCounter.GetCleanCounts(); unsigned numThreads = counts.MaxWorking; tooLong = numThreads * DEQUEUE_DELAY_THRESHOLD; } return (delay > tooLong); } #ifdef _MSC_VER #ifdef HOST_64BIT #pragma warning (default : 4716) #else #pragma warning (default : 4715) #endif #endif /************************************************************************/ struct CreateTimerThreadParams { CLREvent event; BOOL setupSucceeded; }; BOOL ThreadpoolMgr::CreateTimerQueueTimer(PHANDLE phNewTimer, WAITORTIMERCALLBACK Callback, PVOID Parameter, DWORD DueTime, DWORD Period, ULONG Flag) { CONTRACTL { THROWS; // EnsureInitialized, CreateAutoEvent can throw if (GetThreadNULLOk()) {GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);} // There can be calls thru ICorThreadpool MODE_ANY; INJECT_FAULT(COMPlusThrowOM()); } CONTRACTL_END; EnsureInitialized(); // For now we use just one timer thread. Consider using multiple timer threads if // number of timers in the queue exceeds a certain threshold. The logic and code // would be similar to the one for creating wait threads. if (NULL == TimerThread) { CrstHolder csh(&TimerQueueCriticalSection); // check again if (NULL == TimerThread) { CreateTimerThreadParams params; params.event.CreateAutoEvent(FALSE); params.setupSucceeded = FALSE; HANDLE TimerThreadHandle = Thread::CreateUtilityThread(Thread::StackSize_Small, TimerThreadStart, &params, W(".NET Timer")); if (TimerThreadHandle == NULL) { params.event.CloseEvent(); ThrowOutOfMemory(); } { GCX_PREEMP(); for(;;) { // if a host throws because it couldnt allocate another thread, // just retry the wait. if (SafeWait(&params.event,INFINITE, FALSE) != WAIT_TIMEOUT) break; } } params.event.CloseEvent(); if (!params.setupSucceeded) { CloseHandle(TimerThreadHandle); *phNewTimer = NULL; return FALSE; } TimerThread = TimerThreadHandle; } } NewHolder<TimerInfo> timerInfoHolder; TimerInfo * timerInfo = new (nothrow) TimerInfo; if (NULL == timerInfo) ThrowOutOfMemory(); timerInfoHolder.Assign(timerInfo); timerInfo->FiringTime = DueTime; timerInfo->Function = Callback; timerInfo->Context = Parameter; timerInfo->Period = Period; timerInfo->state = 0; timerInfo->flag = Flag; timerInfo->ExternalCompletionEvent = INVALID_HANDLE; timerInfo->ExternalEventSafeHandle = NULL; *phNewTimer = (HANDLE)timerInfo; BOOL status = QueueUserAPC((PAPCFUNC)InsertNewTimer,TimerThread,(size_t)timerInfo); if (FALSE == status) { *phNewTimer = NULL; return FALSE; } timerInfoHolder.SuppressRelease(); return TRUE; } #ifdef _MSC_VER #ifdef HOST_64BIT #pragma warning (disable : 4716) #else #pragma warning (disable : 4715) #endif #endif DWORD WINAPI ThreadpoolMgr::TimerThreadStart(LPVOID p) { ClrFlsSetThreadType (ThreadType_Timer); STATIC_CONTRACT_THROWS; STATIC_CONTRACT_GC_TRIGGERS; // due to SetApartment STATIC_CONTRACT_MODE_PREEMPTIVE; /* cannot use contract because of SEH CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_PREEMPTIVE; } CONTRACTL_END;*/ CreateTimerThreadParams* params = (CreateTimerThreadParams*)p; Thread* pThread = SetupThreadNoThrow(); params->setupSucceeded = (pThread == NULL) ? 0 : 1; params->event.Set(); if (pThread == NULL) return 0; pTimerThread = pThread; // Timer threads never die LastTickCount = GetTickCount(); #ifdef FEATURE_COMINTEROP if (pThread->SetApartment(Thread::AS_InMTA) != Thread::AS_InMTA) { // @todo: should we log the failure return 0; } #endif // FEATURE_COMINTEROP for (;;) { // moved to its own function since EX_TRY consumes stack #ifdef _MSC_VER #pragma inline_depth (0) // the function containing EX_TRY can't be inlined here #endif TimerThreadFire(); #ifdef _MSC_VER #pragma inline_depth (20) #endif } // unreachable } void ThreadpoolMgr::TimerThreadFire() { CONTRACTL { THROWS; GC_TRIGGERS; MODE_PREEMPTIVE; } CONTRACTL_END; EX_TRY { DWORD timeout = FireTimers(); #undef SleepEx SleepEx(timeout, TRUE); #define SleepEx(a,b) Dont_Use_SleepEx(a,b) // the thread could wake up either because an APC completed or the sleep timeout // in both case, we need to sweep the timer queue, firing timers, and readjusting // the next firing time } EX_CATCH { // Assert on debug builds since a dead timer thread is a fatal error _ASSERTE(FALSE); EX_RETHROW; } EX_END_CATCH(SwallowAllExceptions); } #ifdef _MSC_VER #ifdef HOST_64BIT #pragma warning (default : 4716) #else #pragma warning (default : 4715) #endif #endif // Executed as an APC in timer thread void ThreadpoolMgr::InsertNewTimer(TimerInfo* pArg) { CONTRACTL { NOTHROW; GC_TRIGGERS; MODE_ANY; } CONTRACTL_END; _ASSERTE(pArg); TimerInfo * timerInfo = pArg; if (timerInfo->state & TIMER_DELETE) { // timer was deleted before it could be registered DeleteTimer(timerInfo); return; } // set the firing time = current time + due time (note initially firing time = due time) DWORD currentTime = GetTickCount(); if (timerInfo->FiringTime == (ULONG) -1) { timerInfo->state = TIMER_REGISTERED; timerInfo->refCount = 1; } else { timerInfo->FiringTime += currentTime; timerInfo->state = (TIMER_REGISTERED | TIMER_ACTIVE); timerInfo->refCount = 1; // insert the timer in the queue InsertTailList(&TimerQueue,(&timerInfo->link)); } return; } // executed by the Timer thread // sweeps through the list of timers, readjusting the firing times, queueing APCs for // those that have expired, and returns the next firing time interval DWORD ThreadpoolMgr::FireTimers() { CONTRACTL { THROWS; // QueueUserWorkItem can throw if (GetThreadNULLOk()) { GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);} if (GetThreadNULLOk()) { MODE_PREEMPTIVE;} else { DISABLED(MODE_ANY);} } CONTRACTL_END; DWORD currentTime = GetTickCount(); DWORD nextFiringInterval = (DWORD) -1; TimerInfo* timerInfo = NULL; EX_TRY { for (LIST_ENTRY* node = (LIST_ENTRY*) TimerQueue.Flink; node != &TimerQueue; ) { timerInfo = (TimerInfo*) node; node = (LIST_ENTRY*) node->Flink; if (TimeExpired(LastTickCount, currentTime, timerInfo->FiringTime)) { if (timerInfo->Period == 0 || timerInfo->Period == (ULONG) -1) { DeactivateTimer(timerInfo); } InterlockedIncrement(&timerInfo->refCount); if (UsePortableThreadPool()) { GCX_COOP(); ARG_SLOT args[] = { PtrToArgSlot(AsyncTimerCallbackCompletion), PtrToArgSlot(timerInfo) }; MethodDescCallSite(METHOD__THREAD_POOL__UNSAFE_QUEUE_UNMANAGED_WORK_ITEM).Call(args); } else { QueueUserWorkItem(AsyncTimerCallbackCompletion, timerInfo, QUEUE_ONLY /* TimerInfo take care of deleting*/); } if (timerInfo->Period != 0 && timerInfo->Period != (ULONG)-1) { ULONG nextFiringTime = timerInfo->FiringTime + timerInfo->Period; DWORD firingInterval; if (TimeExpired(timerInfo->FiringTime, currentTime, nextFiringTime)) { // Enough time has elapsed to fire the timer yet again. The timer is not able to keep up with the short // period, have it fire 1 ms from now to avoid spinning without a delay. timerInfo->FiringTime = currentTime + 1; firingInterval = 1; } else { timerInfo->FiringTime = nextFiringTime; firingInterval = TimeInterval(nextFiringTime, currentTime); } if (firingInterval < nextFiringInterval) nextFiringInterval = firingInterval; } } else { DWORD firingInterval = TimeInterval(timerInfo->FiringTime, currentTime); if (firingInterval < nextFiringInterval) nextFiringInterval = firingInterval; } } } EX_CATCH { // If QueueUserWorkItem throws OOM, swallow the exception and retry on // the next call to FireTimers(), otherwise retrhow. Exception *ex = GET_EXCEPTION(); // undo the call to DeactivateTimer() InterlockedDecrement(&timerInfo->refCount); timerInfo->state = timerInfo->state & TIMER_ACTIVE; InsertTailList(&TimerQueue, (&timerInfo->link)); if (ex->GetHR() != E_OUTOFMEMORY) { EX_RETHROW; } } EX_END_CATCH(RethrowTerminalExceptions); LastTickCount = currentTime; return nextFiringInterval; } DWORD WINAPI ThreadpoolMgr::AsyncTimerCallbackCompletion(PVOID pArgs) { CONTRACTL { THROWS; GC_TRIGGERS; MODE_PREEMPTIVE; } CONTRACTL_END; Thread* pThread = GetThreadNULLOk(); if (pThread == NULL) { HRESULT hr = ERROR_SUCCESS; ClrFlsSetThreadType(ThreadType_Threadpool_Worker); pThread = SetupThreadNoThrow(&hr); if (pThread == NULL) { return hr; } } { TimerInfo* timerInfo = (TimerInfo*) pArgs; ((WAITORTIMERCALLBACKFUNC) timerInfo->Function) (timerInfo->Context, TRUE) ; if (InterlockedDecrement(&timerInfo->refCount) == 0) { DeleteTimer(timerInfo); } } return ERROR_SUCCESS; } // removes the timer from the timer queue, thereby cancelling it // there may still be pending callbacks that haven't completed void ThreadpoolMgr::DeactivateTimer(TimerInfo* timerInfo) { LIMITED_METHOD_CONTRACT; RemoveEntryList((LIST_ENTRY*) timerInfo); // This timer info could go into another linked list of timer infos // waiting to be released. Reinitialize the list pointers InitializeListHead(&timerInfo->link); timerInfo->state = timerInfo->state & ~TIMER_ACTIVE; } DWORD WINAPI ThreadpoolMgr::AsyncDeleteTimer(PVOID pArgs) { CONTRACTL { THROWS; MODE_PREEMPTIVE; GC_TRIGGERS; } CONTRACTL_END; Thread * pThread = GetThreadNULLOk(); if (pThread == NULL) { HRESULT hr = ERROR_SUCCESS; ClrFlsSetThreadType(ThreadType_Threadpool_Worker); pThread = SetupThreadNoThrow(&hr); if (pThread == NULL) { return hr; } } DeleteTimer((TimerInfo*) pArgs); return ERROR_SUCCESS; } void ThreadpoolMgr::DeleteTimer(TimerInfo* timerInfo) { CONTRACTL { if (GetThreadNULLOk() == pTimerThread) { NOTHROW; } else { THROWS; } GC_TRIGGERS; MODE_ANY; } CONTRACTL_END; _ASSERTE((timerInfo->state & TIMER_ACTIVE) == 0); _ASSERTE(!(timerInfo->flag & WAIT_FREE_CONTEXT)); if (timerInfo->flag & WAIT_INTERNAL_COMPLETION) { timerInfo->InternalCompletionEvent.Set(); return; // the timerInfo will be deleted by the thread that's waiting on InternalCompletionEvent } // ExternalCompletionEvent comes from Host, ExternalEventSafeHandle from managed code. // They are mutually exclusive. _ASSERTE(!(timerInfo->ExternalCompletionEvent != INVALID_HANDLE && timerInfo->ExternalEventSafeHandle != NULL)); if (timerInfo->ExternalCompletionEvent != INVALID_HANDLE) { SetEvent(timerInfo->ExternalCompletionEvent); timerInfo->ExternalCompletionEvent = INVALID_HANDLE; } // We cannot block the timer thread, so some cleanup is deferred to other threads. if (GetThreadNULLOk() == pTimerThread) { // Notify the ExternalEventSafeHandle with an user work item if (timerInfo->ExternalEventSafeHandle != NULL) { BOOL success = FALSE; EX_TRY { if (QueueUserWorkItem(AsyncDeleteTimer, timerInfo, QUEUE_ONLY) != FALSE) { success = TRUE; } } EX_CATCH { } EX_END_CATCH(SwallowAllExceptions); // If unable to queue a user work item, fall back to queueing timer for release // which will happen *sometime* in the future. if (success == FALSE) { QueueTimerInfoForRelease(timerInfo); } return; } // Releasing GC handles can block. So we wont do this on the timer thread. // We'll put it in a list which will be processed by a worker thread if (timerInfo->Context != NULL) { QueueTimerInfoForRelease(timerInfo); return; } } // To get here we are either not the Timer thread or there is no blocking work to be done if (timerInfo->Context != NULL) { GCX_COOP(); delete (ThreadpoolMgr::TimerInfoContext*)timerInfo->Context; } if (timerInfo->ExternalEventSafeHandle != NULL) { ReleaseTimerInfo(timerInfo); } delete timerInfo; } // We add TimerInfos from deleted timers into a linked list. // A worker thread will later release the handles held by the TimerInfo // and recycle them if possible. void ThreadpoolMgr::QueueTimerInfoForRelease(TimerInfo *pTimerInfo) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; // The synchronization in this method depends on the fact that // - There is only one timer thread // - The one and only timer thread is executing this method. // - This function wont go into an alertable state. That could trigger another APC. // Else two threads can be queueing timerinfos and a race could // lead to leaked memory and handles _ASSERTE(pTimerThread == GetThread()); TimerInfo *pHead = NULL; // Make sure this timer info has been deactivated and removed from any other lists _ASSERTE((pTimerInfo->state & TIMER_ACTIVE) == 0); //_ASSERTE(pTimerInfo->link.Blink == &(pTimerInfo->link) && // pTimerInfo->link.Flink == &(pTimerInfo->link)); // Make sure "link" is the first field in TimerInfo _ASSERTE(pTimerInfo == (PVOID)&pTimerInfo->link); // Grab any previously published list if ((pHead = InterlockedExchangeT(&TimerInfosToBeRecycled, NULL)) != NULL) { // If there already is a list, just append InsertTailList((LIST_ENTRY *)pHead, &pTimerInfo->link); pTimerInfo = pHead; } else // If this is the head, make its next and previous ptrs point to itself InitializeListHead((LIST_ENTRY*)&pTimerInfo->link); // Publish the list (void) InterlockedExchangeT(&TimerInfosToBeRecycled, pTimerInfo); } void ThreadpoolMgr::FlushQueueOfTimerInfos() { CONTRACTL { THROWS; GC_TRIGGERS; MODE_ANY; } CONTRACTL_END; TimerInfo *pHeadTimerInfo = NULL, *pCurrTimerInfo = NULL; LIST_ENTRY *pNextInfo = NULL; if ((pHeadTimerInfo = InterlockedExchangeT(&TimerInfosToBeRecycled, NULL)) == NULL) return; do { RemoveHeadList((LIST_ENTRY *)pHeadTimerInfo, pNextInfo); _ASSERTE(pNextInfo != NULL); pCurrTimerInfo = (TimerInfo *) pNextInfo; GCX_COOP(); if (pCurrTimerInfo->Context != NULL) { delete (ThreadpoolMgr::TimerInfoContext*)pCurrTimerInfo->Context; } if (pCurrTimerInfo->ExternalEventSafeHandle != NULL) { ReleaseTimerInfo(pCurrTimerInfo); } delete pCurrTimerInfo; } while ((TimerInfo *)pNextInfo != pHeadTimerInfo); } /************************************************************************/ BOOL ThreadpoolMgr::ChangeTimerQueueTimer( HANDLE Timer, ULONG DueTime, ULONG Period) { CONTRACTL { THROWS; MODE_ANY; GC_NOTRIGGER; INJECT_FAULT(COMPlusThrowOM()); } CONTRACTL_END; _ASSERTE(IsInitialized()); _ASSERTE(Timer); // not possible to give invalid handle in managed code NewHolder<TimerUpdateInfo> updateInfoHolder; TimerUpdateInfo *updateInfo = new TimerUpdateInfo; updateInfoHolder.Assign(updateInfo); updateInfo->Timer = (TimerInfo*) Timer; updateInfo->DueTime = DueTime; updateInfo->Period = Period; BOOL status = QueueUserAPC((PAPCFUNC)UpdateTimer, TimerThread, (size_t) updateInfo); if (status) updateInfoHolder.SuppressRelease(); return(status); } void ThreadpoolMgr::UpdateTimer(TimerUpdateInfo* pArgs) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; TimerUpdateInfo* updateInfo = (TimerUpdateInfo*) pArgs; TimerInfo* timerInfo = updateInfo->Timer; timerInfo->Period = updateInfo->Period; if (updateInfo->DueTime == (ULONG) -1) { if (timerInfo->state & TIMER_ACTIVE) { DeactivateTimer(timerInfo); } // else, noop (the timer was already inactive) _ASSERTE((timerInfo->state & TIMER_ACTIVE) == 0); delete updateInfo; return; } DWORD currentTime = GetTickCount(); timerInfo->FiringTime = currentTime + updateInfo->DueTime; delete updateInfo; if (! (timerInfo->state & TIMER_ACTIVE)) { // timer not active (probably a one shot timer that has expired), so activate it timerInfo->state |= TIMER_ACTIVE; _ASSERTE(timerInfo->refCount >= 1); // insert the timer in the queue InsertTailList(&TimerQueue,(&timerInfo->link)); } return; } /************************************************************************/ BOOL ThreadpoolMgr::DeleteTimerQueueTimer( HANDLE Timer, HANDLE Event) { CONTRACTL { THROWS; MODE_ANY; GC_TRIGGERS; } CONTRACTL_END; _ASSERTE(IsInitialized()); // cannot call delete before creating timer _ASSERTE(Timer); // not possible to give invalid handle in managed code // make volatile to avoid compiler reordering check after async call. // otherwise, DeregisterTimer could delete timerInfo before the comparison. VolatilePtr<TimerInfo> timerInfo = (TimerInfo*) Timer; if (Event == (HANDLE) -1) { //CONTRACT_VIOLATION(ThrowsViolation); timerInfo->InternalCompletionEvent.CreateAutoEvent(FALSE); timerInfo->flag |= WAIT_INTERNAL_COMPLETION; } else if (Event) { timerInfo->ExternalCompletionEvent = Event; } #ifdef _DEBUG else /* Event == NULL */ { _ASSERTE(timerInfo->ExternalCompletionEvent == INVALID_HANDLE); } #endif BOOL isBlocking = timerInfo->flag & WAIT_INTERNAL_COMPLETION; BOOL status = QueueUserAPC((PAPCFUNC)DeregisterTimer, TimerThread, (size_t)(TimerInfo*)timerInfo); if (FALSE == status) { if (isBlocking) timerInfo->InternalCompletionEvent.CloseEvent(); return FALSE; } if (isBlocking) { _ASSERTE(timerInfo->ExternalEventSafeHandle == NULL); _ASSERTE(timerInfo->ExternalCompletionEvent == INVALID_HANDLE); _ASSERTE(GetThreadNULLOk() != pTimerThread); timerInfo->InternalCompletionEvent.Wait(INFINITE,TRUE /*alertable*/); timerInfo->InternalCompletionEvent.CloseEvent(); // Release handles and delete TimerInfo _ASSERTE(timerInfo->refCount == 0); // if WAIT_INTERNAL_COMPLETION flag is not set, timerInfo will be deleted in DeleteTimer. timerInfo->flag &= ~WAIT_INTERNAL_COMPLETION; DeleteTimer(timerInfo); } return status; } void ThreadpoolMgr::DeregisterTimer(TimerInfo* pArgs) { CONTRACTL { NOTHROW; GC_TRIGGERS; MODE_PREEMPTIVE; } CONTRACTL_END; TimerInfo* timerInfo = (TimerInfo*) pArgs; if (! (timerInfo->state & TIMER_REGISTERED) ) { // set state to deleted, so that it does not get registered timerInfo->state |= TIMER_DELETE ; // since the timer has not even been registered, we dont need an interlock to decrease the RefCount timerInfo->refCount--; return; } if (timerInfo->state & TIMER_ACTIVE) { DeactivateTimer(timerInfo); } if (InterlockedDecrement(&timerInfo->refCount) == 0 ) { DeleteTimer(timerInfo); } return; } #endif // !DACCESS_COMPILE
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/libraries/System.Text.Json/tests/System.Text.Json.Tests/Serialization/OnSerializeTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using Xunit; namespace System.Text.Json.Serialization.Tests { public static partial class OnSerializeTests { private class MyClass : IJsonOnDeserializing, IJsonOnDeserialized, IJsonOnSerializing, IJsonOnSerialized { public int MyInt { get; set; } internal int _onSerializingCount; internal int _onSerializedCount; internal int _onDeserializingCount; internal int _onDeserializedCount; public void OnSerializing() { _onSerializingCount++; Assert.Equal(1, MyInt); MyInt++; } public void OnSerialized() { Assert.Equal(1, _onSerializingCount); _onSerializedCount++; Assert.Equal(2, MyInt); MyInt++; } public void OnDeserializing() { _onDeserializingCount++; Assert.Equal(0, MyInt); MyInt = 100; // Gets replaced by the serializer. } public void OnDeserialized() { Assert.Equal(1, _onDeserializingCount); _onDeserializedCount++; Assert.Equal(1, MyInt); MyInt++; } } [Fact] public static void Test_MyClass() { MyClass obj = new(); obj.MyInt = 1; string json = JsonSerializer.Serialize(obj); Assert.Equal("{\"MyInt\":2}", json); Assert.Equal(3, obj.MyInt); Assert.Equal(1, obj._onSerializingCount); Assert.Equal(1, obj._onSerializedCount); Assert.Equal(0, obj._onDeserializingCount); Assert.Equal(0, obj._onDeserializedCount); obj = JsonSerializer.Deserialize<MyClass>("{\"MyInt\":1}"); Assert.Equal(2, obj.MyInt); Assert.Equal(0, obj._onSerializingCount); Assert.Equal(0, obj._onSerializedCount); Assert.Equal(1, obj._onDeserializingCount); Assert.Equal(1, obj._onDeserializedCount); } private struct MyStruct : IJsonOnDeserializing, IJsonOnDeserialized, IJsonOnSerializing, IJsonOnSerialized { public int MyInt { get; set; } internal int _onSerializingCount; internal int _onSerializedCount; internal int _onDeserializingCount; internal int _onDeserializedCount; public void OnSerializing() { _onSerializingCount++; Assert.Equal(1, MyInt); MyInt++; } public void OnSerialized() { Assert.Equal(1, _onSerializingCount); _onSerializedCount++; MyInt++; // should not affect serialization } public void OnDeserializing() { Assert.Equal(0, MyInt); _onDeserializingCount++; MyInt = 100; // Gets replaced by the serializer. } public void OnDeserialized() { Assert.Equal(1, _onDeserializingCount); Assert.Equal(1, MyInt); _onDeserializedCount++; } } [Fact] public static void Test_MyStruct() { MyStruct obj = new(); obj.MyInt = 1; string json = JsonSerializer.Serialize(obj); Assert.Equal("{\"MyInt\":2}", json); // Although the OnSerialize* callbacks are invoked, a struct is passed to the serializer byvalue. Assert.Equal(0, obj._onSerializingCount); Assert.Equal(0, obj._onSerializedCount); Assert.Equal(0, obj._onDeserializingCount); Assert.Equal(0, obj._onDeserializedCount); obj = JsonSerializer.Deserialize<MyStruct>("{\"MyInt\":1}"); Assert.Equal(1, obj.MyInt); Assert.Equal(0, obj._onSerializingCount); Assert.Equal(0, obj._onSerializedCount); Assert.Equal(1, obj._onDeserializingCount); Assert.Equal(1, obj._onDeserializedCount); } private class MyClassWithSmallConstructor : IJsonOnDeserializing, IJsonOnDeserialized, IJsonOnSerializing, IJsonOnSerialized { public int MyInt { get; set; } public MyClassWithSmallConstructor(int myInt) { MyInt = myInt; _constructorCalled = true; } internal bool _constructorCalled; internal int _onSerializingCount; internal int _onSerializedCount; internal int _onDeserializingCount; internal int _onDeserializedCount; public void OnSerializing() { _onSerializingCount++; Assert.Equal(1, MyInt); MyInt++; } public void OnSerialized() { Assert.Equal(1, _onSerializingCount); _onSerializedCount++; Assert.Equal(2, MyInt); MyInt++; } public void OnDeserializing() { _onDeserializingCount++; Assert.Equal(1, MyInt); MyInt++; // Does not get replaced by the serializer since it was passed into the ctor. } public void OnDeserialized() { Assert.Equal(1, _onDeserializingCount); _onDeserializedCount++; Assert.Equal(2, MyInt); MyInt++; } } [Fact] public static void Test_MyClassWithSmallConstructor() { MyClassWithSmallConstructor obj = new(1); Assert.Equal(1, obj.MyInt); string json = JsonSerializer.Serialize(obj); Assert.Equal("{\"MyInt\":2}", json); Assert.Equal(3, obj.MyInt); Assert.True(obj._constructorCalled); Assert.Equal(1, obj._onSerializingCount); Assert.Equal(1, obj._onSerializedCount); Assert.Equal(0, obj._onDeserializingCount); Assert.Equal(0, obj._onDeserializedCount); obj = JsonSerializer.Deserialize<MyClassWithSmallConstructor>("{\"MyInt\":1}"); Assert.True(obj._constructorCalled); Assert.Equal(3, obj.MyInt); Assert.Equal(0, obj._onSerializingCount); Assert.Equal(0, obj._onSerializedCount); Assert.Equal(1, obj._onDeserializingCount); Assert.Equal(1, obj._onDeserializedCount); } private class MyClassWithLargeConstructor : IJsonOnDeserializing, IJsonOnDeserialized, IJsonOnSerializing, IJsonOnSerialized { public int MyInt1 { get; set; } public int MyInt2 { get; set; } public int MyInt3 { get; set; } public int MyInt4 { get; set; } public int MyInt5 { get; set; } public MyClassWithLargeConstructor(int myInt1, int myInt2, int myInt3, int myInt4, int myInt5) { MyInt1 = myInt1; MyInt2 = myInt2; MyInt3 = myInt3; MyInt4 = myInt4; MyInt5 = myInt5; _constructorCalled = true; } internal bool _constructorCalled; internal int _onSerializingCount; internal int _onSerializedCount; internal int _onDeserializingCount; internal int _onDeserializedCount; public void OnSerializing() { _onSerializingCount++; Assert.Equal(1, MyInt1); MyInt1++; } public void OnSerialized() { Assert.Equal(1, _onSerializingCount); _onSerializedCount++; Assert.Equal(2, MyInt1); MyInt1++; } public void OnDeserializing() { _onDeserializingCount++; Assert.Equal(1, MyInt1); MyInt1++; // Does not get replaced by the serializer since it was passed into the ctor. } public void OnDeserialized() { Assert.Equal(1, _onDeserializingCount); _onDeserializedCount++; Assert.Equal(2, MyInt1); MyInt1++; } } [Fact] public static void Test_MyClassWithLargeConstructor() { const string Json = "{\"MyInt1\":1,\"MyInt2\":2,\"MyInt3\":3,\"MyInt4\":4,\"MyInt5\":5}"; MyClassWithLargeConstructor obj = new(1, 2, 3, 4, 5); Assert.Equal(1, obj.MyInt1); Assert.Equal(2, obj.MyInt2); Assert.Equal(3, obj.MyInt3); Assert.Equal(4, obj.MyInt4); Assert.Equal(5, obj.MyInt5); string json = JsonSerializer.Serialize(obj); Assert.Contains("\"MyInt1\":2", json); Assert.Equal(3, obj.MyInt1); // Is updated in the callback Assert.True(obj._constructorCalled); Assert.Equal(1, obj._onSerializingCount); Assert.Equal(1, obj._onSerializedCount); Assert.Equal(0, obj._onDeserializingCount); Assert.Equal(0, obj._onDeserializedCount); obj = JsonSerializer.Deserialize<MyClassWithLargeConstructor>(Json); Assert.True(obj._constructorCalled); Assert.Equal(3, obj.MyInt1); Assert.Equal(0, obj._onSerializingCount); Assert.Equal(0, obj._onSerializedCount); Assert.Equal(1, obj._onDeserializingCount); Assert.Equal(1, obj._onDeserializedCount); } private class MyCyclicClass : IJsonOnDeserializing, IJsonOnDeserialized, IJsonOnSerializing, IJsonOnSerialized { public int MyInt { get; set; } public MyCyclicClass Cycle { get; set; } internal int _onSerializingCount; internal int _onSerializedCount; internal int _onDeserializingCount; internal int _onDeserializedCount; public void OnSerializing() { _onSerializingCount++; Assert.Equal(1, MyInt); MyInt++; } public void OnSerialized() { Assert.Equal(1, _onSerializingCount); _onSerializedCount++; Assert.Equal(2, MyInt); MyInt++; } public void OnDeserializing() { _onDeserializingCount++; Assert.Equal(0, MyInt); MyInt = 100; // Gets replaced by the serializer. } public void OnDeserialized() { Assert.Equal(1, _onDeserializingCount); _onDeserializedCount++; Assert.Equal(1, MyInt); MyInt++; } } [Fact] public static void Test_MyCyclicClass() { const string Json = "{\"$id\":\"1\",\"MyInt\":1,\"Cycle\":{\"$ref\":\"1\"}}"; MyCyclicClass obj = new(); obj.MyInt = 1; obj.Cycle = obj; JsonSerializerOptions options = new(); options.ReferenceHandler = ReferenceHandler.Preserve; string json = JsonSerializer.Serialize(obj, options); Assert.Contains("\"MyInt\":2", json); Assert.Equal(1, obj._onSerializingCount); Assert.Equal(1, obj._onSerializedCount); Assert.Equal(0, obj._onDeserializingCount); Assert.Equal(0, obj._onDeserializedCount); obj = JsonSerializer.Deserialize<MyCyclicClass>(Json, options); Assert.Equal(2, obj.MyInt); Assert.Equal(obj, obj.Cycle); Assert.Equal(0, obj._onSerializingCount); Assert.Equal(0, obj._onSerializedCount); Assert.Equal(1, obj._onDeserializingCount); Assert.Equal(1, obj._onDeserializedCount); } private class MyCollection : List<int>, IJsonOnDeserializing, IJsonOnDeserialized, IJsonOnSerializing, IJsonOnSerialized { public void OnDeserialized() => Assert.True(false, "Not expected"); public void OnDeserializing() => Assert.True(false, "Not expected"); public void OnSerialized() => Assert.True(false, "Not expected"); public void OnSerializing() => Assert.True(false, "Not expected"); } [JsonConverter(converterType: typeof(MyValueConverter))] private class MyValue : IJsonOnDeserializing, IJsonOnDeserialized, IJsonOnSerializing, IJsonOnSerialized { public void OnDeserialized() => Assert.True(false, "Not expected"); public void OnDeserializing() => Assert.True(false, "Not expected"); public void OnSerialized() => Assert.True(false, "Not expected"); public void OnSerializing() => Assert.True(false, "Not expected"); } private class MyValueConverter : JsonConverter<MyValue> { public override MyValue? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new MyValue(); } public override void Write(Utf8JsonWriter writer, MyValue value, JsonSerializerOptions options) { writer.WriteStringValue("dummy"); } } [Fact] public static void NonPocosIgnored() { JsonSerializer.Serialize(new MyCollection()); JsonSerializer.Deserialize<MyCollection>("[]"); JsonSerializer.Serialize(new MyValue()); JsonSerializer.Deserialize<MyCollection>("[]"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using Xunit; namespace System.Text.Json.Serialization.Tests { public static partial class OnSerializeTests { private class MyClass : IJsonOnDeserializing, IJsonOnDeserialized, IJsonOnSerializing, IJsonOnSerialized { public int MyInt { get; set; } internal int _onSerializingCount; internal int _onSerializedCount; internal int _onDeserializingCount; internal int _onDeserializedCount; public void OnSerializing() { _onSerializingCount++; Assert.Equal(1, MyInt); MyInt++; } public void OnSerialized() { Assert.Equal(1, _onSerializingCount); _onSerializedCount++; Assert.Equal(2, MyInt); MyInt++; } public void OnDeserializing() { _onDeserializingCount++; Assert.Equal(0, MyInt); MyInt = 100; // Gets replaced by the serializer. } public void OnDeserialized() { Assert.Equal(1, _onDeserializingCount); _onDeserializedCount++; Assert.Equal(1, MyInt); MyInt++; } } [Fact] public static void Test_MyClass() { MyClass obj = new(); obj.MyInt = 1; string json = JsonSerializer.Serialize(obj); Assert.Equal("{\"MyInt\":2}", json); Assert.Equal(3, obj.MyInt); Assert.Equal(1, obj._onSerializingCount); Assert.Equal(1, obj._onSerializedCount); Assert.Equal(0, obj._onDeserializingCount); Assert.Equal(0, obj._onDeserializedCount); obj = JsonSerializer.Deserialize<MyClass>("{\"MyInt\":1}"); Assert.Equal(2, obj.MyInt); Assert.Equal(0, obj._onSerializingCount); Assert.Equal(0, obj._onSerializedCount); Assert.Equal(1, obj._onDeserializingCount); Assert.Equal(1, obj._onDeserializedCount); } private struct MyStruct : IJsonOnDeserializing, IJsonOnDeserialized, IJsonOnSerializing, IJsonOnSerialized { public int MyInt { get; set; } internal int _onSerializingCount; internal int _onSerializedCount; internal int _onDeserializingCount; internal int _onDeserializedCount; public void OnSerializing() { _onSerializingCount++; Assert.Equal(1, MyInt); MyInt++; } public void OnSerialized() { Assert.Equal(1, _onSerializingCount); _onSerializedCount++; MyInt++; // should not affect serialization } public void OnDeserializing() { Assert.Equal(0, MyInt); _onDeserializingCount++; MyInt = 100; // Gets replaced by the serializer. } public void OnDeserialized() { Assert.Equal(1, _onDeserializingCount); Assert.Equal(1, MyInt); _onDeserializedCount++; } } [Fact] public static void Test_MyStruct() { MyStruct obj = new(); obj.MyInt = 1; string json = JsonSerializer.Serialize(obj); Assert.Equal("{\"MyInt\":2}", json); // Although the OnSerialize* callbacks are invoked, a struct is passed to the serializer byvalue. Assert.Equal(0, obj._onSerializingCount); Assert.Equal(0, obj._onSerializedCount); Assert.Equal(0, obj._onDeserializingCount); Assert.Equal(0, obj._onDeserializedCount); obj = JsonSerializer.Deserialize<MyStruct>("{\"MyInt\":1}"); Assert.Equal(1, obj.MyInt); Assert.Equal(0, obj._onSerializingCount); Assert.Equal(0, obj._onSerializedCount); Assert.Equal(1, obj._onDeserializingCount); Assert.Equal(1, obj._onDeserializedCount); } private class MyClassWithSmallConstructor : IJsonOnDeserializing, IJsonOnDeserialized, IJsonOnSerializing, IJsonOnSerialized { public int MyInt { get; set; } public MyClassWithSmallConstructor(int myInt) { MyInt = myInt; _constructorCalled = true; } internal bool _constructorCalled; internal int _onSerializingCount; internal int _onSerializedCount; internal int _onDeserializingCount; internal int _onDeserializedCount; public void OnSerializing() { _onSerializingCount++; Assert.Equal(1, MyInt); MyInt++; } public void OnSerialized() { Assert.Equal(1, _onSerializingCount); _onSerializedCount++; Assert.Equal(2, MyInt); MyInt++; } public void OnDeserializing() { _onDeserializingCount++; Assert.Equal(1, MyInt); MyInt++; // Does not get replaced by the serializer since it was passed into the ctor. } public void OnDeserialized() { Assert.Equal(1, _onDeserializingCount); _onDeserializedCount++; Assert.Equal(2, MyInt); MyInt++; } } [Fact] public static void Test_MyClassWithSmallConstructor() { MyClassWithSmallConstructor obj = new(1); Assert.Equal(1, obj.MyInt); string json = JsonSerializer.Serialize(obj); Assert.Equal("{\"MyInt\":2}", json); Assert.Equal(3, obj.MyInt); Assert.True(obj._constructorCalled); Assert.Equal(1, obj._onSerializingCount); Assert.Equal(1, obj._onSerializedCount); Assert.Equal(0, obj._onDeserializingCount); Assert.Equal(0, obj._onDeserializedCount); obj = JsonSerializer.Deserialize<MyClassWithSmallConstructor>("{\"MyInt\":1}"); Assert.True(obj._constructorCalled); Assert.Equal(3, obj.MyInt); Assert.Equal(0, obj._onSerializingCount); Assert.Equal(0, obj._onSerializedCount); Assert.Equal(1, obj._onDeserializingCount); Assert.Equal(1, obj._onDeserializedCount); } private class MyClassWithLargeConstructor : IJsonOnDeserializing, IJsonOnDeserialized, IJsonOnSerializing, IJsonOnSerialized { public int MyInt1 { get; set; } public int MyInt2 { get; set; } public int MyInt3 { get; set; } public int MyInt4 { get; set; } public int MyInt5 { get; set; } public MyClassWithLargeConstructor(int myInt1, int myInt2, int myInt3, int myInt4, int myInt5) { MyInt1 = myInt1; MyInt2 = myInt2; MyInt3 = myInt3; MyInt4 = myInt4; MyInt5 = myInt5; _constructorCalled = true; } internal bool _constructorCalled; internal int _onSerializingCount; internal int _onSerializedCount; internal int _onDeserializingCount; internal int _onDeserializedCount; public void OnSerializing() { _onSerializingCount++; Assert.Equal(1, MyInt1); MyInt1++; } public void OnSerialized() { Assert.Equal(1, _onSerializingCount); _onSerializedCount++; Assert.Equal(2, MyInt1); MyInt1++; } public void OnDeserializing() { _onDeserializingCount++; Assert.Equal(1, MyInt1); MyInt1++; // Does not get replaced by the serializer since it was passed into the ctor. } public void OnDeserialized() { Assert.Equal(1, _onDeserializingCount); _onDeserializedCount++; Assert.Equal(2, MyInt1); MyInt1++; } } [Fact] public static void Test_MyClassWithLargeConstructor() { const string Json = "{\"MyInt1\":1,\"MyInt2\":2,\"MyInt3\":3,\"MyInt4\":4,\"MyInt5\":5}"; MyClassWithLargeConstructor obj = new(1, 2, 3, 4, 5); Assert.Equal(1, obj.MyInt1); Assert.Equal(2, obj.MyInt2); Assert.Equal(3, obj.MyInt3); Assert.Equal(4, obj.MyInt4); Assert.Equal(5, obj.MyInt5); string json = JsonSerializer.Serialize(obj); Assert.Contains("\"MyInt1\":2", json); Assert.Equal(3, obj.MyInt1); // Is updated in the callback Assert.True(obj._constructorCalled); Assert.Equal(1, obj._onSerializingCount); Assert.Equal(1, obj._onSerializedCount); Assert.Equal(0, obj._onDeserializingCount); Assert.Equal(0, obj._onDeserializedCount); obj = JsonSerializer.Deserialize<MyClassWithLargeConstructor>(Json); Assert.True(obj._constructorCalled); Assert.Equal(3, obj.MyInt1); Assert.Equal(0, obj._onSerializingCount); Assert.Equal(0, obj._onSerializedCount); Assert.Equal(1, obj._onDeserializingCount); Assert.Equal(1, obj._onDeserializedCount); } private class MyCyclicClass : IJsonOnDeserializing, IJsonOnDeserialized, IJsonOnSerializing, IJsonOnSerialized { public int MyInt { get; set; } public MyCyclicClass Cycle { get; set; } internal int _onSerializingCount; internal int _onSerializedCount; internal int _onDeserializingCount; internal int _onDeserializedCount; public void OnSerializing() { _onSerializingCount++; Assert.Equal(1, MyInt); MyInt++; } public void OnSerialized() { Assert.Equal(1, _onSerializingCount); _onSerializedCount++; Assert.Equal(2, MyInt); MyInt++; } public void OnDeserializing() { _onDeserializingCount++; Assert.Equal(0, MyInt); MyInt = 100; // Gets replaced by the serializer. } public void OnDeserialized() { Assert.Equal(1, _onDeserializingCount); _onDeserializedCount++; Assert.Equal(1, MyInt); MyInt++; } } [Fact] public static void Test_MyCyclicClass() { const string Json = "{\"$id\":\"1\",\"MyInt\":1,\"Cycle\":{\"$ref\":\"1\"}}"; MyCyclicClass obj = new(); obj.MyInt = 1; obj.Cycle = obj; JsonSerializerOptions options = new(); options.ReferenceHandler = ReferenceHandler.Preserve; string json = JsonSerializer.Serialize(obj, options); Assert.Contains("\"MyInt\":2", json); Assert.Equal(1, obj._onSerializingCount); Assert.Equal(1, obj._onSerializedCount); Assert.Equal(0, obj._onDeserializingCount); Assert.Equal(0, obj._onDeserializedCount); obj = JsonSerializer.Deserialize<MyCyclicClass>(Json, options); Assert.Equal(2, obj.MyInt); Assert.Equal(obj, obj.Cycle); Assert.Equal(0, obj._onSerializingCount); Assert.Equal(0, obj._onSerializedCount); Assert.Equal(1, obj._onDeserializingCount); Assert.Equal(1, obj._onDeserializedCount); } private class MyCollection : List<int>, IJsonOnDeserializing, IJsonOnDeserialized, IJsonOnSerializing, IJsonOnSerialized { public void OnDeserialized() => Assert.True(false, "Not expected"); public void OnDeserializing() => Assert.True(false, "Not expected"); public void OnSerialized() => Assert.True(false, "Not expected"); public void OnSerializing() => Assert.True(false, "Not expected"); } [JsonConverter(converterType: typeof(MyValueConverter))] private class MyValue : IJsonOnDeserializing, IJsonOnDeserialized, IJsonOnSerializing, IJsonOnSerialized { public void OnDeserialized() => Assert.True(false, "Not expected"); public void OnDeserializing() => Assert.True(false, "Not expected"); public void OnSerialized() => Assert.True(false, "Not expected"); public void OnSerializing() => Assert.True(false, "Not expected"); } private class MyValueConverter : JsonConverter<MyValue> { public override MyValue? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new MyValue(); } public override void Write(Utf8JsonWriter writer, MyValue value, JsonSerializerOptions options) { writer.WriteStringValue("dummy"); } } [Fact] public static void NonPocosIgnored() { JsonSerializer.Serialize(new MyCollection()); JsonSerializer.Deserialize<MyCollection>("[]"); JsonSerializer.Serialize(new MyValue()); JsonSerializer.Deserialize<MyCollection>("[]"); } } }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/coreclr/pal/src/safecrt/sscanf_s.cpp
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*** *sscanf_s.c - read formatted data from string * * *Purpose: * defines scanf() - reads formatted data from string * *******************************************************************************/ #include <string.h> #include <errno.h> #include <limits.h> #include "internal_securecrt.h" #include "mbusafecrt_internal.h" typedef int (*INPUTFN)(miniFILE *, const unsigned char*, va_list); typedef int (*WINPUTFN)(miniFILE *, const char16_t*, va_list); extern size_t PAL_wcsnlen(const WCHAR* inString, size_t inMaxSize); /*** *static int v[nw]scan_fn([w]inputfn, string, [count], format, ...) * *Purpose: * this is a helper function which is called by the other functions * in this file - sscanf/swscanf/snscanf etc. It calls either _(w)input or * _(w)input_s depending on the first parameter. * *******************************************************************************/ static int __cdecl vscan_fn ( INPUTFN inputfn, const char *string, const char *format, va_list arglist ) { miniFILE str; miniFILE *infile = &str; int retval; size_t count = strlen(string); _VALIDATE_RETURN( (string != NULL), EINVAL, EOF); _VALIDATE_RETURN( (format != NULL), EINVAL, EOF); infile->_flag = _IOREAD|_IOSTRG|_IOMYBUF; infile->_ptr = infile->_base = (char *) string; if(count>(INT_MAX/sizeof(char))) { /* old-style functions allow any large value to mean unbounded */ infile->_cnt = INT_MAX; } else { infile->_cnt = (int)count*sizeof(char); } retval = (inputfn(infile, ( const unsigned char* )format, arglist)); return(retval); } static int __cdecl vwscan_fn ( WINPUTFN inputfn, const char16_t *string, const char16_t *format, va_list arglist ) { miniFILE str; miniFILE *infile = &str; int retval; size_t count = PAL_wcsnlen(string, INT_MAX); _VALIDATE_RETURN( (string != NULL), EINVAL, EOF); _VALIDATE_RETURN( (format != NULL), EINVAL, EOF); infile->_flag = _IOREAD|_IOSTRG|_IOMYBUF; infile->_ptr = infile->_base = (char *) string; if(count>(INT_MAX/sizeof(char16_t))) { /* old-style functions allow any large value to mean unbounded */ infile->_cnt = INT_MAX; } else { infile->_cnt = (int)count*sizeof(char16_t); } retval = (inputfn(infile, format, arglist)); return(retval); } /*** *int sscanf_s(string, format, ...) * Same as sscanf above except that it calls _input_s to do the real work. * *int snscanf_s(string, size, format, ...) * Same as snscanf above except that it calls _input_s to do the real work. * * _input_s has a size check for array parameters. * *******************************************************************************/ DLLEXPORT int __cdecl sscanf_s ( const char *string, const char *format, ... ) { int ret; va_list arglist; va_start(arglist, format); ret = vscan_fn(__tinput_s, string, format, arglist); va_end(arglist); return ret; } int __cdecl swscanf_s ( const char16_t *string, const char16_t *format, ... ) { int ret; va_list arglist; va_start(arglist, format); ret = vwscan_fn(__twinput_s, string, format, arglist); va_end(arglist); return ret; }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*** *sscanf_s.c - read formatted data from string * * *Purpose: * defines scanf() - reads formatted data from string * *******************************************************************************/ #include <string.h> #include <errno.h> #include <limits.h> #include "internal_securecrt.h" #include "mbusafecrt_internal.h" typedef int (*INPUTFN)(miniFILE *, const unsigned char*, va_list); typedef int (*WINPUTFN)(miniFILE *, const char16_t*, va_list); extern size_t PAL_wcsnlen(const WCHAR* inString, size_t inMaxSize); /*** *static int v[nw]scan_fn([w]inputfn, string, [count], format, ...) * *Purpose: * this is a helper function which is called by the other functions * in this file - sscanf/swscanf/snscanf etc. It calls either _(w)input or * _(w)input_s depending on the first parameter. * *******************************************************************************/ static int __cdecl vscan_fn ( INPUTFN inputfn, const char *string, const char *format, va_list arglist ) { miniFILE str; miniFILE *infile = &str; int retval; size_t count = strlen(string); _VALIDATE_RETURN( (string != NULL), EINVAL, EOF); _VALIDATE_RETURN( (format != NULL), EINVAL, EOF); infile->_flag = _IOREAD|_IOSTRG|_IOMYBUF; infile->_ptr = infile->_base = (char *) string; if(count>(INT_MAX/sizeof(char))) { /* old-style functions allow any large value to mean unbounded */ infile->_cnt = INT_MAX; } else { infile->_cnt = (int)count*sizeof(char); } retval = (inputfn(infile, ( const unsigned char* )format, arglist)); return(retval); } static int __cdecl vwscan_fn ( WINPUTFN inputfn, const char16_t *string, const char16_t *format, va_list arglist ) { miniFILE str; miniFILE *infile = &str; int retval; size_t count = PAL_wcsnlen(string, INT_MAX); _VALIDATE_RETURN( (string != NULL), EINVAL, EOF); _VALIDATE_RETURN( (format != NULL), EINVAL, EOF); infile->_flag = _IOREAD|_IOSTRG|_IOMYBUF; infile->_ptr = infile->_base = (char *) string; if(count>(INT_MAX/sizeof(char16_t))) { /* old-style functions allow any large value to mean unbounded */ infile->_cnt = INT_MAX; } else { infile->_cnt = (int)count*sizeof(char16_t); } retval = (inputfn(infile, format, arglist)); return(retval); } /*** *int sscanf_s(string, format, ...) * Same as sscanf above except that it calls _input_s to do the real work. * *int snscanf_s(string, size, format, ...) * Same as snscanf above except that it calls _input_s to do the real work. * * _input_s has a size check for array parameters. * *******************************************************************************/ DLLEXPORT int __cdecl sscanf_s ( const char *string, const char *format, ... ) { int ret; va_list arglist; va_start(arglist, format); ret = vscan_fn(__tinput_s, string, format, arglist); va_end(arglist); return ret; } int __cdecl swscanf_s ( const char16_t *string, const char16_t *format, ... ) { int ret; va_list arglist; va_start(arglist, format); ret = vwscan_fn(__twinput_s, string, format, arglist); va_end(arglist); return ret; }
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/libraries/System.Text.Encodings.Web/tools/updating-encodings.md
### Introduction This folder contains tools which allow updating the Unicode data within the __System.Text.Encodings.Web__ package. These data files come from the Unicode Consortium's web site (see https://www.unicode.org/Public/UCD/latest/) and are used to generate the `UnicodeRanges` class and the internal "defined characters" bitmap against which charaters to be escaped are checked. ### Current implementation The current version of the Unicode data checked in is __13.0.0__. The archived files can be found at https://unicode.org/Public/13.0.0/. ### Updating the implementation Updating the implementation consists of three steps: checking in a new version of the Unicode data files (into the [runtime-assets](https://github.com/dotnet/runtime-assets) repo), generating the shared files used by the runtime and the unit tests, and pointing the unit test files to the correct version of the data files. As a prerequisite for updating the tools, you will need the _dotnet_ tool (version 3.1 or above) available from your local command prompt. 1. Update the [runtime-assets](https://github.com/dotnet/runtime-assets) repo with the new Unicode data files. Instructions for generating new packages are listed at the repo root. Preserve the directory structure already present at https://github.com/dotnet/runtime-assets/tree/master/src/System.Private.Runtime.UnicodeData when making the change. 2. Get the latest __UnicodeData.txt__ and __Blocks.txt__ files from the Unicode Consortium web site. Drop them into a temporary location; they're not going to be committed to the main _runtime_ repo. 3. Open a command prompt and navigate to the __src/libraries/System.Text.Encodings.Web/tools/GenDefinedCharList__ directory, then run the following command, replacing the first parameter with the path to the _UnicodeData.txt_ file you downloaded in the previous step. This command will update the "defined characters" bitmap within the runtime folder. The test project also consumes the file from the _src_ folder, so running this command will update both the runtime and the test project. ```txt dotnet run --framework netcoreapp3.1 -- "path_to_UnicodeData.txt" ../../src/System/Text/Unicode/UnicodeHelpers.generated.cs ``` 4. Open a command prompt and navigate to the __src/libraries/System.Text.Encodings.Web/tools/GenUnicodeRanges__ directory, then run the following command, replacing the first parameter with the path to the _Blocks.txt_ file you downloaded earlier. This command will update the `UnicodeRanges` type in the runtime folder and update the unit tests to exercise the new APIs. ```txt dotnet run --framework netcoreapp3.1 -- "path_to_Blocks.txt" ../../src/System/Text/Unicode/UnicodeRanges.generated.cs ../../tests/UnicodeRangesTests.generated.cs ``` 5. Update the __ref__ APIs to reflect any new `UnicodeRanges` static properties which were added in the previous step, otherwise the unit test project will not be able to reference them. See https://github.com/dotnet/runtime/blob/main/docs/coding-guidelines/updating-ref-source.md for instructions on how to update the reference assemblies. 6. Update the __src/libraries/System.Text.Encodings.Web/tests/System.Text.Encodings.Web.Tests.csproj__ file to reference the new __UnicodeData.txt__ file that was added to the [runtime-assets](https://github.com/dotnet/runtime-assets) repo in step (1). Open the .csproj file in a text editor and replace the `<UnicodeUcdVersion>` property value near the top of the file to reference the new UCD version being consumed. 7. Finally, update the _Current implementation_ section at the beginning of this markdown file to reflect the version of the Unicode data files which were given to the tools. Remember also to update the URL within that section so that these data files can be easily accessed in the future. 8. Commit to Git the __*.cs__, __*.csproj__, and __*.md__ files that were modified as part of the above process.
### Introduction This folder contains tools which allow updating the Unicode data within the __System.Text.Encodings.Web__ package. These data files come from the Unicode Consortium's web site (see https://www.unicode.org/Public/UCD/latest/) and are used to generate the `UnicodeRanges` class and the internal "defined characters" bitmap against which charaters to be escaped are checked. ### Current implementation The current version of the Unicode data checked in is __13.0.0__. The archived files can be found at https://unicode.org/Public/13.0.0/. ### Updating the implementation Updating the implementation consists of three steps: checking in a new version of the Unicode data files (into the [runtime-assets](https://github.com/dotnet/runtime-assets) repo), generating the shared files used by the runtime and the unit tests, and pointing the unit test files to the correct version of the data files. As a prerequisite for updating the tools, you will need the _dotnet_ tool (version 3.1 or above) available from your local command prompt. 1. Update the [runtime-assets](https://github.com/dotnet/runtime-assets) repo with the new Unicode data files. Instructions for generating new packages are listed at the repo root. Preserve the directory structure already present at https://github.com/dotnet/runtime-assets/tree/master/src/System.Private.Runtime.UnicodeData when making the change. 2. Get the latest __UnicodeData.txt__ and __Blocks.txt__ files from the Unicode Consortium web site. Drop them into a temporary location; they're not going to be committed to the main _runtime_ repo. 3. Open a command prompt and navigate to the __src/libraries/System.Text.Encodings.Web/tools/GenDefinedCharList__ directory, then run the following command, replacing the first parameter with the path to the _UnicodeData.txt_ file you downloaded in the previous step. This command will update the "defined characters" bitmap within the runtime folder. The test project also consumes the file from the _src_ folder, so running this command will update both the runtime and the test project. ```txt dotnet run --framework netcoreapp3.1 -- "path_to_UnicodeData.txt" ../../src/System/Text/Unicode/UnicodeHelpers.generated.cs ``` 4. Open a command prompt and navigate to the __src/libraries/System.Text.Encodings.Web/tools/GenUnicodeRanges__ directory, then run the following command, replacing the first parameter with the path to the _Blocks.txt_ file you downloaded earlier. This command will update the `UnicodeRanges` type in the runtime folder and update the unit tests to exercise the new APIs. ```txt dotnet run --framework netcoreapp3.1 -- "path_to_Blocks.txt" ../../src/System/Text/Unicode/UnicodeRanges.generated.cs ../../tests/UnicodeRangesTests.generated.cs ``` 5. Update the __ref__ APIs to reflect any new `UnicodeRanges` static properties which were added in the previous step, otherwise the unit test project will not be able to reference them. See https://github.com/dotnet/runtime/blob/main/docs/coding-guidelines/updating-ref-source.md for instructions on how to update the reference assemblies. 6. Update the __src/libraries/System.Text.Encodings.Web/tests/System.Text.Encodings.Web.Tests.csproj__ file to reference the new __UnicodeData.txt__ file that was added to the [runtime-assets](https://github.com/dotnet/runtime-assets) repo in step (1). Open the .csproj file in a text editor and replace the `<UnicodeUcdVersion>` property value near the top of the file to reference the new UCD version being consumed. 7. Finally, update the _Current implementation_ section at the beginning of this markdown file to reflect the version of the Unicode data files which were given to the tools. Remember also to update the URL within that section so that these data files can be easily accessed in the future. 8. Commit to Git the __*.cs__, __*.csproj__, and __*.md__ files that were modified as part of the above process.
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/tests/JIT/Directed/cmov/Bool_No_Op_cs_do.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="Bool_No_Op.cs" /> </ItemGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <CLRTestPriority>1</CLRTestPriority> </PropertyGroup> <PropertyGroup> <DebugType>Full</DebugType> <Optimize>True</Optimize> </PropertyGroup> <ItemGroup> <Compile Include="Bool_No_Op.cs" /> </ItemGroup> </Project>
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/coreclr/vm/dwreport.h
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // // FILE: dwreport.h // // This file contains declarations for functions used to report errors occuring // in a process running managed code. // // // // ============================================================================ #ifndef __DWREPORT_H__ #define __DWREPORT_H__ // return values for DoFaultReport enum FaultReportResult { FaultReportResultAbort, FaultReportResultDebug, FaultReportResultQuit }; void* GetBucketParametersForManagedException(UINT_PTR ip, TypeOfReportedError tore, Thread * pThread, OBJECTREF * exception); void FreeBucketParametersForManagedException(void *pgmb); HRESULT GetBucketParametersForCurrentException(BucketParameters *pParams); //------------------------------------------------------------------------------ // DoFaultReport // // Description // // Parameters // pExceptionInfo -- information about the exception that caused the error. // If the error is not the result of an exception, pass NULL for this // parameter // Returns // FaultReportResult -- enumeration indicating the // FaultReportResultAbort -- if Watson could not execute normally // FaultReportResultDebug -- if Watson executed normally, and the user // chose to debug the process // FaultReportResultQuit -- if Watson executed normally, and the user // chose to end the process (e.g. pressed "Send Error Report" or // "Don't Send"). // //------------------------------------------------------------------------------ FaultReportResult DoFaultReport( // Was Watson attempted, successful? Run debugger? EXCEPTION_POINTERS *pExceptionInfo, // Information about the fault. TypeOfReportedError tore); // What sort of error is reported. BOOL IsWatsonEnabled(); BOOL RegisterOutOfProcessWatsonCallbacks(); int DwGetAssemblyVersion( // Number of characters written. _In_z_ LPCWSTR wszFilePath, // Path to the executable. _Inout_updates_(cchBuf) WCHAR *pBuf, // Put description here. int cchBuf); HRESULT DwGetFileVersionInfo( // S_OK or error _In_z_ LPCWSTR wszFilePath, // Path to the executable. USHORT& major, USHORT& minor, USHORT& build, USHORT& revision); BOOL ContainsUnicodeChars(_In_z_ LPCWSTR wsz); // Proxy parameters for Resetting Watson buckets struct ResetWatsonBucketsParams { Thread * m_pThread; EXCEPTION_RECORD * pExceptionRecord; }; void ResetWatsonBucketsFavorWorker(void * pParam); extern LONG g_watsonAlreadyLaunched; //---------------------------------------------------------------------------- // Passes data between DoFaultReport and DoFaultReportCallback //---------------------------------------------------------------------------- typedef enum tagEFaultRepRetVal EFaultRepRetVal; struct FaultReportInfo { BOOL /*in*/ m_fDoReportFault; EXCEPTION_POINTERS /*in*/ *m_pExceptionInfo; DWORD /*in*/ m_threadid; FaultReportResult /*out*/ m_faultReportResult; EFaultRepRetVal /*out*/ m_faultRepRetValResult; }; VOID WINAPI DoFaultReportDoFavorCallback(LPVOID pFaultReportInfoAsVoid); ContractFailureKind GetContractFailureKind(OBJECTREF obj); #endif // __DWREPORT_H__
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // // FILE: dwreport.h // // This file contains declarations for functions used to report errors occuring // in a process running managed code. // // // // ============================================================================ #ifndef __DWREPORT_H__ #define __DWREPORT_H__ // return values for DoFaultReport enum FaultReportResult { FaultReportResultAbort, FaultReportResultDebug, FaultReportResultQuit }; void* GetBucketParametersForManagedException(UINT_PTR ip, TypeOfReportedError tore, Thread * pThread, OBJECTREF * exception); void FreeBucketParametersForManagedException(void *pgmb); HRESULT GetBucketParametersForCurrentException(BucketParameters *pParams); //------------------------------------------------------------------------------ // DoFaultReport // // Description // // Parameters // pExceptionInfo -- information about the exception that caused the error. // If the error is not the result of an exception, pass NULL for this // parameter // Returns // FaultReportResult -- enumeration indicating the // FaultReportResultAbort -- if Watson could not execute normally // FaultReportResultDebug -- if Watson executed normally, and the user // chose to debug the process // FaultReportResultQuit -- if Watson executed normally, and the user // chose to end the process (e.g. pressed "Send Error Report" or // "Don't Send"). // //------------------------------------------------------------------------------ FaultReportResult DoFaultReport( // Was Watson attempted, successful? Run debugger? EXCEPTION_POINTERS *pExceptionInfo, // Information about the fault. TypeOfReportedError tore); // What sort of error is reported. BOOL IsWatsonEnabled(); BOOL RegisterOutOfProcessWatsonCallbacks(); int DwGetAssemblyVersion( // Number of characters written. _In_z_ LPCWSTR wszFilePath, // Path to the executable. _Inout_updates_(cchBuf) WCHAR *pBuf, // Put description here. int cchBuf); HRESULT DwGetFileVersionInfo( // S_OK or error _In_z_ LPCWSTR wszFilePath, // Path to the executable. USHORT& major, USHORT& minor, USHORT& build, USHORT& revision); BOOL ContainsUnicodeChars(_In_z_ LPCWSTR wsz); // Proxy parameters for Resetting Watson buckets struct ResetWatsonBucketsParams { Thread * m_pThread; EXCEPTION_RECORD * pExceptionRecord; }; void ResetWatsonBucketsFavorWorker(void * pParam); extern LONG g_watsonAlreadyLaunched; //---------------------------------------------------------------------------- // Passes data between DoFaultReport and DoFaultReportCallback //---------------------------------------------------------------------------- typedef enum tagEFaultRepRetVal EFaultRepRetVal; struct FaultReportInfo { BOOL /*in*/ m_fDoReportFault; EXCEPTION_POINTERS /*in*/ *m_pExceptionInfo; DWORD /*in*/ m_threadid; FaultReportResult /*out*/ m_faultReportResult; EFaultRepRetVal /*out*/ m_faultRepRetValResult; }; VOID WINAPI DoFaultReportDoFavorCallback(LPVOID pFaultReportInfoAsVoid); ContractFailureKind GetContractFailureKind(OBJECTREF obj); #endif // __DWREPORT_H__
-1
dotnet/runtime
66,280
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator
Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
stephentoub
2022-03-07T03:21:23Z
2022-03-07T21:52:38Z
30d66a2c350b4e4a6b5cd5b8aa961b3b23610fc1
457b1ffab6d99b4b9db0e4579c2be4624ba1b3aa
Enable RegexOptions.RightToLeft and lookbehinds in compiler / source generator. Replaces https://github.com/dotnet/runtime/pull/66127 Fixes https://github.com/dotnet/runtime/issues/62345 For .NET 7 we rewrote RegexCompiler as we were writing the source generator, and in doing so we left out support for RegexOptions.RightToLeft as well as lookbehinds (which are implemented via RightToLeft). This adds support for both. I initially started incrementally adding in support for various constructs in lookbehinds, but from a testing perspective it made more sense to just add it all, as then all of the RightToLeft tests are used to validate the constructs that are also in lookbehinds.
./src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/Import.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 Internal.Text; using Internal.TypeSystem; namespace ILCompiler.DependencyAnalysis.ReadyToRun { /// <summary> /// This class represents a single indirection cell in one of the import tables. /// </summary> public class Import : EmbeddedObjectNode, ISymbolDefinitionNode, ISortableSymbolNode { public readonly ImportSectionNode Table; internal readonly SignatureEmbeddedPointerIndirectionNode ImportSignature; internal readonly MethodDesc CallingMethod; public Import(ImportSectionNode tableNode, Signature importSignature, MethodDesc callingMethod = null) { Table = tableNode; CallingMethod = callingMethod; ImportSignature = new SignatureEmbeddedPointerIndirectionNode(this, importSignature); } protected override void OnMarked(NodeFactory factory) { Table.AddImport(factory, this); } protected override string GetName(NodeFactory factory) { Utf8StringBuilder sb = new Utf8StringBuilder(); AppendMangledName(factory.NameMangler, sb); return sb.ToString(); } public override int ClassCode => 667823013; public virtual bool EmitPrecode => Table.EmitPrecode; public override void EncodeData(ref ObjectDataBuilder dataBuilder, NodeFactory factory, bool relocsOnly) { // This needs to be an empty target pointer since it will be filled in with Module* // when loaded by CoreCLR dataBuilder.EmitZeroPointer(); } public virtual void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb) { sb.Append(Table.Name); sb.Append("->"); ImportSignature.AppendMangledName(nameMangler, sb); } public override bool StaticDependenciesAreComputed => true; public override IEnumerable<DependencyListEntry> GetStaticDependencies(NodeFactory factory) { return new DependencyListEntry[] { new DependencyListEntry(ImportSignature, "Signature for ready-to-run fixup import") }; } public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { Import otherNode = (Import)other; int result = comparer.Compare(CallingMethod, otherNode.CallingMethod); if (result != 0) return result; result = comparer.Compare(ImportSignature.Target, otherNode.ImportSignature.Target); if (result != 0) return result; return Table.CompareToImpl(otherNode.Table, comparer); } public override bool RepresentsIndirectionCell => true; int ISymbolDefinitionNode.Offset => OffsetFromBeginningOfArray; int ISymbolNode.Offset => 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; using System.Collections.Generic; using Internal.Text; using Internal.TypeSystem; namespace ILCompiler.DependencyAnalysis.ReadyToRun { /// <summary> /// This class represents a single indirection cell in one of the import tables. /// </summary> public class Import : EmbeddedObjectNode, ISymbolDefinitionNode, ISortableSymbolNode { public readonly ImportSectionNode Table; internal readonly SignatureEmbeddedPointerIndirectionNode ImportSignature; internal readonly MethodDesc CallingMethod; public Import(ImportSectionNode tableNode, Signature importSignature, MethodDesc callingMethod = null) { Table = tableNode; CallingMethod = callingMethod; ImportSignature = new SignatureEmbeddedPointerIndirectionNode(this, importSignature); } protected override void OnMarked(NodeFactory factory) { Table.AddImport(factory, this); } protected override string GetName(NodeFactory factory) { Utf8StringBuilder sb = new Utf8StringBuilder(); AppendMangledName(factory.NameMangler, sb); return sb.ToString(); } public override int ClassCode => 667823013; public virtual bool EmitPrecode => Table.EmitPrecode; public override void EncodeData(ref ObjectDataBuilder dataBuilder, NodeFactory factory, bool relocsOnly) { // This needs to be an empty target pointer since it will be filled in with Module* // when loaded by CoreCLR dataBuilder.EmitZeroPointer(); } public virtual void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb) { sb.Append(Table.Name); sb.Append("->"); ImportSignature.AppendMangledName(nameMangler, sb); } public override bool StaticDependenciesAreComputed => true; public override IEnumerable<DependencyListEntry> GetStaticDependencies(NodeFactory factory) { return new DependencyListEntry[] { new DependencyListEntry(ImportSignature, "Signature for ready-to-run fixup import") }; } public override int CompareToImpl(ISortableNode other, CompilerComparer comparer) { Import otherNode = (Import)other; int result = comparer.Compare(CallingMethod, otherNode.CallingMethod); if (result != 0) return result; result = comparer.Compare(ImportSignature.Target, otherNode.ImportSignature.Target); if (result != 0) return result; return Table.CompareToImpl(otherNode.Table, comparer); } public override bool RepresentsIndirectionCell => true; int ISymbolDefinitionNode.Offset => OffsetFromBeginningOfArray; int ISymbolNode.Offset => 0; } }
-1