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,075 | Keep CLSCompliantAttribute in sync for src <-> ref | Contributes to https://github.com/dotnet/runtime/issues/58163
Until two years ago, ApiCompat validated the CLSCompliantAttribute
but that check was then disabled with a675e1c2c4f46b98ecac1253223649d8f36d5da7.
Re-enable it and only disable the check during baseline api compat
validation, which is performed in ApiCompat.proj. | ViktorHofer | 2022-03-02T11:40:14Z | 2022-03-02T15:17:47Z | 58b8de991cd0cb4cbbb9a52f2a3b9734f30a659c | b61687b07672071fb31d1511d1c28d5eac616e6a | Keep CLSCompliantAttribute in sync for src <-> ref. Contributes to https://github.com/dotnet/runtime/issues/58163
Until two years ago, ApiCompat validated the CLSCompliantAttribute
but that check was then disabled with a675e1c2c4f46b98ecac1253223649d8f36d5da7.
Re-enable it and only disable the check during baseline api compat
validation, which is performed in ApiCompat.proj. | ./src/libraries/System.Private.Xml/tests/XmlReaderLib/TCSkip.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using OLEDB.Test.ModuleCore;
namespace System.Xml.Tests
{
public partial class TCSkip : TCXMLReaderBaseGeneral
{
// Type is System.Xml.Tests.TCSkip
// Test Case
public override void AddChildren()
{
// for function TestSkip1
{
this.AddChild(new CVariation(TestSkip1) { Attribute = new Variation("Call Skip on empty element") { Pri = 0 } });
}
// for function TestSkip2
{
this.AddChild(new CVariation(TestSkip2) { Attribute = new Variation("Call Skip on element") { Pri = 0 } });
}
// for function TestSkip3
{
this.AddChild(new CVariation(TestSkip3) { Attribute = new Variation("Call Skip on element with content") { Pri = 0 } });
}
// for function TestSkip4
{
this.AddChild(new CVariation(TestSkip4) { Attribute = new Variation("Call Skip on text node (leave node)") { Pri = 0 } });
}
// for function skip307543
{
this.AddChild(new CVariation(skip307543) { Attribute = new Variation("Call Skip in while read loop") { Pri = 0 } });
}
// for function TestSkip5
{
this.AddChild(new CVariation(TestSkip5) { Attribute = new Variation("Call Skip on text node with another element: <elem2>text<elem3></elem3></elem2>") });
}
// for function TestSkip6
{
this.AddChild(new CVariation(TestSkip6) { Attribute = new Variation("Call Skip on attribute") { Pri = 0 } });
}
// for function TestSkip7
{
this.AddChild(new CVariation(TestSkip7) { Attribute = new Variation("Call Skip on text node of attribute") });
}
// for function TestSkip8
{
this.AddChild(new CVariation(TestSkip8) { Attribute = new Variation("Call Skip on CDATA") { Pri = 0 } });
}
// for function TestSkip9
{
this.AddChild(new CVariation(TestSkip9) { Attribute = new Variation("Call Skip on Processing Instruction") { Pri = 0 } });
}
// for function TestSkip10
{
this.AddChild(new CVariation(TestSkip10) { Attribute = new Variation("Call Skip on Comment") { Pri = 0 } });
}
// for function TestSkip12
{
this.AddChild(new CVariation(TestSkip12) { Attribute = new Variation("Call Skip on Whitespace") { Pri = 0 } });
}
// for function TestSkip13
{
this.AddChild(new CVariation(TestSkip13) { Attribute = new Variation("Call Skip on EndElement") { Pri = 0 } });
}
// for function TestSkip14
{
this.AddChild(new CVariation(TestSkip14) { Attribute = new Variation("Call Skip on root Element") });
}
// for function TestSkip15
{
this.AddChild(new CVariation(TestSkip15) { Attribute = new Variation("Call Skip on Entity Reference") { Pri = 0 } });
}
// for function TestTextSkip1
{
this.AddChild(new CVariation(TestTextSkip1) { Attribute = new Variation("Call Skip on general entity ref node of attribute") });
}
// for function XmlTextReaderDoesHandleAmpersands
{
this.AddChild(new CVariation(XmlTextReaderDoesHandleAmpersands) { Attribute = new Variation("320154 : XmlTextReader ArgumentOutOfRangeException when handling ampersands") });
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using OLEDB.Test.ModuleCore;
namespace System.Xml.Tests
{
public partial class TCSkip : TCXMLReaderBaseGeneral
{
// Type is System.Xml.Tests.TCSkip
// Test Case
public override void AddChildren()
{
// for function TestSkip1
{
this.AddChild(new CVariation(TestSkip1) { Attribute = new Variation("Call Skip on empty element") { Pri = 0 } });
}
// for function TestSkip2
{
this.AddChild(new CVariation(TestSkip2) { Attribute = new Variation("Call Skip on element") { Pri = 0 } });
}
// for function TestSkip3
{
this.AddChild(new CVariation(TestSkip3) { Attribute = new Variation("Call Skip on element with content") { Pri = 0 } });
}
// for function TestSkip4
{
this.AddChild(new CVariation(TestSkip4) { Attribute = new Variation("Call Skip on text node (leave node)") { Pri = 0 } });
}
// for function skip307543
{
this.AddChild(new CVariation(skip307543) { Attribute = new Variation("Call Skip in while read loop") { Pri = 0 } });
}
// for function TestSkip5
{
this.AddChild(new CVariation(TestSkip5) { Attribute = new Variation("Call Skip on text node with another element: <elem2>text<elem3></elem3></elem2>") });
}
// for function TestSkip6
{
this.AddChild(new CVariation(TestSkip6) { Attribute = new Variation("Call Skip on attribute") { Pri = 0 } });
}
// for function TestSkip7
{
this.AddChild(new CVariation(TestSkip7) { Attribute = new Variation("Call Skip on text node of attribute") });
}
// for function TestSkip8
{
this.AddChild(new CVariation(TestSkip8) { Attribute = new Variation("Call Skip on CDATA") { Pri = 0 } });
}
// for function TestSkip9
{
this.AddChild(new CVariation(TestSkip9) { Attribute = new Variation("Call Skip on Processing Instruction") { Pri = 0 } });
}
// for function TestSkip10
{
this.AddChild(new CVariation(TestSkip10) { Attribute = new Variation("Call Skip on Comment") { Pri = 0 } });
}
// for function TestSkip12
{
this.AddChild(new CVariation(TestSkip12) { Attribute = new Variation("Call Skip on Whitespace") { Pri = 0 } });
}
// for function TestSkip13
{
this.AddChild(new CVariation(TestSkip13) { Attribute = new Variation("Call Skip on EndElement") { Pri = 0 } });
}
// for function TestSkip14
{
this.AddChild(new CVariation(TestSkip14) { Attribute = new Variation("Call Skip on root Element") });
}
// for function TestSkip15
{
this.AddChild(new CVariation(TestSkip15) { Attribute = new Variation("Call Skip on Entity Reference") { Pri = 0 } });
}
// for function TestTextSkip1
{
this.AddChild(new CVariation(TestTextSkip1) { Attribute = new Variation("Call Skip on general entity ref node of attribute") });
}
// for function XmlTextReaderDoesHandleAmpersands
{
this.AddChild(new CVariation(XmlTextReaderDoesHandleAmpersands) { Attribute = new Variation("320154 : XmlTextReader ArgumentOutOfRangeException when handling ampersands") });
}
}
}
}
| -1 |
dotnet/runtime | 66,075 | Keep CLSCompliantAttribute in sync for src <-> ref | Contributes to https://github.com/dotnet/runtime/issues/58163
Until two years ago, ApiCompat validated the CLSCompliantAttribute
but that check was then disabled with a675e1c2c4f46b98ecac1253223649d8f36d5da7.
Re-enable it and only disable the check during baseline api compat
validation, which is performed in ApiCompat.proj. | ViktorHofer | 2022-03-02T11:40:14Z | 2022-03-02T15:17:47Z | 58b8de991cd0cb4cbbb9a52f2a3b9734f30a659c | b61687b07672071fb31d1511d1c28d5eac616e6a | Keep CLSCompliantAttribute in sync for src <-> ref. Contributes to https://github.com/dotnet/runtime/issues/58163
Until two years ago, ApiCompat validated the CLSCompliantAttribute
but that check was then disabled with a675e1c2c4f46b98ecac1253223649d8f36d5da7.
Re-enable it and only disable the check during baseline api compat
validation, which is performed in ApiCompat.proj. | ./src/libraries/System.Globalization.Calendars/tests/System/Globalization/UmAlQuraCalendarTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Xunit;
namespace System.Globalization.Tests
{
public class UmAlQuraCalendarTests : CalendarTestBase
{
public override Calendar Calendar => new UmAlQuraCalendar();
public override DateTime MinSupportedDateTime => new DateTime(1900, 04, 30);
public override DateTime MaxSupportedDateTime => new DateTime(2077, 11, 16, 23, 59, 59).AddTicks(9999999);
public override CalendarAlgorithmType AlgorithmType => CalendarAlgorithmType.LunarCalendar;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Xunit;
namespace System.Globalization.Tests
{
public class UmAlQuraCalendarTests : CalendarTestBase
{
public override Calendar Calendar => new UmAlQuraCalendar();
public override DateTime MinSupportedDateTime => new DateTime(1900, 04, 30);
public override DateTime MaxSupportedDateTime => new DateTime(2077, 11, 16, 23, 59, 59).AddTicks(9999999);
public override CalendarAlgorithmType AlgorithmType => CalendarAlgorithmType.LunarCalendar;
}
}
| -1 |
dotnet/runtime | 66,073 | Use ApiCompatTask in ApiCompat.proj | Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ViktorHofer | 2022-03-02T11:03:07Z | 2022-03-11T17:51:22Z | 3e2d483153adcab27033340fa40ad0bcdc3acc2a | 2575ce5f513c8f5cd37f935ba70b87cbd787c8df | Use ApiCompatTask in ApiCompat.proj. Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ./eng/Version.Details.xml | <Dependencies>
<ProductDependencies>
<Dependency Name="Microsoft.NETCore.Runtime.ICU.Transport" Version="7.0.0-preview.3.22157.1">
<Uri>https://github.com/dotnet/icu</Uri>
<Sha>5416401e2e54d6ce9bef7f0c4a5fe25088c42652</Sha>
</Dependency>
<Dependency Name="System.Net.MsQuic.Transport" Version="7.0.0-alpha.1.22160.2">
<Uri>https://github.com/dotnet/msquic</Uri>
<Sha>4fe73fcad4b0af91cc49fd1f5576f0111f15f6fd</Sha>
</Dependency>
<Dependency Name="Microsoft.NET.Workload.Emscripten.Manifest-7.0.100" Version="7.0.0-preview.3.22128.1">
<Uri>https://github.com/dotnet/emsdk</Uri>
<Sha>0589b22424ef2046b3fa0f96da4ffe261ffdf7c8</Sha>
</Dependency>
<Dependency Name="System.ServiceModel.Primitives" Version="4.9.0-rc2.21473.1">
<Uri>https://github.com/dotnet/wcf</Uri>
<Sha>7f504aabb1988e9a093c1e74d8040bd52feb2f01</Sha>
</Dependency>
<Dependency Name="runtime.linux-arm64.Microsoft.NETCore.Runtime.ObjWriter" Version="1.0.0-alpha.1.22157.1">
<Uri>https://github.com/dotnet/llvm-project</Uri>
<Sha>f17917e8d6a2e3ba069cddeab873554706d502a5</Sha>
</Dependency>
<Dependency Name="runtime.linux-x64.Microsoft.NETCore.Runtime.ObjWriter" Version="1.0.0-alpha.1.22157.1">
<Uri>https://github.com/dotnet/llvm-project</Uri>
<Sha>f17917e8d6a2e3ba069cddeab873554706d502a5</Sha>
</Dependency>
<Dependency Name="runtime.linux-musl-arm64.Microsoft.NETCore.Runtime.ObjWriter" Version="1.0.0-alpha.1.22157.1">
<Uri>https://github.com/dotnet/llvm-project</Uri>
<Sha>f17917e8d6a2e3ba069cddeab873554706d502a5</Sha>
</Dependency>
<Dependency Name="runtime.linux-musl-x64.Microsoft.NETCore.Runtime.ObjWriter" Version="1.0.0-alpha.1.22157.1">
<Uri>https://github.com/dotnet/llvm-project</Uri>
<Sha>f17917e8d6a2e3ba069cddeab873554706d502a5</Sha>
</Dependency>
<Dependency Name="runtime.win-arm64.Microsoft.NETCore.Runtime.ObjWriter" Version="1.0.0-alpha.1.22157.1">
<Uri>https://github.com/dotnet/llvm-project</Uri>
<Sha>f17917e8d6a2e3ba069cddeab873554706d502a5</Sha>
</Dependency>
<Dependency Name="runtime.win-x64.Microsoft.NETCore.Runtime.ObjWriter" Version="1.0.0-alpha.1.22157.1">
<Uri>https://github.com/dotnet/llvm-project</Uri>
<Sha>f17917e8d6a2e3ba069cddeab873554706d502a5</Sha>
</Dependency>
<Dependency Name="runtime.osx.11.0-arm64.Microsoft.NETCore.Runtime.ObjWriter" Version="1.0.0-alpha.1.22157.1">
<Uri>https://github.com/dotnet/llvm-project</Uri>
<Sha>f17917e8d6a2e3ba069cddeab873554706d502a5</Sha>
</Dependency>
<Dependency Name="runtime.osx.10.12-x64.Microsoft.NETCore.Runtime.ObjWriter" Version="1.0.0-alpha.1.22157.1">
<Uri>https://github.com/dotnet/llvm-project</Uri>
<Sha>f17917e8d6a2e3ba069cddeab873554706d502a5</Sha>
</Dependency>
</ProductDependencies>
<ToolsetDependencies>
<Dependency Name="Microsoft.DotNet.Arcade.Sdk" Version="7.0.0-beta.22157.6">
<Uri>https://github.com/dotnet/arcade</Uri>
<Sha>81001b45bd54f9223905bf55f6ed0125273580fa</Sha>
</Dependency>
<Dependency Name="Microsoft.DotNet.Helix.Sdk" Version="7.0.0-beta.22157.6">
<Uri>https://github.com/dotnet/arcade</Uri>
<Sha>81001b45bd54f9223905bf55f6ed0125273580fa</Sha>
</Dependency>
<Dependency Name="Microsoft.DotNet.ApiCompat" Version="7.0.0-beta.22157.6">
<Uri>https://github.com/dotnet/arcade</Uri>
<Sha>81001b45bd54f9223905bf55f6ed0125273580fa</Sha>
</Dependency>
<Dependency Name="Microsoft.DotNet.GenAPI" Version="7.0.0-beta.22157.6">
<Uri>https://github.com/dotnet/arcade</Uri>
<Sha>81001b45bd54f9223905bf55f6ed0125273580fa</Sha>
</Dependency>
<Dependency Name="Microsoft.DotNet.GenFacades" Version="7.0.0-beta.22157.6">
<Uri>https://github.com/dotnet/arcade</Uri>
<Sha>81001b45bd54f9223905bf55f6ed0125273580fa</Sha>
</Dependency>
<Dependency Name="Microsoft.DotNet.XUnitExtensions" Version="7.0.0-beta.22157.6">
<Uri>https://github.com/dotnet/arcade</Uri>
<Sha>81001b45bd54f9223905bf55f6ed0125273580fa</Sha>
</Dependency>
<Dependency Name="Microsoft.DotNet.XUnitConsoleRunner" Version="2.5.1-beta.22157.6">
<Uri>https://github.com/dotnet/arcade</Uri>
<Sha>81001b45bd54f9223905bf55f6ed0125273580fa</Sha>
</Dependency>
<Dependency Name="Microsoft.DotNet.Build.Tasks.Archives" Version="7.0.0-beta.22157.6">
<Uri>https://github.com/dotnet/arcade</Uri>
<Sha>81001b45bd54f9223905bf55f6ed0125273580fa</Sha>
</Dependency>
<Dependency Name="Microsoft.DotNet.Build.Tasks.Packaging" Version="7.0.0-beta.22157.6">
<Uri>https://github.com/dotnet/arcade</Uri>
<Sha>81001b45bd54f9223905bf55f6ed0125273580fa</Sha>
</Dependency>
<Dependency Name="Microsoft.DotNet.Build.Tasks.Installers" Version="7.0.0-beta.22157.6">
<Uri>https://github.com/dotnet/arcade</Uri>
<Sha>81001b45bd54f9223905bf55f6ed0125273580fa</Sha>
</Dependency>
<Dependency Name="Microsoft.DotNet.Build.Tasks.Templating" Version="7.0.0-beta.22157.6">
<Uri>https://github.com/dotnet/arcade</Uri>
<Sha>81001b45bd54f9223905bf55f6ed0125273580fa</Sha>
</Dependency>
<Dependency Name="Microsoft.DotNet.Build.Tasks.Workloads" Version="7.0.0-beta.22157.6">
<Uri>https://github.com/dotnet/arcade</Uri>
<Sha>81001b45bd54f9223905bf55f6ed0125273580fa</Sha>
</Dependency>
<Dependency Name="Microsoft.DotNet.CodeAnalysis" Version="7.0.0-beta.22157.6">
<Uri>https://github.com/dotnet/arcade</Uri>
<Sha>81001b45bd54f9223905bf55f6ed0125273580fa</Sha>
</Dependency>
<Dependency Name="Microsoft.DotNet.Build.Tasks.TargetFramework" Version="7.0.0-beta.22157.6">
<Uri>https://github.com/dotnet/arcade</Uri>
<Sha>81001b45bd54f9223905bf55f6ed0125273580fa</Sha>
</Dependency>
<Dependency Name="Microsoft.DotNet.RemoteExecutor" Version="7.0.0-beta.22157.6">
<Uri>https://github.com/dotnet/arcade</Uri>
<Sha>81001b45bd54f9223905bf55f6ed0125273580fa</Sha>
</Dependency>
<Dependency Name="Microsoft.DotNet.Build.Tasks.Feed" Version="7.0.0-beta.22157.6">
<Uri>https://github.com/dotnet/arcade</Uri>
<Sha>81001b45bd54f9223905bf55f6ed0125273580fa</Sha>
</Dependency>
<Dependency Name="Microsoft.DotNet.VersionTools.Tasks" Version="7.0.0-beta.22157.6">
<Uri>https://github.com/dotnet/arcade</Uri>
<Sha>81001b45bd54f9223905bf55f6ed0125273580fa</Sha>
</Dependency>
<Dependency Name="Microsoft.DotNet.SharedFramework.Sdk" Version="7.0.0-beta.22157.6">
<Uri>https://github.com/dotnet/arcade</Uri>
<Sha>81001b45bd54f9223905bf55f6ed0125273580fa</Sha>
</Dependency>
<Dependency Name="Microsoft.NET.Test.Sdk" Version="16.9.0-preview-20201201-01">
<Uri>https://github.com/microsoft/vstest</Uri>
<Sha>140434f7109d357d0158ade9e5164a4861513965</Sha>
</Dependency>
<Dependency Name="System.ComponentModel.TypeConverter.TestData" Version="7.0.0-beta.22160.1">
<Uri>https://github.com/dotnet/runtime-assets</Uri>
<Sha>0d1f1eaa40d3e584ff491e7c295201556dc793dd</Sha>
</Dependency>
<Dependency Name="System.Drawing.Common.TestData" Version="7.0.0-beta.22160.1">
<Uri>https://github.com/dotnet/runtime-assets</Uri>
<Sha>0d1f1eaa40d3e584ff491e7c295201556dc793dd</Sha>
</Dependency>
<Dependency Name="System.IO.Compression.TestData" Version="7.0.0-beta.22160.1">
<Uri>https://github.com/dotnet/runtime-assets</Uri>
<Sha>0d1f1eaa40d3e584ff491e7c295201556dc793dd</Sha>
</Dependency>
<Dependency Name="System.IO.Packaging.TestData" Version="7.0.0-beta.22160.1">
<Uri>https://github.com/dotnet/runtime-assets</Uri>
<Sha>0d1f1eaa40d3e584ff491e7c295201556dc793dd</Sha>
</Dependency>
<Dependency Name="System.Net.TestData" Version="7.0.0-beta.22160.1">
<Uri>https://github.com/dotnet/runtime-assets</Uri>
<Sha>0d1f1eaa40d3e584ff491e7c295201556dc793dd</Sha>
</Dependency>
<Dependency Name="System.Private.Runtime.UnicodeData" Version="7.0.0-beta.22160.1">
<Uri>https://github.com/dotnet/runtime-assets</Uri>
<Sha>0d1f1eaa40d3e584ff491e7c295201556dc793dd</Sha>
</Dependency>
<Dependency Name="System.Runtime.TimeZoneData" Version="7.0.0-beta.22160.1">
<Uri>https://github.com/dotnet/runtime-assets</Uri>
<Sha>0d1f1eaa40d3e584ff491e7c295201556dc793dd</Sha>
</Dependency>
<Dependency Name="System.Security.Cryptography.X509Certificates.TestData" Version="7.0.0-beta.22160.1">
<Uri>https://github.com/dotnet/runtime-assets</Uri>
<Sha>0d1f1eaa40d3e584ff491e7c295201556dc793dd</Sha>
</Dependency>
<Dependency Name="System.Text.RegularExpressions.TestData" Version="7.0.0-beta.22160.1">
<Uri>https://github.com/dotnet/runtime-assets</Uri>
<Sha>0d1f1eaa40d3e584ff491e7c295201556dc793dd</Sha>
</Dependency>
<Dependency Name="System.Windows.Extensions.TestData" Version="7.0.0-beta.22160.1">
<Uri>https://github.com/dotnet/runtime-assets</Uri>
<Sha>0d1f1eaa40d3e584ff491e7c295201556dc793dd</Sha>
</Dependency>
<Dependency Name="Microsoft.DotNet.CilStrip.Sources" Version="7.0.0-beta.22160.1">
<Uri>https://github.com/dotnet/runtime-assets</Uri>
<Sha>0d1f1eaa40d3e584ff491e7c295201556dc793dd</Sha>
</Dependency>
<Dependency Name="runtime.linux-arm64.Microsoft.NETCore.Runtime.Mono.LLVM.Sdk" Version="11.1.0-alpha.1.22121.2">
<Uri>https://github.com/dotnet/llvm-project</Uri>
<Sha>ca193c123ac7e89e417f1bd0de78cd42e0553924</Sha>
</Dependency>
<Dependency Name="runtime.linux-arm64.Microsoft.NETCore.Runtime.Mono.LLVM.Tools" Version="11.1.0-alpha.1.22121.2">
<Uri>https://github.com/dotnet/llvm-project</Uri>
<Sha>ca193c123ac7e89e417f1bd0de78cd42e0553924</Sha>
</Dependency>
<Dependency Name="runtime.linux-x64.Microsoft.NETCore.Runtime.Mono.LLVM.Sdk" Version="11.1.0-alpha.1.22121.2">
<Uri>https://github.com/dotnet/llvm-project</Uri>
<Sha>ca193c123ac7e89e417f1bd0de78cd42e0553924</Sha>
</Dependency>
<Dependency Name="runtime.linux-x64.Microsoft.NETCore.Runtime.Mono.LLVM.Tools" Version="11.1.0-alpha.1.22121.2">
<Uri>https://github.com/dotnet/llvm-project</Uri>
<Sha>ca193c123ac7e89e417f1bd0de78cd42e0553924</Sha>
</Dependency>
<Dependency Name="runtime.win-x64.Microsoft.NETCore.Runtime.Mono.LLVM.Sdk" Version="11.1.0-alpha.1.22121.2">
<Uri>https://github.com/dotnet/llvm-project</Uri>
<Sha>ca193c123ac7e89e417f1bd0de78cd42e0553924</Sha>
</Dependency>
<Dependency Name="runtime.win-x64.Microsoft.NETCore.Runtime.Mono.LLVM.Tools" Version="11.1.0-alpha.1.22121.2">
<Uri>https://github.com/dotnet/llvm-project</Uri>
<Sha>ca193c123ac7e89e417f1bd0de78cd42e0553924</Sha>
</Dependency>
<Dependency Name="runtime.osx.10.12-x64.Microsoft.NETCore.Runtime.Mono.LLVM.Sdk" Version="11.1.0-alpha.1.22121.2">
<Uri>https://github.com/dotnet/llvm-project</Uri>
<Sha>ca193c123ac7e89e417f1bd0de78cd42e0553924</Sha>
</Dependency>
<Dependency Name="runtime.osx.10.12-x64.Microsoft.NETCore.Runtime.Mono.LLVM.Tools" Version="11.1.0-alpha.1.22121.2">
<Uri>https://github.com/dotnet/llvm-project</Uri>
<Sha>ca193c123ac7e89e417f1bd0de78cd42e0553924</Sha>
</Dependency>
<Dependency Name="Microsoft.NETCore.App.Runtime.win-x64" Version="7.0.0-preview.3.22157.1">
<Uri>https://github.com/dotnet/runtime</Uri>
<Sha>7698a9a80c5f6270aa1122d79ce419c7b03f2498</Sha>
</Dependency>
<Dependency Name="Microsoft.NETCore.DotNetHost" Version="7.0.0-preview.3.22157.1">
<Uri>https://github.com/dotnet/runtime</Uri>
<Sha>7698a9a80c5f6270aa1122d79ce419c7b03f2498</Sha>
</Dependency>
<Dependency Name="Microsoft.NETCore.DotNetHostPolicy" Version="7.0.0-preview.3.22157.1">
<Uri>https://github.com/dotnet/runtime</Uri>
<Sha>7698a9a80c5f6270aa1122d79ce419c7b03f2498</Sha>
</Dependency>
<Dependency Name="runtime.native.System.IO.Ports" Version="7.0.0-preview.3.22157.1">
<Uri>https://github.com/dotnet/runtime</Uri>
<Sha>7698a9a80c5f6270aa1122d79ce419c7b03f2498</Sha>
</Dependency>
<Dependency Name="Microsoft.NETCore.ILAsm" Version="7.0.0-preview.3.22157.1">
<Uri>https://github.com/dotnet/runtime</Uri>
<Sha>7698a9a80c5f6270aa1122d79ce419c7b03f2498</Sha>
</Dependency>
<Dependency Name="Microsoft.NET.Sdk.IL" Version="7.0.0-preview.3.22157.1">
<Uri>https://github.com/dotnet/runtime</Uri>
<Sha>7698a9a80c5f6270aa1122d79ce419c7b03f2498</Sha>
</Dependency>
<Dependency Name="System.Text.Json" Version="7.0.0-preview.3.22157.1">
<Uri>https://github.com/dotnet/runtime</Uri>
<Sha>7698a9a80c5f6270aa1122d79ce419c7b03f2498</Sha>
</Dependency>
<Dependency Name="Microsoft.NET.ILLink.Tasks" Version="7.0.100-1.22160.1">
<Uri>https://github.com/dotnet/linker</Uri>
<Sha>5baeb5e08b4a5fd6995e6247c7cb41b673c5ecdc</Sha>
</Dependency>
<Dependency Name="Microsoft.DotNet.XHarness.TestRunners.Common" Version="1.0.0-prerelease.22160.1">
<Uri>https://github.com/dotnet/xharness</Uri>
<Sha>17956df760439a8eedf6acc2ef510a6fe185124a</Sha>
</Dependency>
<Dependency Name="Microsoft.DotNet.XHarness.TestRunners.Xunit" Version="1.0.0-prerelease.22160.1">
<Uri>https://github.com/dotnet/xharness</Uri>
<Sha>17956df760439a8eedf6acc2ef510a6fe185124a</Sha>
</Dependency>
<Dependency Name="Microsoft.DotNet.XHarness.CLI" Version="1.0.0-prerelease.22160.1">
<Uri>https://github.com/dotnet/xharness</Uri>
<Sha>17956df760439a8eedf6acc2ef510a6fe185124a</Sha>
</Dependency>
<Dependency Name="Microsoft.DotNet.PackageTesting" Version="7.0.0-beta.22157.6">
<Uri>https://github.com/dotnet/arcade</Uri>
<Sha>81001b45bd54f9223905bf55f6ed0125273580fa</Sha>
</Dependency>
<Dependency Name="optimization.windows_nt-x64.MIBC.Runtime" Version="1.0.0-prerelease.22121.2">
<Uri>https://dev.azure.com/dnceng/internal/_git/dotnet-optimization</Uri>
<Sha>a44e13253c25ec42c4700d4d7ba6f84d9751a387</Sha>
</Dependency>
<Dependency Name="optimization.windows_nt-x86.MIBC.Runtime" Version="1.0.0-prerelease.22121.2">
<Uri>https://dev.azure.com/dnceng/internal/_git/dotnet-optimization</Uri>
<Sha>a44e13253c25ec42c4700d4d7ba6f84d9751a387</Sha>
</Dependency>
<Dependency Name="optimization.linux-x64.MIBC.Runtime" Version="1.0.0-prerelease.22121.2">
<Uri>https://dev.azure.com/dnceng/internal/_git/dotnet-optimization</Uri>
<Sha>a44e13253c25ec42c4700d4d7ba6f84d9751a387</Sha>
</Dependency>
<Dependency Name="optimization.PGO.CoreCLR" Version="1.0.0-prerelease.22121.2">
<Uri>https://dev.azure.com/dnceng/internal/_git/dotnet-optimization</Uri>
<Sha>a44e13253c25ec42c4700d4d7ba6f84d9751a387</Sha>
</Dependency>
<Dependency Name="Microsoft.DotNet.HotReload.Utils.Generator.BuildTool" Version="1.0.2-alpha.0.22157.2">
<Uri>https://github.com/dotnet/hotreload-utils</Uri>
<Sha>71e00538eb121ebd6680c8cf4856a0dbd05837bf</Sha>
</Dependency>
<Dependency Name="System.Runtime.Numerics.TestData" Version="7.0.0-beta.22160.1">
<Uri>https://github.com/dotnet/runtime-assets</Uri>
<Sha>0d1f1eaa40d3e584ff491e7c295201556dc793dd</Sha>
</Dependency>
<Dependency Name="Microsoft.CodeAnalysis.NetAnalyzers" Version="7.0.0-preview1.22160.2">
<Uri>https://github.com/dotnet/roslyn-analyzers</Uri>
<Sha>729bd06a94b8f9f76fa1d700acf4bb4948551167</Sha>
</Dependency>
<Dependency Name="Microsoft.DotNet.Compatibility" Version="2.0.0-alpha.1.21525.11">
<Uri>https://github.com/dotnet/sdk</Uri>
<Sha>957ae5ca599fdeaee425d23928d42da711373a5e</Sha>
</Dependency>
</ToolsetDependencies>
</Dependencies>
| <Dependencies>
<ProductDependencies>
<Dependency Name="Microsoft.NETCore.Runtime.ICU.Transport" Version="7.0.0-preview.3.22157.1">
<Uri>https://github.com/dotnet/icu</Uri>
<Sha>5416401e2e54d6ce9bef7f0c4a5fe25088c42652</Sha>
</Dependency>
<Dependency Name="System.Net.MsQuic.Transport" Version="7.0.0-alpha.1.22160.2">
<Uri>https://github.com/dotnet/msquic</Uri>
<Sha>4fe73fcad4b0af91cc49fd1f5576f0111f15f6fd</Sha>
</Dependency>
<Dependency Name="Microsoft.NET.Workload.Emscripten.Manifest-7.0.100" Version="7.0.0-preview.3.22128.1">
<Uri>https://github.com/dotnet/emsdk</Uri>
<Sha>0589b22424ef2046b3fa0f96da4ffe261ffdf7c8</Sha>
</Dependency>
<Dependency Name="System.ServiceModel.Primitives" Version="4.9.0-rc2.21473.1">
<Uri>https://github.com/dotnet/wcf</Uri>
<Sha>7f504aabb1988e9a093c1e74d8040bd52feb2f01</Sha>
</Dependency>
<Dependency Name="runtime.linux-arm64.Microsoft.NETCore.Runtime.ObjWriter" Version="1.0.0-alpha.1.22157.1">
<Uri>https://github.com/dotnet/llvm-project</Uri>
<Sha>f17917e8d6a2e3ba069cddeab873554706d502a5</Sha>
</Dependency>
<Dependency Name="runtime.linux-x64.Microsoft.NETCore.Runtime.ObjWriter" Version="1.0.0-alpha.1.22157.1">
<Uri>https://github.com/dotnet/llvm-project</Uri>
<Sha>f17917e8d6a2e3ba069cddeab873554706d502a5</Sha>
</Dependency>
<Dependency Name="runtime.linux-musl-arm64.Microsoft.NETCore.Runtime.ObjWriter" Version="1.0.0-alpha.1.22157.1">
<Uri>https://github.com/dotnet/llvm-project</Uri>
<Sha>f17917e8d6a2e3ba069cddeab873554706d502a5</Sha>
</Dependency>
<Dependency Name="runtime.linux-musl-x64.Microsoft.NETCore.Runtime.ObjWriter" Version="1.0.0-alpha.1.22157.1">
<Uri>https://github.com/dotnet/llvm-project</Uri>
<Sha>f17917e8d6a2e3ba069cddeab873554706d502a5</Sha>
</Dependency>
<Dependency Name="runtime.win-arm64.Microsoft.NETCore.Runtime.ObjWriter" Version="1.0.0-alpha.1.22157.1">
<Uri>https://github.com/dotnet/llvm-project</Uri>
<Sha>f17917e8d6a2e3ba069cddeab873554706d502a5</Sha>
</Dependency>
<Dependency Name="runtime.win-x64.Microsoft.NETCore.Runtime.ObjWriter" Version="1.0.0-alpha.1.22157.1">
<Uri>https://github.com/dotnet/llvm-project</Uri>
<Sha>f17917e8d6a2e3ba069cddeab873554706d502a5</Sha>
</Dependency>
<Dependency Name="runtime.osx.11.0-arm64.Microsoft.NETCore.Runtime.ObjWriter" Version="1.0.0-alpha.1.22157.1">
<Uri>https://github.com/dotnet/llvm-project</Uri>
<Sha>f17917e8d6a2e3ba069cddeab873554706d502a5</Sha>
</Dependency>
<Dependency Name="runtime.osx.10.12-x64.Microsoft.NETCore.Runtime.ObjWriter" Version="1.0.0-alpha.1.22157.1">
<Uri>https://github.com/dotnet/llvm-project</Uri>
<Sha>f17917e8d6a2e3ba069cddeab873554706d502a5</Sha>
</Dependency>
</ProductDependencies>
<ToolsetDependencies>
<Dependency Name="Microsoft.DotNet.Arcade.Sdk" Version="7.0.0-beta.22157.6">
<Uri>https://github.com/dotnet/arcade</Uri>
<Sha>81001b45bd54f9223905bf55f6ed0125273580fa</Sha>
</Dependency>
<Dependency Name="Microsoft.DotNet.Helix.Sdk" Version="7.0.0-beta.22157.6">
<Uri>https://github.com/dotnet/arcade</Uri>
<Sha>81001b45bd54f9223905bf55f6ed0125273580fa</Sha>
</Dependency>
<Dependency Name="Microsoft.DotNet.ApiCompat" Version="7.0.0-beta.22159.9">
<Uri>https://github.com/dotnet/arcade</Uri>
<Sha>3d988e17f3317c888c82e21b4b3dd5196dfc4d78</Sha>
</Dependency>
<Dependency Name="Microsoft.DotNet.GenAPI" Version="7.0.0-beta.22157.6">
<Uri>https://github.com/dotnet/arcade</Uri>
<Sha>81001b45bd54f9223905bf55f6ed0125273580fa</Sha>
</Dependency>
<Dependency Name="Microsoft.DotNet.GenFacades" Version="7.0.0-beta.22157.6">
<Uri>https://github.com/dotnet/arcade</Uri>
<Sha>81001b45bd54f9223905bf55f6ed0125273580fa</Sha>
</Dependency>
<Dependency Name="Microsoft.DotNet.XUnitExtensions" Version="7.0.0-beta.22157.6">
<Uri>https://github.com/dotnet/arcade</Uri>
<Sha>81001b45bd54f9223905bf55f6ed0125273580fa</Sha>
</Dependency>
<Dependency Name="Microsoft.DotNet.XUnitConsoleRunner" Version="2.5.1-beta.22157.6">
<Uri>https://github.com/dotnet/arcade</Uri>
<Sha>81001b45bd54f9223905bf55f6ed0125273580fa</Sha>
</Dependency>
<Dependency Name="Microsoft.DotNet.Build.Tasks.Archives" Version="7.0.0-beta.22157.6">
<Uri>https://github.com/dotnet/arcade</Uri>
<Sha>81001b45bd54f9223905bf55f6ed0125273580fa</Sha>
</Dependency>
<Dependency Name="Microsoft.DotNet.Build.Tasks.Packaging" Version="7.0.0-beta.22157.6">
<Uri>https://github.com/dotnet/arcade</Uri>
<Sha>81001b45bd54f9223905bf55f6ed0125273580fa</Sha>
</Dependency>
<Dependency Name="Microsoft.DotNet.Build.Tasks.Installers" Version="7.0.0-beta.22157.6">
<Uri>https://github.com/dotnet/arcade</Uri>
<Sha>81001b45bd54f9223905bf55f6ed0125273580fa</Sha>
</Dependency>
<Dependency Name="Microsoft.DotNet.Build.Tasks.Templating" Version="7.0.0-beta.22157.6">
<Uri>https://github.com/dotnet/arcade</Uri>
<Sha>81001b45bd54f9223905bf55f6ed0125273580fa</Sha>
</Dependency>
<Dependency Name="Microsoft.DotNet.Build.Tasks.Workloads" Version="7.0.0-beta.22157.6">
<Uri>https://github.com/dotnet/arcade</Uri>
<Sha>81001b45bd54f9223905bf55f6ed0125273580fa</Sha>
</Dependency>
<Dependency Name="Microsoft.DotNet.CodeAnalysis" Version="7.0.0-beta.22157.6">
<Uri>https://github.com/dotnet/arcade</Uri>
<Sha>81001b45bd54f9223905bf55f6ed0125273580fa</Sha>
</Dependency>
<Dependency Name="Microsoft.DotNet.Build.Tasks.TargetFramework" Version="7.0.0-beta.22157.6">
<Uri>https://github.com/dotnet/arcade</Uri>
<Sha>81001b45bd54f9223905bf55f6ed0125273580fa</Sha>
</Dependency>
<Dependency Name="Microsoft.DotNet.RemoteExecutor" Version="7.0.0-beta.22157.6">
<Uri>https://github.com/dotnet/arcade</Uri>
<Sha>81001b45bd54f9223905bf55f6ed0125273580fa</Sha>
</Dependency>
<Dependency Name="Microsoft.DotNet.Build.Tasks.Feed" Version="7.0.0-beta.22157.6">
<Uri>https://github.com/dotnet/arcade</Uri>
<Sha>81001b45bd54f9223905bf55f6ed0125273580fa</Sha>
</Dependency>
<Dependency Name="Microsoft.DotNet.VersionTools.Tasks" Version="7.0.0-beta.22157.6">
<Uri>https://github.com/dotnet/arcade</Uri>
<Sha>81001b45bd54f9223905bf55f6ed0125273580fa</Sha>
</Dependency>
<Dependency Name="Microsoft.DotNet.SharedFramework.Sdk" Version="7.0.0-beta.22157.6">
<Uri>https://github.com/dotnet/arcade</Uri>
<Sha>81001b45bd54f9223905bf55f6ed0125273580fa</Sha>
</Dependency>
<Dependency Name="Microsoft.NET.Test.Sdk" Version="16.9.0-preview-20201201-01">
<Uri>https://github.com/microsoft/vstest</Uri>
<Sha>140434f7109d357d0158ade9e5164a4861513965</Sha>
</Dependency>
<Dependency Name="System.ComponentModel.TypeConverter.TestData" Version="7.0.0-beta.22160.1">
<Uri>https://github.com/dotnet/runtime-assets</Uri>
<Sha>0d1f1eaa40d3e584ff491e7c295201556dc793dd</Sha>
</Dependency>
<Dependency Name="System.Drawing.Common.TestData" Version="7.0.0-beta.22160.1">
<Uri>https://github.com/dotnet/runtime-assets</Uri>
<Sha>0d1f1eaa40d3e584ff491e7c295201556dc793dd</Sha>
</Dependency>
<Dependency Name="System.IO.Compression.TestData" Version="7.0.0-beta.22160.1">
<Uri>https://github.com/dotnet/runtime-assets</Uri>
<Sha>0d1f1eaa40d3e584ff491e7c295201556dc793dd</Sha>
</Dependency>
<Dependency Name="System.IO.Packaging.TestData" Version="7.0.0-beta.22160.1">
<Uri>https://github.com/dotnet/runtime-assets</Uri>
<Sha>0d1f1eaa40d3e584ff491e7c295201556dc793dd</Sha>
</Dependency>
<Dependency Name="System.Net.TestData" Version="7.0.0-beta.22160.1">
<Uri>https://github.com/dotnet/runtime-assets</Uri>
<Sha>0d1f1eaa40d3e584ff491e7c295201556dc793dd</Sha>
</Dependency>
<Dependency Name="System.Private.Runtime.UnicodeData" Version="7.0.0-beta.22160.1">
<Uri>https://github.com/dotnet/runtime-assets</Uri>
<Sha>0d1f1eaa40d3e584ff491e7c295201556dc793dd</Sha>
</Dependency>
<Dependency Name="System.Runtime.TimeZoneData" Version="7.0.0-beta.22160.1">
<Uri>https://github.com/dotnet/runtime-assets</Uri>
<Sha>0d1f1eaa40d3e584ff491e7c295201556dc793dd</Sha>
</Dependency>
<Dependency Name="System.Security.Cryptography.X509Certificates.TestData" Version="7.0.0-beta.22160.1">
<Uri>https://github.com/dotnet/runtime-assets</Uri>
<Sha>0d1f1eaa40d3e584ff491e7c295201556dc793dd</Sha>
</Dependency>
<Dependency Name="System.Text.RegularExpressions.TestData" Version="7.0.0-beta.22160.1">
<Uri>https://github.com/dotnet/runtime-assets</Uri>
<Sha>0d1f1eaa40d3e584ff491e7c295201556dc793dd</Sha>
</Dependency>
<Dependency Name="System.Windows.Extensions.TestData" Version="7.0.0-beta.22160.1">
<Uri>https://github.com/dotnet/runtime-assets</Uri>
<Sha>0d1f1eaa40d3e584ff491e7c295201556dc793dd</Sha>
</Dependency>
<Dependency Name="Microsoft.DotNet.CilStrip.Sources" Version="7.0.0-beta.22160.1">
<Uri>https://github.com/dotnet/runtime-assets</Uri>
<Sha>0d1f1eaa40d3e584ff491e7c295201556dc793dd</Sha>
</Dependency>
<Dependency Name="runtime.linux-arm64.Microsoft.NETCore.Runtime.Mono.LLVM.Sdk" Version="11.1.0-alpha.1.22121.2">
<Uri>https://github.com/dotnet/llvm-project</Uri>
<Sha>ca193c123ac7e89e417f1bd0de78cd42e0553924</Sha>
</Dependency>
<Dependency Name="runtime.linux-arm64.Microsoft.NETCore.Runtime.Mono.LLVM.Tools" Version="11.1.0-alpha.1.22121.2">
<Uri>https://github.com/dotnet/llvm-project</Uri>
<Sha>ca193c123ac7e89e417f1bd0de78cd42e0553924</Sha>
</Dependency>
<Dependency Name="runtime.linux-x64.Microsoft.NETCore.Runtime.Mono.LLVM.Sdk" Version="11.1.0-alpha.1.22121.2">
<Uri>https://github.com/dotnet/llvm-project</Uri>
<Sha>ca193c123ac7e89e417f1bd0de78cd42e0553924</Sha>
</Dependency>
<Dependency Name="runtime.linux-x64.Microsoft.NETCore.Runtime.Mono.LLVM.Tools" Version="11.1.0-alpha.1.22121.2">
<Uri>https://github.com/dotnet/llvm-project</Uri>
<Sha>ca193c123ac7e89e417f1bd0de78cd42e0553924</Sha>
</Dependency>
<Dependency Name="runtime.win-x64.Microsoft.NETCore.Runtime.Mono.LLVM.Sdk" Version="11.1.0-alpha.1.22121.2">
<Uri>https://github.com/dotnet/llvm-project</Uri>
<Sha>ca193c123ac7e89e417f1bd0de78cd42e0553924</Sha>
</Dependency>
<Dependency Name="runtime.win-x64.Microsoft.NETCore.Runtime.Mono.LLVM.Tools" Version="11.1.0-alpha.1.22121.2">
<Uri>https://github.com/dotnet/llvm-project</Uri>
<Sha>ca193c123ac7e89e417f1bd0de78cd42e0553924</Sha>
</Dependency>
<Dependency Name="runtime.osx.10.12-x64.Microsoft.NETCore.Runtime.Mono.LLVM.Sdk" Version="11.1.0-alpha.1.22121.2">
<Uri>https://github.com/dotnet/llvm-project</Uri>
<Sha>ca193c123ac7e89e417f1bd0de78cd42e0553924</Sha>
</Dependency>
<Dependency Name="runtime.osx.10.12-x64.Microsoft.NETCore.Runtime.Mono.LLVM.Tools" Version="11.1.0-alpha.1.22121.2">
<Uri>https://github.com/dotnet/llvm-project</Uri>
<Sha>ca193c123ac7e89e417f1bd0de78cd42e0553924</Sha>
</Dependency>
<Dependency Name="Microsoft.NETCore.App.Runtime.win-x64" Version="7.0.0-preview.3.22157.1">
<Uri>https://github.com/dotnet/runtime</Uri>
<Sha>7698a9a80c5f6270aa1122d79ce419c7b03f2498</Sha>
</Dependency>
<Dependency Name="Microsoft.NETCore.DotNetHost" Version="7.0.0-preview.3.22157.1">
<Uri>https://github.com/dotnet/runtime</Uri>
<Sha>7698a9a80c5f6270aa1122d79ce419c7b03f2498</Sha>
</Dependency>
<Dependency Name="Microsoft.NETCore.DotNetHostPolicy" Version="7.0.0-preview.3.22157.1">
<Uri>https://github.com/dotnet/runtime</Uri>
<Sha>7698a9a80c5f6270aa1122d79ce419c7b03f2498</Sha>
</Dependency>
<Dependency Name="runtime.native.System.IO.Ports" Version="7.0.0-preview.3.22157.1">
<Uri>https://github.com/dotnet/runtime</Uri>
<Sha>7698a9a80c5f6270aa1122d79ce419c7b03f2498</Sha>
</Dependency>
<Dependency Name="Microsoft.NETCore.ILAsm" Version="7.0.0-preview.3.22157.1">
<Uri>https://github.com/dotnet/runtime</Uri>
<Sha>7698a9a80c5f6270aa1122d79ce419c7b03f2498</Sha>
</Dependency>
<Dependency Name="Microsoft.NET.Sdk.IL" Version="7.0.0-preview.3.22157.1">
<Uri>https://github.com/dotnet/runtime</Uri>
<Sha>7698a9a80c5f6270aa1122d79ce419c7b03f2498</Sha>
</Dependency>
<Dependency Name="System.Text.Json" Version="7.0.0-preview.3.22157.1">
<Uri>https://github.com/dotnet/runtime</Uri>
<Sha>7698a9a80c5f6270aa1122d79ce419c7b03f2498</Sha>
</Dependency>
<Dependency Name="Microsoft.NET.ILLink.Tasks" Version="7.0.100-1.22160.1">
<Uri>https://github.com/dotnet/linker</Uri>
<Sha>5baeb5e08b4a5fd6995e6247c7cb41b673c5ecdc</Sha>
</Dependency>
<Dependency Name="Microsoft.DotNet.XHarness.TestRunners.Common" Version="1.0.0-prerelease.22160.1">
<Uri>https://github.com/dotnet/xharness</Uri>
<Sha>17956df760439a8eedf6acc2ef510a6fe185124a</Sha>
</Dependency>
<Dependency Name="Microsoft.DotNet.XHarness.TestRunners.Xunit" Version="1.0.0-prerelease.22160.1">
<Uri>https://github.com/dotnet/xharness</Uri>
<Sha>17956df760439a8eedf6acc2ef510a6fe185124a</Sha>
</Dependency>
<Dependency Name="Microsoft.DotNet.XHarness.CLI" Version="1.0.0-prerelease.22160.1">
<Uri>https://github.com/dotnet/xharness</Uri>
<Sha>17956df760439a8eedf6acc2ef510a6fe185124a</Sha>
</Dependency>
<Dependency Name="Microsoft.DotNet.PackageTesting" Version="7.0.0-beta.22157.6">
<Uri>https://github.com/dotnet/arcade</Uri>
<Sha>81001b45bd54f9223905bf55f6ed0125273580fa</Sha>
</Dependency>
<Dependency Name="optimization.windows_nt-x64.MIBC.Runtime" Version="1.0.0-prerelease.22121.2">
<Uri>https://dev.azure.com/dnceng/internal/_git/dotnet-optimization</Uri>
<Sha>a44e13253c25ec42c4700d4d7ba6f84d9751a387</Sha>
</Dependency>
<Dependency Name="optimization.windows_nt-x86.MIBC.Runtime" Version="1.0.0-prerelease.22121.2">
<Uri>https://dev.azure.com/dnceng/internal/_git/dotnet-optimization</Uri>
<Sha>a44e13253c25ec42c4700d4d7ba6f84d9751a387</Sha>
</Dependency>
<Dependency Name="optimization.linux-x64.MIBC.Runtime" Version="1.0.0-prerelease.22121.2">
<Uri>https://dev.azure.com/dnceng/internal/_git/dotnet-optimization</Uri>
<Sha>a44e13253c25ec42c4700d4d7ba6f84d9751a387</Sha>
</Dependency>
<Dependency Name="optimization.PGO.CoreCLR" Version="1.0.0-prerelease.22121.2">
<Uri>https://dev.azure.com/dnceng/internal/_git/dotnet-optimization</Uri>
<Sha>a44e13253c25ec42c4700d4d7ba6f84d9751a387</Sha>
</Dependency>
<Dependency Name="Microsoft.DotNet.HotReload.Utils.Generator.BuildTool" Version="1.0.2-alpha.0.22157.2">
<Uri>https://github.com/dotnet/hotreload-utils</Uri>
<Sha>71e00538eb121ebd6680c8cf4856a0dbd05837bf</Sha>
</Dependency>
<Dependency Name="System.Runtime.Numerics.TestData" Version="7.0.0-beta.22160.1">
<Uri>https://github.com/dotnet/runtime-assets</Uri>
<Sha>0d1f1eaa40d3e584ff491e7c295201556dc793dd</Sha>
</Dependency>
<Dependency Name="Microsoft.CodeAnalysis.NetAnalyzers" Version="7.0.0-preview1.22160.2">
<Uri>https://github.com/dotnet/roslyn-analyzers</Uri>
<Sha>729bd06a94b8f9f76fa1d700acf4bb4948551167</Sha>
</Dependency>
<Dependency Name="Microsoft.DotNet.Compatibility" Version="2.0.0-alpha.1.21525.11">
<Uri>https://github.com/dotnet/sdk</Uri>
<Sha>957ae5ca599fdeaee425d23928d42da711373a5e</Sha>
</Dependency>
</ToolsetDependencies>
</Dependencies>
| 1 |
dotnet/runtime | 66,073 | Use ApiCompatTask in ApiCompat.proj | Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ViktorHofer | 2022-03-02T11:03:07Z | 2022-03-11T17:51:22Z | 3e2d483153adcab27033340fa40ad0bcdc3acc2a | 2575ce5f513c8f5cd37f935ba70b87cbd787c8df | Use ApiCompatTask in ApiCompat.proj. Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ./eng/Versions.props | <Project>
<PropertyGroup>
<!-- The .NET product branding version -->
<ProductVersion>7.0.0</ProductVersion>
<!-- File version numbers -->
<MajorVersion>7</MajorVersion>
<MinorVersion>0</MinorVersion>
<PatchVersion>0</PatchVersion>
<SdkBandVersion>7.0.100</SdkBandVersion>
<PreReleaseVersionLabel>preview</PreReleaseVersionLabel>
<PreReleaseVersionIteration>3</PreReleaseVersionIteration>
<!-- Set assembly version to align with major and minor version,
as for the patches and revisions should be manually updated per assembly if it is serviced. -->
<AssemblyVersion>$(MajorVersion).$(MinorVersion).0.0</AssemblyVersion>
<!-- Enable to remove prerelease label. -->
<StabilizePackageVersion Condition="'$(StabilizePackageVersion)' == ''">false</StabilizePackageVersion>
<DotNetFinalVersionKind Condition="'$(StabilizePackageVersion)' == 'true'">release</DotNetFinalVersionKind>
<!-- Opt-in/out repo features -->
<UsingToolMicrosoftNetILLinkTasks>true</UsingToolMicrosoftNetILLinkTasks>
<UsingToolIbcOptimization>false</UsingToolIbcOptimization>
<UsingToolXliff>false</UsingToolXliff>
<LastReleasedStableAssemblyVersion>$(AssemblyVersion)</LastReleasedStableAssemblyVersion>
<UsingToolMicrosoftNetCompilers>true</UsingToolMicrosoftNetCompilers>
</PropertyGroup>
<!--
For source generator support we need to target multiple versions of Rolsyn in order to be able to run on older versions of Roslyn.
We pin these versions as we need to match them exactly for any scenarios that run Roslyn on .NET Framework, like Visual Studio.
-->
<PropertyGroup>
<MicrosoftCodeAnalysisVersion_3_11>3.11.0</MicrosoftCodeAnalysisVersion_3_11>
<MicrosoftCodeAnalysisVersion_4_0>4.0.1</MicrosoftCodeAnalysisVersion_4_0>
</PropertyGroup>
<PropertyGroup>
<!-- Code analysis dependencies -->
<MicrosoftCodeAnalysisAnalyzersVersion>3.3.3</MicrosoftCodeAnalysisAnalyzersVersion>
<MicrosoftCodeAnalysisCSharpCodeStyleVersion>4.2.0-2.22128.1</MicrosoftCodeAnalysisCSharpCodeStyleVersion>
<MicrosoftCodeAnalysisCSharpWorkspacesVersion>4.2.0-2.22128.1</MicrosoftCodeAnalysisCSharpWorkspacesVersion>
<MicrosoftCodeAnalysisCSharpVersion>4.2.0-2.22128.1</MicrosoftCodeAnalysisCSharpVersion>
<MicrosoftCodeAnalysisNetAnalyzersVersion>7.0.0-preview1.22160.2</MicrosoftCodeAnalysisNetAnalyzersVersion>
<MicrosoftCodeAnalysisVersion>4.2.0-2.22128.1</MicrosoftCodeAnalysisVersion>
<!--
TODO: Remove pinned compiler version once arcade supplies runtime with a compiler capable of handling !!
and has https://github.com/dotnet/roslyn/pull/59776
-->
<MicrosoftNetCompilersToolsetVersion>4.2.0-2.22128.1</MicrosoftNetCompilersToolsetVersion>
<!-- SDK dependencies -->
<MicrosoftDotNetCompatibilityVersion>2.0.0-alpha.1.21525.11</MicrosoftDotNetCompatibilityVersion>
<!-- Arcade dependencies -->
<MicrosoftDotNetApiCompatVersion>7.0.0-beta.22157.6</MicrosoftDotNetApiCompatVersion>
<MicrosoftDotNetBuildTasksFeedVersion>7.0.0-beta.22157.6</MicrosoftDotNetBuildTasksFeedVersion>
<MicrosoftDotNetCodeAnalysisVersion>7.0.0-beta.22157.6</MicrosoftDotNetCodeAnalysisVersion>
<MicrosoftDotNetGenAPIVersion>7.0.0-beta.22157.6</MicrosoftDotNetGenAPIVersion>
<MicrosoftDotNetGenFacadesVersion>7.0.0-beta.22157.6</MicrosoftDotNetGenFacadesVersion>
<MicrosoftDotNetXUnitExtensionsVersion>7.0.0-beta.22157.6</MicrosoftDotNetXUnitExtensionsVersion>
<MicrosoftDotNetXUnitConsoleRunnerVersion>2.5.1-beta.22157.6</MicrosoftDotNetXUnitConsoleRunnerVersion>
<MicrosoftDotNetBuildTasksArchivesVersion>7.0.0-beta.22157.6</MicrosoftDotNetBuildTasksArchivesVersion>
<MicrosoftDotNetBuildTasksInstallersVersion>7.0.0-beta.22157.6</MicrosoftDotNetBuildTasksInstallersVersion>
<MicrosoftDotNetBuildTasksPackagingVersion>7.0.0-beta.22157.6</MicrosoftDotNetBuildTasksPackagingVersion>
<MicrosoftDotNetBuildTasksTargetFrameworkVersion>7.0.0-beta.22157.6</MicrosoftDotNetBuildTasksTargetFrameworkVersion>
<MicrosoftDotNetBuildTasksTemplatingVersion>7.0.0-beta.22157.6</MicrosoftDotNetBuildTasksTemplatingVersion>
<MicrosoftDotNetBuildTasksWorkloadsPackageVersion>7.0.0-beta.22157.6</MicrosoftDotNetBuildTasksWorkloadsPackageVersion>
<MicrosoftDotNetRemoteExecutorVersion>7.0.0-beta.22157.6</MicrosoftDotNetRemoteExecutorVersion>
<MicrosoftDotNetVersionToolsTasksVersion>7.0.0-beta.22157.6</MicrosoftDotNetVersionToolsTasksVersion>
<MicrosoftDotNetPackageTestingVersion>7.0.0-beta.22157.6</MicrosoftDotNetPackageTestingVersion>
<!-- NuGet dependencies -->
<NuGetBuildTasksPackVersion>6.0.0-preview.1.102</NuGetBuildTasksPackVersion>
<!-- Installer dependencies -->
<MicrosoftNETCoreAppRuntimewinx64Version>7.0.0-preview.3.22157.1</MicrosoftNETCoreAppRuntimewinx64Version>
<MicrosoftNETCoreDotNetHostVersion>7.0.0-preview.3.22157.1</MicrosoftNETCoreDotNetHostVersion>
<MicrosoftNETCoreDotNetHostPolicyVersion>7.0.0-preview.3.22157.1</MicrosoftNETCoreDotNetHostPolicyVersion>
<MicrosoftExtensionsDependencyModelVersion>3.1.0</MicrosoftExtensionsDependencyModelVersion>
<!-- CoreClr dependencies -->
<MicrosoftNETCoreILAsmVersion>7.0.0-preview.3.22157.1</MicrosoftNETCoreILAsmVersion>
<runtimelinuxarm64MicrosoftNETCoreRuntimeObjWriterVersion>1.0.0-alpha.1.22157.1</runtimelinuxarm64MicrosoftNETCoreRuntimeObjWriterVersion>
<runtimelinuxx64MicrosoftNETCoreRuntimeObjWriterVersion>1.0.0-alpha.1.22157.1</runtimelinuxx64MicrosoftNETCoreRuntimeObjWriterVersion>
<runtimelinuxmuslarm64MicrosoftNETCoreRuntimeObjWriterVersion>1.0.0-alpha.1.22157.1</runtimelinuxmuslarm64MicrosoftNETCoreRuntimeObjWriterVersion>
<runtimelinuxmuslx64MicrosoftNETCoreRuntimeObjWriterVersion>1.0.0-alpha.1.22157.1</runtimelinuxmuslx64MicrosoftNETCoreRuntimeObjWriterVersion>
<runtimewinarm64MicrosoftNETCoreRuntimeObjWriterVersion>1.0.0-alpha.1.22157.1</runtimewinarm64MicrosoftNETCoreRuntimeObjWriterVersion>
<runtimewinx64MicrosoftNETCoreRuntimeObjWriterVersion>1.0.0-alpha.1.22157.1</runtimewinx64MicrosoftNETCoreRuntimeObjWriterVersion>
<runtimeosx110arm64MicrosoftNETCoreRuntimeObjWriterVersion>1.0.0-alpha.1.22157.1</runtimeosx110arm64MicrosoftNETCoreRuntimeObjWriterVersion>
<runtimeosx1012x64MicrosoftNETCoreRuntimeObjWriterVersion>1.0.0-alpha.1.22157.1</runtimeosx1012x64MicrosoftNETCoreRuntimeObjWriterVersion>
<!-- Libraries dependencies -->
<MicrosoftBclAsyncInterfacesVersion>6.0.0</MicrosoftBclAsyncInterfacesVersion>
<MicrosoftWin32PrimitivesVersion>4.3.0</MicrosoftWin32PrimitivesVersion>
<MicrosoftWin32RegistryVersion>5.0.0</MicrosoftWin32RegistryVersion>
<StyleCopAnalyzersVersion>1.2.0-beta.406</StyleCopAnalyzersVersion>
<SystemBuffersVersion>4.5.1</SystemBuffersVersion>
<SystemCollectionsVersion>4.3.0</SystemCollectionsVersion>
<SystemCollectionsImmutableVersion>6.0.0</SystemCollectionsImmutableVersion>
<SystemComponentModelAnnotationsVersion>5.0.0</SystemComponentModelAnnotationsVersion>
<SystemDataSqlClientVersion>4.8.3</SystemDataSqlClientVersion>
<SystemDataDataSetExtensionsVersion>4.5.0</SystemDataDataSetExtensionsVersion>
<SystemDiagnosticsContractsVersion>4.3.0</SystemDiagnosticsContractsVersion>
<SystemDynamicRuntimeVersion>4.3.0</SystemDynamicRuntimeVersion>
<SystemIOFileSystemAccessControlVersion>5.0.0</SystemIOFileSystemAccessControlVersion>
<SystemIOPipesAccessControlVersion>5.0.0</SystemIOPipesAccessControlVersion>
<SystemLinqExpressionsVersion>4.3.0</SystemLinqExpressionsVersion>
<SystemMemoryVersion>4.5.4</SystemMemoryVersion>
<SystemNetPrimitivesVersion>4.3.1</SystemNetPrimitivesVersion>
<SystemNumericsVectorsVersion>4.5.0</SystemNumericsVectorsVersion>
<SystemReflectionMetadataVersion>6.0.0</SystemReflectionMetadataVersion>
<SystemReflectionEmitVersion>4.7.0</SystemReflectionEmitVersion>
<SystemReflectionEmitILGenerationVersion>4.7.0</SystemReflectionEmitILGenerationVersion>
<SystemReflectionEmitLightweightVersion>4.7.0</SystemReflectionEmitLightweightVersion>
<SystemRuntimeVersion>4.3.1</SystemRuntimeVersion>
<SystemRuntimeExtensionsVersion>4.3.1</SystemRuntimeExtensionsVersion>
<SystemRuntimeInteropServicesVersion>4.3.0</SystemRuntimeInteropServicesVersion>
<SystemRuntimeInteropServicesRuntimeInformationVersion>4.3.0</SystemRuntimeInteropServicesRuntimeInformationVersion>
<SystemRuntimeSerializationPrimitivesVersion>4.3.0</SystemRuntimeSerializationPrimitivesVersion>
<SystemSecurityAccessControlVersion>6.0.0</SystemSecurityAccessControlVersion>
<SystemSecurityCryptographyAlgorithmsVersion>4.3.1</SystemSecurityCryptographyAlgorithmsVersion>
<SystemSecurityCryptographyCngVersion>5.0.0</SystemSecurityCryptographyCngVersion>
<SystemSecurityCryptographyOpenSslVersion>5.0.0</SystemSecurityCryptographyOpenSslVersion>
<SystemSecurityPrincipalWindowsVersion>5.0.0</SystemSecurityPrincipalWindowsVersion>
<SystemServiceModelPrimitivesVersion>4.9.0</SystemServiceModelPrimitivesVersion>
<SystemTextJsonVersion>7.0.0-preview.3.22157.1</SystemTextJsonVersion>
<SystemRuntimeCompilerServicesUnsafeVersion>6.0.0</SystemRuntimeCompilerServicesUnsafeVersion>
<SystemThreadingTasksExtensionsVersion>4.5.4</SystemThreadingTasksExtensionsVersion>
<SystemValueTupleVersion>4.5.0</SystemValueTupleVersion>
<runtimenativeSystemIOPortsVersion>7.0.0-preview.3.22157.1</runtimenativeSystemIOPortsVersion>
<!-- Runtime-Assets dependencies -->
<SystemRuntimeNumericsTestDataVersion>7.0.0-beta.22160.1</SystemRuntimeNumericsTestDataVersion>
<SystemComponentModelTypeConverterTestDataVersion>7.0.0-beta.22160.1</SystemComponentModelTypeConverterTestDataVersion>
<SystemDrawingCommonTestDataVersion>7.0.0-beta.22160.1</SystemDrawingCommonTestDataVersion>
<SystemIOCompressionTestDataVersion>7.0.0-beta.22160.1</SystemIOCompressionTestDataVersion>
<SystemIOPackagingTestDataVersion>7.0.0-beta.22160.1</SystemIOPackagingTestDataVersion>
<SystemNetTestDataVersion>7.0.0-beta.22160.1</SystemNetTestDataVersion>
<SystemPrivateRuntimeUnicodeDataVersion>7.0.0-beta.22160.1</SystemPrivateRuntimeUnicodeDataVersion>
<SystemRuntimeTimeZoneDataVersion>7.0.0-beta.22160.1</SystemRuntimeTimeZoneDataVersion>
<SystemSecurityCryptographyX509CertificatesTestDataVersion>7.0.0-beta.22160.1</SystemSecurityCryptographyX509CertificatesTestDataVersion>
<SystemTextRegularExpressionsTestDataVersion>7.0.0-beta.22160.1</SystemTextRegularExpressionsTestDataVersion>
<SystemWindowsExtensionsTestDataVersion>7.0.0-beta.22160.1</SystemWindowsExtensionsTestDataVersion>
<MicrosoftDotNetCilStripSourcesVersion>7.0.0-beta.22160.1</MicrosoftDotNetCilStripSourcesVersion>
<!-- dotnet-optimization dependencies -->
<optimizationwindows_ntx64MIBCRuntimeVersion>1.0.0-prerelease.22121.2</optimizationwindows_ntx64MIBCRuntimeVersion>
<optimizationwindows_ntx86MIBCRuntimeVersion>1.0.0-prerelease.22121.2</optimizationwindows_ntx86MIBCRuntimeVersion>
<optimizationlinuxx64MIBCRuntimeVersion>1.0.0-prerelease.22121.2</optimizationlinuxx64MIBCRuntimeVersion>
<optimizationPGOCoreCLRVersion>1.0.0-prerelease.22121.2</optimizationPGOCoreCLRVersion>
<!-- Not auto-updated. -->
<MicrosoftDiaSymReaderNativeVersion>16.9.0-beta1.21055.5</MicrosoftDiaSymReaderNativeVersion>
<SystemCommandLineVersion>2.0.0-beta1.20253.1</SystemCommandLineVersion>
<TraceEventVersion>2.0.65</TraceEventVersion>
<CommandLineParserVersion>2.2.0</CommandLineParserVersion>
<NETStandardLibraryRefVersion>2.1.0</NETStandardLibraryRefVersion>
<NetStandardLibraryVersion>2.0.3</NetStandardLibraryVersion>
<MicrosoftDiagnosticsToolsRuntimeClientVersion>1.0.4-preview6.19326.1</MicrosoftDiagnosticsToolsRuntimeClientVersion>
<DNNEVersion>1.0.27</DNNEVersion>
<MicrosoftBuildVersion>16.10.0</MicrosoftBuildVersion>
<MicrosoftBuildTasksCoreVersion>$(MicrosoftBuildVersion)</MicrosoftBuildTasksCoreVersion>
<NugetProjectModelVersion>5.8.0</NugetProjectModelVersion>
<NugetPackagingVersion>5.8.0</NugetPackagingVersion>
<!-- Testing -->
<MicrosoftNETCoreCoreDisToolsVersion>1.0.1-prerelease-00006</MicrosoftNETCoreCoreDisToolsVersion>
<MicrosoftNETTestSdkVersion>16.9.0-preview-20201201-01</MicrosoftNETTestSdkVersion>
<MicrosoftDotNetXHarnessTestRunnersCommonVersion>1.0.0-prerelease.22160.1</MicrosoftDotNetXHarnessTestRunnersCommonVersion>
<MicrosoftDotNetXHarnessTestRunnersXunitVersion>1.0.0-prerelease.22160.1</MicrosoftDotNetXHarnessTestRunnersXunitVersion>
<MicrosoftDotNetXHarnessCLIVersion>1.0.0-prerelease.22160.1</MicrosoftDotNetXHarnessCLIVersion>
<MicrosoftDotNetHotReloadUtilsGeneratorBuildToolVersion>1.0.2-alpha.0.22157.2</MicrosoftDotNetHotReloadUtilsGeneratorBuildToolVersion>
<XUnitVersion>2.4.2-pre.22</XUnitVersion>
<XUnitAnalyzersVersion>0.12.0-pre.20</XUnitAnalyzersVersion>
<XUnitRunnerVisualStudioVersion>2.4.2</XUnitRunnerVisualStudioVersion>
<CoverletCollectorVersion>3.1.2</CoverletCollectorVersion>
<NewtonsoftJsonVersion>12.0.3</NewtonsoftJsonVersion>
<SQLitePCLRawbundle_greenVersion>2.0.4</SQLitePCLRawbundle_greenVersion>
<MoqVersion>4.12.0</MoqVersion>
<FsCheckVersion>2.14.3</FsCheckVersion>
<SdkVersionForWorkloadTesting>7.0.100-preview.3.22151.18</SdkVersionForWorkloadTesting>
<CompilerPlatformTestingVersion>1.1.1-beta1.22103.1</CompilerPlatformTestingVersion>
<!-- Docs -->
<MicrosoftPrivateIntellisenseVersion>6.0.0-preview-20220104.1</MicrosoftPrivateIntellisenseVersion>
<!-- ILLink -->
<MicrosoftNETILLinkTasksVersion>7.0.100-1.22160.1</MicrosoftNETILLinkTasksVersion>
<MicrosoftNETILLinkAnalyzerPackageVersion>$(MicrosoftNETILLinkTasksVersion)</MicrosoftNETILLinkAnalyzerPackageVersion>
<!-- ICU -->
<MicrosoftNETCoreRuntimeICUTransportVersion>7.0.0-preview.3.22157.1</MicrosoftNETCoreRuntimeICUTransportVersion>
<!-- MsQuic -->
<SystemNetMsQuicTransportVersion>7.0.0-alpha.1.22160.2</SystemNetMsQuicTransportVersion>
<!-- Mono LLVM -->
<runtimelinuxarm64MicrosoftNETCoreRuntimeMonoLLVMSdkVersion>11.1.0-alpha.1.22121.2</runtimelinuxarm64MicrosoftNETCoreRuntimeMonoLLVMSdkVersion>
<runtimelinuxarm64MicrosoftNETCoreRuntimeMonoLLVMToolsVersion>11.1.0-alpha.1.22121.2</runtimelinuxarm64MicrosoftNETCoreRuntimeMonoLLVMToolsVersion>
<runtimelinuxx64MicrosoftNETCoreRuntimeMonoLLVMSdkVersion>11.1.0-alpha.1.22121.2</runtimelinuxx64MicrosoftNETCoreRuntimeMonoLLVMSdkVersion>
<runtimelinuxx64MicrosoftNETCoreRuntimeMonoLLVMToolsVersion>11.1.0-alpha.1.22121.2</runtimelinuxx64MicrosoftNETCoreRuntimeMonoLLVMToolsVersion>
<runtimewinx64MicrosoftNETCoreRuntimeMonoLLVMSdkVersion>11.1.0-alpha.1.22121.2</runtimewinx64MicrosoftNETCoreRuntimeMonoLLVMSdkVersion>
<runtimewinx64MicrosoftNETCoreRuntimeMonoLLVMToolsVersion>11.1.0-alpha.1.22121.2</runtimewinx64MicrosoftNETCoreRuntimeMonoLLVMToolsVersion>
<runtimeosx1012x64MicrosoftNETCoreRuntimeMonoLLVMSdkVersion>11.1.0-alpha.1.22121.2</runtimeosx1012x64MicrosoftNETCoreRuntimeMonoLLVMSdkVersion>
<runtimeosx1012x64MicrosoftNETCoreRuntimeMonoLLVMToolsVersion>11.1.0-alpha.1.22121.2</runtimeosx1012x64MicrosoftNETCoreRuntimeMonoLLVMToolsVersion>
<!-- emscripten / Node -->
<MicrosoftNETWorkloadEmscriptenManifest70100Version>7.0.0-preview.3.22128.1</MicrosoftNETWorkloadEmscriptenManifest70100Version>
<MicrosoftNETRuntimeEmscriptenVersion>$(MicrosoftNETWorkloadEmscriptenManifest70100Version)</MicrosoftNETRuntimeEmscriptenVersion>
<!-- workloads -->
<SwixPackageVersion>1.1.87-gba258badda</SwixPackageVersion>
<WixPackageVersion>1.0.0-v3.14.0.5722</WixPackageVersion>
<MonoWorkloadManifestVersion>6.0.0-preview.5.21275.7</MonoWorkloadManifestVersion>
</PropertyGroup>
</Project>
| <Project>
<PropertyGroup>
<!-- The .NET product branding version -->
<ProductVersion>7.0.0</ProductVersion>
<!-- File version numbers -->
<MajorVersion>7</MajorVersion>
<MinorVersion>0</MinorVersion>
<PatchVersion>0</PatchVersion>
<SdkBandVersion>7.0.100</SdkBandVersion>
<PreReleaseVersionLabel>preview</PreReleaseVersionLabel>
<PreReleaseVersionIteration>3</PreReleaseVersionIteration>
<!-- Set assembly version to align with major and minor version,
as for the patches and revisions should be manually updated per assembly if it is serviced. -->
<AssemblyVersion>$(MajorVersion).$(MinorVersion).0.0</AssemblyVersion>
<!-- Enable to remove prerelease label. -->
<StabilizePackageVersion Condition="'$(StabilizePackageVersion)' == ''">false</StabilizePackageVersion>
<DotNetFinalVersionKind Condition="'$(StabilizePackageVersion)' == 'true'">release</DotNetFinalVersionKind>
<!-- Opt-in/out repo features -->
<UsingToolMicrosoftNetILLinkTasks>true</UsingToolMicrosoftNetILLinkTasks>
<UsingToolIbcOptimization>false</UsingToolIbcOptimization>
<UsingToolXliff>false</UsingToolXliff>
<LastReleasedStableAssemblyVersion>$(AssemblyVersion)</LastReleasedStableAssemblyVersion>
<UsingToolMicrosoftNetCompilers>true</UsingToolMicrosoftNetCompilers>
</PropertyGroup>
<!--
For source generator support we need to target multiple versions of Rolsyn in order to be able to run on older versions of Roslyn.
We pin these versions as we need to match them exactly for any scenarios that run Roslyn on .NET Framework, like Visual Studio.
-->
<PropertyGroup>
<MicrosoftCodeAnalysisVersion_3_11>3.11.0</MicrosoftCodeAnalysisVersion_3_11>
<MicrosoftCodeAnalysisVersion_4_0>4.0.1</MicrosoftCodeAnalysisVersion_4_0>
</PropertyGroup>
<PropertyGroup>
<!-- Code analysis dependencies -->
<MicrosoftCodeAnalysisAnalyzersVersion>3.3.3</MicrosoftCodeAnalysisAnalyzersVersion>
<MicrosoftCodeAnalysisCSharpCodeStyleVersion>4.2.0-2.22128.1</MicrosoftCodeAnalysisCSharpCodeStyleVersion>
<MicrosoftCodeAnalysisCSharpWorkspacesVersion>4.2.0-2.22128.1</MicrosoftCodeAnalysisCSharpWorkspacesVersion>
<MicrosoftCodeAnalysisCSharpVersion>4.2.0-2.22128.1</MicrosoftCodeAnalysisCSharpVersion>
<MicrosoftCodeAnalysisNetAnalyzersVersion>7.0.0-preview1.22160.2</MicrosoftCodeAnalysisNetAnalyzersVersion>
<MicrosoftCodeAnalysisVersion>4.2.0-2.22128.1</MicrosoftCodeAnalysisVersion>
<!--
TODO: Remove pinned compiler version once arcade supplies runtime with a compiler capable of handling !!
and has https://github.com/dotnet/roslyn/pull/59776
-->
<MicrosoftNetCompilersToolsetVersion>4.2.0-2.22128.1</MicrosoftNetCompilersToolsetVersion>
<!-- SDK dependencies -->
<MicrosoftDotNetCompatibilityVersion>2.0.0-alpha.1.21525.11</MicrosoftDotNetCompatibilityVersion>
<!-- Arcade dependencies -->
<MicrosoftDotNetApiCompatVersion>7.0.0-beta.22159.9</MicrosoftDotNetApiCompatVersion>
<MicrosoftDotNetBuildTasksFeedVersion>7.0.0-beta.22157.6</MicrosoftDotNetBuildTasksFeedVersion>
<MicrosoftDotNetCodeAnalysisVersion>7.0.0-beta.22157.6</MicrosoftDotNetCodeAnalysisVersion>
<MicrosoftDotNetGenAPIVersion>7.0.0-beta.22157.6</MicrosoftDotNetGenAPIVersion>
<MicrosoftDotNetGenFacadesVersion>7.0.0-beta.22157.6</MicrosoftDotNetGenFacadesVersion>
<MicrosoftDotNetXUnitExtensionsVersion>7.0.0-beta.22157.6</MicrosoftDotNetXUnitExtensionsVersion>
<MicrosoftDotNetXUnitConsoleRunnerVersion>2.5.1-beta.22157.6</MicrosoftDotNetXUnitConsoleRunnerVersion>
<MicrosoftDotNetBuildTasksArchivesVersion>7.0.0-beta.22157.6</MicrosoftDotNetBuildTasksArchivesVersion>
<MicrosoftDotNetBuildTasksInstallersVersion>7.0.0-beta.22157.6</MicrosoftDotNetBuildTasksInstallersVersion>
<MicrosoftDotNetBuildTasksPackagingVersion>7.0.0-beta.22157.6</MicrosoftDotNetBuildTasksPackagingVersion>
<MicrosoftDotNetBuildTasksTargetFrameworkVersion>7.0.0-beta.22157.6</MicrosoftDotNetBuildTasksTargetFrameworkVersion>
<MicrosoftDotNetBuildTasksTemplatingVersion>7.0.0-beta.22157.6</MicrosoftDotNetBuildTasksTemplatingVersion>
<MicrosoftDotNetBuildTasksWorkloadsPackageVersion>7.0.0-beta.22157.6</MicrosoftDotNetBuildTasksWorkloadsPackageVersion>
<MicrosoftDotNetRemoteExecutorVersion>7.0.0-beta.22157.6</MicrosoftDotNetRemoteExecutorVersion>
<MicrosoftDotNetVersionToolsTasksVersion>7.0.0-beta.22157.6</MicrosoftDotNetVersionToolsTasksVersion>
<MicrosoftDotNetPackageTestingVersion>7.0.0-beta.22157.6</MicrosoftDotNetPackageTestingVersion>
<!-- NuGet dependencies -->
<NuGetBuildTasksPackVersion>6.0.0-preview.1.102</NuGetBuildTasksPackVersion>
<!-- Installer dependencies -->
<MicrosoftNETCoreAppRuntimewinx64Version>7.0.0-preview.3.22157.1</MicrosoftNETCoreAppRuntimewinx64Version>
<MicrosoftNETCoreDotNetHostVersion>7.0.0-preview.3.22157.1</MicrosoftNETCoreDotNetHostVersion>
<MicrosoftNETCoreDotNetHostPolicyVersion>7.0.0-preview.3.22157.1</MicrosoftNETCoreDotNetHostPolicyVersion>
<MicrosoftExtensionsDependencyModelVersion>3.1.0</MicrosoftExtensionsDependencyModelVersion>
<!-- CoreClr dependencies -->
<MicrosoftNETCoreILAsmVersion>7.0.0-preview.3.22157.1</MicrosoftNETCoreILAsmVersion>
<runtimelinuxarm64MicrosoftNETCoreRuntimeObjWriterVersion>1.0.0-alpha.1.22157.1</runtimelinuxarm64MicrosoftNETCoreRuntimeObjWriterVersion>
<runtimelinuxx64MicrosoftNETCoreRuntimeObjWriterVersion>1.0.0-alpha.1.22157.1</runtimelinuxx64MicrosoftNETCoreRuntimeObjWriterVersion>
<runtimelinuxmuslarm64MicrosoftNETCoreRuntimeObjWriterVersion>1.0.0-alpha.1.22157.1</runtimelinuxmuslarm64MicrosoftNETCoreRuntimeObjWriterVersion>
<runtimelinuxmuslx64MicrosoftNETCoreRuntimeObjWriterVersion>1.0.0-alpha.1.22157.1</runtimelinuxmuslx64MicrosoftNETCoreRuntimeObjWriterVersion>
<runtimewinarm64MicrosoftNETCoreRuntimeObjWriterVersion>1.0.0-alpha.1.22157.1</runtimewinarm64MicrosoftNETCoreRuntimeObjWriterVersion>
<runtimewinx64MicrosoftNETCoreRuntimeObjWriterVersion>1.0.0-alpha.1.22157.1</runtimewinx64MicrosoftNETCoreRuntimeObjWriterVersion>
<runtimeosx110arm64MicrosoftNETCoreRuntimeObjWriterVersion>1.0.0-alpha.1.22157.1</runtimeosx110arm64MicrosoftNETCoreRuntimeObjWriterVersion>
<runtimeosx1012x64MicrosoftNETCoreRuntimeObjWriterVersion>1.0.0-alpha.1.22157.1</runtimeosx1012x64MicrosoftNETCoreRuntimeObjWriterVersion>
<!-- Libraries dependencies -->
<MicrosoftBclAsyncInterfacesVersion>6.0.0</MicrosoftBclAsyncInterfacesVersion>
<MicrosoftWin32PrimitivesVersion>4.3.0</MicrosoftWin32PrimitivesVersion>
<MicrosoftWin32RegistryVersion>5.0.0</MicrosoftWin32RegistryVersion>
<StyleCopAnalyzersVersion>1.2.0-beta.406</StyleCopAnalyzersVersion>
<SystemBuffersVersion>4.5.1</SystemBuffersVersion>
<SystemCollectionsVersion>4.3.0</SystemCollectionsVersion>
<SystemCollectionsImmutableVersion>6.0.0</SystemCollectionsImmutableVersion>
<SystemComponentModelAnnotationsVersion>5.0.0</SystemComponentModelAnnotationsVersion>
<SystemDataSqlClientVersion>4.8.3</SystemDataSqlClientVersion>
<SystemDataDataSetExtensionsVersion>4.5.0</SystemDataDataSetExtensionsVersion>
<SystemDiagnosticsContractsVersion>4.3.0</SystemDiagnosticsContractsVersion>
<SystemDynamicRuntimeVersion>4.3.0</SystemDynamicRuntimeVersion>
<SystemIOFileSystemAccessControlVersion>5.0.0</SystemIOFileSystemAccessControlVersion>
<SystemIOPipesAccessControlVersion>5.0.0</SystemIOPipesAccessControlVersion>
<SystemLinqExpressionsVersion>4.3.0</SystemLinqExpressionsVersion>
<SystemMemoryVersion>4.5.4</SystemMemoryVersion>
<SystemNetPrimitivesVersion>4.3.1</SystemNetPrimitivesVersion>
<SystemNumericsVectorsVersion>4.5.0</SystemNumericsVectorsVersion>
<SystemReflectionMetadataVersion>6.0.0</SystemReflectionMetadataVersion>
<SystemReflectionEmitVersion>4.7.0</SystemReflectionEmitVersion>
<SystemReflectionEmitILGenerationVersion>4.7.0</SystemReflectionEmitILGenerationVersion>
<SystemReflectionEmitLightweightVersion>4.7.0</SystemReflectionEmitLightweightVersion>
<SystemRuntimeVersion>4.3.1</SystemRuntimeVersion>
<SystemRuntimeExtensionsVersion>4.3.1</SystemRuntimeExtensionsVersion>
<SystemRuntimeInteropServicesVersion>4.3.0</SystemRuntimeInteropServicesVersion>
<SystemRuntimeInteropServicesRuntimeInformationVersion>4.3.0</SystemRuntimeInteropServicesRuntimeInformationVersion>
<SystemRuntimeSerializationPrimitivesVersion>4.3.0</SystemRuntimeSerializationPrimitivesVersion>
<SystemSecurityAccessControlVersion>6.0.0</SystemSecurityAccessControlVersion>
<SystemSecurityCryptographyAlgorithmsVersion>4.3.1</SystemSecurityCryptographyAlgorithmsVersion>
<SystemSecurityCryptographyCngVersion>5.0.0</SystemSecurityCryptographyCngVersion>
<SystemSecurityCryptographyOpenSslVersion>5.0.0</SystemSecurityCryptographyOpenSslVersion>
<SystemSecurityPrincipalWindowsVersion>5.0.0</SystemSecurityPrincipalWindowsVersion>
<SystemServiceModelPrimitivesVersion>4.9.0</SystemServiceModelPrimitivesVersion>
<SystemTextJsonVersion>7.0.0-preview.3.22157.1</SystemTextJsonVersion>
<SystemRuntimeCompilerServicesUnsafeVersion>6.0.0</SystemRuntimeCompilerServicesUnsafeVersion>
<SystemThreadingTasksExtensionsVersion>4.5.4</SystemThreadingTasksExtensionsVersion>
<SystemValueTupleVersion>4.5.0</SystemValueTupleVersion>
<runtimenativeSystemIOPortsVersion>7.0.0-preview.3.22157.1</runtimenativeSystemIOPortsVersion>
<!-- Runtime-Assets dependencies -->
<SystemRuntimeNumericsTestDataVersion>7.0.0-beta.22160.1</SystemRuntimeNumericsTestDataVersion>
<SystemComponentModelTypeConverterTestDataVersion>7.0.0-beta.22160.1</SystemComponentModelTypeConverterTestDataVersion>
<SystemDrawingCommonTestDataVersion>7.0.0-beta.22160.1</SystemDrawingCommonTestDataVersion>
<SystemIOCompressionTestDataVersion>7.0.0-beta.22160.1</SystemIOCompressionTestDataVersion>
<SystemIOPackagingTestDataVersion>7.0.0-beta.22160.1</SystemIOPackagingTestDataVersion>
<SystemNetTestDataVersion>7.0.0-beta.22160.1</SystemNetTestDataVersion>
<SystemPrivateRuntimeUnicodeDataVersion>7.0.0-beta.22160.1</SystemPrivateRuntimeUnicodeDataVersion>
<SystemRuntimeTimeZoneDataVersion>7.0.0-beta.22160.1</SystemRuntimeTimeZoneDataVersion>
<SystemSecurityCryptographyX509CertificatesTestDataVersion>7.0.0-beta.22160.1</SystemSecurityCryptographyX509CertificatesTestDataVersion>
<SystemTextRegularExpressionsTestDataVersion>7.0.0-beta.22160.1</SystemTextRegularExpressionsTestDataVersion>
<SystemWindowsExtensionsTestDataVersion>7.0.0-beta.22160.1</SystemWindowsExtensionsTestDataVersion>
<MicrosoftDotNetCilStripSourcesVersion>7.0.0-beta.22160.1</MicrosoftDotNetCilStripSourcesVersion>
<!-- dotnet-optimization dependencies -->
<optimizationwindows_ntx64MIBCRuntimeVersion>1.0.0-prerelease.22121.2</optimizationwindows_ntx64MIBCRuntimeVersion>
<optimizationwindows_ntx86MIBCRuntimeVersion>1.0.0-prerelease.22121.2</optimizationwindows_ntx86MIBCRuntimeVersion>
<optimizationlinuxx64MIBCRuntimeVersion>1.0.0-prerelease.22121.2</optimizationlinuxx64MIBCRuntimeVersion>
<optimizationPGOCoreCLRVersion>1.0.0-prerelease.22121.2</optimizationPGOCoreCLRVersion>
<!-- Not auto-updated. -->
<MicrosoftDiaSymReaderNativeVersion>16.9.0-beta1.21055.5</MicrosoftDiaSymReaderNativeVersion>
<SystemCommandLineVersion>2.0.0-beta1.20253.1</SystemCommandLineVersion>
<TraceEventVersion>2.0.65</TraceEventVersion>
<CommandLineParserVersion>2.2.0</CommandLineParserVersion>
<NETStandardLibraryRefVersion>2.1.0</NETStandardLibraryRefVersion>
<NetStandardLibraryVersion>2.0.3</NetStandardLibraryVersion>
<MicrosoftDiagnosticsToolsRuntimeClientVersion>1.0.4-preview6.19326.1</MicrosoftDiagnosticsToolsRuntimeClientVersion>
<DNNEVersion>1.0.27</DNNEVersion>
<MicrosoftBuildVersion>16.10.0</MicrosoftBuildVersion>
<MicrosoftBuildTasksCoreVersion>$(MicrosoftBuildVersion)</MicrosoftBuildTasksCoreVersion>
<NugetProjectModelVersion>5.8.0</NugetProjectModelVersion>
<NugetPackagingVersion>5.8.0</NugetPackagingVersion>
<!-- Testing -->
<MicrosoftNETCoreCoreDisToolsVersion>1.0.1-prerelease-00006</MicrosoftNETCoreCoreDisToolsVersion>
<MicrosoftNETTestSdkVersion>16.9.0-preview-20201201-01</MicrosoftNETTestSdkVersion>
<MicrosoftDotNetXHarnessTestRunnersCommonVersion>1.0.0-prerelease.22160.1</MicrosoftDotNetXHarnessTestRunnersCommonVersion>
<MicrosoftDotNetXHarnessTestRunnersXunitVersion>1.0.0-prerelease.22160.1</MicrosoftDotNetXHarnessTestRunnersXunitVersion>
<MicrosoftDotNetXHarnessCLIVersion>1.0.0-prerelease.22160.1</MicrosoftDotNetXHarnessCLIVersion>
<MicrosoftDotNetHotReloadUtilsGeneratorBuildToolVersion>1.0.2-alpha.0.22157.2</MicrosoftDotNetHotReloadUtilsGeneratorBuildToolVersion>
<XUnitVersion>2.4.2-pre.22</XUnitVersion>
<XUnitAnalyzersVersion>0.12.0-pre.20</XUnitAnalyzersVersion>
<XUnitRunnerVisualStudioVersion>2.4.2</XUnitRunnerVisualStudioVersion>
<CoverletCollectorVersion>3.1.2</CoverletCollectorVersion>
<NewtonsoftJsonVersion>12.0.3</NewtonsoftJsonVersion>
<SQLitePCLRawbundle_greenVersion>2.0.4</SQLitePCLRawbundle_greenVersion>
<MoqVersion>4.12.0</MoqVersion>
<FsCheckVersion>2.14.3</FsCheckVersion>
<SdkVersionForWorkloadTesting>7.0.100-preview.3.22151.18</SdkVersionForWorkloadTesting>
<CompilerPlatformTestingVersion>1.1.1-beta1.22103.1</CompilerPlatformTestingVersion>
<!-- Docs -->
<MicrosoftPrivateIntellisenseVersion>6.0.0-preview-20220104.1</MicrosoftPrivateIntellisenseVersion>
<!-- ILLink -->
<MicrosoftNETILLinkTasksVersion>7.0.100-1.22160.1</MicrosoftNETILLinkTasksVersion>
<MicrosoftNETILLinkAnalyzerPackageVersion>$(MicrosoftNETILLinkTasksVersion)</MicrosoftNETILLinkAnalyzerPackageVersion>
<!-- ICU -->
<MicrosoftNETCoreRuntimeICUTransportVersion>7.0.0-preview.3.22157.1</MicrosoftNETCoreRuntimeICUTransportVersion>
<!-- MsQuic -->
<SystemNetMsQuicTransportVersion>7.0.0-alpha.1.22160.2</SystemNetMsQuicTransportVersion>
<!-- Mono LLVM -->
<runtimelinuxarm64MicrosoftNETCoreRuntimeMonoLLVMSdkVersion>11.1.0-alpha.1.22121.2</runtimelinuxarm64MicrosoftNETCoreRuntimeMonoLLVMSdkVersion>
<runtimelinuxarm64MicrosoftNETCoreRuntimeMonoLLVMToolsVersion>11.1.0-alpha.1.22121.2</runtimelinuxarm64MicrosoftNETCoreRuntimeMonoLLVMToolsVersion>
<runtimelinuxx64MicrosoftNETCoreRuntimeMonoLLVMSdkVersion>11.1.0-alpha.1.22121.2</runtimelinuxx64MicrosoftNETCoreRuntimeMonoLLVMSdkVersion>
<runtimelinuxx64MicrosoftNETCoreRuntimeMonoLLVMToolsVersion>11.1.0-alpha.1.22121.2</runtimelinuxx64MicrosoftNETCoreRuntimeMonoLLVMToolsVersion>
<runtimewinx64MicrosoftNETCoreRuntimeMonoLLVMSdkVersion>11.1.0-alpha.1.22121.2</runtimewinx64MicrosoftNETCoreRuntimeMonoLLVMSdkVersion>
<runtimewinx64MicrosoftNETCoreRuntimeMonoLLVMToolsVersion>11.1.0-alpha.1.22121.2</runtimewinx64MicrosoftNETCoreRuntimeMonoLLVMToolsVersion>
<runtimeosx1012x64MicrosoftNETCoreRuntimeMonoLLVMSdkVersion>11.1.0-alpha.1.22121.2</runtimeosx1012x64MicrosoftNETCoreRuntimeMonoLLVMSdkVersion>
<runtimeosx1012x64MicrosoftNETCoreRuntimeMonoLLVMToolsVersion>11.1.0-alpha.1.22121.2</runtimeosx1012x64MicrosoftNETCoreRuntimeMonoLLVMToolsVersion>
<!-- emscripten / Node -->
<MicrosoftNETWorkloadEmscriptenManifest70100Version>7.0.0-preview.3.22128.1</MicrosoftNETWorkloadEmscriptenManifest70100Version>
<MicrosoftNETRuntimeEmscriptenVersion>$(MicrosoftNETWorkloadEmscriptenManifest70100Version)</MicrosoftNETRuntimeEmscriptenVersion>
<!-- workloads -->
<SwixPackageVersion>1.1.87-gba258badda</SwixPackageVersion>
<WixPackageVersion>1.0.0-v3.14.0.5722</WixPackageVersion>
<MonoWorkloadManifestVersion>6.0.0-preview.5.21275.7</MonoWorkloadManifestVersion>
</PropertyGroup>
</Project>
| 1 |
dotnet/runtime | 66,073 | Use ApiCompatTask in ApiCompat.proj | Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ViktorHofer | 2022-03-02T11:03:07Z | 2022-03-11T17:51:22Z | 3e2d483153adcab27033340fa40ad0bcdc3acc2a | 2575ce5f513c8f5cd37f935ba70b87cbd787c8df | Use ApiCompatTask in ApiCompat.proj. Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ./src/libraries/Directory.Build.props | <Project>
<PropertyGroup>
<SkipInferTargetOSName>true</SkipInferTargetOSName>
<DisableArcadeTestFramework>true</DisableArcadeTestFramework>
<!-- Set OutDirName to change the BaseOutputPath and BaseIntermediateOutputPath properties to include the ref subfolder. -->
<_projectDirName>$([System.IO.Path]::GetFileName('$(MSBuildProjectDirectory)'))</_projectDirName>
<IsReferenceAssemblyProject Condition="'$(_projectDirName)' == 'ref'">true</IsReferenceAssemblyProject>
<OutDirName Condition="'$(IsReferenceAssemblyProject)' == 'true'">$(MSBuildProjectName)$([System.IO.Path]::DirectorySeparatorChar)ref</OutDirName>
</PropertyGroup>
<Import Project="..\..\Directory.Build.props" />
<PropertyGroup>
<BeforeTargetFrameworkInferenceTargets>$(RepositoryEngineeringDir)BeforeTargetFrameworkInference.targets</BeforeTargetFrameworkInferenceTargets>
<RuntimeGraph>$(LibrariesProjectRoot)OSGroups.json</RuntimeGraph>
<ShouldUnsetParentConfigurationAndPlatform>false</ShouldUnsetParentConfigurationAndPlatform>
<GeneratePlatformNotSupportedAssemblyHeaderFile>$(RepositoryEngineeringDir)LicenseHeader.txt</GeneratePlatformNotSupportedAssemblyHeaderFile>
</PropertyGroup>
<!-- Define test projects and companions -->
<PropertyGroup Condition="$(MSBuildProjectFullPath.Contains('$([System.IO.Path]::DirectorySeparatorChar)tests$([System.IO.Path]::DirectorySeparatorChar)'))">
<IsTestProject Condition="$(MSBuildProjectName.EndsWith('.UnitTests')) or $(MSBuildProjectName.EndsWith('.Tests'))">true</IsTestProject>
<IsTrimmingTestProject Condition="$(MSBuildProjectName.EndsWith('.TrimmingTests'))">true</IsTrimmingTestProject>
<IsTestSupportProject Condition="'$(IsTestProject)' != 'true' and '$(IsTrimmingTestProject)' != 'true'">true</IsTestSupportProject>
<!-- Treat test assemblies as non-shipping (do not publish or sign them). -->
<IsShipping Condition="'$(IsTestProject)' == 'true' or '$(IsTestSupportProject)' == 'true' or '$(IsTrimmingTestProject)' == 'true'">false</IsShipping>
</PropertyGroup>
<PropertyGroup>
<!-- Treat as a generator project if either the parent or the parent parent directory is named gen. -->
<IsGeneratorProject Condition="'$(_projectDirName)' == 'gen' or
$([System.IO.Path]::GetFileName('$([System.IO.Path]::GetFullPath('$(MSBuildProjectDirectory)\..'))')) == 'gen'">true</IsGeneratorProject>
<IsSourceProject Condition="'$(IsSourceProject)' == '' and
'$(IsReferenceAssemblyProject)' != 'true' and
'$(IsGeneratorProject)' != 'true' and
'$(IsTestProject)' != 'true' and
'$(IsTrimmingTestProject)' != 'true' and
'$(IsTestSupportProject)' != 'true' and
'$(UsingMicrosoftNoTargetsSdk)' != 'true' and
'$(UsingMicrosoftTraversalSdk)' != 'true'">true</IsSourceProject>
</PropertyGroup>
<!-- Warnings that should be disabled in our test projects. -->
<PropertyGroup Condition="'$(IsTestProject)' == 'true' or '$(IsTestSupportProject)' == 'true'">
<!-- don't warn on usage of BinaryFormatter from test projects -->
<NoWarn>$(NoWarn);SYSLIB0011</NoWarn>
<!-- allow nullable annotated files to be incorporated into tests without warning -->
<Nullable Condition="'$(Nullable)' == '' and '$(Language)' == 'C#'">annotations</Nullable>
</PropertyGroup>
<!-- Unique assembly versions increases(3x) the compiler throughput during reference package updates. -->
<PropertyGroup Condition="'$(IsGeneratorProject)' == 'true'">
<AutoGenerateAssemblyVersion>true</AutoGenerateAssemblyVersion>
<!-- To suppress warnings about reseting the assembly version.-->
<AssemblyVersion />
</PropertyGroup>
<PropertyGroup>
<RunApiCompatForSrc>$([MSBuild]::ValueOrDefault('$(IsSourceProject)', 'false'))</RunApiCompatForSrc>
<RunMatchingRefApiCompat>$([MSBuild]::ValueOrDefault('$(IsSourceProject)', 'false'))</RunMatchingRefApiCompat>
<ApiCompatEnforceOptionalRules>true</ApiCompatEnforceOptionalRules>
<ApiCompatExcludeAttributeList>$(RepositoryEngineeringDir)DefaultGenApiDocIds.txt,$(RepositoryEngineeringDir)ApiCompatExcludeAttributes.txt</ApiCompatExcludeAttributeList>
</PropertyGroup>
<ItemGroup>
<!-- Projects which are manually built. -->
<ProjectExclusions Include="$(CommonTestPath)System\Net\Prerequisites\**\*.csproj" />
</ItemGroup>
<Import Project="NetCoreAppLibrary.props" />
<Import Project="$(RepositoryEngineeringDir)referenceAssemblies.props" Condition="'$(IsReferenceAssemblyProject)' == 'true'" />
<PropertyGroup>
<!-- Default any assembly not specifying a key to use the Open Key -->
<StrongNameKeyId>Open</StrongNameKeyId>
<!-- Microsoft.Extensions projects have a separate StrongNameKeyId -->
<StrongNameKeyId Condition="$(MSBuildProjectName.StartsWith('Microsoft.Extensions.'))">MicrosoftAspNetCore</StrongNameKeyId>
<!-- We can't generate an apphost without restoring the targeting pack. -->
<UseAppHost>false</UseAppHost>
<EnableDefaultItems>false</EnableDefaultItems>
</PropertyGroup>
<!-- Language configuration -->
<PropertyGroup>
<GenFacadesIgnoreBuildAndRevisionMismatch>true</GenFacadesIgnoreBuildAndRevisionMismatch>
<!-- Disable analyzers for tests and unsupported projects -->
<RunAnalyzers Condition="'$(IsTestProject)' != 'true' and '$(IsSourceProject)' != 'true'">false</RunAnalyzers>
<!-- Enable documentation file generation by the compiler for all libraries except for vbproj. -->
<GenerateDocumentationFile Condition="'$(IsSourceProject)' == 'true' and '$(MSBuildProjectExtension)' != '.vbproj'">true</GenerateDocumentationFile>
<CLSCompliant Condition="'$(CLSCompliant)' == '' and '$(IsTestProject)' != 'true' and '$(IsTestSupportProject)' != 'true'">true</CLSCompliant>
</PropertyGroup>
<ItemGroup Condition="'$(IsTestProject)' == 'true'">
<EditorConfigFiles Remove="$(RepositoryEngineeringDir)CodeAnalysis.src.globalconfig" />
<EditorConfigFiles Include="$(RepositoryEngineeringDir)CodeAnalysis.test.globalconfig" />
</ItemGroup>
<!-- Set up common paths -->
<PropertyGroup>
<!-- Helix properties -->
<OSPlatformConfig>$(TargetOS).$(Platform).$(Configuration)</OSPlatformConfig>
<TestArchiveRoot>$(ArtifactsDir)helix/</TestArchiveRoot>
<TestArchiveTestsRoot Condition="$(IsFunctionalTest) != true">$(TestArchiveRoot)tests/</TestArchiveTestsRoot>
<TestArchiveTestsRoot Condition="$(IsFunctionalTest) == true">$(TestArchiveRoot)runonly/</TestArchiveTestsRoot>
<TestArchiveTestsRoot Condition="'$(Scenario)' == 'BuildWasmApps'">$(TestArchiveRoot)buildwasmapps/</TestArchiveTestsRoot>
<TestArchiveTestsDir>$(TestArchiveTestsRoot)$(OSPlatformConfig)/</TestArchiveTestsDir>
<TestArchiveRuntimeRoot>$(TestArchiveRoot)runtime/</TestArchiveRuntimeRoot>
<UseAppBundleRootForBuildingTests Condition="'$(ArchiveTests)' == 'true' and '$(BuildTestsOnHelix)' != 'true' and '$(TargetsAppleMobile)' == 'true'">true</UseAppBundleRootForBuildingTests>
<AppBundleRoot Condition="'$(UseAppBundleRootForBuildingTests)' == 'true'">$(ArtifactsDir)bundles\</AppBundleRoot>
<CommonPathRoot>$([MSBuild]::NormalizeDirectory('$(LibrariesProjectRoot)', 'Common'))</CommonPathRoot>
<CommonPath>$([MSBuild]::NormalizeDirectory('$(CommonPathRoot)', 'src'))</CommonPath>
<CommonTestPath>$([MSBuild]::NormalizeDirectory('$(CommonPathRoot)', 'tests'))</CommonTestPath>
</PropertyGroup>
<ItemGroup Condition="'$(IsTestProject)' == 'true' and '$(SkipTestUtilitiesReference)' != 'true'">
<ProjectReference Include="$(CommonTestPath)TestUtilities\TestUtilities.csproj" />
</ItemGroup>
<PropertyGroup Condition="'$(IsTestProject)' == 'true'">
<EnableTestSupport>true</EnableTestSupport>
<!-- TODO: Remove these conditions when VSTest is used in CI. -->
<EnableRunSettingsSupport Condition="'$(ContinuousIntegrationBuild)' != 'true'">true</EnableRunSettingsSupport>
<EnableCoverageSupport Condition="'$(ContinuousIntegrationBuild)' != 'true'">true</EnableCoverageSupport>
</PropertyGroup>
<!-- To enable the interpreter for mono desktop, we need to pass an env switch -->
<PropertyGroup>
<MonoEnvOptions Condition="'$(MonoEnvOptions)' == '' and '$(TargetsMobile)' != 'true' and '$(MonoForceInterpreter)' == 'true'">--interpreter</MonoEnvOptions>
</PropertyGroup>
<PropertyGroup Condition="'$(TargetsMobile)' == 'true'">
<SdkWithNoWorkloadForTestingPath>$(ArtifactsBinDir)sdk-no-workload\</SdkWithNoWorkloadForTestingPath>
<SdkWithNoWorkloadForTestingPath>$([MSBuild]::NormalizeDirectory($(SdkWithNoWorkloadForTestingPath)))</SdkWithNoWorkloadForTestingPath>
<SdkWithNoWorkloadStampPath>$(SdkWithNoWorkloadForTestingPath)version-$(SdkVersionForWorkloadTesting).stamp</SdkWithNoWorkloadStampPath>
<SdkWithNoWorkload_WorkloadStampPath>$(SdkWithNoWorkloadForTestingPath)workload.stamp</SdkWithNoWorkload_WorkloadStampPath>
<SdkWithWorkloadForTestingPath>$(ArtifactsBinDir)dotnet-workload\</SdkWithWorkloadForTestingPath>
<SdkWithWorkloadForTestingPath>$([MSBuild]::NormalizeDirectory($(SdkWithWorkloadForTestingPath)))</SdkWithWorkloadForTestingPath>
<SdkWithWorkloadStampPath>$(SdkWithWorkloadForTestingPath)version-$(SdkVersionForWorkloadTesting).stamp</SdkWithWorkloadStampPath>
<SdkWithWorkload_WorkloadStampPath>$(SdkWithWorkloadForTestingPath)workload.stamp</SdkWithWorkload_WorkloadStampPath>
</PropertyGroup>
<Import Project="$(RepositoryEngineeringDir)testing\tests.props" Condition="'$(EnableTestSupport)' == 'true'" />
<!-- Use msbuild path functions as that property is used in bash scripts. -->
<ItemGroup>
<CoverageExcludeByFile Include="$([MSBuild]::NormalizePath('$(LibrariesProjectRoot)', 'Common', 'src', 'System', 'SR.*'))" />
<CoverageExcludeByFile Include="$([MSBuild]::NormalizePath('$(LibrariesProjectRoot)', 'Common', 'src', 'System', 'NotImplemented.cs'))" />
<!-- Link to the testhost folder to probe additional assemblies. -->
<CoverageIncludeDirectory Include="shared\Microsoft.NETCore.App\$(ProductVersion)" />
</ItemGroup>
</Project>
| <Project>
<PropertyGroup>
<SkipInferTargetOSName>true</SkipInferTargetOSName>
<DisableArcadeTestFramework>true</DisableArcadeTestFramework>
<!-- Set OutDirName to change the BaseOutputPath and BaseIntermediateOutputPath properties to include the ref subfolder. -->
<_projectDirName>$([System.IO.Path]::GetFileName('$(MSBuildProjectDirectory)'))</_projectDirName>
<IsReferenceAssemblyProject Condition="'$(_projectDirName)' == 'ref'">true</IsReferenceAssemblyProject>
<OutDirName Condition="'$(IsReferenceAssemblyProject)' == 'true'">$(MSBuildProjectName)$([System.IO.Path]::DirectorySeparatorChar)ref</OutDirName>
</PropertyGroup>
<Import Project="..\..\Directory.Build.props" />
<PropertyGroup>
<BeforeTargetFrameworkInferenceTargets>$(RepositoryEngineeringDir)BeforeTargetFrameworkInference.targets</BeforeTargetFrameworkInferenceTargets>
<RuntimeGraph>$(LibrariesProjectRoot)OSGroups.json</RuntimeGraph>
<ShouldUnsetParentConfigurationAndPlatform>false</ShouldUnsetParentConfigurationAndPlatform>
<GeneratePlatformNotSupportedAssemblyHeaderFile>$(RepositoryEngineeringDir)LicenseHeader.txt</GeneratePlatformNotSupportedAssemblyHeaderFile>
</PropertyGroup>
<!-- Define test projects and companions -->
<PropertyGroup Condition="$(MSBuildProjectFullPath.Contains('$([System.IO.Path]::DirectorySeparatorChar)tests$([System.IO.Path]::DirectorySeparatorChar)'))">
<IsTestProject Condition="$(MSBuildProjectName.EndsWith('.UnitTests')) or $(MSBuildProjectName.EndsWith('.Tests'))">true</IsTestProject>
<IsTrimmingTestProject Condition="$(MSBuildProjectName.EndsWith('.TrimmingTests'))">true</IsTrimmingTestProject>
<IsTestSupportProject Condition="'$(IsTestProject)' != 'true' and '$(IsTrimmingTestProject)' != 'true'">true</IsTestSupportProject>
<!-- Treat test assemblies as non-shipping (do not publish or sign them). -->
<IsShipping Condition="'$(IsTestProject)' == 'true' or '$(IsTestSupportProject)' == 'true' or '$(IsTrimmingTestProject)' == 'true'">false</IsShipping>
</PropertyGroup>
<PropertyGroup>
<!-- Treat as a generator project if either the parent or the parent parent directory is named gen. -->
<IsGeneratorProject Condition="'$(_projectDirName)' == 'gen' or
$([System.IO.Path]::GetFileName('$([System.IO.Path]::GetFullPath('$(MSBuildProjectDirectory)\..'))')) == 'gen'">true</IsGeneratorProject>
<IsSourceProject Condition="'$(IsSourceProject)' == '' and
'$(IsReferenceAssemblyProject)' != 'true' and
'$(IsGeneratorProject)' != 'true' and
'$(IsTestProject)' != 'true' and
'$(IsTrimmingTestProject)' != 'true' and
'$(IsTestSupportProject)' != 'true' and
'$(UsingMicrosoftNoTargetsSdk)' != 'true' and
'$(UsingMicrosoftTraversalSdk)' != 'true'">true</IsSourceProject>
</PropertyGroup>
<!-- Warnings that should be disabled in our test projects. -->
<PropertyGroup Condition="'$(IsTestProject)' == 'true' or '$(IsTestSupportProject)' == 'true'">
<!-- don't warn on usage of BinaryFormatter from test projects -->
<NoWarn>$(NoWarn);SYSLIB0011</NoWarn>
<!-- allow nullable annotated files to be incorporated into tests without warning -->
<Nullable Condition="'$(Nullable)' == '' and '$(Language)' == 'C#'">annotations</Nullable>
</PropertyGroup>
<!-- Unique assembly versions increases(3x) the compiler throughput during reference package updates. -->
<PropertyGroup Condition="'$(IsGeneratorProject)' == 'true'">
<AutoGenerateAssemblyVersion>true</AutoGenerateAssemblyVersion>
<!-- To suppress warnings about reseting the assembly version.-->
<AssemblyVersion />
</PropertyGroup>
<!-- ApiCompat setting -->
<PropertyGroup>
<RunApiCompatForSrc>$([MSBuild]::ValueOrDefault('$(IsSourceProject)', 'false'))</RunApiCompatForSrc>
<RunMatchingRefApiCompat>$([MSBuild]::ValueOrDefault('$(IsSourceProject)', 'false'))</RunMatchingRefApiCompat>
<ApiCompatEnforceOptionalRules>true</ApiCompatEnforceOptionalRules>
</PropertyGroup>
<ItemGroup>
<ApiCompatExcludeAttributesFile Include="$(RepositoryEngineeringDir)DefaultGenApiDocIds.txt" />
<ApiCompatExcludeAttributesFile Include="$(RepositoryEngineeringDir)ApiCompatExcludeAttributes.txt" />
</ItemGroup>
<ItemGroup>
<!-- Projects which are manually built. -->
<ProjectExclusions Include="$(CommonTestPath)System\Net\Prerequisites\**\*.csproj" />
</ItemGroup>
<Import Project="NetCoreAppLibrary.props" />
<Import Project="$(RepositoryEngineeringDir)referenceAssemblies.props" Condition="'$(IsReferenceAssemblyProject)' == 'true'" />
<PropertyGroup>
<!-- Default any assembly not specifying a key to use the Open Key -->
<StrongNameKeyId>Open</StrongNameKeyId>
<!-- Microsoft.Extensions projects have a separate StrongNameKeyId -->
<StrongNameKeyId Condition="$(MSBuildProjectName.StartsWith('Microsoft.Extensions.'))">MicrosoftAspNetCore</StrongNameKeyId>
<!-- We can't generate an apphost without restoring the targeting pack. -->
<UseAppHost>false</UseAppHost>
<EnableDefaultItems>false</EnableDefaultItems>
</PropertyGroup>
<!-- Language configuration -->
<PropertyGroup>
<GenFacadesIgnoreBuildAndRevisionMismatch>true</GenFacadesIgnoreBuildAndRevisionMismatch>
<!-- Disable analyzers for tests and unsupported projects -->
<RunAnalyzers Condition="'$(IsTestProject)' != 'true' and '$(IsSourceProject)' != 'true'">false</RunAnalyzers>
<!-- Enable documentation file generation by the compiler for all libraries except for vbproj. -->
<GenerateDocumentationFile Condition="'$(IsSourceProject)' == 'true' and '$(MSBuildProjectExtension)' != '.vbproj'">true</GenerateDocumentationFile>
<CLSCompliant Condition="'$(CLSCompliant)' == '' and '$(IsTestProject)' != 'true' and '$(IsTestSupportProject)' != 'true'">true</CLSCompliant>
</PropertyGroup>
<ItemGroup Condition="'$(IsTestProject)' == 'true'">
<EditorConfigFiles Remove="$(RepositoryEngineeringDir)CodeAnalysis.src.globalconfig" />
<EditorConfigFiles Include="$(RepositoryEngineeringDir)CodeAnalysis.test.globalconfig" />
</ItemGroup>
<!-- Set up common paths -->
<PropertyGroup>
<!-- Helix properties -->
<OSPlatformConfig>$(TargetOS).$(Platform).$(Configuration)</OSPlatformConfig>
<TestArchiveRoot>$(ArtifactsDir)helix/</TestArchiveRoot>
<TestArchiveTestsRoot Condition="$(IsFunctionalTest) != true">$(TestArchiveRoot)tests/</TestArchiveTestsRoot>
<TestArchiveTestsRoot Condition="$(IsFunctionalTest) == true">$(TestArchiveRoot)runonly/</TestArchiveTestsRoot>
<TestArchiveTestsRoot Condition="'$(Scenario)' == 'BuildWasmApps'">$(TestArchiveRoot)buildwasmapps/</TestArchiveTestsRoot>
<TestArchiveTestsDir>$(TestArchiveTestsRoot)$(OSPlatformConfig)/</TestArchiveTestsDir>
<TestArchiveRuntimeRoot>$(TestArchiveRoot)runtime/</TestArchiveRuntimeRoot>
<UseAppBundleRootForBuildingTests Condition="'$(ArchiveTests)' == 'true' and '$(BuildTestsOnHelix)' != 'true' and '$(TargetsAppleMobile)' == 'true'">true</UseAppBundleRootForBuildingTests>
<AppBundleRoot Condition="'$(UseAppBundleRootForBuildingTests)' == 'true'">$(ArtifactsDir)bundles\</AppBundleRoot>
<CommonPathRoot>$([MSBuild]::NormalizeDirectory('$(LibrariesProjectRoot)', 'Common'))</CommonPathRoot>
<CommonPath>$([MSBuild]::NormalizeDirectory('$(CommonPathRoot)', 'src'))</CommonPath>
<CommonTestPath>$([MSBuild]::NormalizeDirectory('$(CommonPathRoot)', 'tests'))</CommonTestPath>
</PropertyGroup>
<ItemGroup Condition="'$(IsTestProject)' == 'true' and '$(SkipTestUtilitiesReference)' != 'true'">
<ProjectReference Include="$(CommonTestPath)TestUtilities\TestUtilities.csproj" />
</ItemGroup>
<PropertyGroup Condition="'$(IsTestProject)' == 'true'">
<EnableTestSupport>true</EnableTestSupport>
<!-- TODO: Remove these conditions when VSTest is used in CI. -->
<EnableRunSettingsSupport Condition="'$(ContinuousIntegrationBuild)' != 'true'">true</EnableRunSettingsSupport>
<EnableCoverageSupport Condition="'$(ContinuousIntegrationBuild)' != 'true'">true</EnableCoverageSupport>
</PropertyGroup>
<!-- To enable the interpreter for mono desktop, we need to pass an env switch -->
<PropertyGroup>
<MonoEnvOptions Condition="'$(MonoEnvOptions)' == '' and '$(TargetsMobile)' != 'true' and '$(MonoForceInterpreter)' == 'true'">--interpreter</MonoEnvOptions>
</PropertyGroup>
<PropertyGroup Condition="'$(TargetsMobile)' == 'true'">
<SdkWithNoWorkloadForTestingPath>$(ArtifactsBinDir)sdk-no-workload\</SdkWithNoWorkloadForTestingPath>
<SdkWithNoWorkloadForTestingPath>$([MSBuild]::NormalizeDirectory($(SdkWithNoWorkloadForTestingPath)))</SdkWithNoWorkloadForTestingPath>
<SdkWithNoWorkloadStampPath>$(SdkWithNoWorkloadForTestingPath)version-$(SdkVersionForWorkloadTesting).stamp</SdkWithNoWorkloadStampPath>
<SdkWithNoWorkload_WorkloadStampPath>$(SdkWithNoWorkloadForTestingPath)workload.stamp</SdkWithNoWorkload_WorkloadStampPath>
<SdkWithWorkloadForTestingPath>$(ArtifactsBinDir)dotnet-workload\</SdkWithWorkloadForTestingPath>
<SdkWithWorkloadForTestingPath>$([MSBuild]::NormalizeDirectory($(SdkWithWorkloadForTestingPath)))</SdkWithWorkloadForTestingPath>
<SdkWithWorkloadStampPath>$(SdkWithWorkloadForTestingPath)version-$(SdkVersionForWorkloadTesting).stamp</SdkWithWorkloadStampPath>
<SdkWithWorkload_WorkloadStampPath>$(SdkWithWorkloadForTestingPath)workload.stamp</SdkWithWorkload_WorkloadStampPath>
</PropertyGroup>
<Import Project="$(RepositoryEngineeringDir)testing\tests.props" Condition="'$(EnableTestSupport)' == 'true'" />
<!-- Use msbuild path functions as that property is used in bash scripts. -->
<ItemGroup>
<CoverageExcludeByFile Include="$([MSBuild]::NormalizePath('$(LibrariesProjectRoot)', 'Common', 'src', 'System', 'SR.*'))" />
<CoverageExcludeByFile Include="$([MSBuild]::NormalizePath('$(LibrariesProjectRoot)', 'Common', 'src', 'System', 'NotImplemented.cs'))" />
<!-- Link to the testhost folder to probe additional assemblies. -->
<CoverageIncludeDirectory Include="shared\Microsoft.NETCore.App\$(ProductVersion)" />
</ItemGroup>
</Project>
| 1 |
dotnet/runtime | 66,073 | Use ApiCompatTask in ApiCompat.proj | Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ViktorHofer | 2022-03-02T11:03:07Z | 2022-03-11T17:51:22Z | 3e2d483153adcab27033340fa40ad0bcdc3acc2a | 2575ce5f513c8f5cd37f935ba70b87cbd787c8df | Use ApiCompatTask in ApiCompat.proj. Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ./src/libraries/apicompat/ApiCompat.proj | <Project Sdk="Microsoft.Build.NoTargets">
<PropertyGroup>
<TargetFramework>$(NetCoreAppCurrent)-$(TargetOS)</TargetFramework>
<!-- Reference the dependencies to have the assemblies available for API comparison. -->
<NoTargetsDoNotReferenceOutputAssemblies>false</NoTargetsDoNotReferenceOutputAssemblies>
<!-- Target reference assemblies instead of implementation assemblies. -->
<CompileUsingReferenceAssemblies>true</CompileUsingReferenceAssemblies>
<TrimOutPrivateAssembliesFromReferencePath>true</TrimOutPrivateAssembliesFromReferencePath>
<ApiCompatNSBaselineFile>$(MSBuildThisFileDirectory)ApiCompatBaseline.netcoreapp.netstandard.txt</ApiCompatNSBaselineFile>
<ApiCompatNSOnlyBaselineFile>$(MSBuildThisFileDirectory)ApiCompatBaseline.netcoreapp.netstandardOnly.txt</ApiCompatNSOnlyBaselineFile>
<PreviousNetCoreAppBaselineFile>$(MSBuildThisFileDirectory)ApiCompatBaseline.PreviousNetCoreApp.txt</PreviousNetCoreAppBaselineFile>
</PropertyGroup>
<ItemGroup>
<ApiCompatExcludeAttributeFile Include="$(ApiCompatExcludeAttributeList.Split(','))" />
<ApiCompatExcludeAttributeFile Include="ApiCompatBaselineExcludedAttributes.txt" />
</ItemGroup>
<!-- For API comparision, ApiCompat needs both the inbox and the out-of-band assemblies plus the shims to be built. -->
<ItemGroup>
<ProjectReference Include="..\sfx-src.proj;
..\oob-src.proj;
..\shims.proj" />
</ItemGroup>
<ItemGroup>
<PackageDownload Include="Microsoft.NETCore.App.Ref" Version="[$(NetCoreAppLatestStablePackageBaselineVersion)]" />
<PackageDownload Include="NETStandard.Library.Ref" Version="[$(NETStandardLibraryRefVersion)]" />
<PackageDownload Include="NETStandard.Library" Version="[$(NetStandardLibraryVersion)]" />
<PackageReference Include="Microsoft.DotNet.ApiCompat" Version="$(MicrosoftDotNetApiCompatVersion)" IsImplicitlyDefined="true" />
</ItemGroup>
<Target Name="RunApiCompat"
DependsOnTargets="FindReferenceAssembliesForReferences"
AfterTargets="Build"
Inputs="@(ReferencePathWithRefAssemblies);$(ApiCompatNSBaselineFile);$(ApiCompatNSOnlyBaselineFile);$(PreviousNetCoreAppBaselineFile);@(ApiCompatExcludeAttributeFile)"
Outputs="$(IntermediateOutputPath)$(TargetArchitecture)-marker.txt">
<PropertyGroup>
<ApiCompatResponseFile>$(IntermediateOutputPath)apicompat.rsp</ApiCompatResponseFile>
<ApiCompatExitCode>0</ApiCompatExitCode>
<!-- TODO: Replace with ReferencePathWithRefAssemblies when ApiCompat supports passing in a list of assemblies: https://github.com/dotnet/arcade/issues/8394. -->
<ApiCompatArgs>--impl-dirs "$(LibrariesAllRefArtifactsPath.TrimEnd('\/'))"</ApiCompatArgs>
<ApiCompatArgs Condition="'@(ApiCompatExcludeAttributeFile)' != ''">$(ApiCompatArgs) --exclude-attributes "@(ApiCompatExcludeAttributeFile->Metadata('FullPath'), ',')"</ApiCompatArgs>
</PropertyGroup>
<WriteLinesToFile File="$(ApiCompatResponseFile)"
Lines="$(ApiCompatArgs)"
Overwrite="true" />
<!-- In order to update the .NETStandard baseline, you can just start the build with /p:UpdateNETStandardBaseline=true -->
<PropertyGroup>
<NetStandardLibrary20RefPath>$([MSBuild]::NormalizeDirectory('$(NuGetPackageRoot)', 'netstandard.library', '$(NetStandardLibraryVersion)', 'build', 'netstandard2.0', 'ref'))</NetStandardLibrary20RefPath>
<NetStandard21OnlyRef>$(NETStandard21RefPath)netstandard.dll</NetStandard21OnlyRef>
<NetStandard21BaselineModifer>--baseline</NetStandard21BaselineModifer>
<NetStandard21BaselineModifer Condition="'$(UpdateNETStandardBaseline)' == 'true'">></NetStandard21BaselineModifer>
</PropertyGroup>
<Message Importance="high" Text="ApiCompat -> Comparing $(NetCoreAppCurrent) reference assemblies against .NETStandard2.x and .NETCoreApp$(NetCoreAppLatestStableVersion)..." />
<Exec Command="$(_ApiCompatCommand) "$(NetStandard21OnlyRef)" @"$(ApiCompatResponseFile)" $(NetStandard21BaselineModifer) "$(ApiCompatNSOnlyBaselineFile)""
CustomErrorRegularExpression="^[a-zA-Z]+ :"
StandardOutputImportance="Low"
IgnoreExitCode="true">
<Output TaskParameter="ExitCode" PropertyName="ApiCompatExitCode" />
</Exec>
<Error Condition="'$(ApiCompatExitCode)' != '0'" Text="ApiCompat failed comparing netstandard.dll to $(NetCoreAppCurrent)" />
<Exec Command="$(_ApiCompatCommand) "$(NetStandardLibrary20RefPath.TrimEnd('\/'))" --baseline "$(ApiCompatNSBaselineFile)" @"$(ApiCompatResponseFile)""
CustomErrorRegularExpression="^[a-zA-Z]+ :"
StandardOutputImportance="Low"
IgnoreExitCode="true">
<Output TaskParameter="ExitCode" PropertyName="ApiCompatExitCode" />
</Exec>
<Error Condition="'$(ApiCompatExitCode)' != '0'" Text="ApiCompat failed comparing netstandard to $(NetCoreAppCurrent)" />
<!-- In order to update the previous .NETCoreApp baseline, you can just start the build with /p:UpdatePreviousNetCoreAppBaseline=true -->
<PropertyGroup>
<PreviousNetCoreAppRefPath>$([MSBuild]::NormalizeDirectory('$(NuGetPackageRoot)', 'microsoft.netcore.app.ref', '$(NetCoreAppLatestStablePackageBaselineVersion)', 'ref', '$(NetCoreAppLatestStable)'))</PreviousNetCoreAppRefPath>
<PreviousNetCoreAppBaselineParam>--baseline</PreviousNetCoreAppBaselineParam>
<PreviousNetCoreAppBaselineParam Condition="'$(UpdatePreviousNetCoreAppBaseline)' == 'true'">></PreviousNetCoreAppBaselineParam>
</PropertyGroup>
<Exec Command="$(_ApiCompatCommand) "$(PreviousNetCoreAppRefPath.TrimEnd('\/'))" @"$(ApiCompatResponseFile)" $(PreviousNetCoreAppBaselineParam) "$(PreviousNetCoreAppBaselineFile)""
CustomErrorRegularExpression="^[a-zA-Z]+ :"
StandardOutputImportance="Low"
IgnoreExitCode="true">
<Output TaskParameter="ExitCode" PropertyName="ApiCompatExitCode" />
</Exec>
<Error Condition="'$(ApiCompatExitCode)' != '0'" Text="ApiCompat failed comparing $(NetCoreAppLatestStable) to $(NetCoreAppCurrent). If this breaking change is intentional, the ApiCompat baseline can be updated by running 'dotnet build $(MSBuildThisFileFullPath) /p:UpdatePreviousNetCoreAppBaseline=true'" />
<!-- Create a marker file which serves as the target's output to enable incremental builds. -->
<Touch Files="$(IntermediateOutputPath)$(TargetArchitecture)-marker.txt"
AlwaysCreate="true" />
</Target>
<Target Name="CleanAdditionalFiles" AfterTargets="Clean">
<RemoveDir Directories="$(IntermediateOutputPath)" />
</Target>
</Project>
| <Project Sdk="Microsoft.Build.NoTargets">
<PropertyGroup>
<TargetFramework>$(NetCoreAppCurrent)-$(TargetOS)</TargetFramework>
<!-- Reference the dependencies to have the assemblies available for API comparison. -->
<NoTargetsDoNotReferenceOutputAssemblies>false</NoTargetsDoNotReferenceOutputAssemblies>
<!-- Target reference assemblies instead of implementation assemblies. -->
<CompileUsingReferenceAssemblies>true</CompileUsingReferenceAssemblies>
<TrimOutPrivateAssembliesFromReferencePath>true</TrimOutPrivateAssembliesFromReferencePath>
<ApiCompatNetStandard20BaselineFile>$(MSBuildThisFileDirectory)ApiCompatBaseline.netstandard2.0.txt</ApiCompatNetStandard20BaselineFile>
<ApiCompatNetStandard21BaselineFile>$(MSBuildThisFileDirectory)ApiCompatBaseline.netstandard2.1.txt</ApiCompatNetStandard21BaselineFile>
<ApiCompatNetCoreAppLatestStableBaselineFile>$(MSBuildThisFileDirectory)ApiCompatBaseline.NetCoreAppLatestStable.txt</ApiCompatNetCoreAppLatestStableBaselineFile>
</PropertyGroup>
<ItemGroup>
<!-- The globally defined DefaultGenApiDocIds.txt and the ApiCompatExcludeAttributes.txt exclude attribute files apply as well. -->
<ApiCompatExcludeAttributesFile Include="ApiCompatBaselineExcludedAttributes.txt" />
</ItemGroup>
<!-- For API comparision, ApiCompat needs both the inbox and the out-of-band assemblies plus the shims to be built. -->
<ItemGroup>
<ProjectReference Include="..\sfx-src.proj;
..\oob-src.proj;
..\shims.proj" />
</ItemGroup>
<ItemGroup>
<PackageDownload Include="Microsoft.NETCore.App.Ref" Version="[$(NetCoreAppLatestStablePackageBaselineVersion)]" />
<PackageDownload Include="NETStandard.Library.Ref" Version="[$(NETStandardLibraryRefVersion)]" />
<PackageDownload Include="NETStandard.Library" Version="[$(NetStandardLibraryVersion)]" />
<PackageReference Include="Microsoft.DotNet.ApiCompat" Version="$(MicrosoftDotNetApiCompatVersion)" IsImplicitlyDefined="true" />
</ItemGroup>
<Target Name="RunApiCompat"
DependsOnTargets="FindReferenceAssembliesForReferences"
AfterTargets="Build"
Inputs="@(ReferencePathWithRefAssemblies);$(ApiCompatNetStandard20BaselineFile);$(ApiCompatNetStandard21BaselineFile);$(ApiCompatNetCoreAppLatestStableBaselineFile);@(ApiCompatExcludeAttributesFile)"
Outputs="$(IntermediateOutputPath)$(TargetArchitecture)-marker.txt">
<Message Text="ApiCompat -> Comparing $(NetCoreAppCurrent) reference assemblies against .NETStandard2.x and .NETCoreApp$(NetCoreAppLatestStableVersion)..." Importance="high" />
<PropertyGroup Condition="'$(UpdateBaselineFiles)' == 'true'">
<ApiCompatNetStandard21OutputFile>$(ApiCompatNetStandard21BaselineFile)</ApiCompatNetStandard21OutputFile>
<ApiCompatNetStandard20OutputFile>$(ApiCompatNetStandard20BaselineFile)</ApiCompatNetStandard20OutputFile>
<ApiCompatNetCoreAppLatestStableOutputFile>$(ApiCompatNetCoreAppLatestStableBaselineFile)</ApiCompatNetCoreAppLatestStableOutputFile>
<ApiCompatNetStandard21BaselineFile />
<ApiCompatNetStandard20BaselineFile />
<ApiCompatNetCoreAppLatestStableBaselineFile />
</PropertyGroup>
<Delete Files="$(ApiCompatNetStandard21OutputFile);$(ApiCompatNetStandard20OutputFile);$(ApiCompatNetCoreAppLatestStableOutputFile)"
Condition="'$(UpdateBaselineFiles)' == 'true'" />
<!-- ApiCompat: NetCoreAppCurrent <-> netstandard2.1 -->
<ApiCompatTask Contracts="$(NETStandard21RefPath)netstandard.dll"
ExcludeAttributes="@(ApiCompatExcludeAttributesFile)"
ImplementationDirectories="$(LibrariesAllRefArtifactsPath)"
BaselineFiles="$(ApiCompatNetStandard21BaselineFile)"
ValidateBaseline="true"
OutFilePath="$(ApiCompatNetStandard21OutputFile)"
DisableAssemblyResolveTraceListener="true"
IgnoreExitCode="true">
<Output TaskParameter="ExitCode" PropertyName="ApiCompatExitCode" />
</ApiCompatTask>
<Error Condition="'$(ApiCompatExitCode)' != '0'" Text="ApiCompat failed comparing netstandard.dll to $(NetCoreAppCurrent). If this breaking change is intentional, the ApiCompat baseline files can be updated by running 'dotnet build $(MSBuildThisFileFullPath) --no-incremental /p:UpdateBaselineFiles=true'." />
<!-- ApiCompat: NetCoreAppCurrent <-> netstandard2.0 -->
<ApiCompatTask Contracts="$([MSBuild]::NormalizeDirectory('$(NuGetPackageRoot)', 'netstandard.library', '$(NetStandardLibraryVersion)', 'build', 'netstandard2.0', 'ref'))"
ExcludeAttributes="@(ApiCompatExcludeAttributesFile)"
ImplementationDirectories="$(LibrariesAllRefArtifactsPath)"
BaselineFiles="$(ApiCompatNetStandard20BaselineFile)"
ValidateBaseline="true"
OutFilePath="$(ApiCompatNetStandard20OutputFile)"
DisableAssemblyResolveTraceListener="true"
IgnoreExitCode="true">
<Output TaskParameter="ExitCode" PropertyName="ApiCompatExitCode" />
</ApiCompatTask>
<Error Condition="'$(ApiCompatExitCode)' != '0'" Text="ApiCompat failed comparing netstandard to $(NetCoreAppCurrent). If this breaking change is intentional, the ApiCompat baseline files can be updated by running 'dotnet build $(MSBuildThisFileFullPath) --no-incremental /p:UpdateBaselineFiles=true'." />
<!-- ApiCompat: NetCoreAppCurrent <-> NetCoreAppLatestStable -->
<ApiCompatTask Contracts="$([MSBuild]::NormalizeDirectory('$(NuGetPackageRoot)', 'microsoft.netcore.app.ref', '$(NetCoreAppLatestStablePackageBaselineVersion)', 'ref', '$(NetCoreAppLatestStable)'))"
ExcludeAttributes="@(ApiCompatExcludeAttributesFile)"
ImplementationDirectories="$(LibrariesAllRefArtifactsPath)"
BaselineFiles="$(ApiCompatNetCoreAppLatestStableBaselineFile)"
ValidateBaseline="true"
OutFilePath="$(ApiCompatNetCoreAppLatestStableOutputFile)"
DisableAssemblyResolveTraceListener="true"
IgnoreExitCode="true">
<Output TaskParameter="ExitCode" PropertyName="ApiCompatExitCode" />
</ApiCompatTask>
<Error Condition="'$(ApiCompatExitCode)' != '0'" Text="ApiCompat failed comparing $(NetCoreAppLatestStable) to $(NetCoreAppCurrent). If this breaking change is intentional, the ApiCompat baseline files can be updated by running 'dotnet build $(MSBuildThisFileFullPath) --no-incremental /p:UpdateBaselineFiles=true'." />
<!-- Create a marker file which serves as the target's output to enable incremental builds. -->
<Touch Files="$(IntermediateOutputPath)$(TargetArchitecture)-marker.txt"
AlwaysCreate="true" />
</Target>
<Target Name="CleanAdditionalFiles" AfterTargets="Clean">
<RemoveDir Directories="$(IntermediateOutputPath)" />
</Target>
</Project>
| 1 |
dotnet/runtime | 66,073 | Use ApiCompatTask in ApiCompat.proj | Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ViktorHofer | 2022-03-02T11:03:07Z | 2022-03-11T17:51:22Z | 3e2d483153adcab27033340fa40ad0bcdc3acc2a | 2575ce5f513c8f5cd37f935ba70b87cbd787c8df | Use ApiCompatTask in ApiCompat.proj. Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ./src/libraries/System.Private.Xml/tests/Xslt/TestFiles/TestData/XsltScenarios/EXslt/math-source.xml | <?xml version="1.0" encoding="utf-8" ?>
<data>
<orders>
<order>100</order>
<order>1.99</order>
<order>12.99</order>
<order>59.99</order>
<order>2.99</order>
<order>1.99</order>
<order>999.99</order>
<order>123.45</order>
<order>999.99</order>
</orders>
<bad-data>23.99]</bad-data>
<bad-data>22.99</bad-data>
</data>
| <?xml version="1.0" encoding="utf-8" ?>
<data>
<orders>
<order>100</order>
<order>1.99</order>
<order>12.99</order>
<order>59.99</order>
<order>2.99</order>
<order>1.99</order>
<order>999.99</order>
<order>123.45</order>
<order>999.99</order>
</orders>
<bad-data>23.99]</bad-data>
<bad-data>22.99</bad-data>
</data>
| -1 |
dotnet/runtime | 66,073 | Use ApiCompatTask in ApiCompat.proj | Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ViktorHofer | 2022-03-02T11:03:07Z | 2022-03-11T17:51:22Z | 3e2d483153adcab27033340fa40ad0bcdc3acc2a | 2575ce5f513c8f5cd37f935ba70b87cbd787c8df | Use ApiCompatTask in ApiCompat.proj. Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ./eng/Tools.props | <Project>
<PropertyGroup>
<!-- Unset the repo tool manifest property in CI as we don't use repo tools there anyway,
until https://github.com/dotnet/sdk/issues/10938 is fixed. -->
<_RepoToolManifest Condition="'$(ContinuousIntegrationBuild)' == 'true'" />
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.DotNet.Build.Tasks.Packaging" Version="$(MicrosoftDotNetBuildTasksPackagingVersion)" />
<!-- enable source link in pkgproj -->
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="$(MicrosoftSourceLinkVersion)" PrivateAssets="all" IsImplicitlyDefined="true" />
<PackageReference Include="Microsoft.SourceLink.AzureRepos.Git" Version="$(MicrosoftSourceLinkVersion)" PrivateAssets="all" IsImplicitlyDefined="true" />
</ItemGroup>
<!-- excluded from source build -->
<ItemGroup Condition="'$(DotNetBuildFromSource)' != 'true'">
<PackageReference Include="Microsoft.DotNet.Build.Tasks.Feed" Version="$(MicrosoftDotNetBuildTasksFeedVersion)" />
<PackageReference Include="Microsoft.DotNet.VersionTools.Tasks" Version="$(MicrosoftDotNetVersionToolsTasksVersion)" />
</ItemGroup>
</Project>
| <Project>
<PropertyGroup>
<!-- Unset the repo tool manifest property in CI as we don't use repo tools there anyway,
until https://github.com/dotnet/sdk/issues/10938 is fixed. -->
<_RepoToolManifest Condition="'$(ContinuousIntegrationBuild)' == 'true'" />
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.DotNet.Build.Tasks.Packaging" Version="$(MicrosoftDotNetBuildTasksPackagingVersion)" />
<!-- enable source link in pkgproj -->
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="$(MicrosoftSourceLinkVersion)" PrivateAssets="all" IsImplicitlyDefined="true" />
<PackageReference Include="Microsoft.SourceLink.AzureRepos.Git" Version="$(MicrosoftSourceLinkVersion)" PrivateAssets="all" IsImplicitlyDefined="true" />
</ItemGroup>
<!-- excluded from source build -->
<ItemGroup Condition="'$(DotNetBuildFromSource)' != 'true'">
<PackageReference Include="Microsoft.DotNet.Build.Tasks.Feed" Version="$(MicrosoftDotNetBuildTasksFeedVersion)" />
<PackageReference Include="Microsoft.DotNet.VersionTools.Tasks" Version="$(MicrosoftDotNetVersionToolsTasksVersion)" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime | 66,073 | Use ApiCompatTask in ApiCompat.proj | Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ViktorHofer | 2022-03-02T11:03:07Z | 2022-03-11T17:51:22Z | 3e2d483153adcab27033340fa40ad0bcdc3acc2a | 2575ce5f513c8f5cd37f935ba70b87cbd787c8df | Use ApiCompatTask in ApiCompat.proj. Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ./src/libraries/System.Private.Xml/tests/Xslt/TestFiles/TestData/XsltApi/Resolver_test.xml | <?xml version="1.0"?>
<doc>foo</doc> | <?xml version="1.0"?>
<doc>foo</doc> | -1 |
dotnet/runtime | 66,073 | Use ApiCompatTask in ApiCompat.proj | Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ViktorHofer | 2022-03-02T11:03:07Z | 2022-03-11T17:51:22Z | 3e2d483153adcab27033340fa40ad0bcdc3acc2a | 2575ce5f513c8f5cd37f935ba70b87cbd787c8df | Use ApiCompatTask in ApiCompat.proj. Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ./src/tests/Interop/MonoAPI/MonoMono/Directory.Build.props | <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\..\Directory.Build.props" />
<ItemGroup>
<ProjectReference Include="$(TestSourceDir)Common/CoreCLRTestLibrary/CoreCLRTestLibrary.csproj" />
</ItemGroup>
</Project>
| <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\..\Directory.Build.props" />
<ItemGroup>
<ProjectReference Include="$(TestSourceDir)Common/CoreCLRTestLibrary/CoreCLRTestLibrary.csproj" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime | 66,073 | Use ApiCompatTask in ApiCompat.proj | Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ViktorHofer | 2022-03-02T11:03:07Z | 2022-03-11T17:51:22Z | 3e2d483153adcab27033340fa40ad0bcdc3acc2a | 2575ce5f513c8f5cd37f935ba70b87cbd787c8df | Use ApiCompatTask in ApiCompat.proj. Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ./src/installer/pkg/sfx/bundle/shared-framework-distribution-template-arm64.xml | <?xml version="1.0" encoding="utf-8" standalone="no"?>
<installer-gui-script minSpecVersion="1">
<background file="dotnetbackground.png" mime-type="image/png"/>
<options customize="never" require-scripts="false" hostArchitectures="arm64" />
<welcome file="welcome.html" mime-type="text/html" />
<conclusion file="conclusion.html" mime-type="text/html" />
<volume-check>
<allowed-os-versions>
<os-version min="11.0" />
</allowed-os-versions>
</volume-check>
</installer-gui-script>
| <?xml version="1.0" encoding="utf-8" standalone="no"?>
<installer-gui-script minSpecVersion="1">
<background file="dotnetbackground.png" mime-type="image/png"/>
<options customize="never" require-scripts="false" hostArchitectures="arm64" />
<welcome file="welcome.html" mime-type="text/html" />
<conclusion file="conclusion.html" mime-type="text/html" />
<volume-check>
<allowed-os-versions>
<os-version min="11.0" />
</allowed-os-versions>
</volume-check>
</installer-gui-script>
| -1 |
dotnet/runtime | 66,073 | Use ApiCompatTask in ApiCompat.proj | Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ViktorHofer | 2022-03-02T11:03:07Z | 2022-03-11T17:51:22Z | 3e2d483153adcab27033340fa40ad0bcdc3acc2a | 2575ce5f513c8f5cd37f935ba70b87cbd787c8df | Use ApiCompatTask in ApiCompat.proj. Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ./src/libraries/System.Private.Xml/tests/ILLink.Descriptors.ModuleCore.xml | <linker>
<assembly fullname="ModuleCore">
<type fullname="OLEDB.Test.ModuleCore.XmlInlineDataDiscoverer">
<method signature="System.Void .ctor()" />
</type>
</assembly>
</linker>
| <linker>
<assembly fullname="ModuleCore">
<type fullname="OLEDB.Test.ModuleCore.XmlInlineDataDiscoverer">
<method signature="System.Void .ctor()" />
</type>
</assembly>
</linker>
| -1 |
dotnet/runtime | 66,073 | Use ApiCompatTask in ApiCompat.proj | Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ViktorHofer | 2022-03-02T11:03:07Z | 2022-03-11T17:51:22Z | 3e2d483153adcab27033340fa40ad0bcdc3acc2a | 2575ce5f513c8f5cd37f935ba70b87cbd787c8df | Use ApiCompatTask in ApiCompat.proj. Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ./src/libraries/System.Private.Xml/tests/Xslt/TestFiles/TestData/XsltApi/Exceptions.xml | <exceptions>
<!-- XPath Exceptions -->
<exception res="Xp_UnclosedString" message="This is an unclosed string."/>
<exception res="Xp_TokenExpected" message="A token was expected."/>
<exception res="Xp_NodeTestExpected" message="A NodeTest was expected at {0}."/>
<exception res="Xp_ExprExpected" message="'{0}' is an invalid expression."/>
<exception res="Xp_NumberExpected" message="A number was expected."/>
<exception res="Xp_BooleanExpected" message="A boolean value was expected."/>
<exception res="Xp_QueryExpected" message="A query was expected."/>
<exception res="Xp_UnknownMethod" message="'{0}()' is an unknown method."/>
<exception res="Xp_TestExpected" message="A test was expected."/>
<exception res="Xp_InvalidArgument" message="'{0}' function in {1} has an invalid argument. Maybe ')' is missing."/>
<exception res="Xp_InvalidArgumentType" message="The argument to function '{0}' cannot be converted to nodeset."/>
<exception res="Xp_InvalidNumArgs" message="Function '{0}' in {1} has invalid number of arguments."/>
<exception res="Xp_InvalidName" message="This is an invalid name."/>
<exception res="Xp_InvalidNodeType" message="This is an invalid NodeType."/>
<exception res="Xp_InvalidToken" message="{0} has an invalid token."/>
<exception res="Xp_FunctionExpected" message="A function was expected."/>
<exception res="Xp_NodeSetExpected" message="The expression passed to this method should result in a NodeSet."/>
<exception res="Xp_NoXPathActive" message="No XPath query is currently active. Call Select() first."/>
<exception res="Xp_NotSupported" message="The XPath query '{0}' is not supported."/>
<exception res="Xp_InvalidPattern" message="{0} is an invalid XSLT pattern."/>
<exception res="Xp_InvalidPatternString" message="{0} is an invalid XSLT pattern."/>
<exception res="Xp_InvalidKeyPattern" message="{0} is an invalid key pattern. It either has a variable reference or key function."/>
<exception res="Xp_BadQueryObject" message="This is an invalid object. Only objects returned from Compile() can be passed as input."/>
<exception res="Xp_InvalidDataRecordFilter" message="This is an invalid filter for a data record."/>
<exception res="Xp_NoSelectedSet" message="There is no result set from the selection."/>
<exception res="Xp_MovedFromSelection" message="The current node is not the previously selected node."/>
<exception res="Xp_ConstantExpected" message="The expression passed to this method should result in a constant."/>
<exception res="Xp_UndefinedXsltContext" message="XsltContext is needed for this query because of an unknown function."/>
<exception res="Xp_BadContext" message="The context passed to the SetContext method is invalid."/>
<exception res="Xp_BadQueryString" message="The xpath expression passed into compile is null or empty."/>
<exception res="Xp_NoContext" message="Namespace Manager or XsltContext needed. This query has prefix or variable or userdefined function."/>
<!-- XSLT Exceptions -->
<exception res="Xslt_CompileError" message="{0}({1},{2}) :\n"/>
<exception res="Xslt_WrongStylesheetElement" message="Stylesheet should start from 'xsl:stylesheet' or 'xsl:transform' element or from literal result element with 'xsl:version' attribute."/>
<exception res="Xslt_UnsuppFunction" message="'{0}()' is an unsupported XSLT function."/>
<exception res="Xslt_NotFirstImport" message="'xsl:import' should be the first instruction of the stylesheet."/>
<exception res="Xslt_UnexpectedKeyword" message="'{0}' is an unexpected keyword."/>
<exception res="Xslt_NullNsAtTopLevel" message="Top level elements should have non-null namespace, {0}."/>
<exception res="Xslt_InvalidContents" message="The contents of '{0}' are invalid."/>
<exception res="Xslt_InvalidStylesheet" message="This is an invalid style sheet."/>
<exception res="Xslt_InvalidNamespace" message="This is an invalid namespace."/>
<exception res="Xslt_UnsuppKeyword" message="'{0}' is an unsupported keyword."/>
<exception res="Xslt_InvalidKeyword" message="'{0}' is an invalid keyword."/>
<exception res="Xslt_InvalidAttribute" message="'{0}' is an invalid attribute for '{1}' element."/>
<exception res="Xslt_MissingAttribute" message="Missing mandatory attribute '{0}'."/>
<exception res="Xslt_InvalidAttrValue" message="'{1}' is an invalid value for '{0}' attribute."/>
<exception res="Xslt_EmptyTagRequired" message="The tag '{0}' must be empty."/>
<exception res="Xslt_CircularInclude" message="There is a circular import or include of the file, {0}."/>
<exception res="Xslt_CantResolve" message="Cannot resolve the referenced document '{0}'."/>
<exception res="Xslt_SingleRightAvt" message="There should be a single right curly brace outside AVT expression '{0}'."/>
<exception res="Xslt_OpenBracesAvt" message="The braces are not closed in AVT expression '{0}'."/>
<exception res="Xslt_OpenLiteralAvt" message="The literal in AVT expression is not correctly closed '{0}'."/>
<exception res="Xslt_InvalidXPath" message="'{0}' is an invalid XPath expression."/>
<exception res="Xslt_InvalidQName" message="'{0}' is an invalid QName."/>
<exception res="Xslt_InvalidPIName" message="'{0}' is an invalid name for a processing instruction."/>
<exception res="Xslt_VariableCntSel" message="The '{0}' variable has both a select attribute of '{1}' and non-empty contents."/>
<exception res="Xslt_NoStylesheetLoaded" message="No stylesheet was loaded."/>
<exception res="Xslt_InvalidOperation" message="Invalid operation."/>
<exception res="Xslt_Internal" message="An XSLT internal error has occurred."/>
<exception res="Xslt_DupTemplateName" message="'{0}' is a duplicate template name."/>
<exception res="Xslt_TemplateNoAttrib" message="An xsl:template requires at least a match or name attribute."/>
<exception res="Xslt_InvalidVariable" message="The variable or param '{0}' is either not defined or it is out of scope."/>
<exception res="Xslt_DupVarName" message="Variable or param '{0}' was duplicated within the same scope."/>
<exception res="Xslt_WrongNumberArgs" message="XSLT function '{0}' has the wrong number of arguments."/>
<exception res="Xslt_UnknownXsltFunction" message="'{0}()' is an unknown XSLT function."/>
<exception res="Xslt_InvalidFuncOperand" message="The function operand type is invalid."/>
<exception res="Xslt_NoNodeSetConversion" message="Cannot convert the operand to NodeSet."/>
<exception res="Xslt_NoNavigatorConversion" message="Cannot convert the operand to 'Result tree fragment'."/>
<exception res="Xslt_InvalidXPathContext" message="The XPath context is invalid."/>
<exception res="Xslt_NoAttributeSet" message="A reference to attribute set '{0}' cannot be resolved. An xsl:attribute-set of this name must be declared at the top-level of the stylesheet."/>
<exception res="Xslt_CircularAttributeSet" message="There was a circular reference in the '{0}' xsl:attribute-set declaration."/>
<exception res="Xslt_VarNeedsXmlEditor" message="The variables require editing capabilities from the XmlNavigator you provided (XmlEditor)."/>
<exception res="Xslt_InvalidCallTemplate" message="The named template '{0}' does not exist."/>
<exception res="Xslt_WrongNamespace" message="The wrong namespace was used for XSL. Use 'http://www.w3.org/1999/XSL/Transform'."/>
<exception res="Xslt_InvalidPrefix" message="Prefix '{0}' is not defined."/>
<exception res="Xslt_FunctionFailed" message="Function '{0}()' has failed."/>
<exception res="Xslt_InvalidFormat" message="Invalid format."/>
<exception res="Xslt_ScriptMixLang" message="Mixing scripting languages for the same namespace is not supported."/>
<exception res="Xslt_ScriptCompileErrors" message="Script compile errors:\n{0}"/>
<exception res="Xslt_ScriptInvalidPrefix" message="Cannot find the script or external object that implements prefix '{0}'."/>
<exception res="Xslt_ScriptDub" message="Namespace '{0}' has duplicate implementation."/>
<exception res="Xslt_ScriptEmpty" message="msxsl:script cannot be empty."/>
<exception res="Xslt_ScriptInvalidLang" message="The scripting language '{0}' is not supported."/>
<exception res="Xslt_DupDecimalFormat" message="Decimal format '{0}' has duplicate declaration."/>
<exception res="Xslt_NoDecimalFormat" message="Decimal format '{0}' is not declared in the stylesheet but is referenced. "/>
<exception res="Xslt_InfiniteLoop" message="Calling template '{0}' will result in an infinite loop."/>
<exception res="Xslt_CircularReference" message="There is a circular reference in definition of variable '{0}'."/>
<exception res="Xslt_UndefinedVarReference" message="Variable '{0}' is not defined in the stylesheet but is referenced."/>
<exception res="Xslt_InvalidExtensionNamespace" message="Extension namespace cannot be 'null' nor XSLT namespace URI."/>
<exception res="Xslt_InvalidParamNamespace" message="Parameter cannot belong to XSLT namespace."/>
<exception res="Xslt_InvalidModeAttribute" message="xsl:template cannot have 'mode' attribute without a 'match' attribute."/>
<exception res="Xslt_MultipleRoots" message="There are multiple root elements in the output xml."/>
<!-- XML Exceptions -->
<exception res="Xml_BadStartNameChar" message="The '{0}' character, hexadecimal value {1}, cannot begin a name."/>
<exception res="Xml_ResolveUrl" message="There was an error accessing {0}."/>
<exception res="Xml_NullResolver" message="Resolving of external URIs was prohibited. "/>
</exceptions> | <exceptions>
<!-- XPath Exceptions -->
<exception res="Xp_UnclosedString" message="This is an unclosed string."/>
<exception res="Xp_TokenExpected" message="A token was expected."/>
<exception res="Xp_NodeTestExpected" message="A NodeTest was expected at {0}."/>
<exception res="Xp_ExprExpected" message="'{0}' is an invalid expression."/>
<exception res="Xp_NumberExpected" message="A number was expected."/>
<exception res="Xp_BooleanExpected" message="A boolean value was expected."/>
<exception res="Xp_QueryExpected" message="A query was expected."/>
<exception res="Xp_UnknownMethod" message="'{0}()' is an unknown method."/>
<exception res="Xp_TestExpected" message="A test was expected."/>
<exception res="Xp_InvalidArgument" message="'{0}' function in {1} has an invalid argument. Maybe ')' is missing."/>
<exception res="Xp_InvalidArgumentType" message="The argument to function '{0}' cannot be converted to nodeset."/>
<exception res="Xp_InvalidNumArgs" message="Function '{0}' in {1} has invalid number of arguments."/>
<exception res="Xp_InvalidName" message="This is an invalid name."/>
<exception res="Xp_InvalidNodeType" message="This is an invalid NodeType."/>
<exception res="Xp_InvalidToken" message="{0} has an invalid token."/>
<exception res="Xp_FunctionExpected" message="A function was expected."/>
<exception res="Xp_NodeSetExpected" message="The expression passed to this method should result in a NodeSet."/>
<exception res="Xp_NoXPathActive" message="No XPath query is currently active. Call Select() first."/>
<exception res="Xp_NotSupported" message="The XPath query '{0}' is not supported."/>
<exception res="Xp_InvalidPattern" message="{0} is an invalid XSLT pattern."/>
<exception res="Xp_InvalidPatternString" message="{0} is an invalid XSLT pattern."/>
<exception res="Xp_InvalidKeyPattern" message="{0} is an invalid key pattern. It either has a variable reference or key function."/>
<exception res="Xp_BadQueryObject" message="This is an invalid object. Only objects returned from Compile() can be passed as input."/>
<exception res="Xp_InvalidDataRecordFilter" message="This is an invalid filter for a data record."/>
<exception res="Xp_NoSelectedSet" message="There is no result set from the selection."/>
<exception res="Xp_MovedFromSelection" message="The current node is not the previously selected node."/>
<exception res="Xp_ConstantExpected" message="The expression passed to this method should result in a constant."/>
<exception res="Xp_UndefinedXsltContext" message="XsltContext is needed for this query because of an unknown function."/>
<exception res="Xp_BadContext" message="The context passed to the SetContext method is invalid."/>
<exception res="Xp_BadQueryString" message="The xpath expression passed into compile is null or empty."/>
<exception res="Xp_NoContext" message="Namespace Manager or XsltContext needed. This query has prefix or variable or userdefined function."/>
<!-- XSLT Exceptions -->
<exception res="Xslt_CompileError" message="{0}({1},{2}) :\n"/>
<exception res="Xslt_WrongStylesheetElement" message="Stylesheet should start from 'xsl:stylesheet' or 'xsl:transform' element or from literal result element with 'xsl:version' attribute."/>
<exception res="Xslt_UnsuppFunction" message="'{0}()' is an unsupported XSLT function."/>
<exception res="Xslt_NotFirstImport" message="'xsl:import' should be the first instruction of the stylesheet."/>
<exception res="Xslt_UnexpectedKeyword" message="'{0}' is an unexpected keyword."/>
<exception res="Xslt_NullNsAtTopLevel" message="Top level elements should have non-null namespace, {0}."/>
<exception res="Xslt_InvalidContents" message="The contents of '{0}' are invalid."/>
<exception res="Xslt_InvalidStylesheet" message="This is an invalid style sheet."/>
<exception res="Xslt_InvalidNamespace" message="This is an invalid namespace."/>
<exception res="Xslt_UnsuppKeyword" message="'{0}' is an unsupported keyword."/>
<exception res="Xslt_InvalidKeyword" message="'{0}' is an invalid keyword."/>
<exception res="Xslt_InvalidAttribute" message="'{0}' is an invalid attribute for '{1}' element."/>
<exception res="Xslt_MissingAttribute" message="Missing mandatory attribute '{0}'."/>
<exception res="Xslt_InvalidAttrValue" message="'{1}' is an invalid value for '{0}' attribute."/>
<exception res="Xslt_EmptyTagRequired" message="The tag '{0}' must be empty."/>
<exception res="Xslt_CircularInclude" message="There is a circular import or include of the file, {0}."/>
<exception res="Xslt_CantResolve" message="Cannot resolve the referenced document '{0}'."/>
<exception res="Xslt_SingleRightAvt" message="There should be a single right curly brace outside AVT expression '{0}'."/>
<exception res="Xslt_OpenBracesAvt" message="The braces are not closed in AVT expression '{0}'."/>
<exception res="Xslt_OpenLiteralAvt" message="The literal in AVT expression is not correctly closed '{0}'."/>
<exception res="Xslt_InvalidXPath" message="'{0}' is an invalid XPath expression."/>
<exception res="Xslt_InvalidQName" message="'{0}' is an invalid QName."/>
<exception res="Xslt_InvalidPIName" message="'{0}' is an invalid name for a processing instruction."/>
<exception res="Xslt_VariableCntSel" message="The '{0}' variable has both a select attribute of '{1}' and non-empty contents."/>
<exception res="Xslt_NoStylesheetLoaded" message="No stylesheet was loaded."/>
<exception res="Xslt_InvalidOperation" message="Invalid operation."/>
<exception res="Xslt_Internal" message="An XSLT internal error has occurred."/>
<exception res="Xslt_DupTemplateName" message="'{0}' is a duplicate template name."/>
<exception res="Xslt_TemplateNoAttrib" message="An xsl:template requires at least a match or name attribute."/>
<exception res="Xslt_InvalidVariable" message="The variable or param '{0}' is either not defined or it is out of scope."/>
<exception res="Xslt_DupVarName" message="Variable or param '{0}' was duplicated within the same scope."/>
<exception res="Xslt_WrongNumberArgs" message="XSLT function '{0}' has the wrong number of arguments."/>
<exception res="Xslt_UnknownXsltFunction" message="'{0}()' is an unknown XSLT function."/>
<exception res="Xslt_InvalidFuncOperand" message="The function operand type is invalid."/>
<exception res="Xslt_NoNodeSetConversion" message="Cannot convert the operand to NodeSet."/>
<exception res="Xslt_NoNavigatorConversion" message="Cannot convert the operand to 'Result tree fragment'."/>
<exception res="Xslt_InvalidXPathContext" message="The XPath context is invalid."/>
<exception res="Xslt_NoAttributeSet" message="A reference to attribute set '{0}' cannot be resolved. An xsl:attribute-set of this name must be declared at the top-level of the stylesheet."/>
<exception res="Xslt_CircularAttributeSet" message="There was a circular reference in the '{0}' xsl:attribute-set declaration."/>
<exception res="Xslt_VarNeedsXmlEditor" message="The variables require editing capabilities from the XmlNavigator you provided (XmlEditor)."/>
<exception res="Xslt_InvalidCallTemplate" message="The named template '{0}' does not exist."/>
<exception res="Xslt_WrongNamespace" message="The wrong namespace was used for XSL. Use 'http://www.w3.org/1999/XSL/Transform'."/>
<exception res="Xslt_InvalidPrefix" message="Prefix '{0}' is not defined."/>
<exception res="Xslt_FunctionFailed" message="Function '{0}()' has failed."/>
<exception res="Xslt_InvalidFormat" message="Invalid format."/>
<exception res="Xslt_ScriptMixLang" message="Mixing scripting languages for the same namespace is not supported."/>
<exception res="Xslt_ScriptCompileErrors" message="Script compile errors:\n{0}"/>
<exception res="Xslt_ScriptInvalidPrefix" message="Cannot find the script or external object that implements prefix '{0}'."/>
<exception res="Xslt_ScriptDub" message="Namespace '{0}' has duplicate implementation."/>
<exception res="Xslt_ScriptEmpty" message="msxsl:script cannot be empty."/>
<exception res="Xslt_ScriptInvalidLang" message="The scripting language '{0}' is not supported."/>
<exception res="Xslt_DupDecimalFormat" message="Decimal format '{0}' has duplicate declaration."/>
<exception res="Xslt_NoDecimalFormat" message="Decimal format '{0}' is not declared in the stylesheet but is referenced. "/>
<exception res="Xslt_InfiniteLoop" message="Calling template '{0}' will result in an infinite loop."/>
<exception res="Xslt_CircularReference" message="There is a circular reference in definition of variable '{0}'."/>
<exception res="Xslt_UndefinedVarReference" message="Variable '{0}' is not defined in the stylesheet but is referenced."/>
<exception res="Xslt_InvalidExtensionNamespace" message="Extension namespace cannot be 'null' nor XSLT namespace URI."/>
<exception res="Xslt_InvalidParamNamespace" message="Parameter cannot belong to XSLT namespace."/>
<exception res="Xslt_InvalidModeAttribute" message="xsl:template cannot have 'mode' attribute without a 'match' attribute."/>
<exception res="Xslt_MultipleRoots" message="There are multiple root elements in the output xml."/>
<!-- XML Exceptions -->
<exception res="Xml_BadStartNameChar" message="The '{0}' character, hexadecimal value {1}, cannot begin a name."/>
<exception res="Xml_ResolveUrl" message="There was an error accessing {0}."/>
<exception res="Xml_NullResolver" message="Resolving of external URIs was prohibited. "/>
</exceptions> | -1 |
dotnet/runtime | 66,073 | Use ApiCompatTask in ApiCompat.proj | Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ViktorHofer | 2022-03-02T11:03:07Z | 2022-03-11T17:51:22Z | 3e2d483153adcab27033340fa40ad0bcdc3acc2a | 2575ce5f513c8f5cd37f935ba70b87cbd787c8df | Use ApiCompatTask in ApiCompat.proj. Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ./src/libraries/System.ServiceModel.Syndication/tests/TestFeeds/RssFeeds/skipHours.xml | <!--
Description: skipHours contains 1 valid hour
Expect: ValidHour{parent:skipHours,element:hour}
-->
<rss version="2.0">
<channel>
<title>RSS 2.0 test case</title>
<link>http://www.contoso.com/testcases/rss20/</link>
<description>skipHours contains 1 valid hour</description>
<skipHours>
<hour>12</hour>
</skipHours>
</channel>
</rss>
| <!--
Description: skipHours contains 1 valid hour
Expect: ValidHour{parent:skipHours,element:hour}
-->
<rss version="2.0">
<channel>
<title>RSS 2.0 test case</title>
<link>http://www.contoso.com/testcases/rss20/</link>
<description>skipHours contains 1 valid hour</description>
<skipHours>
<hour>12</hour>
</skipHours>
</channel>
</rss>
| -1 |
dotnet/runtime | 66,073 | Use ApiCompatTask in ApiCompat.proj | Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ViktorHofer | 2022-03-02T11:03:07Z | 2022-03-11T17:51:22Z | 3e2d483153adcab27033340fa40ad0bcdc3acc2a | 2575ce5f513c8f5cd37f935ba70b87cbd787c8df | Use ApiCompatTask in ApiCompat.proj. Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ./src/libraries/System.ComponentModel.TypeConverter/src/ILLink/ILLink.Substitutions.xml | <linker>
<assembly fullname="System.ComponentModel.TypeConverter">
<type fullname="System.ComponentModel.Design.DesigntimeLicenseContextSerializer" feature="System.ComponentModel.TypeConverter.EnableUnsafeBinaryFormatterInDesigntimeLicenseContextSerialization" featurevalue="false">
<method signature="System.Boolean get_EnableUnsafeBinaryFormatterInDesigntimeLicenseContextSerialization()" body="stub" value="false" />
</type>
</assembly>
</linker>
| <linker>
<assembly fullname="System.ComponentModel.TypeConverter">
<type fullname="System.ComponentModel.Design.DesigntimeLicenseContextSerializer" feature="System.ComponentModel.TypeConverter.EnableUnsafeBinaryFormatterInDesigntimeLicenseContextSerialization" featurevalue="false">
<method signature="System.Boolean get_EnableUnsafeBinaryFormatterInDesigntimeLicenseContextSerialization()" body="stub" value="false" />
</type>
</assembly>
</linker>
| -1 |
dotnet/runtime | 66,073 | Use ApiCompatTask in ApiCompat.proj | Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ViktorHofer | 2022-03-02T11:03:07Z | 2022-03-11T17:51:22Z | 3e2d483153adcab27033340fa40ad0bcdc3acc2a | 2575ce5f513c8f5cd37f935ba70b87cbd787c8df | Use ApiCompatTask in ApiCompat.proj. Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ./src/libraries/System.Private.Xml/tests/Xslt/TestFiles/TestData/XsltScenarios/EXslt/out/math-atan_2.xml | <out>
<test1>0.4636476090008061</test1>
<test2>-0.7328151017865065</test2>
<test3>NaN</test3>
<test4>1.5707963267948965</test4>
<test5>-1.5707963267948965</test5>
<test6>0</test6>
</out> | <out>
<test1>0.4636476090008061</test1>
<test2>-0.7328151017865065</test2>
<test3>NaN</test3>
<test4>1.5707963267948965</test4>
<test5>-1.5707963267948965</test5>
<test6>0</test6>
</out> | -1 |
dotnet/runtime | 66,073 | Use ApiCompatTask in ApiCompat.proj | Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ViktorHofer | 2022-03-02T11:03:07Z | 2022-03-11T17:51:22Z | 3e2d483153adcab27033340fa40ad0bcdc3acc2a | 2575ce5f513c8f5cd37f935ba70b87cbd787c8df | Use ApiCompatTask in ApiCompat.proj. Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ./src/libraries/System.ServiceModel.Syndication/tests/TestFeeds/AtomFeeds/id-empty-path.xml | <!--
Description: id with an empty path for schemes like http produces a warning
Expect: NonCanonicalURI{element:id,parent:feed}
-->
<feed xmlns="http://www.w3.org/2005/Atom">
<title>Example Feed</title>
<link href="http://contoso.com/"/>
<updated>2003-12-13T18:30:02Z</updated>
<author>
<name>Author Name</name>
</author>
<id>http://contoso.com</id>
<entry>
<title>Atom-Powered Robots Run Amok</title>
<link href="http://contoso.com/2003/12/13/atom03"/>
<id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id>
<updated>2003-12-13T18:30:02Z</updated>
<summary>Some text.</summary>
</entry>
</feed>
| <!--
Description: id with an empty path for schemes like http produces a warning
Expect: NonCanonicalURI{element:id,parent:feed}
-->
<feed xmlns="http://www.w3.org/2005/Atom">
<title>Example Feed</title>
<link href="http://contoso.com/"/>
<updated>2003-12-13T18:30:02Z</updated>
<author>
<name>Author Name</name>
</author>
<id>http://contoso.com</id>
<entry>
<title>Atom-Powered Robots Run Amok</title>
<link href="http://contoso.com/2003/12/13/atom03"/>
<id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id>
<updated>2003-12-13T18:30:02Z</updated>
<summary>Some text.</summary>
</entry>
</feed>
| -1 |
dotnet/runtime | 66,073 | Use ApiCompatTask in ApiCompat.proj | Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ViktorHofer | 2022-03-02T11:03:07Z | 2022-03-11T17:51:22Z | 3e2d483153adcab27033340fa40ad0bcdc3acc2a | 2575ce5f513c8f5cd37f935ba70b87cbd787c8df | Use ApiCompatTask in ApiCompat.proj. Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ./src/libraries/System.ServiceModel.Syndication/tests/TestFeeds/RssFeeds/webMaster_name_and_email.xml | <!--
Description: webMaster cannot include name and email in parentheses
Expect: InvalidContact{parent:channel,element:webMaster}
-->
<rss version="2.0">
<channel>
<title>Invalid webMaster</title>
<link>http://contoso.com/rss/2.0/</link>
<description>webMaster must include email address</description>
<webMaster>[email protected]</webMaster>
</channel>
</rss>
| <!--
Description: webMaster cannot include name and email in parentheses
Expect: InvalidContact{parent:channel,element:webMaster}
-->
<rss version="2.0">
<channel>
<title>Invalid webMaster</title>
<link>http://contoso.com/rss/2.0/</link>
<description>webMaster must include email address</description>
<webMaster>[email protected]</webMaster>
</channel>
</rss>
| -1 |
dotnet/runtime | 66,073 | Use ApiCompatTask in ApiCompat.proj | Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ViktorHofer | 2022-03-02T11:03:07Z | 2022-03-11T17:51:22Z | 3e2d483153adcab27033340fa40ad0bcdc3acc2a | 2575ce5f513c8f5cd37f935ba70b87cbd787c8df | Use ApiCompatTask in ApiCompat.proj. Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ./src/tests/Loader/classloader/generics/Variance/IL/Unbox001.reflect.xml | <linker>
<assembly fullname="Unbox001">
<type fullname="*" required="true" />
</assembly>
</linker>
| <linker>
<assembly fullname="Unbox001">
<type fullname="*" required="true" />
</assembly>
</linker>
| -1 |
dotnet/runtime | 66,073 | Use ApiCompatTask in ApiCompat.proj | Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ViktorHofer | 2022-03-02T11:03:07Z | 2022-03-11T17:51:22Z | 3e2d483153adcab27033340fa40ad0bcdc3acc2a | 2575ce5f513c8f5cd37f935ba70b87cbd787c8df | Use ApiCompatTask in ApiCompat.proj. Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ./src/libraries/System.Runtime.InteropServices/Directory.Build.props | <Project>
<Import Project="..\Directory.Build.props" />
<PropertyGroup>
<StrongNameKeyId>Microsoft</StrongNameKeyId>
<IncludePlatformAttributes>true</IncludePlatformAttributes>
</PropertyGroup>
</Project> | <Project>
<Import Project="..\Directory.Build.props" />
<PropertyGroup>
<StrongNameKeyId>Microsoft</StrongNameKeyId>
<IncludePlatformAttributes>true</IncludePlatformAttributes>
</PropertyGroup>
</Project> | -1 |
dotnet/runtime | 66,073 | Use ApiCompatTask in ApiCompat.proj | Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ViktorHofer | 2022-03-02T11:03:07Z | 2022-03-11T17:51:22Z | 3e2d483153adcab27033340fa40ad0bcdc3acc2a | 2575ce5f513c8f5cd37f935ba70b87cbd787c8df | Use ApiCompatTask in ApiCompat.proj. Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ./src/libraries/System.ServiceModel.Syndication/tests/TestFeeds/AtomFeeds/invalid-xml-base.xml | <!--
Description: xml base with an invalid iri
Expect: InvalidUriChar{element:xml:base}
-->
<feed xmlns="http://www.w3.org/2005/Atom" xml:base="invalid iri">
<title>Example Feed</title>
<link href="http://contoso.com/"/>
<updated>2003-12-13T18:30:02Z</updated>
<author>
<name>Author Name</name>
</author>
<id>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id>
<entry>
<title>Atom-Powered Robots Run Amok</title>
<link href="http://contoso.com/2003/12/13/atom03"/>
<id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id>
<updated>2003-12-13T18:30:02Z</updated>
<summary>Some text.</summary>
</entry>
</feed>
| <!--
Description: xml base with an invalid iri
Expect: InvalidUriChar{element:xml:base}
-->
<feed xmlns="http://www.w3.org/2005/Atom" xml:base="invalid iri">
<title>Example Feed</title>
<link href="http://contoso.com/"/>
<updated>2003-12-13T18:30:02Z</updated>
<author>
<name>Author Name</name>
</author>
<id>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id>
<entry>
<title>Atom-Powered Robots Run Amok</title>
<link href="http://contoso.com/2003/12/13/atom03"/>
<id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id>
<updated>2003-12-13T18:30:02Z</updated>
<summary>Some text.</summary>
</entry>
</feed>
| -1 |
dotnet/runtime | 66,073 | Use ApiCompatTask in ApiCompat.proj | Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ViktorHofer | 2022-03-02T11:03:07Z | 2022-03-11T17:51:22Z | 3e2d483153adcab27033340fa40ad0bcdc3acc2a | 2575ce5f513c8f5cd37f935ba70b87cbd787c8df | Use ApiCompatTask in ApiCompat.proj. Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ./src/libraries/System.Private.Xml/tests/Xslt/TestFiles/TestData/XsltApiV2/Exceptions.xml | <exceptions>
<!-- XPath Exceptions -->
<exception res="Xp_UnclosedString" message="This is an unclosed string."/>
<exception res="Xp_TokenExpected" message="A token was expected."/>
<exception res="Xp_NodeTestExpected" message="A NodeTest was expected at {0}."/>
<exception res="Xp_ExprExpected" message="'{0}' is an invalid expression."/>
<exception res="Xp_NumberExpected" message="A number was expected."/>
<exception res="Xp_BooleanExpected" message="A boolean value was expected."/>
<exception res="Xp_QueryExpected" message="A query was expected."/>
<exception res="Xp_UnknownMethod" message="'{0}()' is an unknown method."/>
<exception res="Xp_TestExpected" message="A test was expected."/>
<exception res="Xp_InvalidArgument" message="'{0}' function in {1} has an invalid argument. Maybe ')' is missing."/>
<exception res="Xp_InvalidArgumentType" message="The argument to function '{0}' cannot be converted to nodeset."/>
<exception res="Xp_InvalidNumArgs" message="Function '{0}' in {1} has invalid number of arguments."/>
<exception res="Xp_InvalidName" message="This is an invalid name."/>
<exception res="Xp_InvalidNodeType" message="This is an invalid NodeType."/>
<exception res="Xp_InvalidToken" message="{0} has an invalid token."/>
<exception res="Xp_FunctionExpected" message="A function was expected."/>
<exception res="Xp_NodeSetExpected" message="The expression passed to this method should result in a NodeSet."/>
<exception res="Xp_NoXPathActive" message="No XPath query is currently active. Call Select() first."/>
<exception res="Xp_NotSupported" message="The XPath query '{0}' is not supported."/>
<exception res="Xp_InvalidPattern" message="{0} is an invalid XSLT pattern."/>
<exception res="Xp_InvalidPatternString" message="{0} is an invalid XSLT pattern."/>
<exception res="Xp_InvalidKeyPattern" message="{0} is an invalid key pattern. It either has a variable reference or key function."/>
<exception res="Xp_BadQueryObject" message="This is an invalid object. Only objects returned from Compile() can be passed as input."/>
<exception res="Xp_InvalidDataRecordFilter" message="This is an invalid filter for a data record."/>
<exception res="Xp_NoSelectedSet" message="There is no result set from the selection."/>
<exception res="Xp_MovedFromSelection" message="The current node is not the previously selected node."/>
<exception res="Xp_ConstantExpected" message="The expression passed to this method should result in a constant."/>
<exception res="Xp_UndefinedXsltContext" message="XsltContext is needed for this query because of an unknown function."/>
<exception res="Xp_BadContext" message="The context passed to the SetContext method is invalid."/>
<exception res="Xp_BadQueryString" message="The xpath expression passed into compile is null or empty."/>
<exception res="Xp_NoContext" message="Namespace Manager or XsltContext needed. This query has prefix or variable or userdefined function."/>
<exception res="XPath_ScientificNotation" message="Scientific notation is not allowed."/>
<!-- XSLT Exceptions -->
<exception res="Xslt_CompileError" message="{0}({1},{2}) :\n"/>
<exception res="Xslt_WrongStylesheetElement" message="Stylesheet must start either with an 'xsl:stylesheet' or an 'xsl:transform' element, or with a literal result element that has an 'xsl:version' attribute, where prefix 'xsl' denotes the 'http://www.w3.org/1999/XSL/Transform' namespace."/>
<exception res="Xslt_UnsuppFunction" message="'{0}()' is an unsupported XSLT function."/>
<exception res="Xslt_NotFirstImport" message="'xsl:import' should be the first instruction of the stylesheet."/>
<exception res="Xslt_UnexpectedKeyword" message="'{0}' is an unexpected keyword."/>
<exception res="Xslt_NullNsAtTopLevel" message="Top level elements should have non-null namespace, {0}."/>
<exception res="Xslt_InvalidContents" message="The contents of '{0}' are invalid."/>
<exception res="Xslt_InvalidStylesheet" message="This is an invalid style sheet."/>
<exception res="Xslt_InvalidNamespace" message="This is an invalid namespace."/>
<exception res="Xslt_UnsuppKeyword" message="'{0}' is an unsupported keyword."/>
<exception res="Xslt_InvalidKeyword" message="'{0}' is an invalid keyword."/>
<exception res="Xslt_InvalidAttribute" message="'{0}' is an invalid attribute for '{1}' element."/>
<exception res="Xslt_MissingAttribute" message="Missing mandatory attribute '{0}'."/>
<exception res="Xslt_InvalidAttrValue" message="'{1}' is an invalid value for '{0}' attribute."/>
<exception res="Xslt_EmptyTagRequired" message="The tag '{0}' must be empty."/>
<exception res="Xslt_CircularInclude" message="There is a circular import or include of the file, {0}."/>
<exception res="Xslt_CantResolve" message="Cannot resolve '{0}'."/>
<exception res="Xslt_SingleRightAvt" message="There should be a single right curly brace outside AVT expression '{0}'."/>
<exception res="Xslt_OpenBracesAvt" message="The braces are not closed in AVT expression '{0}'."/>
<exception res="Xslt_OpenLiteralAvt" message="The literal in AVT expression is not correctly closed '{0}'."/>
<exception res="Xslt_InvalidXPath" message="'{0}' is an invalid XPath expression."/>
<exception res="Xslt_InvalidQName" message="'{0}' is an invalid QName."/>
<exception res="Xslt_InvalidPIName" message="'{0}' is an invalid name for a processing instruction."/>
<exception res="Xslt_VariableCntSel" message="The '{0}' variable has both a select attribute of '{1}' and non-empty contents."/>
<exception res="Xslt_NoStylesheetLoaded" message="No stylesheet was loaded."/>
<exception res="Xslt_InvalidOperation" message="Invalid operation."/>
<exception res="Xslt_Internal" message="An XSLT internal error has occurred."/>
<exception res="Xslt_DupTemplateName" message="'{0}' is a duplicate template name."/>
<exception res="Xslt_TemplateNoAttrib" message="An xsl:template requires at least a match or name attribute."/>
<exception res="Xslt_InvalidVariable" message="The variable or param '{0}' is either not defined or it is out of scope."/>
<exception res="Xslt_DupVarName" message="Variable or param '{0}' was duplicated within the same scope."/>
<exception res="Xslt_WrongNumberArgs" message="XSLT function '{0}' has the wrong number of arguments."/>
<exception res="Xslt_UnknownXsltFunction" message="'{0}()' is an unknown XSLT function."/>
<exception res="Xslt_InvalidFuncOperand" message="The function operand type is invalid."/>
<exception res="Xslt_NoNodeSetConversion" message="Cannot convert the operand to NodeSet."/>
<exception res="Xslt_NoNavigatorConversion" message="Cannot convert the operand to 'Result tree fragment'."/>
<exception res="Xslt_InvalidXPathContext" message="The XPath context is invalid."/>
<exception res="Xslt_NoAttributeSet" message="A reference to attribute set '{0}' cannot be resolved. An xsl:attribute-set of this name must be declared at the top-level of the stylesheet."/>
<exception res="Xslt_CircularAttributeSet" message="There was a circular reference in the '{0}' xsl:attribute-set declaration."/>
<exception res="Xslt_VarNeedsXmlEditor" message="The variables require editing capabilities from the XmlNavigator you provided (XmlEditor)."/>
<exception res="Xslt_InvalidCallTemplate" message="The named template '{0}' does not exist."/>
<exception res="Xslt_WrongNamespace" message="The wrong namespace was used for XSL. Use 'http://www.w3.org/1999/XSL/Transform'."/>
<exception res="Xslt_InvalidPrefix" message="Prefix '{0}' is not defined."/>
<exception res="Xslt_FunctionFailed" message="Function '{0}()' has failed."/>
<exception res="Xslt_InvalidFormat" message="Invalid format."/>
<exception res="Xslt_ScriptMixLang" message="Mixing scripting languages for the same namespace is not supported."/>
<exception res="Xslt_ScriptCompileErrors" message="Script compile errors:\n{0}"/>
<exception res="Xslt_ScriptInvalidPrefix" message="Cannot find the script or external object that implements prefix '{0}'."/>
<exception res="Xslt_ScriptDub" message="Namespace '{0}' has duplicate implementation."/>
<exception res="Xslt_ScriptEmpty" message="msxsl:script cannot be empty."/>
<exception res="Xslt_ScriptInvalidLang" message="The scripting language '{0}' is not supported."/>
<exception res="Xslt_DupDecimalFormat" message="Decimal format '{0}' has duplicate declaration."/>
<exception res="Xslt_NoDecimalFormat" message="Decimal format '{0}' is not declared in the stylesheet but is referenced. "/>
<exception res="Xslt_InfiniteLoop" message="Calling template '{0}' will result in an infinite loop."/>
<exception res="Xslt_CircularReference" message="There is a circular reference in definition of variable '{0}'."/>
<exception res="Xslt_UndefinedVarReference" message="Variable '{0}' is not defined in the stylesheet but is referenced."/>
<exception res="Xslt_InvalidExtensionNamespace" message="Extension namespace cannot be 'null' nor XSLT namespace URI."/>
<exception res="Xslt_InvalidParamNamespace" message="Parameter cannot belong to XSLT namespace."/>
<exception res="Xslt_InvalidModeAttribute" message="xsl:template cannot have 'mode' attribute without a 'match' attribute."/>
<exception res="Xslt_MultipleRoots" message="There are multiple root elements in the output xml."/>
<exception res="XmlIl_BadXmlState" message="An item of type '{0}' cannot be constructed within a node of type '{1}'." />
<exception res="Xslt_CannotLoadStylesheet" message="Cannot load the stylesheet object referenced by URI '{0}', because the provided XmlResolver returned an object of type '{1}'. One of Stream, XmlReader, and IXPathNavigable types was expected." />
<!-- XML Exceptions -->
<exception res="Xml_BadStartNameChar" message="The '{0}' character, hexadecimal value {1}, cannot begin a name."/>
<exception res="Xml_ResolveUrl" message="There was an error accessing {0}."/>
<exception res="Xml_NullResolver" message="Resolving of external URIs was prohibited. "/>
</exceptions> | <exceptions>
<!-- XPath Exceptions -->
<exception res="Xp_UnclosedString" message="This is an unclosed string."/>
<exception res="Xp_TokenExpected" message="A token was expected."/>
<exception res="Xp_NodeTestExpected" message="A NodeTest was expected at {0}."/>
<exception res="Xp_ExprExpected" message="'{0}' is an invalid expression."/>
<exception res="Xp_NumberExpected" message="A number was expected."/>
<exception res="Xp_BooleanExpected" message="A boolean value was expected."/>
<exception res="Xp_QueryExpected" message="A query was expected."/>
<exception res="Xp_UnknownMethod" message="'{0}()' is an unknown method."/>
<exception res="Xp_TestExpected" message="A test was expected."/>
<exception res="Xp_InvalidArgument" message="'{0}' function in {1} has an invalid argument. Maybe ')' is missing."/>
<exception res="Xp_InvalidArgumentType" message="The argument to function '{0}' cannot be converted to nodeset."/>
<exception res="Xp_InvalidNumArgs" message="Function '{0}' in {1} has invalid number of arguments."/>
<exception res="Xp_InvalidName" message="This is an invalid name."/>
<exception res="Xp_InvalidNodeType" message="This is an invalid NodeType."/>
<exception res="Xp_InvalidToken" message="{0} has an invalid token."/>
<exception res="Xp_FunctionExpected" message="A function was expected."/>
<exception res="Xp_NodeSetExpected" message="The expression passed to this method should result in a NodeSet."/>
<exception res="Xp_NoXPathActive" message="No XPath query is currently active. Call Select() first."/>
<exception res="Xp_NotSupported" message="The XPath query '{0}' is not supported."/>
<exception res="Xp_InvalidPattern" message="{0} is an invalid XSLT pattern."/>
<exception res="Xp_InvalidPatternString" message="{0} is an invalid XSLT pattern."/>
<exception res="Xp_InvalidKeyPattern" message="{0} is an invalid key pattern. It either has a variable reference or key function."/>
<exception res="Xp_BadQueryObject" message="This is an invalid object. Only objects returned from Compile() can be passed as input."/>
<exception res="Xp_InvalidDataRecordFilter" message="This is an invalid filter for a data record."/>
<exception res="Xp_NoSelectedSet" message="There is no result set from the selection."/>
<exception res="Xp_MovedFromSelection" message="The current node is not the previously selected node."/>
<exception res="Xp_ConstantExpected" message="The expression passed to this method should result in a constant."/>
<exception res="Xp_UndefinedXsltContext" message="XsltContext is needed for this query because of an unknown function."/>
<exception res="Xp_BadContext" message="The context passed to the SetContext method is invalid."/>
<exception res="Xp_BadQueryString" message="The xpath expression passed into compile is null or empty."/>
<exception res="Xp_NoContext" message="Namespace Manager or XsltContext needed. This query has prefix or variable or userdefined function."/>
<exception res="XPath_ScientificNotation" message="Scientific notation is not allowed."/>
<!-- XSLT Exceptions -->
<exception res="Xslt_CompileError" message="{0}({1},{2}) :\n"/>
<exception res="Xslt_WrongStylesheetElement" message="Stylesheet must start either with an 'xsl:stylesheet' or an 'xsl:transform' element, or with a literal result element that has an 'xsl:version' attribute, where prefix 'xsl' denotes the 'http://www.w3.org/1999/XSL/Transform' namespace."/>
<exception res="Xslt_UnsuppFunction" message="'{0}()' is an unsupported XSLT function."/>
<exception res="Xslt_NotFirstImport" message="'xsl:import' should be the first instruction of the stylesheet."/>
<exception res="Xslt_UnexpectedKeyword" message="'{0}' is an unexpected keyword."/>
<exception res="Xslt_NullNsAtTopLevel" message="Top level elements should have non-null namespace, {0}."/>
<exception res="Xslt_InvalidContents" message="The contents of '{0}' are invalid."/>
<exception res="Xslt_InvalidStylesheet" message="This is an invalid style sheet."/>
<exception res="Xslt_InvalidNamespace" message="This is an invalid namespace."/>
<exception res="Xslt_UnsuppKeyword" message="'{0}' is an unsupported keyword."/>
<exception res="Xslt_InvalidKeyword" message="'{0}' is an invalid keyword."/>
<exception res="Xslt_InvalidAttribute" message="'{0}' is an invalid attribute for '{1}' element."/>
<exception res="Xslt_MissingAttribute" message="Missing mandatory attribute '{0}'."/>
<exception res="Xslt_InvalidAttrValue" message="'{1}' is an invalid value for '{0}' attribute."/>
<exception res="Xslt_EmptyTagRequired" message="The tag '{0}' must be empty."/>
<exception res="Xslt_CircularInclude" message="There is a circular import or include of the file, {0}."/>
<exception res="Xslt_CantResolve" message="Cannot resolve '{0}'."/>
<exception res="Xslt_SingleRightAvt" message="There should be a single right curly brace outside AVT expression '{0}'."/>
<exception res="Xslt_OpenBracesAvt" message="The braces are not closed in AVT expression '{0}'."/>
<exception res="Xslt_OpenLiteralAvt" message="The literal in AVT expression is not correctly closed '{0}'."/>
<exception res="Xslt_InvalidXPath" message="'{0}' is an invalid XPath expression."/>
<exception res="Xslt_InvalidQName" message="'{0}' is an invalid QName."/>
<exception res="Xslt_InvalidPIName" message="'{0}' is an invalid name for a processing instruction."/>
<exception res="Xslt_VariableCntSel" message="The '{0}' variable has both a select attribute of '{1}' and non-empty contents."/>
<exception res="Xslt_NoStylesheetLoaded" message="No stylesheet was loaded."/>
<exception res="Xslt_InvalidOperation" message="Invalid operation."/>
<exception res="Xslt_Internal" message="An XSLT internal error has occurred."/>
<exception res="Xslt_DupTemplateName" message="'{0}' is a duplicate template name."/>
<exception res="Xslt_TemplateNoAttrib" message="An xsl:template requires at least a match or name attribute."/>
<exception res="Xslt_InvalidVariable" message="The variable or param '{0}' is either not defined or it is out of scope."/>
<exception res="Xslt_DupVarName" message="Variable or param '{0}' was duplicated within the same scope."/>
<exception res="Xslt_WrongNumberArgs" message="XSLT function '{0}' has the wrong number of arguments."/>
<exception res="Xslt_UnknownXsltFunction" message="'{0}()' is an unknown XSLT function."/>
<exception res="Xslt_InvalidFuncOperand" message="The function operand type is invalid."/>
<exception res="Xslt_NoNodeSetConversion" message="Cannot convert the operand to NodeSet."/>
<exception res="Xslt_NoNavigatorConversion" message="Cannot convert the operand to 'Result tree fragment'."/>
<exception res="Xslt_InvalidXPathContext" message="The XPath context is invalid."/>
<exception res="Xslt_NoAttributeSet" message="A reference to attribute set '{0}' cannot be resolved. An xsl:attribute-set of this name must be declared at the top-level of the stylesheet."/>
<exception res="Xslt_CircularAttributeSet" message="There was a circular reference in the '{0}' xsl:attribute-set declaration."/>
<exception res="Xslt_VarNeedsXmlEditor" message="The variables require editing capabilities from the XmlNavigator you provided (XmlEditor)."/>
<exception res="Xslt_InvalidCallTemplate" message="The named template '{0}' does not exist."/>
<exception res="Xslt_WrongNamespace" message="The wrong namespace was used for XSL. Use 'http://www.w3.org/1999/XSL/Transform'."/>
<exception res="Xslt_InvalidPrefix" message="Prefix '{0}' is not defined."/>
<exception res="Xslt_FunctionFailed" message="Function '{0}()' has failed."/>
<exception res="Xslt_InvalidFormat" message="Invalid format."/>
<exception res="Xslt_ScriptMixLang" message="Mixing scripting languages for the same namespace is not supported."/>
<exception res="Xslt_ScriptCompileErrors" message="Script compile errors:\n{0}"/>
<exception res="Xslt_ScriptInvalidPrefix" message="Cannot find the script or external object that implements prefix '{0}'."/>
<exception res="Xslt_ScriptDub" message="Namespace '{0}' has duplicate implementation."/>
<exception res="Xslt_ScriptEmpty" message="msxsl:script cannot be empty."/>
<exception res="Xslt_ScriptInvalidLang" message="The scripting language '{0}' is not supported."/>
<exception res="Xslt_DupDecimalFormat" message="Decimal format '{0}' has duplicate declaration."/>
<exception res="Xslt_NoDecimalFormat" message="Decimal format '{0}' is not declared in the stylesheet but is referenced. "/>
<exception res="Xslt_InfiniteLoop" message="Calling template '{0}' will result in an infinite loop."/>
<exception res="Xslt_CircularReference" message="There is a circular reference in definition of variable '{0}'."/>
<exception res="Xslt_UndefinedVarReference" message="Variable '{0}' is not defined in the stylesheet but is referenced."/>
<exception res="Xslt_InvalidExtensionNamespace" message="Extension namespace cannot be 'null' nor XSLT namespace URI."/>
<exception res="Xslt_InvalidParamNamespace" message="Parameter cannot belong to XSLT namespace."/>
<exception res="Xslt_InvalidModeAttribute" message="xsl:template cannot have 'mode' attribute without a 'match' attribute."/>
<exception res="Xslt_MultipleRoots" message="There are multiple root elements in the output xml."/>
<exception res="XmlIl_BadXmlState" message="An item of type '{0}' cannot be constructed within a node of type '{1}'." />
<exception res="Xslt_CannotLoadStylesheet" message="Cannot load the stylesheet object referenced by URI '{0}', because the provided XmlResolver returned an object of type '{1}'. One of Stream, XmlReader, and IXPathNavigable types was expected." />
<!-- XML Exceptions -->
<exception res="Xml_BadStartNameChar" message="The '{0}' character, hexadecimal value {1}, cannot begin a name."/>
<exception res="Xml_ResolveUrl" message="There was an error accessing {0}."/>
<exception res="Xml_NullResolver" message="Resolving of external URIs was prohibited. "/>
</exceptions> | -1 |
dotnet/runtime | 66,073 | Use ApiCompatTask in ApiCompat.proj | Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ViktorHofer | 2022-03-02T11:03:07Z | 2022-03-11T17:51:22Z | 3e2d483153adcab27033340fa40ad0bcdc3acc2a | 2575ce5f513c8f5cd37f935ba70b87cbd787c8df | Use ApiCompatTask in ApiCompat.proj. Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ./src/libraries/System.Private.CoreLib/src/ILLink/ILLink.LinkAttributes.Shared.xml | <linker>
<!-- The following attributes are only necessary when debugging is supported -->
<assembly fullname="System.Private.CoreLib" feature="System.Diagnostics.Debugger.IsSupported" featurevalue="false">
<type fullname="System.Diagnostics.DebuggableAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Diagnostics.DebuggerBrowsableAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Diagnostics.DebuggerDisplayAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Diagnostics.DebuggerHiddenAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Diagnostics.DebuggerNonUserCodeAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Diagnostics.DebuggerStepperBoundaryAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Diagnostics.DebuggerStepThroughAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Diagnostics.DebuggerTypeProxyAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Diagnostics.DebuggerVisualizerAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
</assembly>
<assembly fullname="System.Private.CoreLib" feature="System.Reflection.Metadata.MetadataUpdater.IsSupported" featurevalue="false">
<type fullname="System.Reflection.Metadata.MetadataUpdateHandlerAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
</assembly>
<assembly fullname="System.Private.CoreLib" feature="System.Diagnostics.Tracing.EventSource.IsSupported" featurevalue="false">
<type fullname="System.Diagnostics.Tracing.EventSourceAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Diagnostics.Tracing.EventAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Diagnostics.Tracing.EventDataAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Diagnostics.Tracing.EventFieldAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Diagnostics.Tracing.EventIgnoreAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Diagnostics.Tracing.NonEventAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
</assembly>
<!--
The following attributes are necessary when NullabilityInfoContext is supported.
Note these attributes are allowed to be in any assembly.
-->
<assembly fullname="*" feature="System.Reflection.NullabilityInfoContext.IsSupported" featurevalue="false">
<type fullname="System.Diagnostics.CodeAnalysis.AllowNullAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Diagnostics.CodeAnalysis.DisallowNullAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Diagnostics.CodeAnalysis.MaybeNullAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Diagnostics.CodeAnalysis.MaybeNullWhenAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Diagnostics.CodeAnalysis.NotNullAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Runtime.CompilerServices.NullableAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Runtime.CompilerServices.NullableContextAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Runtime.CompilerServices.NullablePublicOnlyAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
</assembly>
<!-- The following attributes are only necessary when COM is supported -->
<assembly fullname="System.Private.CoreLib" feature="System.Runtime.InteropServices.BuiltInComInterop.IsSupported" featurevalue="false">
<type fullname="System.Runtime.InteropServices.ClassInterfaceAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Runtime.InteropServices.ComDefaultInterfaceAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Runtime.InteropServices.ComEventInterfaceAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Runtime.InteropServices.ComSourceInterfacesAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Runtime.InteropServices.ComVisibleAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Runtime.InteropServices.DispIdAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Runtime.InteropServices.InterfaceTypeAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Runtime.InteropServices.ProgIdAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
</assembly>
<!--
Attributes listed below here should be behind the 'System.AggressiveAttributeTrimming' feature switch, which
is only enabled by default on app models that need as much size savings as possible.
-->
<assembly fullname="System.Private.CoreLib" feature="System.AggressiveAttributeTrimming" featurevalue="true">
<!-- System -->
<type fullname="System.CLSCompliantAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.ObsoleteAttribute">
<!--
Note that removing this attribute can change runtime behavior. For example,
System.Xml.Serialization will behave differently if a ctor is Obsolete.
This is low enough risk on when 'System.AggressiveAttributeTrimming' is enabled to justify
removing the attribute for size savings. The app developer can override this setting
to keep all ObsoleteAttributes.
-->
<attribute internal="RemoveAttributeInstances" />
</type>
<!-- System.Diagnostics.CodeAnalysis -->
<type fullname="System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<!-- System.Reflection -->
<type fullname="System.Reflection.AssemblyCompanyAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Reflection.AssemblyConfigurationAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Reflection.AssemblyCopyrightAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Reflection.AssemblyDefaultAliasAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Reflection.AssemblyDescriptionAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Reflection.AssemblyProductAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Reflection.AssemblyTitleAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<!-- System.Runtime.CompilerServices -->
<type fullname="System.Runtime.CompilerServices.AsyncMethodBuilderAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Runtime.CompilerServices.CallerArgumentExpressionAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Runtime.CompilerServices.CallerMemberNameAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Runtime.CompilerServices.CallerFilePathAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Runtime.CompilerServices.CallerLineNumberAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Runtime.CompilerServices.CallerMemberNameAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Runtime.CompilerServices.CompilerGlobalScopeAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Runtime.CompilerServices.IsReadOnlyAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Runtime.CompilerServices.EnumeratorCancellationAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Runtime.CompilerServices.ExtensionAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Runtime.CompilerServices.SkipLocalsInitAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Runtime.CompilerServices.TupleElementNamesAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<!-- System.Runtime.Versioning -->
<type fullname="System.Runtime.Versioning.SupportedOSPlatformAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Runtime.Versioning.UnsupportedOSPlatformAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Runtime.Versioning.SupportedOSPlatformGuardAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Runtime.Versioning.UnsupportedOSPlatformGuardAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Runtime.Versioning.TargetPlatformAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<!-- System.ComponentModel -->
<type fullname="System.ComponentModel.EditorBrowsableAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
</assembly>
<!-- Attributes that are allowed to be in any assembly -->
<assembly fullname="*" feature="System.AggressiveAttributeTrimming" featurevalue="true">
<!-- Attributes that tooling allows to be in any assembly to support earlier TFMs -->
<type fullname="System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Diagnostics.CodeAnalysis.RequiresAssemblyFilesAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Diagnostics.CodeAnalysis.RequiresDynamicCodeAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Diagnostics.CodeAnalysis.SuppressMessageAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Diagnostics.CodeAnalysis.NotNullWhenAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Diagnostics.CodeAnalysis.DoesNotReturnAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Diagnostics.CodeAnalysis.DoesNotReturnIfAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Diagnostics.CodeAnalysis.MemberNotNullAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Diagnostics.CodeAnalysis.MemberNotNullWhenAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Runtime.InteropServices.LibraryImportAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.CodeDom.Compiler.GeneratedCodeAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<!-- The following attributes are generated by the compiler, so they could be in any assembly -->
<!-- System.Runtime.CompilerServices -->
<type fullname="System.Runtime.CompilerServices.IsUnmanagedAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Runtime.CompilerServices.NativeIntegerAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<!-- Microsoft.CodeAnalysis -->
<type fullname="Microsoft.CodeAnalysis.EmbeddedAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<!-- Metadata attributes present in most core SDKs assemblies -->
<type fullname="System.Reflection.AssemblyMetadataAttribute">
<attribute internal="RemoveAttributeInstances">
<argument type="System.Object">
<argument>Serviceable</argument>
</argument>
</attribute>
</type>
<type fullname="System.Reflection.AssemblyMetadataAttribute">
<attribute internal="RemoveAttributeInstances">
<argument type="System.Object">
<argument>PreferInbox</argument>
</argument>
</attribute>
</type>
<type fullname="System.Reflection.AssemblyMetadataAttribute">
<attribute internal="RemoveAttributeInstances">
<argument type="System.Object">
<argument>.NETFrameworkAssembly</argument>
</argument>
</attribute>
</type>
<type fullname="System.Reflection.AssemblyMetadataAttribute">
<attribute internal="RemoveAttributeInstances">
<argument type="System.Object">
<argument>RepositoryUrl</argument>
</argument>
</attribute>
</type>
<type fullname="System.Reflection.AssemblyMetadataAttribute">
<attribute internal="RemoveAttributeInstances">
<argument type="System.Object">
<argument>SourceCommitUrl</argument>
</argument>
</attribute>
</type>
<type fullname="System.Reflection.AssemblyMetadataAttribute">
<attribute internal="RemoveAttributeInstances">
<argument type="System.Object">
<argument>CommitHash</argument>
</argument>
</attribute>
</type>
<type fullname="System.Reflection.AssemblyMetadataAttribute">
<attribute internal="RemoveAttributeInstances">
<argument type="System.Object">
<argument>IsTrimmable</argument>
</argument>
</attribute>
</type>
</assembly>
</linker>
| <linker>
<!-- The following attributes are only necessary when debugging is supported -->
<assembly fullname="System.Private.CoreLib" feature="System.Diagnostics.Debugger.IsSupported" featurevalue="false">
<type fullname="System.Diagnostics.DebuggableAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Diagnostics.DebuggerBrowsableAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Diagnostics.DebuggerDisplayAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Diagnostics.DebuggerHiddenAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Diagnostics.DebuggerNonUserCodeAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Diagnostics.DebuggerStepperBoundaryAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Diagnostics.DebuggerStepThroughAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Diagnostics.DebuggerTypeProxyAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Diagnostics.DebuggerVisualizerAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
</assembly>
<assembly fullname="System.Private.CoreLib" feature="System.Reflection.Metadata.MetadataUpdater.IsSupported" featurevalue="false">
<type fullname="System.Reflection.Metadata.MetadataUpdateHandlerAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
</assembly>
<assembly fullname="System.Private.CoreLib" feature="System.Diagnostics.Tracing.EventSource.IsSupported" featurevalue="false">
<type fullname="System.Diagnostics.Tracing.EventSourceAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Diagnostics.Tracing.EventAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Diagnostics.Tracing.EventDataAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Diagnostics.Tracing.EventFieldAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Diagnostics.Tracing.EventIgnoreAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Diagnostics.Tracing.NonEventAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
</assembly>
<!--
The following attributes are necessary when NullabilityInfoContext is supported.
Note these attributes are allowed to be in any assembly.
-->
<assembly fullname="*" feature="System.Reflection.NullabilityInfoContext.IsSupported" featurevalue="false">
<type fullname="System.Diagnostics.CodeAnalysis.AllowNullAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Diagnostics.CodeAnalysis.DisallowNullAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Diagnostics.CodeAnalysis.MaybeNullAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Diagnostics.CodeAnalysis.MaybeNullWhenAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Diagnostics.CodeAnalysis.NotNullAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Runtime.CompilerServices.NullableAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Runtime.CompilerServices.NullableContextAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Runtime.CompilerServices.NullablePublicOnlyAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
</assembly>
<!-- The following attributes are only necessary when COM is supported -->
<assembly fullname="System.Private.CoreLib" feature="System.Runtime.InteropServices.BuiltInComInterop.IsSupported" featurevalue="false">
<type fullname="System.Runtime.InteropServices.ClassInterfaceAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Runtime.InteropServices.ComDefaultInterfaceAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Runtime.InteropServices.ComEventInterfaceAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Runtime.InteropServices.ComSourceInterfacesAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Runtime.InteropServices.ComVisibleAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Runtime.InteropServices.DispIdAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Runtime.InteropServices.InterfaceTypeAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Runtime.InteropServices.ProgIdAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
</assembly>
<!--
Attributes listed below here should be behind the 'System.AggressiveAttributeTrimming' feature switch, which
is only enabled by default on app models that need as much size savings as possible.
-->
<assembly fullname="System.Private.CoreLib" feature="System.AggressiveAttributeTrimming" featurevalue="true">
<!-- System -->
<type fullname="System.CLSCompliantAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.ObsoleteAttribute">
<!--
Note that removing this attribute can change runtime behavior. For example,
System.Xml.Serialization will behave differently if a ctor is Obsolete.
This is low enough risk on when 'System.AggressiveAttributeTrimming' is enabled to justify
removing the attribute for size savings. The app developer can override this setting
to keep all ObsoleteAttributes.
-->
<attribute internal="RemoveAttributeInstances" />
</type>
<!-- System.Diagnostics.CodeAnalysis -->
<type fullname="System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<!-- System.Reflection -->
<type fullname="System.Reflection.AssemblyCompanyAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Reflection.AssemblyConfigurationAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Reflection.AssemblyCopyrightAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Reflection.AssemblyDefaultAliasAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Reflection.AssemblyDescriptionAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Reflection.AssemblyProductAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Reflection.AssemblyTitleAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<!-- System.Runtime.CompilerServices -->
<type fullname="System.Runtime.CompilerServices.AsyncMethodBuilderAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Runtime.CompilerServices.CallerArgumentExpressionAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Runtime.CompilerServices.CallerMemberNameAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Runtime.CompilerServices.CallerFilePathAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Runtime.CompilerServices.CallerLineNumberAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Runtime.CompilerServices.CallerMemberNameAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Runtime.CompilerServices.CompilerGlobalScopeAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Runtime.CompilerServices.IsReadOnlyAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Runtime.CompilerServices.EnumeratorCancellationAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Runtime.CompilerServices.ExtensionAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Runtime.CompilerServices.SkipLocalsInitAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Runtime.CompilerServices.TupleElementNamesAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<!-- System.Runtime.Versioning -->
<type fullname="System.Runtime.Versioning.SupportedOSPlatformAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Runtime.Versioning.UnsupportedOSPlatformAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Runtime.Versioning.SupportedOSPlatformGuardAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Runtime.Versioning.UnsupportedOSPlatformGuardAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Runtime.Versioning.TargetPlatformAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<!-- System.ComponentModel -->
<type fullname="System.ComponentModel.EditorBrowsableAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
</assembly>
<!-- Attributes that are allowed to be in any assembly -->
<assembly fullname="*" feature="System.AggressiveAttributeTrimming" featurevalue="true">
<!-- Attributes that tooling allows to be in any assembly to support earlier TFMs -->
<type fullname="System.Diagnostics.CodeAnalysis.DynamicallyAccessedMembersAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Diagnostics.CodeAnalysis.RequiresAssemblyFilesAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Diagnostics.CodeAnalysis.RequiresDynamicCodeAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Diagnostics.CodeAnalysis.SuppressMessageAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Diagnostics.CodeAnalysis.NotNullWhenAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Diagnostics.CodeAnalysis.DoesNotReturnAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Diagnostics.CodeAnalysis.DoesNotReturnIfAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Diagnostics.CodeAnalysis.MemberNotNullAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Diagnostics.CodeAnalysis.MemberNotNullWhenAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Runtime.InteropServices.LibraryImportAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.CodeDom.Compiler.GeneratedCodeAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<!-- The following attributes are generated by the compiler, so they could be in any assembly -->
<!-- System.Runtime.CompilerServices -->
<type fullname="System.Runtime.CompilerServices.IsUnmanagedAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<type fullname="System.Runtime.CompilerServices.NativeIntegerAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<!-- Microsoft.CodeAnalysis -->
<type fullname="Microsoft.CodeAnalysis.EmbeddedAttribute">
<attribute internal="RemoveAttributeInstances" />
</type>
<!-- Metadata attributes present in most core SDKs assemblies -->
<type fullname="System.Reflection.AssemblyMetadataAttribute">
<attribute internal="RemoveAttributeInstances">
<argument type="System.Object">
<argument>Serviceable</argument>
</argument>
</attribute>
</type>
<type fullname="System.Reflection.AssemblyMetadataAttribute">
<attribute internal="RemoveAttributeInstances">
<argument type="System.Object">
<argument>PreferInbox</argument>
</argument>
</attribute>
</type>
<type fullname="System.Reflection.AssemblyMetadataAttribute">
<attribute internal="RemoveAttributeInstances">
<argument type="System.Object">
<argument>.NETFrameworkAssembly</argument>
</argument>
</attribute>
</type>
<type fullname="System.Reflection.AssemblyMetadataAttribute">
<attribute internal="RemoveAttributeInstances">
<argument type="System.Object">
<argument>RepositoryUrl</argument>
</argument>
</attribute>
</type>
<type fullname="System.Reflection.AssemblyMetadataAttribute">
<attribute internal="RemoveAttributeInstances">
<argument type="System.Object">
<argument>SourceCommitUrl</argument>
</argument>
</attribute>
</type>
<type fullname="System.Reflection.AssemblyMetadataAttribute">
<attribute internal="RemoveAttributeInstances">
<argument type="System.Object">
<argument>CommitHash</argument>
</argument>
</attribute>
</type>
<type fullname="System.Reflection.AssemblyMetadataAttribute">
<attribute internal="RemoveAttributeInstances">
<argument type="System.Object">
<argument>IsTrimmable</argument>
</argument>
</attribute>
</type>
</assembly>
</linker>
| -1 |
dotnet/runtime | 66,073 | Use ApiCompatTask in ApiCompat.proj | Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ViktorHofer | 2022-03-02T11:03:07Z | 2022-03-11T17:51:22Z | 3e2d483153adcab27033340fa40ad0bcdc3acc2a | 2575ce5f513c8f5cd37f935ba70b87cbd787c8df | Use ApiCompatTask in ApiCompat.proj. Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ./src/coreclr/nativeaot/BuildIntegration/BuildIntegration.proj | <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="Build">
<Import Project="../Directory.Build.props" />
<PropertyGroup>
<OutputPath>$(RuntimeBinDir)/build/</OutputPath>
</PropertyGroup>
<ItemGroup>
<Content Include="*.*" Exclude="$(MSBuildProjectFile)" />
</ItemGroup>
<Target Name="Build">
<Copy SourceFiles="@(Content)" DestinationFolder="$(OutputPath)" />
</Target>
<Target Name="Restore" />
</Project>
| <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="Build">
<Import Project="../Directory.Build.props" />
<PropertyGroup>
<OutputPath>$(RuntimeBinDir)/build/</OutputPath>
</PropertyGroup>
<ItemGroup>
<Content Include="*.*" Exclude="$(MSBuildProjectFile)" />
</ItemGroup>
<Target Name="Build">
<Copy SourceFiles="@(Content)" DestinationFolder="$(OutputPath)" />
</Target>
<Target Name="Restore" />
</Project>
| -1 |
dotnet/runtime | 66,073 | Use ApiCompatTask in ApiCompat.proj | Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ViktorHofer | 2022-03-02T11:03:07Z | 2022-03-11T17:51:22Z | 3e2d483153adcab27033340fa40ad0bcdc3acc2a | 2575ce5f513c8f5cd37f935ba70b87cbd787c8df | Use ApiCompatTask in ApiCompat.proj. Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ./src/libraries/oob.proj | <Project Sdk="Microsoft.Build.NoTargets">
<PropertyGroup>
<TargetFramework>$(NetCoreAppCurrent)-$(TargetOS)</TargetFramework>
<!-- By default, build the NetCoreAppCurrent vertical only. -->
<BuildTargetFramework Condition="'$(BuildAllConfigurations)' != 'true'">$(NetCoreAppCurrent)</BuildTargetFramework>
</PropertyGroup>
<ItemGroup Condition="'$(BuildTargetFramework)' == '$(NetCoreAppCurrent)' or '$(BuildTargetFramework)' == ''">
<ProjectReference Include="sfx-src.proj" OutputItemType="SharedFrameworkAssembly" />
<ProjectReference Include="oob-src.proj" OutputItemType="OOBAssembly" />
<ProjectReference Include="shims.proj" OutputItemType="SharedFrameworkAssembly" />
<ProjectReference Include="apicompat\ApiCompat.proj"
Condition="'$(DotNetBuildFromSource)' != 'true' and '$(RunApiCompat)' != 'false'" />
</ItemGroup>
<ItemGroup Condition="'$(BuildTargetFramework)' != '$(NetCoreAppCurrent)' or '$(BuildTargetFramework)' == ''">
<ProjectReference Include="oob-all.proj" SkipGetTargetFrameworkProperties="true" />
</ItemGroup>
<!-- Support building reference projects only. -->
<ItemGroup Condition="'$(RefOnly)' == 'true'">
<ProjectReference Remove="@(ProjectReference)" />
<ProjectReference Include="sfx-ref.proj" OutputItemType="SharedFrameworkAssembly" />
<ProjectReference Include="oob-ref.proj" />
<ProjectReference Include="shims.proj" OutputItemType="SharedFrameworkAssembly" />
</ItemGroup>
<ImportGroup Condition="'$(BuildTargetFramework)' == '$(NetCoreAppCurrent)' or '$(BuildTargetFramework)' == ''">
<!-- Re-generate the targeting pack's framework list to include shims. -->
<Import Project="frameworklist.targets" />
<!-- Import the illink file which contains some of the logic required to illink the out-of-band assemblies. -->
<Import Project="$(RepositoryEngineeringDir)illink.targets" />
</ImportGroup>
<Target Name="GetTrimOOBAssembliesInputs"
DependsOnTargets="ResolveProjectReferences">
<PropertyGroup>
<OOBAssembliesTrimmedArtifactsPath>$([MSBuild]::NormalizeDirectory('$(ILLinkTrimAssemblyArtifactsRootDir)', 'trimmed-oobs'))</OOBAssembliesTrimmedArtifactsPath>
<OOBAssembliesMarkerFile>$(IntermediateOutputPath)linker-$(TargetArchitecture)-marker.txt</OOBAssembliesMarkerFile>
</PropertyGroup>
<ItemGroup>
<!-- Include suppression XML files bin-placed in earlier per-library linker run. -->
<OOBLibrarySuppressionsXml Include="$(ILLinkTrimAssemblyOOBSuppressionsXmlsDir)*.xml" />
<!-- The following is the list of all the OOBs we will ignore for now -->
<OOBAssemblyToIgnore Include="System.CodeDom;
System.ComponentModel.Composition;
System.ComponentModel.Composition.Registration;
System.Composition.AttributedModel;
System.Composition.Convention;
System.Composition.Hosting;
System.Composition.Runtime;
System.Composition.TypedParts;
System.Configuration.ConfigurationManager;
System.Speech;
Microsoft.Extensions.DependencyInjection.Specification.Tests" />
<!-- Move items to FileName so that we can subtract them. -->
<OOBAssemblyWithFilename Include="@(OOBAssembly->Metadata('Filename'))"
OriginalIdentity="%(Identity)" />
<OOBAssemblyToTrimWithFilename Include="@(OOBAssemblyWithFilename)"
Exclude="@(OOBAssemblyToIgnore)" />
<OOBAssemblyToIgnoreWithFilename Include="@(OOBAssemblyWithFilename)"
Exclude="@(OOBAssemblyToTrimWithFilename)" />
<OOBAssemblyToTrim Include="@(OOBAssemblyToTrimWithFilename->Metadata('OriginalIdentity'))" />
<OOBAssemblyReference Include="@(OOBAssemblyToIgnoreWithFilename->Metadata('OriginalIdentity'));
@(SharedFrameworkAssembly)" />
</ItemGroup>
</Target>
<Target Name="TrimOOBAssemblies"
AfterTargets="Build"
Condition="'$(RefOnly)' != 'true' and '@(OOBAssembly)' != ''"
DependsOnTargets="GetTrimOOBAssembliesInputs;PrepareForAssembliesTrim"
Inputs="$(ILLinkTasksAssembly);@(OOBAssemblyToTrim);@(OOBAssemblyReference);@(OOBLibrarySuppressionsXml)"
Outputs="$(OOBAssembliesMarkerFile)">
<Message Text="$(MSBuildProjectName) -> Trimming $(PackageRID) out-of-band assemblies with ILLinker..." Importance="high" />
<PropertyGroup>
<OOBILLinkArgs>$(ILLinkArgs)</OOBILLinkArgs>
<OOBILLinkArgs Condition="'@(OOBLibrarySuppressionsXml)' != ''" >$(OOBILLinkArgs) --link-attributes "@(OOBLibrarySuppressionsXml->'%(FullPath)', '" --link-attributes "')"</OOBILLinkArgs>
</PropertyGroup>
<ILLink AssemblyPaths=""
RootAssemblyNames="@(OOBAssemblyToTrim)"
ReferenceAssemblyPaths="@(OOBAssemblyReference)"
OutputDirectory="$(OOBAssembliesTrimmedArtifactsPath)"
ExtraArgs="$(OOBILLinkArgs)"
ToolExe="$(_DotNetHostFileName)"
ToolPath="$(_DotNetHostDirectory)" />
<!-- Create a marker file which serves as the target's output to enable incremental builds. -->
<MakeDir Directories="$([System.IO.Path]::GetDirectoryName('$(OOBAssembliesMarkerFile)'))" />
<Touch Files="$(OOBAssembliesMarkerFile)"
AlwaysCreate="true" />
</Target>
<Target Name="SetAzureDevOpsVariableForBuiltPackages"
Condition="'$(ContinuousIntegrationBuild)' == 'true'"
AfterTargets="Build;Pack">
<Message Condition="Exists('$(ArtifactsDir)packages')" Importance="High" Text="##vso[task.setvariable variable=_librariesBuildProducedPackages]true" />
</Target>
</Project>
| <Project Sdk="Microsoft.Build.NoTargets">
<PropertyGroup>
<TargetFramework>$(NetCoreAppCurrent)-$(TargetOS)</TargetFramework>
<!-- By default, build the NetCoreAppCurrent vertical only. -->
<BuildTargetFramework Condition="'$(BuildAllConfigurations)' != 'true'">$(NetCoreAppCurrent)</BuildTargetFramework>
</PropertyGroup>
<ItemGroup Condition="'$(BuildTargetFramework)' == '$(NetCoreAppCurrent)' or '$(BuildTargetFramework)' == ''">
<ProjectReference Include="sfx-src.proj" OutputItemType="SharedFrameworkAssembly" />
<ProjectReference Include="oob-src.proj" OutputItemType="OOBAssembly" />
<ProjectReference Include="shims.proj" OutputItemType="SharedFrameworkAssembly" />
<ProjectReference Include="apicompat\ApiCompat.proj"
Condition="'$(DotNetBuildFromSource)' != 'true' and '$(RunApiCompat)' != 'false'" />
</ItemGroup>
<ItemGroup Condition="'$(BuildTargetFramework)' != '$(NetCoreAppCurrent)' or '$(BuildTargetFramework)' == ''">
<ProjectReference Include="oob-all.proj" SkipGetTargetFrameworkProperties="true" />
</ItemGroup>
<!-- Support building reference projects only. -->
<ItemGroup Condition="'$(RefOnly)' == 'true'">
<ProjectReference Remove="@(ProjectReference)" />
<ProjectReference Include="sfx-ref.proj" OutputItemType="SharedFrameworkAssembly" />
<ProjectReference Include="oob-ref.proj" />
<ProjectReference Include="shims.proj" OutputItemType="SharedFrameworkAssembly" />
</ItemGroup>
<ImportGroup Condition="'$(BuildTargetFramework)' == '$(NetCoreAppCurrent)' or '$(BuildTargetFramework)' == ''">
<!-- Re-generate the targeting pack's framework list to include shims. -->
<Import Project="frameworklist.targets" />
<!-- Import the illink file which contains some of the logic required to illink the out-of-band assemblies. -->
<Import Project="$(RepositoryEngineeringDir)illink.targets" />
</ImportGroup>
<Target Name="GetTrimOOBAssembliesInputs"
DependsOnTargets="ResolveProjectReferences">
<PropertyGroup>
<OOBAssembliesTrimmedArtifactsPath>$([MSBuild]::NormalizeDirectory('$(ILLinkTrimAssemblyArtifactsRootDir)', 'trimmed-oobs'))</OOBAssembliesTrimmedArtifactsPath>
<OOBAssembliesMarkerFile>$(IntermediateOutputPath)linker-$(TargetArchitecture)-marker.txt</OOBAssembliesMarkerFile>
</PropertyGroup>
<ItemGroup>
<!-- Include suppression XML files bin-placed in earlier per-library linker run. -->
<OOBLibrarySuppressionsXml Include="$(ILLinkTrimAssemblyOOBSuppressionsXmlsDir)*.xml" />
<!-- The following is the list of all the OOBs we will ignore for now -->
<OOBAssemblyToIgnore Include="System.CodeDom;
System.ComponentModel.Composition;
System.ComponentModel.Composition.Registration;
System.Composition.AttributedModel;
System.Composition.Convention;
System.Composition.Hosting;
System.Composition.Runtime;
System.Composition.TypedParts;
System.Configuration.ConfigurationManager;
System.Speech;
Microsoft.Extensions.DependencyInjection.Specification.Tests" />
<!-- Move items to FileName so that we can subtract them. -->
<OOBAssemblyWithFilename Include="@(OOBAssembly->Metadata('Filename'))"
OriginalIdentity="%(Identity)" />
<OOBAssemblyToTrimWithFilename Include="@(OOBAssemblyWithFilename)"
Exclude="@(OOBAssemblyToIgnore)" />
<OOBAssemblyToIgnoreWithFilename Include="@(OOBAssemblyWithFilename)"
Exclude="@(OOBAssemblyToTrimWithFilename)" />
<OOBAssemblyToTrim Include="@(OOBAssemblyToTrimWithFilename->Metadata('OriginalIdentity'))" />
<OOBAssemblyReference Include="@(OOBAssemblyToIgnoreWithFilename->Metadata('OriginalIdentity'));
@(SharedFrameworkAssembly)" />
</ItemGroup>
</Target>
<Target Name="TrimOOBAssemblies"
AfterTargets="Build"
Condition="'$(RefOnly)' != 'true' and '@(OOBAssembly)' != ''"
DependsOnTargets="GetTrimOOBAssembliesInputs;PrepareForAssembliesTrim"
Inputs="$(ILLinkTasksAssembly);@(OOBAssemblyToTrim);@(OOBAssemblyReference);@(OOBLibrarySuppressionsXml)"
Outputs="$(OOBAssembliesMarkerFile)">
<Message Text="$(MSBuildProjectName) -> Trimming $(PackageRID) out-of-band assemblies with ILLinker..." Importance="high" />
<PropertyGroup>
<OOBILLinkArgs>$(ILLinkArgs)</OOBILLinkArgs>
<OOBILLinkArgs Condition="'@(OOBLibrarySuppressionsXml)' != ''" >$(OOBILLinkArgs) --link-attributes "@(OOBLibrarySuppressionsXml->'%(FullPath)', '" --link-attributes "')"</OOBILLinkArgs>
</PropertyGroup>
<ILLink AssemblyPaths=""
RootAssemblyNames="@(OOBAssemblyToTrim)"
ReferenceAssemblyPaths="@(OOBAssemblyReference)"
OutputDirectory="$(OOBAssembliesTrimmedArtifactsPath)"
ExtraArgs="$(OOBILLinkArgs)"
ToolExe="$(_DotNetHostFileName)"
ToolPath="$(_DotNetHostDirectory)" />
<!-- Create a marker file which serves as the target's output to enable incremental builds. -->
<MakeDir Directories="$([System.IO.Path]::GetDirectoryName('$(OOBAssembliesMarkerFile)'))" />
<Touch Files="$(OOBAssembliesMarkerFile)"
AlwaysCreate="true" />
</Target>
<Target Name="SetAzureDevOpsVariableForBuiltPackages"
Condition="'$(ContinuousIntegrationBuild)' == 'true'"
AfterTargets="Build;Pack">
<Message Condition="Exists('$(ArtifactsDir)packages')" Importance="High" Text="##vso[task.setvariable variable=_librariesBuildProducedPackages]true" />
</Target>
</Project>
| -1 |
dotnet/runtime | 66,073 | Use ApiCompatTask in ApiCompat.proj | Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ViktorHofer | 2022-03-02T11:03:07Z | 2022-03-11T17:51:22Z | 3e2d483153adcab27033340fa40ad0bcdc3acc2a | 2575ce5f513c8f5cd37f935ba70b87cbd787c8df | Use ApiCompatTask in ApiCompat.proj. Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ./src/libraries/System.Private.Xml/tests/Xslt/TestFiles/TestData/XsltScenarios/EXslt/out/datetime-week-in-year.xml | <out>
<test1>27</test1>
<test1>NaN</test1>
</out> | <out>
<test1>27</test1>
<test1>NaN</test1>
</out> | -1 |
dotnet/runtime | 66,073 | Use ApiCompatTask in ApiCompat.proj | Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ViktorHofer | 2022-03-02T11:03:07Z | 2022-03-11T17:51:22Z | 3e2d483153adcab27033340fa40ad0bcdc3acc2a | 2575ce5f513c8f5cd37f935ba70b87cbd787c8df | Use ApiCompatTask in ApiCompat.proj. Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ./src/libraries/System.Private.Xml/tests/XmlSchema/TestFiles/StandardTests/xsd10/attributeGroup/attgC024.xml | <doc xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" att="123" att2="abc"></doc>
| <doc xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" att="123" att2="abc"></doc>
| -1 |
dotnet/runtime | 66,073 | Use ApiCompatTask in ApiCompat.proj | Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ViktorHofer | 2022-03-02T11:03:07Z | 2022-03-11T17:51:22Z | 3e2d483153adcab27033340fa40ad0bcdc3acc2a | 2575ce5f513c8f5cd37f935ba70b87cbd787c8df | Use ApiCompatTask in ApiCompat.proj. Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ./src/tests/Loader/classloader/MethodImpl/self_override1.reflect.xml | <linker>
<assembly fullname="self_override1">
<type fullname="*" required="true" />
</assembly>
</linker>
| <linker>
<assembly fullname="self_override1">
<type fullname="*" required="true" />
</assembly>
</linker>
| -1 |
dotnet/runtime | 66,073 | Use ApiCompatTask in ApiCompat.proj | Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ViktorHofer | 2022-03-02T11:03:07Z | 2022-03-11T17:51:22Z | 3e2d483153adcab27033340fa40ad0bcdc3acc2a | 2575ce5f513c8f5cd37f935ba70b87cbd787c8df | Use ApiCompatTask in ApiCompat.proj. Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ./src/coreclr/tools/Directory.Build.props | <Project>
<Import Project="../Directory.Build.props" />
<PropertyGroup>
<IsShipping>false</IsShipping>
<SignAssembly>false</SignAssembly>
<RunAnalyzers>false</RunAnalyzers>
</PropertyGroup>
<!-- MSBuild doesn't understand the Checked configuration -->
<PropertyGroup Condition="'$(Configuration)' == 'Checked'">
<Optimize Condition="'$(Optimize)' == ''">true</Optimize>
<DefineConstants>DEBUG;$(DefineConstants)</DefineConstants>
</PropertyGroup>
</Project>
| <Project>
<Import Project="../Directory.Build.props" />
<PropertyGroup>
<IsShipping>false</IsShipping>
<SignAssembly>false</SignAssembly>
<RunAnalyzers>false</RunAnalyzers>
</PropertyGroup>
<!-- MSBuild doesn't understand the Checked configuration -->
<PropertyGroup Condition="'$(Configuration)' == 'Checked'">
<Optimize Condition="'$(Optimize)' == ''">true</Optimize>
<DefineConstants>DEBUG;$(DefineConstants)</DefineConstants>
</PropertyGroup>
</Project>
| -1 |
dotnet/runtime | 66,073 | Use ApiCompatTask in ApiCompat.proj | Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ViktorHofer | 2022-03-02T11:03:07Z | 2022-03-11T17:51:22Z | 3e2d483153adcab27033340fa40ad0bcdc3acc2a | 2575ce5f513c8f5cd37f935ba70b87cbd787c8df | Use ApiCompatTask in ApiCompat.proj. Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ./src/libraries/System.ServiceModel.Syndication/tests/TestFeeds/AtomFeeds/multiple-categories-entry.xml | <!--
Description: entry with multiple atom:category elements
Expect: !Error
-->
<feed xmlns="http://www.w3.org/2005/Atom">
<title>Example Feed</title>
<link href="http://contoso.com/"/>
<updated>2003-12-13T18:30:02Z</updated>
<author>
<name>Author Name</name>
</author>
<id>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id>
<entry>
<title>Atom-Powered Robots Run Amok</title>
<link href="http://contoso.com/2003/12/13/atom03"/>
<id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id>
<updated>2003-12-13T18:30:02Z</updated>
<summary>Some text.</summary>
<category term="technology"/>
<category term="business"/>
</entry>
</feed>
| <!--
Description: entry with multiple atom:category elements
Expect: !Error
-->
<feed xmlns="http://www.w3.org/2005/Atom">
<title>Example Feed</title>
<link href="http://contoso.com/"/>
<updated>2003-12-13T18:30:02Z</updated>
<author>
<name>Author Name</name>
</author>
<id>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id>
<entry>
<title>Atom-Powered Robots Run Amok</title>
<link href="http://contoso.com/2003/12/13/atom03"/>
<id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id>
<updated>2003-12-13T18:30:02Z</updated>
<summary>Some text.</summary>
<category term="technology"/>
<category term="business"/>
</entry>
</feed>
| -1 |
dotnet/runtime | 66,073 | Use ApiCompatTask in ApiCompat.proj | Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ViktorHofer | 2022-03-02T11:03:07Z | 2022-03-11T17:51:22Z | 3e2d483153adcab27033340fa40ad0bcdc3acc2a | 2575ce5f513c8f5cd37f935ba70b87cbd787c8df | Use ApiCompatTask in ApiCompat.proj. Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ./src/tests/JIT/Regression/JitBlue/DevDiv_815940/DevDiv_815940_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="DevDiv_815940.cs" />
</ItemGroup>
</Project>
| <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<PropertyGroup>
<DebugType>Full</DebugType>
<Optimize>False</Optimize>
</PropertyGroup>
<ItemGroup>
<Compile Include="DevDiv_815940.cs" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime | 66,073 | Use ApiCompatTask in ApiCompat.proj | Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ViktorHofer | 2022-03-02T11:03:07Z | 2022-03-11T17:51:22Z | 3e2d483153adcab27033340fa40ad0bcdc3acc2a | 2575ce5f513c8f5cd37f935ba70b87cbd787c8df | Use ApiCompatTask in ApiCompat.proj. Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ./src/tests/JIT/HardwareIntrinsics/General/Vector64/CreateElement.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\General\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void CreateElementSingle()
{
var test = new VectorCreate__CreateElementSingle();
// Validates basic functionality works
test.RunBasicScenario();
// Validates calling via reflection works
test.RunReflectionScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorCreate__CreateElementSingle
{
private static readonly int LargestVectorSize = 8;
private static readonly int ElementCount = Unsafe.SizeOf<Vector64<Single>>() / sizeof(Single);
public bool Succeeded { get; set; } = true;
public void RunBasicScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario));
Single[] values = new Single[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetSingle();
}
Vector64<Single> result = Vector64.Create(values[0], values[1]);
ValidateResult(result, values);
}
public void RunReflectionScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario));
Type[] operandTypes = new Type[ElementCount];
Single[] values = new Single[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
operandTypes[i] = typeof(Single);
values[i] = TestLibrary.Generator.GetSingle();
}
object result = typeof(Vector64)
.GetMethod(nameof(Vector64.Create), operandTypes)
.Invoke(null, new object[] { values[0], values[1] });
ValidateResult((Vector64<Single>)(result), values);
}
private void ValidateResult(Vector64<Single> result, Single[] expectedValues, [CallerMemberName] string method = "")
{
Single[] resultElements = new Single[ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref resultElements[0]), result);
ValidateResult(resultElements, expectedValues, method);
}
private void ValidateResult(Single[] resultElements, Single[] expectedValues, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < ElementCount; i++)
{
if (resultElements[i] != expectedValues[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector64.Create(Single): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", expectedValues)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", resultElements)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\General\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void CreateElementSingle()
{
var test = new VectorCreate__CreateElementSingle();
// Validates basic functionality works
test.RunBasicScenario();
// Validates calling via reflection works
test.RunReflectionScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorCreate__CreateElementSingle
{
private static readonly int LargestVectorSize = 8;
private static readonly int ElementCount = Unsafe.SizeOf<Vector64<Single>>() / sizeof(Single);
public bool Succeeded { get; set; } = true;
public void RunBasicScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario));
Single[] values = new Single[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetSingle();
}
Vector64<Single> result = Vector64.Create(values[0], values[1]);
ValidateResult(result, values);
}
public void RunReflectionScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario));
Type[] operandTypes = new Type[ElementCount];
Single[] values = new Single[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
operandTypes[i] = typeof(Single);
values[i] = TestLibrary.Generator.GetSingle();
}
object result = typeof(Vector64)
.GetMethod(nameof(Vector64.Create), operandTypes)
.Invoke(null, new object[] { values[0], values[1] });
ValidateResult((Vector64<Single>)(result), values);
}
private void ValidateResult(Vector64<Single> result, Single[] expectedValues, [CallerMemberName] string method = "")
{
Single[] resultElements = new Single[ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref resultElements[0]), result);
ValidateResult(resultElements, expectedValues, method);
}
private void ValidateResult(Single[] resultElements, Single[] expectedValues, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < ElementCount; i++)
{
if (resultElements[i] != expectedValues[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector64.Create(Single): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", expectedValues)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", resultElements)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
dotnet/runtime | 66,073 | Use ApiCompatTask in ApiCompat.proj | Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ViktorHofer | 2022-03-02T11:03:07Z | 2022-03-11T17:51:22Z | 3e2d483153adcab27033340fa40ad0bcdc3acc2a | 2575ce5f513c8f5cd37f935ba70b87cbd787c8df | Use ApiCompatTask in ApiCompat.proj. Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ./src/coreclr/dlls/mscordac/CMakeLists.txt | add_definitions(-DFEATURE_NO_HOST)
set(CLR_DAC_SOURCES
)
add_definitions(-DFX_VER_INTERNALNAME_STR=mscordaccore.dll)
if(CLR_CMAKE_HOST_WIN32)
list(APPEND CLR_DAC_SOURCES
Native.rc
)
set(DEF_SOURCES
mscordac.src
)
set(CURRENT_BINARY_DIR_FOR_CONFIG ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_CFG_INTDIR})
# Preprocess exports definition file
preprocess_file(${CMAKE_CURRENT_SOURCE_DIR}/${DEF_SOURCES} ${CURRENT_BINARY_DIR_FOR_CONFIG}/mscordac.def)
# Create target to add file dependency on mscordac.def
add_custom_target(mscordaccore_def DEPENDS ${CURRENT_BINARY_DIR_FOR_CONFIG}/mscordac.def)
# No library groups for Win32
set(START_LIBRARY_GROUP)
set(END_LIBRARY_GROUP)
else(CLR_CMAKE_HOST_WIN32)
set(DEF_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/mscordac_unixexports.src)
set(EXPORTS_FILE ${CMAKE_CURRENT_BINARY_DIR}/mscordac.exports)
# Add dependency on export file
add_custom_target(mscordaccore_exports DEPENDS ${EXPORTS_FILE})
if(CLR_CMAKE_HOST_OSX OR CLR_CMAKE_HOST_FREEBSD OR CLR_CMAKE_HOST_NETBSD OR CLR_CMAKE_HOST_SUNOS)
generate_exports_file(${DEF_SOURCES} ${EXPORTS_FILE})
endif(CLR_CMAKE_HOST_OSX OR CLR_CMAKE_HOST_FREEBSD OR CLR_CMAKE_HOST_NETBSD OR CLR_CMAKE_HOST_SUNOS)
if(CORECLR_SET_RPATH AND CLR_CMAKE_HOST_OSX AND CLR_CMAKE_HOST_ARCH_ARM64)
set(CMAKE_BUILD_WITH_INSTALL_NAME_DIR ON)
set(CMAKE_INSTALL_NAME_DIR "@rpath")
endif(CORECLR_SET_RPATH AND CLR_CMAKE_HOST_OSX AND CLR_CMAKE_HOST_ARCH_ARM64)
if(CLR_CMAKE_HOST_LINUX)
# Generate DAC export file with the DAC_ prefix
generate_exports_file_prefix(${DEF_SOURCES} ${EXPORTS_FILE} DAC_)
set(REDEFINES_FILE_SCRIPT ${CMAKE_SOURCE_DIR}/generateredefinesfile.sh)
if (CLR_CMAKE_HOST_ARCH_ARM OR CLR_CMAKE_HOST_ARCH_ARM64 OR CLR_CMAKE_HOST_ARCH_LOONGARCH64)
set(JUMP_INSTRUCTION b)
else()
set(JUMP_INSTRUCTION jmp)
endif()
# Generate the palredefines.inc file to map from the imported prefixed APIs (foo to DAC_foo)
set(PAL_REDEFINES_INC ${GENERATED_INCLUDE_DIR}/palredefines.inc)
add_custom_command(
OUTPUT ${PAL_REDEFINES_INC}
COMMAND ${REDEFINES_FILE_SCRIPT} ${DEF_SOURCES} ${JUMP_INSTRUCTION} "" DAC_ > ${PAL_REDEFINES_INC}
DEPENDS ${DEF_SOURCES} ${REDEFINES_FILE_SCRIPT}
COMMENT "Generating PAL redefines file -> ${PAL_REDEFINES_INC}"
VERBATIM
)
add_custom_target(pal_redefines_file DEPENDS ${PAL_REDEFINES_INC})
# Generate the libredefines.inc file for the DAC to export the prefixed APIs (DAC_foo to foo)
set(LIB_REDEFINES_INC ${GENERATED_INCLUDE_DIR}/libredefines.inc)
add_custom_command(
OUTPUT ${LIB_REDEFINES_INC}
COMMAND ${REDEFINES_FILE_SCRIPT} ${DEF_SOURCES} ${JUMP_INSTRUCTION} DAC_ > ${LIB_REDEFINES_INC}
DEPENDS ${DEF_SOURCES} ${REDEFINES_FILE_SCRIPT}
COMMENT "Generating DAC export redefines file -> ${LIB_REDEFINES_INC}"
)
add_custom_target(lib_redefines_inc DEPENDS ${LIB_REDEFINES_INC})
# Add lib redefines file to DAC
list(APPEND CLR_DAC_SOURCES libredefines.S)
endif(CLR_CMAKE_HOST_LINUX)
if(CLR_CMAKE_HOST_LINUX OR CLR_CMAKE_HOST_FREEBSD OR CLR_CMAKE_HOST_NETBSD OR CLR_CMAKE_HOST_SUNOS)
# This option is necessary to ensure that the overloaded delete operator defined inside
# of the utilcode will be used instead of the standard library delete operator.
set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Xlinker -Bsymbolic")
# The following linked options can be inserted into the linker libraries list to
# ensure proper resolving of circular references between a subset of the libraries.
set(START_LIBRARY_GROUP -Wl,--start-group)
set(END_LIBRARY_GROUP -Wl,--end-group)
# These options are used to force every object to be included even if it's unused.
set(START_WHOLE_ARCHIVE -Wl,--whole-archive)
set(END_WHOLE_ARCHIVE -Wl,--no-whole-archive)
endif(CLR_CMAKE_HOST_LINUX OR CLR_CMAKE_HOST_FREEBSD OR CLR_CMAKE_HOST_NETBSD OR CLR_CMAKE_HOST_SUNOS)
set_exports_linker_option(${EXPORTS_FILE})
endif(CLR_CMAKE_HOST_WIN32)
# Create object library to enable creation of proper dependency of mscordaccore.exp on mscordac.obj and
# mscordaccore on both the mscordaccore.exp and mscordac.obj.
add_library_clr(mscordacobj OBJECT mscordac.cpp)
add_library_clr(mscordaccore SHARED ${CLR_DAC_SOURCES} $<TARGET_OBJECTS:mscordacobj>)
set_target_properties(mscordacobj mscordaccore PROPERTIES DAC_COMPONENT TRUE)
if(CLR_CMAKE_HOST_LINUX)
add_dependencies(mscordaccore lib_redefines_inc)
endif(CLR_CMAKE_HOST_LINUX)
if(CLR_CMAKE_HOST_UNIX)
add_dependencies(mscordaccore mscordaccore_exports)
set_property(TARGET mscordaccore APPEND_STRING PROPERTY LINK_FLAGS ${EXPORTS_LINKER_OPTION})
set_property(TARGET mscordaccore APPEND_STRING PROPERTY LINK_DEPENDS ${EXPORTS_FILE})
endif(CLR_CMAKE_HOST_UNIX)
# IMPORTANT! Please do not rearrange the order of the libraries. The linker on Linux is
# order dependent and changing the order can result in undefined symbols in the shared
# library.
set(COREDAC_LIBRARIES
${START_LIBRARY_GROUP} # Start group of libraries that have circular references
cee_dac
cordbee_dac
${START_WHOLE_ARCHIVE} # force all exports to be available
corguids
daccess
${END_WHOLE_ARCHIVE}
dbgutil
mdcompiler_dac
mdruntime_dac
mdruntimerw_dac
utilcode_dac
unwinder_dac
${END_LIBRARY_GROUP} # End group of libraries that have circular references
)
if(CLR_CMAKE_HOST_WIN32)
# mscordac.def should be generated before mscordaccore.dll is built
add_dependencies(mscordaccore mscordaccore_def)
# Generate export file
add_custom_command(
DEPENDS mscordaccore_def "${CURRENT_BINARY_DIR_FOR_CONFIG}/mscordac.def" mscordacobj daccess
OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/mscordaccore.exp
COMMAND lib.exe /OUT:"${CMAKE_CURRENT_BINARY_DIR}/mscordaccore.lib" /DEF:"${CURRENT_BINARY_DIR_FOR_CONFIG}/mscordac.def" "$<TARGET_FILE:daccess>" $<$<OR:$<CONFIG:Release>,$<CONFIG:Relwithdebinfo>>:/LTCG> ${STATIC_LIBRARY_FLAGS} $<TARGET_OBJECTS:mscordacobj>
COMMENT "Generating mscordaccore.exp export file"
)
set_source_files_properties(
${CMAKE_CURRENT_BINARY_DIR}/mscordaccore.exp
PROPERTIES GENERATED TRUE
)
add_custom_target(mscordaccore_exp DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/mscordaccore.exp)
add_dependencies(mscordaccore_exp mscordacobj)
add_dependencies(mscordaccore mscordaccore_exp mscordacobj)
set(COREDAC_LIBRARIES
${CMAKE_CURRENT_BINARY_DIR}/mscordaccore.exp # export file
${COREDAC_LIBRARIES}
kernel32.lib
advapi32.lib
ole32.lib
oleaut32.lib
uuid.lib
user32.lib
${STATIC_MT_CRT_LIB}
${STATIC_MT_VCRT_LIB}
)
else(CLR_CMAKE_HOST_WIN32)
list(APPEND COREDAC_LIBRARIES
mscorrc
${START_WHOLE_ARCHIVE} # force all PAL objects to be included so all exports are available
coreclrpal
palrt
${END_WHOLE_ARCHIVE}
)
endif(CLR_CMAKE_HOST_WIN32)
if(CLR_CMAKE_HOST_WIN32 AND CLR_CMAKE_TARGET_UNIX)
list(APPEND COREDAC_LIBRARIES
libunwind_xdac
)
endif(CLR_CMAKE_HOST_WIN32 AND CLR_CMAKE_TARGET_UNIX)
if(CLR_CMAKE_HOST_UNIX)
list(APPEND COREDAC_LIBRARIES
coreclrpal_dac
)
endif(CLR_CMAKE_HOST_UNIX)
target_link_libraries(mscordaccore PRIVATE ${COREDAC_LIBRARIES})
# add the install targets
install_clr(TARGETS mscordaccore DESTINATIONS . sharedFramework COMPONENT runtime)
if(CLR_CMAKE_HOST_WIN32)
set(LONG_NAME_HOST_ARCH ${CLR_CMAKE_HOST_ARCH})
set(LONG_NAME_TARGET_ARCH ${CLR_CMAKE_TARGET_ARCH})
if (LONG_NAME_HOST_ARCH STREQUAL x64)
set(LONG_NAME_HOST_ARCH "amd64")
endif()
if (LONG_NAME_TARGET_ARCH STREQUAL x64)
set(LONG_NAME_TARGET_ARCH "amd64")
endif()
message ("Read file version from native version header at '${VERSION_HEADER_PATH}'.")
file(READ "${VERSION_HEADER_PATH}" NATIVE_VERSION_HEADER)
string(REGEX MATCH "#define VER_FILEVERSION[ \t]+[0-9]+(,[0-9]+)+" FILE_VERSION_LINE "${NATIVE_VERSION_HEADER}")
string(REGEX MATCHALL "[0-9]+" FILE_VERSION_COMPONENTS "${FILE_VERSION_LINE}")
list(JOIN FILE_VERSION_COMPONENTS "." FILE_VERSION)
install(PROGRAMS $<TARGET_FILE:mscordaccore> RENAME mscordaccore_${LONG_NAME_HOST_ARCH}_${LONG_NAME_TARGET_ARCH}_${FILE_VERSION}.dll DESTINATION sharedFramework COMPONENT runtime)
if (NOT FEATURE_CROSSBITNESS)
install(PROGRAMS $<TARGET_FILE:mscordaccore> RENAME mscordaccore_${LONG_NAME_HOST_ARCH}_${LONG_NAME_TARGET_ARCH}_${FILE_VERSION}.dll DESTINATION sharedFramework COMPONENT crosscomponents)
endif()
endif()
| add_definitions(-DFEATURE_NO_HOST)
set(CLR_DAC_SOURCES
)
add_definitions(-DFX_VER_INTERNALNAME_STR=mscordaccore.dll)
if(CLR_CMAKE_HOST_WIN32)
list(APPEND CLR_DAC_SOURCES
Native.rc
)
set(DEF_SOURCES
mscordac.src
)
set(CURRENT_BINARY_DIR_FOR_CONFIG ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_CFG_INTDIR})
# Preprocess exports definition file
preprocess_file(${CMAKE_CURRENT_SOURCE_DIR}/${DEF_SOURCES} ${CURRENT_BINARY_DIR_FOR_CONFIG}/mscordac.def)
# Create target to add file dependency on mscordac.def
add_custom_target(mscordaccore_def DEPENDS ${CURRENT_BINARY_DIR_FOR_CONFIG}/mscordac.def)
# No library groups for Win32
set(START_LIBRARY_GROUP)
set(END_LIBRARY_GROUP)
else(CLR_CMAKE_HOST_WIN32)
set(DEF_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/mscordac_unixexports.src)
set(EXPORTS_FILE ${CMAKE_CURRENT_BINARY_DIR}/mscordac.exports)
# Add dependency on export file
add_custom_target(mscordaccore_exports DEPENDS ${EXPORTS_FILE})
if(CLR_CMAKE_HOST_OSX OR CLR_CMAKE_HOST_FREEBSD OR CLR_CMAKE_HOST_NETBSD OR CLR_CMAKE_HOST_SUNOS)
generate_exports_file(${DEF_SOURCES} ${EXPORTS_FILE})
endif(CLR_CMAKE_HOST_OSX OR CLR_CMAKE_HOST_FREEBSD OR CLR_CMAKE_HOST_NETBSD OR CLR_CMAKE_HOST_SUNOS)
if(CORECLR_SET_RPATH AND CLR_CMAKE_HOST_OSX AND CLR_CMAKE_HOST_ARCH_ARM64)
set(CMAKE_BUILD_WITH_INSTALL_NAME_DIR ON)
set(CMAKE_INSTALL_NAME_DIR "@rpath")
endif(CORECLR_SET_RPATH AND CLR_CMAKE_HOST_OSX AND CLR_CMAKE_HOST_ARCH_ARM64)
if(CLR_CMAKE_HOST_LINUX)
# Generate DAC export file with the DAC_ prefix
generate_exports_file_prefix(${DEF_SOURCES} ${EXPORTS_FILE} DAC_)
set(REDEFINES_FILE_SCRIPT ${CMAKE_SOURCE_DIR}/generateredefinesfile.sh)
if (CLR_CMAKE_HOST_ARCH_ARM OR CLR_CMAKE_HOST_ARCH_ARM64 OR CLR_CMAKE_HOST_ARCH_LOONGARCH64)
set(JUMP_INSTRUCTION b)
else()
set(JUMP_INSTRUCTION jmp)
endif()
# Generate the palredefines.inc file to map from the imported prefixed APIs (foo to DAC_foo)
set(PAL_REDEFINES_INC ${GENERATED_INCLUDE_DIR}/palredefines.inc)
add_custom_command(
OUTPUT ${PAL_REDEFINES_INC}
COMMAND ${REDEFINES_FILE_SCRIPT} ${DEF_SOURCES} ${JUMP_INSTRUCTION} "" DAC_ > ${PAL_REDEFINES_INC}
DEPENDS ${DEF_SOURCES} ${REDEFINES_FILE_SCRIPT}
COMMENT "Generating PAL redefines file -> ${PAL_REDEFINES_INC}"
VERBATIM
)
add_custom_target(pal_redefines_file DEPENDS ${PAL_REDEFINES_INC})
# Generate the libredefines.inc file for the DAC to export the prefixed APIs (DAC_foo to foo)
set(LIB_REDEFINES_INC ${GENERATED_INCLUDE_DIR}/libredefines.inc)
add_custom_command(
OUTPUT ${LIB_REDEFINES_INC}
COMMAND ${REDEFINES_FILE_SCRIPT} ${DEF_SOURCES} ${JUMP_INSTRUCTION} DAC_ > ${LIB_REDEFINES_INC}
DEPENDS ${DEF_SOURCES} ${REDEFINES_FILE_SCRIPT}
COMMENT "Generating DAC export redefines file -> ${LIB_REDEFINES_INC}"
)
add_custom_target(lib_redefines_inc DEPENDS ${LIB_REDEFINES_INC})
# Add lib redefines file to DAC
list(APPEND CLR_DAC_SOURCES libredefines.S)
endif(CLR_CMAKE_HOST_LINUX)
if(CLR_CMAKE_HOST_LINUX OR CLR_CMAKE_HOST_FREEBSD OR CLR_CMAKE_HOST_NETBSD OR CLR_CMAKE_HOST_SUNOS)
# This option is necessary to ensure that the overloaded delete operator defined inside
# of the utilcode will be used instead of the standard library delete operator.
set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Xlinker -Bsymbolic")
# The following linked options can be inserted into the linker libraries list to
# ensure proper resolving of circular references between a subset of the libraries.
set(START_LIBRARY_GROUP -Wl,--start-group)
set(END_LIBRARY_GROUP -Wl,--end-group)
# These options are used to force every object to be included even if it's unused.
set(START_WHOLE_ARCHIVE -Wl,--whole-archive)
set(END_WHOLE_ARCHIVE -Wl,--no-whole-archive)
endif(CLR_CMAKE_HOST_LINUX OR CLR_CMAKE_HOST_FREEBSD OR CLR_CMAKE_HOST_NETBSD OR CLR_CMAKE_HOST_SUNOS)
set_exports_linker_option(${EXPORTS_FILE})
endif(CLR_CMAKE_HOST_WIN32)
# Create object library to enable creation of proper dependency of mscordaccore.exp on mscordac.obj and
# mscordaccore on both the mscordaccore.exp and mscordac.obj.
add_library_clr(mscordacobj OBJECT mscordac.cpp)
add_library_clr(mscordaccore SHARED ${CLR_DAC_SOURCES} $<TARGET_OBJECTS:mscordacobj>)
set_target_properties(mscordacobj mscordaccore PROPERTIES DAC_COMPONENT TRUE)
if(CLR_CMAKE_HOST_LINUX)
add_dependencies(mscordaccore lib_redefines_inc)
endif(CLR_CMAKE_HOST_LINUX)
if(CLR_CMAKE_HOST_UNIX)
add_dependencies(mscordaccore mscordaccore_exports)
set_property(TARGET mscordaccore APPEND_STRING PROPERTY LINK_FLAGS ${EXPORTS_LINKER_OPTION})
set_property(TARGET mscordaccore APPEND_STRING PROPERTY LINK_DEPENDS ${EXPORTS_FILE})
endif(CLR_CMAKE_HOST_UNIX)
# IMPORTANT! Please do not rearrange the order of the libraries. The linker on Linux is
# order dependent and changing the order can result in undefined symbols in the shared
# library.
set(COREDAC_LIBRARIES
${START_LIBRARY_GROUP} # Start group of libraries that have circular references
cee_dac
cordbee_dac
${START_WHOLE_ARCHIVE} # force all exports to be available
corguids
daccess
${END_WHOLE_ARCHIVE}
dbgutil
mdcompiler_dac
mdruntime_dac
mdruntimerw_dac
utilcode_dac
unwinder_dac
${END_LIBRARY_GROUP} # End group of libraries that have circular references
)
if(CLR_CMAKE_HOST_WIN32)
# mscordac.def should be generated before mscordaccore.dll is built
add_dependencies(mscordaccore mscordaccore_def)
# Generate export file
add_custom_command(
DEPENDS mscordaccore_def "${CURRENT_BINARY_DIR_FOR_CONFIG}/mscordac.def" mscordacobj daccess
OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/mscordaccore.exp
COMMAND lib.exe /OUT:"${CMAKE_CURRENT_BINARY_DIR}/mscordaccore.lib" /DEF:"${CURRENT_BINARY_DIR_FOR_CONFIG}/mscordac.def" "$<TARGET_FILE:daccess>" $<$<OR:$<CONFIG:Release>,$<CONFIG:Relwithdebinfo>>:/LTCG> ${STATIC_LIBRARY_FLAGS} $<TARGET_OBJECTS:mscordacobj>
COMMENT "Generating mscordaccore.exp export file"
)
set_source_files_properties(
${CMAKE_CURRENT_BINARY_DIR}/mscordaccore.exp
PROPERTIES GENERATED TRUE
)
add_custom_target(mscordaccore_exp DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/mscordaccore.exp)
add_dependencies(mscordaccore_exp mscordacobj)
add_dependencies(mscordaccore mscordaccore_exp mscordacobj)
set(COREDAC_LIBRARIES
${CMAKE_CURRENT_BINARY_DIR}/mscordaccore.exp # export file
${COREDAC_LIBRARIES}
kernel32.lib
advapi32.lib
ole32.lib
oleaut32.lib
uuid.lib
user32.lib
${STATIC_MT_CRT_LIB}
${STATIC_MT_VCRT_LIB}
)
else(CLR_CMAKE_HOST_WIN32)
list(APPEND COREDAC_LIBRARIES
mscorrc
${START_WHOLE_ARCHIVE} # force all PAL objects to be included so all exports are available
coreclrpal
palrt
${END_WHOLE_ARCHIVE}
)
endif(CLR_CMAKE_HOST_WIN32)
if(CLR_CMAKE_HOST_WIN32 AND CLR_CMAKE_TARGET_UNIX)
list(APPEND COREDAC_LIBRARIES
libunwind_xdac
)
endif(CLR_CMAKE_HOST_WIN32 AND CLR_CMAKE_TARGET_UNIX)
if(CLR_CMAKE_HOST_UNIX)
list(APPEND COREDAC_LIBRARIES
coreclrpal_dac
)
endif(CLR_CMAKE_HOST_UNIX)
target_link_libraries(mscordaccore PRIVATE ${COREDAC_LIBRARIES})
# add the install targets
install_clr(TARGETS mscordaccore DESTINATIONS . sharedFramework COMPONENT runtime)
if(CLR_CMAKE_HOST_WIN32)
set(LONG_NAME_HOST_ARCH ${CLR_CMAKE_HOST_ARCH})
set(LONG_NAME_TARGET_ARCH ${CLR_CMAKE_TARGET_ARCH})
if (LONG_NAME_HOST_ARCH STREQUAL x64)
set(LONG_NAME_HOST_ARCH "amd64")
endif()
if (LONG_NAME_TARGET_ARCH STREQUAL x64)
set(LONG_NAME_TARGET_ARCH "amd64")
endif()
message ("Read file version from native version header at '${VERSION_HEADER_PATH}'.")
file(READ "${VERSION_HEADER_PATH}" NATIVE_VERSION_HEADER)
string(REGEX MATCH "#define VER_FILEVERSION[ \t]+[0-9]+(,[0-9]+)+" FILE_VERSION_LINE "${NATIVE_VERSION_HEADER}")
string(REGEX MATCHALL "[0-9]+" FILE_VERSION_COMPONENTS "${FILE_VERSION_LINE}")
list(JOIN FILE_VERSION_COMPONENTS "." FILE_VERSION)
install(PROGRAMS $<TARGET_FILE:mscordaccore> RENAME mscordaccore_${LONG_NAME_HOST_ARCH}_${LONG_NAME_TARGET_ARCH}_${FILE_VERSION}.dll DESTINATION sharedFramework COMPONENT runtime)
if (NOT FEATURE_CROSSBITNESS)
install(PROGRAMS $<TARGET_FILE:mscordaccore> RENAME mscordaccore_${LONG_NAME_HOST_ARCH}_${LONG_NAME_TARGET_ARCH}_${FILE_VERSION}.dll DESTINATION sharedFramework COMPONENT crosscomponents)
endif()
endif()
| -1 |
dotnet/runtime | 66,073 | Use ApiCompatTask in ApiCompat.proj | Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ViktorHofer | 2022-03-02T11:03:07Z | 2022-03-11T17:51:22Z | 3e2d483153adcab27033340fa40ad0bcdc3acc2a | 2575ce5f513c8f5cd37f935ba70b87cbd787c8df | Use ApiCompatTask in ApiCompat.proj. Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ./src/tests/Interop/COM/Dynamic/Server/DynamicTestServer.X.manifest | <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<assemblyIdentity
type="win32"
name="DynamicTestServer.X"
version="1.0.0.0" />
<file name = "DynamicTestServer.dll">
<!-- Basic Test -->
<comClass
clsid="{ED349A5B-257B-4349-8CB8-2C30B0C05FC3}"
threadingModel="Both" />
<!-- CollectionTest -->
<comClass
clsid="{1FFF64AE-FF9C-41AB-BF80-3ECA831AEC40}"
threadingModel="Both" />
<!-- EventTest -->
<comClass
clsid="{23425222-10FE-46BA-8B1A-1D42D2D73464}"
threadingModel="Both" />
<!-- ParametersTest -->
<comClass
clsid="{787FEAF2-34F6-4244-884A-0A142DAB3B77}"
threadingModel="Both" />
</file>
</assembly>
| <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<assemblyIdentity
type="win32"
name="DynamicTestServer.X"
version="1.0.0.0" />
<file name = "DynamicTestServer.dll">
<!-- Basic Test -->
<comClass
clsid="{ED349A5B-257B-4349-8CB8-2C30B0C05FC3}"
threadingModel="Both" />
<!-- CollectionTest -->
<comClass
clsid="{1FFF64AE-FF9C-41AB-BF80-3ECA831AEC40}"
threadingModel="Both" />
<!-- EventTest -->
<comClass
clsid="{23425222-10FE-46BA-8B1A-1D42D2D73464}"
threadingModel="Both" />
<!-- ParametersTest -->
<comClass
clsid="{787FEAF2-34F6-4244-884A-0A142DAB3B77}"
threadingModel="Both" />
</file>
</assembly>
| -1 |
dotnet/runtime | 66,073 | Use ApiCompatTask in ApiCompat.proj | Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ViktorHofer | 2022-03-02T11:03:07Z | 2022-03-11T17:51:22Z | 3e2d483153adcab27033340fa40ad0bcdc3acc2a | 2575ce5f513c8f5cd37f935ba70b87cbd787c8df | Use ApiCompatTask in ApiCompat.proj. Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ./src/libraries/System.Private.Xml/tests/Xslt/TestFiles/TestData/XsltApi/xsltarg_multithreading5.xsl | <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:myObj="urn:my-obj5">
<xsl:template match="/">
<result>Function1:<xsl:value-of select="myObj:Fn1()"/></result>
</xsl:template>
</xsl:stylesheet> | <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:myObj="urn:my-obj5">
<xsl:template match="/">
<result>Function1:<xsl:value-of select="myObj:Fn1()"/></result>
</xsl:template>
</xsl:stylesheet> | -1 |
dotnet/runtime | 66,073 | Use ApiCompatTask in ApiCompat.proj | Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ViktorHofer | 2022-03-02T11:03:07Z | 2022-03-11T17:51:22Z | 3e2d483153adcab27033340fa40ad0bcdc3acc2a | 2575ce5f513c8f5cd37f935ba70b87cbd787c8df | Use ApiCompatTask in ApiCompat.proj. Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ./src/native/external/brotli/enc/hash_composite_inc.h | /* NOLINT(build/header_guard) */
/* Copyright 2018 Google Inc. All Rights Reserved.
Distributed under MIT license.
See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
*/
/* template parameters: FN, HASHER_A, HASHER_B */
/* Composite hasher: This hasher allows to combine two other hashers, HASHER_A
and HASHER_B. */
#define HashComposite HASHER()
#define FN_A(X) EXPAND_CAT(X, HASHER_A)
#define FN_B(X) EXPAND_CAT(X, HASHER_B)
static BROTLI_INLINE size_t FN(HashTypeLength)(void) {
size_t a = FN_A(HashTypeLength)();
size_t b = FN_B(HashTypeLength)();
return a > b ? a : b;
}
static BROTLI_INLINE size_t FN(StoreLookahead)(void) {
size_t a = FN_A(StoreLookahead)();
size_t b = FN_B(StoreLookahead)();
return a > b ? a : b;
}
typedef struct HashComposite {
HASHER_A ha;
HASHER_B hb;
HasherCommon hb_common;
/* Shortcuts. */
void* extra;
HasherCommon* common;
BROTLI_BOOL fresh;
const BrotliEncoderParams* params;
} HashComposite;
static void FN(Initialize)(HasherCommon* common,
HashComposite* BROTLI_RESTRICT self, const BrotliEncoderParams* params) {
self->common = common;
self->extra = common->extra;
self->hb_common = *self->common;
self->fresh = BROTLI_TRUE;
self->params = params;
/* TODO: Initialize of the hashers is defered to Prepare (and params
remembered here) because we don't get the one_shot and input_size params
here that are needed to know the memory size of them. Instead provide
those params to all hashers FN(Initialize) */
}
static void FN(Prepare)(
HashComposite* BROTLI_RESTRICT self, BROTLI_BOOL one_shot,
size_t input_size, const uint8_t* BROTLI_RESTRICT data) {
if (self->fresh) {
self->fresh = BROTLI_FALSE;
self->hb_common.extra = (uint8_t*)self->extra +
FN_A(HashMemAllocInBytes)(self->params, one_shot, input_size);
FN_A(Initialize)(self->common, &self->ha, self->params);
FN_B(Initialize)(&self->hb_common, &self->hb, self->params);
}
FN_A(Prepare)(&self->ha, one_shot, input_size, data);
FN_B(Prepare)(&self->hb, one_shot, input_size, data);
}
static BROTLI_INLINE size_t FN(HashMemAllocInBytes)(
const BrotliEncoderParams* params, BROTLI_BOOL one_shot,
size_t input_size) {
return FN_A(HashMemAllocInBytes)(params, one_shot, input_size) +
FN_B(HashMemAllocInBytes)(params, one_shot, input_size);
}
static BROTLI_INLINE void FN(Store)(HashComposite* BROTLI_RESTRICT self,
const uint8_t* BROTLI_RESTRICT data, const size_t mask, const size_t ix) {
FN_A(Store)(&self->ha, data, mask, ix);
FN_B(Store)(&self->hb, data, mask, ix);
}
static BROTLI_INLINE void FN(StoreRange)(
HashComposite* BROTLI_RESTRICT self, const uint8_t* BROTLI_RESTRICT data,
const size_t mask, const size_t ix_start,
const size_t ix_end) {
FN_A(StoreRange)(&self->ha, data, mask, ix_start, ix_end);
FN_B(StoreRange)(&self->hb, data, mask, ix_start, ix_end);
}
static BROTLI_INLINE void FN(StitchToPreviousBlock)(
HashComposite* BROTLI_RESTRICT self,
size_t num_bytes, size_t position, const uint8_t* ringbuffer,
size_t ring_buffer_mask) {
FN_A(StitchToPreviousBlock)(&self->ha, num_bytes, position,
ringbuffer, ring_buffer_mask);
FN_B(StitchToPreviousBlock)(&self->hb, num_bytes, position,
ringbuffer, ring_buffer_mask);
}
static BROTLI_INLINE void FN(PrepareDistanceCache)(
HashComposite* BROTLI_RESTRICT self, int* BROTLI_RESTRICT distance_cache) {
FN_A(PrepareDistanceCache)(&self->ha, distance_cache);
FN_B(PrepareDistanceCache)(&self->hb, distance_cache);
}
static BROTLI_INLINE void FN(FindLongestMatch)(
HashComposite* BROTLI_RESTRICT self,
const BrotliEncoderDictionary* dictionary,
const uint8_t* BROTLI_RESTRICT data, const size_t ring_buffer_mask,
const int* BROTLI_RESTRICT distance_cache, const size_t cur_ix,
const size_t max_length, const size_t max_backward,
const size_t dictionary_distance, const size_t max_distance,
HasherSearchResult* BROTLI_RESTRICT out) {
FN_A(FindLongestMatch)(&self->ha, dictionary, data, ring_buffer_mask,
distance_cache, cur_ix, max_length, max_backward, dictionary_distance,
max_distance, out);
FN_B(FindLongestMatch)(&self->hb, dictionary, data, ring_buffer_mask,
distance_cache, cur_ix, max_length, max_backward, dictionary_distance,
max_distance, out);
}
#undef HashComposite
| /* NOLINT(build/header_guard) */
/* Copyright 2018 Google Inc. All Rights Reserved.
Distributed under MIT license.
See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
*/
/* template parameters: FN, HASHER_A, HASHER_B */
/* Composite hasher: This hasher allows to combine two other hashers, HASHER_A
and HASHER_B. */
#define HashComposite HASHER()
#define FN_A(X) EXPAND_CAT(X, HASHER_A)
#define FN_B(X) EXPAND_CAT(X, HASHER_B)
static BROTLI_INLINE size_t FN(HashTypeLength)(void) {
size_t a = FN_A(HashTypeLength)();
size_t b = FN_B(HashTypeLength)();
return a > b ? a : b;
}
static BROTLI_INLINE size_t FN(StoreLookahead)(void) {
size_t a = FN_A(StoreLookahead)();
size_t b = FN_B(StoreLookahead)();
return a > b ? a : b;
}
typedef struct HashComposite {
HASHER_A ha;
HASHER_B hb;
HasherCommon hb_common;
/* Shortcuts. */
void* extra;
HasherCommon* common;
BROTLI_BOOL fresh;
const BrotliEncoderParams* params;
} HashComposite;
static void FN(Initialize)(HasherCommon* common,
HashComposite* BROTLI_RESTRICT self, const BrotliEncoderParams* params) {
self->common = common;
self->extra = common->extra;
self->hb_common = *self->common;
self->fresh = BROTLI_TRUE;
self->params = params;
/* TODO: Initialize of the hashers is defered to Prepare (and params
remembered here) because we don't get the one_shot and input_size params
here that are needed to know the memory size of them. Instead provide
those params to all hashers FN(Initialize) */
}
static void FN(Prepare)(
HashComposite* BROTLI_RESTRICT self, BROTLI_BOOL one_shot,
size_t input_size, const uint8_t* BROTLI_RESTRICT data) {
if (self->fresh) {
self->fresh = BROTLI_FALSE;
self->hb_common.extra = (uint8_t*)self->extra +
FN_A(HashMemAllocInBytes)(self->params, one_shot, input_size);
FN_A(Initialize)(self->common, &self->ha, self->params);
FN_B(Initialize)(&self->hb_common, &self->hb, self->params);
}
FN_A(Prepare)(&self->ha, one_shot, input_size, data);
FN_B(Prepare)(&self->hb, one_shot, input_size, data);
}
static BROTLI_INLINE size_t FN(HashMemAllocInBytes)(
const BrotliEncoderParams* params, BROTLI_BOOL one_shot,
size_t input_size) {
return FN_A(HashMemAllocInBytes)(params, one_shot, input_size) +
FN_B(HashMemAllocInBytes)(params, one_shot, input_size);
}
static BROTLI_INLINE void FN(Store)(HashComposite* BROTLI_RESTRICT self,
const uint8_t* BROTLI_RESTRICT data, const size_t mask, const size_t ix) {
FN_A(Store)(&self->ha, data, mask, ix);
FN_B(Store)(&self->hb, data, mask, ix);
}
static BROTLI_INLINE void FN(StoreRange)(
HashComposite* BROTLI_RESTRICT self, const uint8_t* BROTLI_RESTRICT data,
const size_t mask, const size_t ix_start,
const size_t ix_end) {
FN_A(StoreRange)(&self->ha, data, mask, ix_start, ix_end);
FN_B(StoreRange)(&self->hb, data, mask, ix_start, ix_end);
}
static BROTLI_INLINE void FN(StitchToPreviousBlock)(
HashComposite* BROTLI_RESTRICT self,
size_t num_bytes, size_t position, const uint8_t* ringbuffer,
size_t ring_buffer_mask) {
FN_A(StitchToPreviousBlock)(&self->ha, num_bytes, position,
ringbuffer, ring_buffer_mask);
FN_B(StitchToPreviousBlock)(&self->hb, num_bytes, position,
ringbuffer, ring_buffer_mask);
}
static BROTLI_INLINE void FN(PrepareDistanceCache)(
HashComposite* BROTLI_RESTRICT self, int* BROTLI_RESTRICT distance_cache) {
FN_A(PrepareDistanceCache)(&self->ha, distance_cache);
FN_B(PrepareDistanceCache)(&self->hb, distance_cache);
}
static BROTLI_INLINE void FN(FindLongestMatch)(
HashComposite* BROTLI_RESTRICT self,
const BrotliEncoderDictionary* dictionary,
const uint8_t* BROTLI_RESTRICT data, const size_t ring_buffer_mask,
const int* BROTLI_RESTRICT distance_cache, const size_t cur_ix,
const size_t max_length, const size_t max_backward,
const size_t dictionary_distance, const size_t max_distance,
HasherSearchResult* BROTLI_RESTRICT out) {
FN_A(FindLongestMatch)(&self->ha, dictionary, data, ring_buffer_mask,
distance_cache, cur_ix, max_length, max_backward, dictionary_distance,
max_distance, out);
FN_B(FindLongestMatch)(&self->hb, dictionary, data, ring_buffer_mask,
distance_cache, cur_ix, max_length, max_backward, dictionary_distance,
max_distance, out);
}
#undef HashComposite
| -1 |
dotnet/runtime | 66,073 | Use ApiCompatTask in ApiCompat.proj | Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ViktorHofer | 2022-03-02T11:03:07Z | 2022-03-11T17:51:22Z | 3e2d483153adcab27033340fa40ad0bcdc3acc2a | 2575ce5f513c8f5cd37f935ba70b87cbd787c8df | Use ApiCompatTask in ApiCompat.proj. Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ./src/tests/JIT/CodeGenBringUpTests/JTrue1_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="JTrue1.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="JTrue1.cs" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime | 66,073 | Use ApiCompatTask in ApiCompat.proj | Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ViktorHofer | 2022-03-02T11:03:07Z | 2022-03-11T17:51:22Z | 3e2d483153adcab27033340fa40ad0bcdc3acc2a | 2575ce5f513c8f5cd37f935ba70b87cbd787c8df | Use ApiCompatTask in ApiCompat.proj. Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ./src/tests/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b80764/b80764.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 JitTest
{
internal class Test
{
private static unsafe void initbuf(byte* buf, int num)
{
for (int i = 0; i < 100; i++)
buf[i] = (byte)i;
Console.WriteLine("buffer " + num.ToString() + " allocated");
}
private static unsafe void ckbuf(byte* buf, int num)
{
if (buf != null)
{
for (int i = 0; i < 100; i++)
{
if (buf[i] != (byte)i)
{
Console.WriteLine("buffer " + num.ToString() + " is garbage !!");
return;
}
}
}
Console.WriteLine("buffer " + num.ToString() + " is OK");
}
private static unsafe int Main()
{
byte* buf1 = stackalloc byte[100], buf2 = null, buf3 = null;
initbuf(buf1, 1);
ckbuf(buf1, 1);
try
{
Console.WriteLine("--- entered outer try ---");
byte* TEMP1 = stackalloc byte[100];
buf2 = TEMP1;
initbuf(buf2, 2);
ckbuf(buf1, 1);
ckbuf(buf2, 2);
try
{
Console.WriteLine("--- entered inner try ---");
byte* TEMP2 = stackalloc byte[100];
buf3 = TEMP2;
initbuf(buf3, 3);
ckbuf(buf1, 1);
ckbuf(buf2, 2);
ckbuf(buf3, 3);
Console.WriteLine("--- throwing exception ---");
throw new Exception();
}
finally
{
Console.WriteLine("--- finally ---");
ckbuf(buf1, 1);
ckbuf(buf2, 2);
ckbuf(buf3, 3);
}
}
catch (Exception)
{
Console.WriteLine("--- catch ---");
ckbuf(buf1, 1);
ckbuf(buf2, 2);
ckbuf(buf3, 3);
}
Console.WriteLine("--- after try-catch ---");
ckbuf(buf1, 1);
ckbuf(buf2, 2);
ckbuf(buf3, 3);
Console.WriteLine("=== TEST ENDED ===");
return 100;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Runtime.InteropServices;
namespace JitTest
{
internal class Test
{
private static unsafe void initbuf(byte* buf, int num)
{
for (int i = 0; i < 100; i++)
buf[i] = (byte)i;
Console.WriteLine("buffer " + num.ToString() + " allocated");
}
private static unsafe void ckbuf(byte* buf, int num)
{
if (buf != null)
{
for (int i = 0; i < 100; i++)
{
if (buf[i] != (byte)i)
{
Console.WriteLine("buffer " + num.ToString() + " is garbage !!");
return;
}
}
}
Console.WriteLine("buffer " + num.ToString() + " is OK");
}
private static unsafe int Main()
{
byte* buf1 = stackalloc byte[100], buf2 = null, buf3 = null;
initbuf(buf1, 1);
ckbuf(buf1, 1);
try
{
Console.WriteLine("--- entered outer try ---");
byte* TEMP1 = stackalloc byte[100];
buf2 = TEMP1;
initbuf(buf2, 2);
ckbuf(buf1, 1);
ckbuf(buf2, 2);
try
{
Console.WriteLine("--- entered inner try ---");
byte* TEMP2 = stackalloc byte[100];
buf3 = TEMP2;
initbuf(buf3, 3);
ckbuf(buf1, 1);
ckbuf(buf2, 2);
ckbuf(buf3, 3);
Console.WriteLine("--- throwing exception ---");
throw new Exception();
}
finally
{
Console.WriteLine("--- finally ---");
ckbuf(buf1, 1);
ckbuf(buf2, 2);
ckbuf(buf3, 3);
}
}
catch (Exception)
{
Console.WriteLine("--- catch ---");
ckbuf(buf1, 1);
ckbuf(buf2, 2);
ckbuf(buf3, 3);
}
Console.WriteLine("--- after try-catch ---");
ckbuf(buf1, 1);
ckbuf(buf2, 2);
ckbuf(buf3, 3);
Console.WriteLine("=== TEST ENDED ===");
return 100;
}
}
}
| -1 |
dotnet/runtime | 66,073 | Use ApiCompatTask in ApiCompat.proj | Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ViktorHofer | 2022-03-02T11:03:07Z | 2022-03-11T17:51:22Z | 3e2d483153adcab27033340fa40ad0bcdc3acc2a | 2575ce5f513c8f5cd37f935ba70b87cbd787c8df | Use ApiCompatTask in ApiCompat.proj. Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ./src/tests/JIT/Performance/CodeQuality/Math/Functions/Double/TanhDouble.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 Functions
{
public static partial class MathTests
{
// Tests Math.Tanh(double) over 5000 iterations for the domain -1, +1
private const double tanhDoubleDelta = 0.0004;
private const double tanhDoubleExpectedResult = 0.76159415578341827;
public static void TanhDoubleTest()
{
var result = 0.0; var value = -1.0;
for (var iteration = 0; iteration < iterations; iteration++)
{
value += tanhDoubleDelta;
result += Math.Tanh(value);
}
var diff = Math.Abs(tanhDoubleExpectedResult - result);
if (diff > doubleEpsilon)
{
throw new Exception($"Expected Result {tanhDoubleExpectedResult,20:g17}; Actual Result {result,20:g17}");
}
}
}
}
| // 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 Functions
{
public static partial class MathTests
{
// Tests Math.Tanh(double) over 5000 iterations for the domain -1, +1
private const double tanhDoubleDelta = 0.0004;
private const double tanhDoubleExpectedResult = 0.76159415578341827;
public static void TanhDoubleTest()
{
var result = 0.0; var value = -1.0;
for (var iteration = 0; iteration < iterations; iteration++)
{
value += tanhDoubleDelta;
result += Math.Tanh(value);
}
var diff = Math.Abs(tanhDoubleExpectedResult - result);
if (diff > doubleEpsilon)
{
throw new Exception($"Expected Result {tanhDoubleExpectedResult,20:g17}; Actual Result {result,20:g17}");
}
}
}
}
| -1 |
dotnet/runtime | 66,073 | Use ApiCompatTask in ApiCompat.proj | Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ViktorHofer | 2022-03-02T11:03:07Z | 2022-03-11T17:51:22Z | 3e2d483153adcab27033340fa40ad0bcdc3acc2a | 2575ce5f513c8f5cd37f935ba70b87cbd787c8df | Use ApiCompatTask in ApiCompat.proj. Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ./src/tests/Loader/classloader/TypeGeneratorTests/TypeGeneratorTest976/Generated976.ilproj | <Project Sdk="Microsoft.NET.Sdk.IL">
<PropertyGroup>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<ItemGroup>
<Compile Include="Generated976.il" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\TestFramework\TestFramework.csproj" />
</ItemGroup>
</Project>
| <Project Sdk="Microsoft.NET.Sdk.IL">
<PropertyGroup>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<ItemGroup>
<Compile Include="Generated976.il" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\TestFramework\TestFramework.csproj" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime | 66,073 | Use ApiCompatTask in ApiCompat.proj | Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ViktorHofer | 2022-03-02T11:03:07Z | 2022-03-11T17:51:22Z | 3e2d483153adcab27033340fa40ad0bcdc3acc2a | 2575ce5f513c8f5cd37f935ba70b87cbd787c8df | Use ApiCompatTask in ApiCompat.proj. Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ./src/tests/JIT/Directed/coverage/oldtests/lclfldadd_cs_r.csproj | <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
</PropertyGroup>
<PropertyGroup>
<DebugType>None</DebugType>
<Optimize>False</Optimize>
</PropertyGroup>
<ItemGroup>
<Compile Include="lclfldadd.cs" />
</ItemGroup>
</Project>
| <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
</PropertyGroup>
<PropertyGroup>
<DebugType>None</DebugType>
<Optimize>False</Optimize>
</PropertyGroup>
<ItemGroup>
<Compile Include="lclfldadd.cs" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime | 66,073 | Use ApiCompatTask in ApiCompat.proj | Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ViktorHofer | 2022-03-02T11:03:07Z | 2022-03-11T17:51:22Z | 3e2d483153adcab27033340fa40ad0bcdc3acc2a | 2575ce5f513c8f5cd37f935ba70b87cbd787c8df | Use ApiCompatTask in ApiCompat.proj. Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ./src/libraries/System.Private.Xml/tests/Xslt/TestFiles/TestData/xsltc/baseline/pft10.txt | <?xml version="1.0" encoding="utf-8"?>Hello, world! | <?xml version="1.0" encoding="utf-8"?>Hello, world! | -1 |
dotnet/runtime | 66,073 | Use ApiCompatTask in ApiCompat.proj | Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ViktorHofer | 2022-03-02T11:03:07Z | 2022-03-11T17:51:22Z | 3e2d483153adcab27033340fa40ad0bcdc3acc2a | 2575ce5f513c8f5cd37f935ba70b87cbd787c8df | Use ApiCompatTask in ApiCompat.proj. Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ./src/tests/Loader/classloader/TypeGeneratorTests/TypeGeneratorTest873/Generated873.ilproj | <Project Sdk="Microsoft.NET.Sdk.IL">
<PropertyGroup>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<ItemGroup>
<Compile Include="Generated873.il" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\TestFramework\TestFramework.csproj" />
</ItemGroup>
</Project>
| <Project Sdk="Microsoft.NET.Sdk.IL">
<PropertyGroup>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<ItemGroup>
<Compile Include="Generated873.il" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\TestFramework\TestFramework.csproj" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime | 66,073 | Use ApiCompatTask in ApiCompat.proj | Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ViktorHofer | 2022-03-02T11:03:07Z | 2022-03-11T17:51:22Z | 3e2d483153adcab27033340fa40ad0bcdc3acc2a | 2575ce5f513c8f5cd37f935ba70b87cbd787c8df | Use ApiCompatTask in ApiCompat.proj. Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ./src/tests/Loader/classloader/TypeGeneratorTests/TypeGeneratorTest800/Generated800.ilproj | <Project Sdk="Microsoft.NET.Sdk.IL">
<PropertyGroup>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<ItemGroup>
<Compile Include="Generated800.il" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\TestFramework\TestFramework.csproj" />
</ItemGroup>
</Project>
| <Project Sdk="Microsoft.NET.Sdk.IL">
<PropertyGroup>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<ItemGroup>
<Compile Include="Generated800.il" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\TestFramework\TestFramework.csproj" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime | 66,073 | Use ApiCompatTask in ApiCompat.proj | Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ViktorHofer | 2022-03-02T11:03:07Z | 2022-03-11T17:51:22Z | 3e2d483153adcab27033340fa40ad0bcdc3acc2a | 2575ce5f513c8f5cd37f935ba70b87cbd787c8df | Use ApiCompatTask in ApiCompat.proj. Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ./src/tests/GC/Performance/Tests/Node.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace EEGC
{
public class Node
{
public Node left;
public Node right;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace EEGC
{
public class Node
{
public Node left;
public Node right;
}
}
| -1 |
dotnet/runtime | 66,073 | Use ApiCompatTask in ApiCompat.proj | Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ViktorHofer | 2022-03-02T11:03:07Z | 2022-03-11T17:51:22Z | 3e2d483153adcab27033340fa40ad0bcdc3acc2a | 2575ce5f513c8f5cd37f935ba70b87cbd787c8df | Use ApiCompatTask in ApiCompat.proj. Requires https://github.com/dotnet/arcade/pull/8523
As ApiCompat now has a task that allows to run in-proc, use that instead
of shelving out. Also use items instead of properties to define
the attribute exclusion list.
Unfortunately msbuild doesn't support running targets in parallel, only projects. Moving every ApiCompatTask invocation into a separate project is overkill and just increases the overall evaluation and restore time. Therefore stick with running the ApiCompat invocations sequentially. | ./src/tests/JIT/opt/virtualstubdispatch/hashcode/cderived9.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 VirtFunc
{
public class CDerived9
{
public override int GetHashCode() { return 9; }
}
}
| // 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 VirtFunc
{
public class CDerived9
{
public override int GetHashCode() { return 9; }
}
}
| -1 |
dotnet/runtime | 66,057 | Address TODO to switch to generated p/invoke | Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | elinor-fung | 2022-03-02T03:31:28Z | 2022-03-02T19:08:30Z | a4b8893a118357b55c0add9a39cc5aeb097a0bb8 | 1abbbb4adf6bf02549f4c6e021176534dcc4f974 | Address TODO to switch to generated p/invoke. Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | ./src/libraries/Common/src/Interop/Windows/Advapi32/Interop.ChangeServiceConfig2.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.InteropServices;
internal static partial class Interop
{
internal static partial class Advapi32
{
[GeneratedDllImport(Libraries.Advapi32, EntryPoint = "ChangeServiceConfig2W", SetLastError = true)]
public static partial bool ChangeServiceConfig2(SafeServiceHandle serviceHandle, uint infoLevel, ref SERVICE_DESCRIPTION serviceDesc);
#pragma warning disable DLLIMPORTGENANALYZER015 // Use 'GeneratedDllImportAttribute' instead of 'DllImportAttribute' to generate P/Invoke marshalling code at compile time
// TODO: [DllImportGenerator] Switch to use GeneratedDllImport once we support non-blittable types.
[DllImport(Libraries.Advapi32, EntryPoint = "ChangeServiceConfig2W", ExactSpelling = true, SetLastError = true)]
public static extern bool ChangeServiceConfig2(SafeServiceHandle serviceHandle, uint infoLevel, ref SERVICE_DELAYED_AUTOSTART_INFO serviceDesc);
#pragma warning restore DLLIMPORTGENANALYZER015
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.InteropServices;
internal static partial class Interop
{
internal static partial class Advapi32
{
[GeneratedDllImport(Libraries.Advapi32, EntryPoint = "ChangeServiceConfig2W", SetLastError = true)]
public static partial bool ChangeServiceConfig2(SafeServiceHandle serviceHandle, uint infoLevel, ref SERVICE_DESCRIPTION serviceDesc);
}
}
| 1 |
dotnet/runtime | 66,057 | Address TODO to switch to generated p/invoke | Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | elinor-fung | 2022-03-02T03:31:28Z | 2022-03-02T19:08:30Z | a4b8893a118357b55c0add9a39cc5aeb097a0bb8 | 1abbbb4adf6bf02549f4c6e021176534dcc4f974 | Address TODO to switch to generated p/invoke. Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | ./src/libraries/Common/src/Interop/Windows/Kernel32/Interop.CreateToolhelp32Snapshot.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 Kernel32
{
[Flags]
internal enum SnapshotFlags : uint
{
HeapList = 0x00000001,
Process = 0x00000002,
Thread = 0x00000004,
Module = 0x00000008,
Module32 = 0x00000010,
All = (HeapList | Process | Thread | Module),
Inherit = 0x80000000,
NoHeaps = 0x40000000
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
internal struct PROCESSENTRY32
{
internal int dwSize;
internal int cntUsage;
internal int th32ProcessID;
internal IntPtr th32DefaultHeapID;
internal int th32ModuleID;
internal int cntThreads;
internal int th32ParentProcessID;
internal int pcPriClassBase;
internal int dwFlags;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAX_PATH)]
internal string szExeFile;
}
// https://docs.microsoft.com/windows/desktop/api/tlhelp32/nf-tlhelp32-createtoolhelp32snapshot
[GeneratedDllImport(Libraries.Kernel32, SetLastError = true)]
internal static partial IntPtr CreateToolhelp32Snapshot(SnapshotFlags dwFlags, uint th32ProcessID);
#pragma warning disable DLLIMPORTGENANALYZER015 // Use 'GeneratedDllImportAttribute' instead of 'DllImportAttribute' to generate P/Invoke marshalling code at compile time
// TODO: [DllImportGenerator] Switch to use GeneratedDllImport once we support non-blittable types.
// https://docs.microsoft.com/windows/desktop/api/tlhelp32/nf-tlhelp32-process32first
[DllImport(Libraries.Kernel32, SetLastError = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
internal static extern bool Process32First(IntPtr hSnapshot, ref PROCESSENTRY32 lppe);
// https://docs.microsoft.com/windows/desktop/api/tlhelp32/nf-tlhelp32-process32next
[DllImport(Libraries.Kernel32, SetLastError = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
internal static extern bool Process32Next(IntPtr hSnapshot, ref PROCESSENTRY32 lppe);
#pragma warning restore DLLIMPORTGENANALYZER015
}
}
| // 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 Kernel32
{
[Flags]
internal enum SnapshotFlags : uint
{
HeapList = 0x00000001,
Process = 0x00000002,
Thread = 0x00000004,
Module = 0x00000008,
Module32 = 0x00000010,
All = (HeapList | Process | Thread | Module),
Inherit = 0x80000000,
NoHeaps = 0x40000000
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal unsafe struct PROCESSENTRY32
{
internal int dwSize;
internal int cntUsage;
internal int th32ProcessID;
internal IntPtr th32DefaultHeapID;
internal int th32ModuleID;
internal int cntThreads;
internal int th32ParentProcessID;
internal int pcPriClassBase;
internal int dwFlags;
internal fixed char szExeFile[MAX_PATH];
}
// https://docs.microsoft.com/windows/desktop/api/tlhelp32/nf-tlhelp32-createtoolhelp32snapshot
[GeneratedDllImport(Libraries.Kernel32, SetLastError = true)]
internal static partial IntPtr CreateToolhelp32Snapshot(SnapshotFlags dwFlags, uint th32ProcessID);
// https://docs.microsoft.com/windows/desktop/api/tlhelp32/nf-tlhelp32-process32first
[GeneratedDllImport(Libraries.Kernel32, EntryPoint = "Process32FirstW", SetLastError = true)]
internal static partial bool Process32First(IntPtr hSnapshot, ref PROCESSENTRY32 lppe);
// https://docs.microsoft.com/windows/desktop/api/tlhelp32/nf-tlhelp32-process32next
[GeneratedDllImport(Libraries.Kernel32, EntryPoint = "Process32NextW", SetLastError = true)]
internal static partial bool Process32Next(IntPtr hSnapshot, ref PROCESSENTRY32 lppe);
}
}
| 1 |
dotnet/runtime | 66,057 | Address TODO to switch to generated p/invoke | Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | elinor-fung | 2022-03-02T03:31:28Z | 2022-03-02T19:08:30Z | a4b8893a118357b55c0add9a39cc5aeb097a0bb8 | 1abbbb4adf6bf02549f4c6e021176534dcc4f974 | Address TODO to switch to generated p/invoke. Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | ./src/libraries/Microsoft.Extensions.Hosting.WindowsServices/src/Microsoft.Extensions.Hosting.WindowsServices.csproj | <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>$(NetCoreAppCurrent);$(NetCoreAppMinimum);netstandard2.1;netstandard2.0;$(NetFrameworkMinimum)</TargetFrameworks>
<EnableDefaultItems>true</EnableDefaultItems>
<!-- Use targeting pack references instead of granular ones in the project file. -->
<DisableImplicitAssemblyReferences>false</DisableImplicitAssemblyReferences>
<IsPackable>true</IsPackable>
<PackageDescription>.NET hosting infrastructure for Windows Services.</PackageDescription>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<EnableDllImportGenerator>true</EnableDllImportGenerator>
</PropertyGroup>
<ItemGroup>
<Compile Include="$(CommonPath)Interop\Windows\Interop.Libraries.cs"
Link="Common\Interop\Windows\Interop.Libraries.cs" />
<Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.CloseHandle.cs"
Link="Common\Interop\Windows\Kernel32\Interop.CloseHandle.cs" />
<Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.CreateToolhelp32Snapshot.cs"
Link="Common\Interop\Windows\Kernel32\Interop.CreateToolhelp32Snapshot.cs" />
<Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.MAX_PATH.cs"
Link="Common\Interop\Windows\Kernel32\Interop.MAX_PATH.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="$(LibrariesProjectRoot)Microsoft.Extensions.Hosting\src\Microsoft.Extensions.Hosting.csproj" />
<ProjectReference Include="$(LibrariesProjectRoot)Microsoft.Extensions.Logging.EventLog\src\Microsoft.Extensions.Logging.EventLog.csproj" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFrameworkIdentifier)' != '.NETFramework'">
<ProjectReference Include="$(LibrariesProjectRoot)System.ServiceProcess.ServiceController\src\System.ServiceProcess.ServiceController.csproj" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFrameworkIdentifier)' == '.NETFramework'">
<Reference Include="System.ServiceProcess" />
</ItemGroup>
</Project>
| <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>$(NetCoreAppCurrent);$(NetCoreAppMinimum);netstandard2.1;netstandard2.0;$(NetFrameworkMinimum)</TargetFrameworks>
<EnableDefaultItems>true</EnableDefaultItems>
<!-- Use targeting pack references instead of granular ones in the project file. -->
<DisableImplicitAssemblyReferences>false</DisableImplicitAssemblyReferences>
<IsPackable>true</IsPackable>
<PackageDescription>.NET hosting infrastructure for Windows Services.</PackageDescription>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<EnableDllImportGenerator>true</EnableDllImportGenerator>
</PropertyGroup>
<ItemGroup>
<Compile Include="$(CommonPath)DisableRuntimeMarshalling.cs"
Link="Common\DisableRuntimeMarshalling.cs"
Condition="$([MSBuild]::IsTargetFrameworkCompatible('$(TargetFramework)', 'net7.0'))" />
<Compile Include="$(CommonPath)Interop\Windows\Interop.Libraries.cs"
Link="Common\Interop\Windows\Interop.Libraries.cs" />
<Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.CloseHandle.cs"
Link="Common\Interop\Windows\Kernel32\Interop.CloseHandle.cs" />
<Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.CreateToolhelp32Snapshot.cs"
Link="Common\Interop\Windows\Kernel32\Interop.CreateToolhelp32Snapshot.cs" />
<Compile Include="$(CommonPath)Interop\Windows\Kernel32\Interop.MAX_PATH.cs"
Link="Common\Interop\Windows\Kernel32\Interop.MAX_PATH.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="$(LibrariesProjectRoot)Microsoft.Extensions.Hosting\src\Microsoft.Extensions.Hosting.csproj" />
<ProjectReference Include="$(LibrariesProjectRoot)Microsoft.Extensions.Logging.EventLog\src\Microsoft.Extensions.Logging.EventLog.csproj" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFrameworkIdentifier)' != '.NETFramework'">
<ProjectReference Include="$(LibrariesProjectRoot)System.ServiceProcess.ServiceController\src\System.ServiceProcess.ServiceController.csproj" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFrameworkIdentifier)' == '.NETFramework'">
<Reference Include="System.ServiceProcess" />
</ItemGroup>
</Project>
| 1 |
dotnet/runtime | 66,057 | Address TODO to switch to generated p/invoke | Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | elinor-fung | 2022-03-02T03:31:28Z | 2022-03-02T19:08:30Z | a4b8893a118357b55c0add9a39cc5aeb097a0bb8 | 1abbbb4adf6bf02549f4c6e021176534dcc4f974 | Address TODO to switch to generated p/invoke. Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | ./src/libraries/System.ServiceProcess.ServiceController/tests/System.ServiceProcess.ServiceController.TestService/System.ServiceProcess.ServiceController.TestService.csproj | <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<OutputType>Exe</OutputType>
<TargetFrameworks>$(NetCoreAppCurrent);$(NetFrameworkMinimum)</TargetFrameworks>
<Nullable>annotations</Nullable>
<EnableDllImportGenerator>true</EnableDllImportGenerator>
</PropertyGroup>
<ItemGroup>
<Compile Include="Helpers.cs" />
<Compile Include="Program.cs" />
<Compile Include="TestServiceInstaller.cs" />
<Compile Include="TestService.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="..\..\src\Microsoft\Win32\SafeHandles\SafeServiceHandle.cs"
Link="Microsoft\Win32\SafeHandles\SafeServiceHandle.cs" />
<Compile Include="$(CommonPath)DisableRuntimeMarshalling.cs"
Link="Common\DisableRuntimeMarshalling.cs"
Condition="'$(TargetFrameworkIdentifier)' == '.NETCoreApp'" />
<Compile Include="$(CommonPath)Interop\Windows\Interop.Libraries.cs"
Link="Common\Interop\Windows\Interop.Libraries.cs" />
<Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.ServiceProcessOptions.cs"
Link="Common\Interop\Windows\Interop.ServiceProcessOptions.cs" />
<Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.CloseServiceHandle.cs"
Link="Common\Interop\Windows\Interop.CloseServiceHandle.cs" />
<Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.OpenSCManager.cs"
Link="Common\Interop\Windows\Interop.OpenSCManager.cs" />
<Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.OpenService.cs"
Link="Common\Interop\Windows\Interop.OpenService.cs" />
<Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.CreateService.cs"
Link="Common\Interop\Windows\Interop.CreateService.cs" />
<Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.SERVICE_DESCRIPTION.cs"
Link="Common\Interop\Windows\Interop.SERVICE_DESCRIPTION.cs" />
<Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.ChangeServiceConfig2.cs"
Link="Common\Interop\Windows\Interop.ChangeServiceConfig2.cs" />
<Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.SERVICE_DELAYED_AUTOSTART_INFO.cs"
Link="Common\Interop\Windows\Interop.SERVICE_DELAYED_AUTOSTART_INFO.cs" />
<Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.DeleteService.cs"
Link="Common\Interop\Windows\Interop.DeleteService.cs" />
<Compile Include="$(CommonTestPath)System\Threading\Tasks\TaskTimeoutExtensions.cs"
Link="Common\System\Threading\Tasks\TaskTimeoutExtensions.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\System.ServiceProcess.ServiceController.csproj" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFrameworkIdentifier)' == '.NETFramework'">
<Reference Include="System.ServiceProcess" />
</ItemGroup>
</Project>
| <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<OutputType>Exe</OutputType>
<TargetFrameworks>$(NetCoreAppCurrent);$(NetFrameworkMinimum)</TargetFrameworks>
<Nullable>annotations</Nullable>
<EnableDllImportGenerator>true</EnableDllImportGenerator>
</PropertyGroup>
<ItemGroup>
<Compile Include="Helpers.cs" />
<Compile Include="Program.cs" />
<Compile Include="TestServiceInstaller.cs" />
<Compile Include="TestService.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="..\..\src\Microsoft\Win32\SafeHandles\SafeServiceHandle.cs"
Link="Microsoft\Win32\SafeHandles\SafeServiceHandle.cs" />
<Compile Include="$(CommonPath)DisableRuntimeMarshalling.cs"
Link="Common\DisableRuntimeMarshalling.cs"
Condition="'$(TargetFrameworkIdentifier)' == '.NETCoreApp'" />
<Compile Include="$(CommonPath)Interop\Windows\Interop.Libraries.cs"
Link="Common\Interop\Windows\Interop.Libraries.cs" />
<Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.ServiceProcessOptions.cs"
Link="Common\Interop\Windows\Interop.ServiceProcessOptions.cs" />
<Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.CloseServiceHandle.cs"
Link="Common\Interop\Windows\Interop.CloseServiceHandle.cs" />
<Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.OpenSCManager.cs"
Link="Common\Interop\Windows\Interop.OpenSCManager.cs" />
<Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.OpenService.cs"
Link="Common\Interop\Windows\Interop.OpenService.cs" />
<Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.CreateService.cs"
Link="Common\Interop\Windows\Interop.CreateService.cs" />
<Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.SERVICE_DESCRIPTION.cs"
Link="Common\Interop\Windows\Interop.SERVICE_DESCRIPTION.cs" />
<Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.ChangeServiceConfig2.cs"
Link="Common\Interop\Windows\Interop.ChangeServiceConfig2.cs" />
<Compile Include="$(CommonPath)Interop\Windows\Advapi32\Interop.DeleteService.cs"
Link="Common\Interop\Windows\Interop.DeleteService.cs" />
<Compile Include="$(CommonTestPath)System\Threading\Tasks\TaskTimeoutExtensions.cs"
Link="Common\System\Threading\Tasks\TaskTimeoutExtensions.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\System.ServiceProcess.ServiceController.csproj" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFrameworkIdentifier)' == '.NETFramework'">
<Reference Include="System.ServiceProcess" />
</ItemGroup>
</Project>
| 1 |
dotnet/runtime | 66,057 | Address TODO to switch to generated p/invoke | Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | elinor-fung | 2022-03-02T03:31:28Z | 2022-03-02T19:08:30Z | a4b8893a118357b55c0add9a39cc5aeb097a0bb8 | 1abbbb4adf6bf02549f4c6e021176534dcc4f974 | Address TODO to switch to generated p/invoke. Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | ./src/libraries/System.Data.Common/src/System/Data/Common/DbProviderSpecificTypePropertyAttribute.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.Data.Common
{
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class DbProviderSpecificTypePropertyAttribute : System.Attribute
{
public DbProviderSpecificTypePropertyAttribute(bool isProviderSpecificTypeProperty)
{
IsProviderSpecificTypeProperty = isProviderSpecificTypeProperty;
}
public bool IsProviderSpecificTypeProperty { get; }
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace System.Data.Common
{
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class DbProviderSpecificTypePropertyAttribute : System.Attribute
{
public DbProviderSpecificTypePropertyAttribute(bool isProviderSpecificTypeProperty)
{
IsProviderSpecificTypeProperty = isProviderSpecificTypeProperty;
}
public bool IsProviderSpecificTypeProperty { get; }
}
}
| -1 |
dotnet/runtime | 66,057 | Address TODO to switch to generated p/invoke | Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | elinor-fung | 2022-03-02T03:31:28Z | 2022-03-02T19:08:30Z | a4b8893a118357b55c0add9a39cc5aeb097a0bb8 | 1abbbb4adf6bf02549f4c6e021176534dcc4f974 | Address TODO to switch to generated p/invoke. Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | ./src/tests/baseservices/threading/generics/WaitCallback/thread08.csproj | <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<ItemGroup>
<Compile Include="thread08.cs" />
</ItemGroup>
</Project>
| <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<ItemGroup>
<Compile Include="thread08.cs" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime | 66,057 | Address TODO to switch to generated p/invoke | Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | elinor-fung | 2022-03-02T03:31:28Z | 2022-03-02T19:08:30Z | a4b8893a118357b55c0add9a39cc5aeb097a0bb8 | 1abbbb4adf6bf02549f4c6e021176534dcc4f974 | Address TODO to switch to generated p/invoke. Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | ./src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/StorePal.Android.LoaderPal.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics;
using System.Threading;
using Internal.Cryptography;
using Microsoft.Win32.SafeHandles;
namespace System.Security.Cryptography.X509Certificates
{
internal sealed partial class StorePal
{
private sealed class AndroidCertLoader : ILoaderPal
{
private ICertificatePal[]? _certs;
public AndroidCertLoader(SafeX509Handle[] certHandles)
{
_certs = new ICertificatePal[certHandles.Length];
for (int i = 0; i < certHandles.Length; i++)
{
SafeX509Handle handle = certHandles[i];
Debug.Assert(!handle.IsInvalid);
_certs[i] = AndroidCertificatePal.FromHandle(handle.DangerousGetHandle());
}
}
public AndroidCertLoader(ICertificatePal[] certs)
{
_certs = certs;
}
public void Dispose()
{
if (_certs != null)
_certs.DisposeAll();
}
public void MoveTo(X509Certificate2Collection collection)
{
ICertificatePal[]? certs = Interlocked.Exchange(ref _certs, null);
Debug.Assert(certs != null);
foreach (ICertificatePal cert in certs)
{
collection.Add(new X509Certificate2(cert));
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics;
using System.Threading;
using Internal.Cryptography;
using Microsoft.Win32.SafeHandles;
namespace System.Security.Cryptography.X509Certificates
{
internal sealed partial class StorePal
{
private sealed class AndroidCertLoader : ILoaderPal
{
private ICertificatePal[]? _certs;
public AndroidCertLoader(SafeX509Handle[] certHandles)
{
_certs = new ICertificatePal[certHandles.Length];
for (int i = 0; i < certHandles.Length; i++)
{
SafeX509Handle handle = certHandles[i];
Debug.Assert(!handle.IsInvalid);
_certs[i] = AndroidCertificatePal.FromHandle(handle.DangerousGetHandle());
}
}
public AndroidCertLoader(ICertificatePal[] certs)
{
_certs = certs;
}
public void Dispose()
{
if (_certs != null)
_certs.DisposeAll();
}
public void MoveTo(X509Certificate2Collection collection)
{
ICertificatePal[]? certs = Interlocked.Exchange(ref _certs, null);
Debug.Assert(certs != null);
foreach (ICertificatePal cert in certs)
{
collection.Add(new X509Certificate2(cert));
}
}
}
}
}
| -1 |
dotnet/runtime | 66,057 | Address TODO to switch to generated p/invoke | Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | elinor-fung | 2022-03-02T03:31:28Z | 2022-03-02T19:08:30Z | a4b8893a118357b55c0add9a39cc5aeb097a0bb8 | 1abbbb4adf6bf02549f4c6e021176534dcc4f974 | Address TODO to switch to generated p/invoke. Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | ./src/libraries/System.Text.Json/tests/System.Text.Json.Tests/TrimmingTests/Helper.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace SerializerTrimmingTest
{
internal static class TestHelper
{
/// <summary>
/// Used when comparing JSON payloads with more than two properties.
/// We cannot check for string equality since property ordering depends
/// on reflection ordering which is not guaranteed.
/// </summary>
public static bool JsonEqual(string expected, string actual)
{
using JsonDocument expectedDom = JsonDocument.Parse(expected);
using JsonDocument actualDom = JsonDocument.Parse(actual);
return JsonEqual(expectedDom.RootElement, actualDom.RootElement);
}
private static bool JsonEqual(JsonElement expected, JsonElement actual)
{
JsonValueKind valueKind = expected.ValueKind;
if (valueKind != actual.ValueKind)
{
return false;
}
switch (valueKind)
{
case JsonValueKind.Object:
var propertyNames = new HashSet<string>();
foreach (JsonProperty property in expected.EnumerateObject())
{
propertyNames.Add(property.Name);
}
foreach (JsonProperty property in actual.EnumerateObject())
{
propertyNames.Add(property.Name);
}
foreach (string name in propertyNames)
{
if (!JsonEqual(expected.GetProperty(name), actual.GetProperty(name)))
{
return false;
}
}
return true;
case JsonValueKind.Array:
JsonElement.ArrayEnumerator expectedEnumerator = actual.EnumerateArray();
JsonElement.ArrayEnumerator actualEnumerator = expected.EnumerateArray();
while (expectedEnumerator.MoveNext())
{
if (!actualEnumerator.MoveNext())
{
return false;
}
if (!JsonEqual(expectedEnumerator.Current, actualEnumerator.Current))
{
return false;
}
}
return !actualEnumerator.MoveNext();
case JsonValueKind.String:
return expected.GetString() == actual.GetString();
case JsonValueKind.Number:
case JsonValueKind.True:
case JsonValueKind.False:
case JsonValueKind.Null:
return expected.GetRawText() == actual.GetRawText();
default:
throw new NotSupportedException($"Unexpected JsonValueKind: JsonValueKind.{valueKind}.");
}
}
public static bool AssertCollectionAndSerialize<T>(object obj, string json)
{
return obj is T && JsonSerializer.Serialize(obj) == json;
}
}
public class MyClass
{
public int X { get; set; }
[JsonInclude]
public int Y;
}
internal struct MyStruct
{
public int X { get; }
[JsonInclude]
public int Y;
[JsonConstructor]
public MyStruct(int x, int y) => (X, Y) = (x, y);
}
internal class MyClassWithParameterizedCtor
{
public int X { get; set; }
[JsonInclude]
public int Y;
public MyClassWithParameterizedCtor(int x, int y) => (X, Y) = (x, y);
}
internal class MyBigClass
{
public string A { get; }
[JsonInclude]
public string B;
public string C { get; }
[JsonInclude]
public int One;
public int Two { get; }
[JsonInclude]
public int Three;
public MyBigClass(string a, string b, string c, int one, int two, int three)
{
A = a;
B = b;
C = c;
One = one;
Two = two;
Three = three;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace SerializerTrimmingTest
{
internal static class TestHelper
{
/// <summary>
/// Used when comparing JSON payloads with more than two properties.
/// We cannot check for string equality since property ordering depends
/// on reflection ordering which is not guaranteed.
/// </summary>
public static bool JsonEqual(string expected, string actual)
{
using JsonDocument expectedDom = JsonDocument.Parse(expected);
using JsonDocument actualDom = JsonDocument.Parse(actual);
return JsonEqual(expectedDom.RootElement, actualDom.RootElement);
}
private static bool JsonEqual(JsonElement expected, JsonElement actual)
{
JsonValueKind valueKind = expected.ValueKind;
if (valueKind != actual.ValueKind)
{
return false;
}
switch (valueKind)
{
case JsonValueKind.Object:
var propertyNames = new HashSet<string>();
foreach (JsonProperty property in expected.EnumerateObject())
{
propertyNames.Add(property.Name);
}
foreach (JsonProperty property in actual.EnumerateObject())
{
propertyNames.Add(property.Name);
}
foreach (string name in propertyNames)
{
if (!JsonEqual(expected.GetProperty(name), actual.GetProperty(name)))
{
return false;
}
}
return true;
case JsonValueKind.Array:
JsonElement.ArrayEnumerator expectedEnumerator = actual.EnumerateArray();
JsonElement.ArrayEnumerator actualEnumerator = expected.EnumerateArray();
while (expectedEnumerator.MoveNext())
{
if (!actualEnumerator.MoveNext())
{
return false;
}
if (!JsonEqual(expectedEnumerator.Current, actualEnumerator.Current))
{
return false;
}
}
return !actualEnumerator.MoveNext();
case JsonValueKind.String:
return expected.GetString() == actual.GetString();
case JsonValueKind.Number:
case JsonValueKind.True:
case JsonValueKind.False:
case JsonValueKind.Null:
return expected.GetRawText() == actual.GetRawText();
default:
throw new NotSupportedException($"Unexpected JsonValueKind: JsonValueKind.{valueKind}.");
}
}
public static bool AssertCollectionAndSerialize<T>(object obj, string json)
{
return obj is T && JsonSerializer.Serialize(obj) == json;
}
}
public class MyClass
{
public int X { get; set; }
[JsonInclude]
public int Y;
}
internal struct MyStruct
{
public int X { get; }
[JsonInclude]
public int Y;
[JsonConstructor]
public MyStruct(int x, int y) => (X, Y) = (x, y);
}
internal class MyClassWithParameterizedCtor
{
public int X { get; set; }
[JsonInclude]
public int Y;
public MyClassWithParameterizedCtor(int x, int y) => (X, Y) = (x, y);
}
internal class MyBigClass
{
public string A { get; }
[JsonInclude]
public string B;
public string C { get; }
[JsonInclude]
public int One;
public int Two { get; }
[JsonInclude]
public int Three;
public MyBigClass(string a, string b, string c, int one, int two, int three)
{
A = a;
B = b;
C = c;
One = one;
Two = two;
Three = three;
}
}
}
| -1 |
dotnet/runtime | 66,057 | Address TODO to switch to generated p/invoke | Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | elinor-fung | 2022-03-02T03:31:28Z | 2022-03-02T19:08:30Z | a4b8893a118357b55c0add9a39cc5aeb097a0bb8 | 1abbbb4adf6bf02549f4c6e021176534dcc4f974 | Address TODO to switch to generated p/invoke. Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | ./src/tests/nativeaot/SmokeTests/Dataflow/Dataflow.csproj | <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<CLRTestKind>BuildAndRun</CLRTestKind>
<CLRTestPriority>0</CLRTestPriority>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<!-- We don't run the scanner in optimized builds -->
<CLRTestTargetUnsupported Condition="'$(IlcMultiModule)' == 'true'">true</CLRTestTargetUnsupported>
</PropertyGroup>
<ItemGroup>
<Compile Include="Dataflow.cs" />
</ItemGroup>
</Project>
| <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<CLRTestKind>BuildAndRun</CLRTestKind>
<CLRTestPriority>0</CLRTestPriority>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<!-- We don't run the scanner in optimized builds -->
<CLRTestTargetUnsupported Condition="'$(IlcMultiModule)' == 'true'">true</CLRTestTargetUnsupported>
</PropertyGroup>
<ItemGroup>
<Compile Include="Dataflow.cs" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime | 66,057 | Address TODO to switch to generated p/invoke | Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | elinor-fung | 2022-03-02T03:31:28Z | 2022-03-02T19:08:30Z | a4b8893a118357b55c0add9a39cc5aeb097a0bb8 | 1abbbb4adf6bf02549f4c6e021176534dcc4f974 | Address TODO to switch to generated p/invoke. Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | ./src/tests/JIT/HardwareIntrinsics/Arm/AdvSimd/ShiftRightLogical.Vector128.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.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void ShiftRightLogical_Vector128_Int64_1()
{
var test = new ImmUnaryOpTest__ShiftRightLogical_Vector128_Int64_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_Vector128_Int64_1
{
private struct DataTable
{
private byte[] inArray;
private byte[] outArray;
private GCHandle inHandle;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int64[] inArray, Int64[] outArray, int alignment)
{
int sizeOfinArray = inArray.Length * Unsafe.SizeOf<Int64>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int64>();
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<Int64, 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 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(ImmUnaryOpTest__ShiftRightLogical_Vector128_Int64_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_Vector128_Int64_1 testClass)
{
fixed (Vector128<Int64>* pFld = &_fld)
{
var result = AdvSimd.ShiftRightLogical(
AdvSimd.LoadVector128((Int64*)(pFld)),
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 readonly byte Imm = 1;
private static Int64[] _data = new Int64[Op1ElementCount];
private static Vector128<Int64> _clsVar;
private Vector128<Int64> _fld;
private DataTable _dataTable;
static ImmUnaryOpTest__ShiftRightLogical_Vector128_Int64_1()
{
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 ImmUnaryOpTest__ShiftRightLogical_Vector128_Int64_1()
{
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 DataTable(_data, new Int64[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<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 = AdvSimd.ShiftRightLogical(
AdvSimd.LoadVector128((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(AdvSimd).GetMethod(nameof(AdvSimd.ShiftRightLogical), new Type[] { typeof(Vector128<Int64>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int64>>(_dataTable.inArrayPtr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(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(Vector128<Int64>), typeof(byte) })
.Invoke(null, new object[] {
AdvSimd.LoadVector128((Int64*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(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 (Vector128<Int64>* pClsVar = &_clsVar)
{
var result = AdvSimd.ShiftRightLogical(
AdvSimd.LoadVector128((Int64*)(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<Vector128<Int64>>(_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.LoadVector128((Int64*)(_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_Vector128_Int64_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_Vector128_Int64_1();
fixed (Vector128<Int64>* pFld = &test._fld)
{
var result = AdvSimd.ShiftRightLogical(
AdvSimd.LoadVector128((Int64*)(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 (Vector128<Int64>* pFld = &_fld)
{
var result = AdvSimd.ShiftRightLogical(
AdvSimd.LoadVector128((Int64*)(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.LoadVector128((Int64*)(&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(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;
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)}<Int64>(Vector128<Int64>, 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_Vector128_Int64_1()
{
var test = new ImmUnaryOpTest__ShiftRightLogical_Vector128_Int64_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_Vector128_Int64_1
{
private struct DataTable
{
private byte[] inArray;
private byte[] outArray;
private GCHandle inHandle;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int64[] inArray, Int64[] outArray, int alignment)
{
int sizeOfinArray = inArray.Length * Unsafe.SizeOf<Int64>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int64>();
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<Int64, 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 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(ImmUnaryOpTest__ShiftRightLogical_Vector128_Int64_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_Vector128_Int64_1 testClass)
{
fixed (Vector128<Int64>* pFld = &_fld)
{
var result = AdvSimd.ShiftRightLogical(
AdvSimd.LoadVector128((Int64*)(pFld)),
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 readonly byte Imm = 1;
private static Int64[] _data = new Int64[Op1ElementCount];
private static Vector128<Int64> _clsVar;
private Vector128<Int64> _fld;
private DataTable _dataTable;
static ImmUnaryOpTest__ShiftRightLogical_Vector128_Int64_1()
{
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 ImmUnaryOpTest__ShiftRightLogical_Vector128_Int64_1()
{
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 DataTable(_data, new Int64[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<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 = AdvSimd.ShiftRightLogical(
AdvSimd.LoadVector128((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(AdvSimd).GetMethod(nameof(AdvSimd.ShiftRightLogical), new Type[] { typeof(Vector128<Int64>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int64>>(_dataTable.inArrayPtr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(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(Vector128<Int64>), typeof(byte) })
.Invoke(null, new object[] {
AdvSimd.LoadVector128((Int64*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(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 (Vector128<Int64>* pClsVar = &_clsVar)
{
var result = AdvSimd.ShiftRightLogical(
AdvSimd.LoadVector128((Int64*)(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<Vector128<Int64>>(_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.LoadVector128((Int64*)(_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_Vector128_Int64_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_Vector128_Int64_1();
fixed (Vector128<Int64>* pFld = &test._fld)
{
var result = AdvSimd.ShiftRightLogical(
AdvSimd.LoadVector128((Int64*)(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 (Vector128<Int64>* pFld = &_fld)
{
var result = AdvSimd.ShiftRightLogical(
AdvSimd.LoadVector128((Int64*)(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.LoadVector128((Int64*)(&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(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;
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)}<Int64>(Vector128<Int64>, 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,057 | Address TODO to switch to generated p/invoke | Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | elinor-fung | 2022-03-02T03:31:28Z | 2022-03-02T19:08:30Z | a4b8893a118357b55c0add9a39cc5aeb097a0bb8 | 1abbbb4adf6bf02549f4c6e021176534dcc4f974 | Address TODO to switch to generated p/invoke. Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | ./src/coreclr/tools/Common/Internal/Metadata/NativeFormat/MdBinaryReaderGen.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// NOTE: This is a generated file - do not manually edit!
#pragma warning disable 649
using System;
using System.IO;
using System.Collections.Generic;
using System.Reflection;
using Internal.NativeFormat;
using Debug = System.Diagnostics.Debug;
namespace Internal.Metadata.NativeFormat
{
internal static partial class MdBinaryReader
{
public static unsafe uint Read(this NativeReader reader, uint offset, out BooleanCollection values)
{
values = new BooleanCollection(reader, offset);
uint count;
offset = reader.DecodeUnsigned(offset, out count);
offset = checked(offset + count * sizeof(bool));
return offset;
} // Read
public static unsafe uint Read(this NativeReader reader, uint offset, out CharCollection values)
{
values = new CharCollection(reader, offset);
uint count;
offset = reader.DecodeUnsigned(offset, out count);
offset = checked(offset + count * sizeof(char));
return offset;
} // Read
public static unsafe uint Read(this NativeReader reader, uint offset, out ByteCollection values)
{
values = new ByteCollection(reader, offset);
uint count;
offset = reader.DecodeUnsigned(offset, out count);
offset = checked(offset + count * sizeof(byte));
return offset;
} // Read
public static unsafe uint Read(this NativeReader reader, uint offset, out SByteCollection values)
{
values = new SByteCollection(reader, offset);
uint count;
offset = reader.DecodeUnsigned(offset, out count);
offset = checked(offset + count * sizeof(sbyte));
return offset;
} // Read
public static unsafe uint Read(this NativeReader reader, uint offset, out Int16Collection values)
{
values = new Int16Collection(reader, offset);
uint count;
offset = reader.DecodeUnsigned(offset, out count);
offset = checked(offset + count * sizeof(short));
return offset;
} // Read
public static unsafe uint Read(this NativeReader reader, uint offset, out UInt16Collection values)
{
values = new UInt16Collection(reader, offset);
uint count;
offset = reader.DecodeUnsigned(offset, out count);
offset = checked(offset + count * sizeof(ushort));
return offset;
} // Read
public static unsafe uint Read(this NativeReader reader, uint offset, out Int32Collection values)
{
values = new Int32Collection(reader, offset);
uint count;
offset = reader.DecodeUnsigned(offset, out count);
offset = checked(offset + count * sizeof(int));
return offset;
} // Read
public static unsafe uint Read(this NativeReader reader, uint offset, out UInt32Collection values)
{
values = new UInt32Collection(reader, offset);
uint count;
offset = reader.DecodeUnsigned(offset, out count);
offset = checked(offset + count * sizeof(uint));
return offset;
} // Read
public static unsafe uint Read(this NativeReader reader, uint offset, out Int64Collection values)
{
values = new Int64Collection(reader, offset);
uint count;
offset = reader.DecodeUnsigned(offset, out count);
offset = checked(offset + count * sizeof(long));
return offset;
} // Read
public static unsafe uint Read(this NativeReader reader, uint offset, out UInt64Collection values)
{
values = new UInt64Collection(reader, offset);
uint count;
offset = reader.DecodeUnsigned(offset, out count);
offset = checked(offset + count * sizeof(ulong));
return offset;
} // Read
public static unsafe uint Read(this NativeReader reader, uint offset, out SingleCollection values)
{
values = new SingleCollection(reader, offset);
uint count;
offset = reader.DecodeUnsigned(offset, out count);
offset = checked(offset + count * sizeof(float));
return offset;
} // Read
public static unsafe uint Read(this NativeReader reader, uint offset, out DoubleCollection values)
{
values = new DoubleCollection(reader, offset);
uint count;
offset = reader.DecodeUnsigned(offset, out count);
offset = checked(offset + count * sizeof(double));
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out AssemblyFlags value)
{
uint ivalue;
offset = reader.DecodeUnsigned(offset, out ivalue);
value = (AssemblyFlags)ivalue;
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out AssemblyHashAlgorithm value)
{
uint ivalue;
offset = reader.DecodeUnsigned(offset, out ivalue);
value = (AssemblyHashAlgorithm)ivalue;
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out CallingConventions value)
{
uint ivalue;
offset = reader.DecodeUnsigned(offset, out ivalue);
value = (CallingConventions)ivalue;
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out EventAttributes value)
{
uint ivalue;
offset = reader.DecodeUnsigned(offset, out ivalue);
value = (EventAttributes)ivalue;
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out FieldAttributes value)
{
uint ivalue;
offset = reader.DecodeUnsigned(offset, out ivalue);
value = (FieldAttributes)ivalue;
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out GenericParameterAttributes value)
{
uint ivalue;
offset = reader.DecodeUnsigned(offset, out ivalue);
value = (GenericParameterAttributes)ivalue;
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out GenericParameterKind value)
{
uint ivalue;
offset = reader.DecodeUnsigned(offset, out ivalue);
value = (GenericParameterKind)ivalue;
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out MethodAttributes value)
{
uint ivalue;
offset = reader.DecodeUnsigned(offset, out ivalue);
value = (MethodAttributes)ivalue;
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out MethodImplAttributes value)
{
uint ivalue;
offset = reader.DecodeUnsigned(offset, out ivalue);
value = (MethodImplAttributes)ivalue;
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out MethodSemanticsAttributes value)
{
uint ivalue;
offset = reader.DecodeUnsigned(offset, out ivalue);
value = (MethodSemanticsAttributes)ivalue;
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out NamedArgumentMemberKind value)
{
uint ivalue;
offset = reader.DecodeUnsigned(offset, out ivalue);
value = (NamedArgumentMemberKind)ivalue;
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ParameterAttributes value)
{
uint ivalue;
offset = reader.DecodeUnsigned(offset, out ivalue);
value = (ParameterAttributes)ivalue;
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out PInvokeAttributes value)
{
uint ivalue;
offset = reader.DecodeUnsigned(offset, out ivalue);
value = (PInvokeAttributes)ivalue;
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out PropertyAttributes value)
{
uint ivalue;
offset = reader.DecodeUnsigned(offset, out ivalue);
value = (PropertyAttributes)ivalue;
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out TypeAttributes value)
{
uint ivalue;
offset = reader.DecodeUnsigned(offset, out ivalue);
value = (TypeAttributes)ivalue;
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out HandleCollection values)
{
values = new HandleCollection(reader, offset);
uint count;
offset = reader.DecodeUnsigned(offset, out count);
for (uint i = 0; i < count; ++i)
{
offset = reader.SkipInteger(offset);
}
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ArraySignatureHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ArraySignatureHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ByReferenceSignatureHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ByReferenceSignatureHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantBooleanArrayHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantBooleanArrayHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantBooleanValueHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantBooleanValueHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantBoxedEnumValueHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantBoxedEnumValueHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantByteArrayHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantByteArrayHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantByteValueHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantByteValueHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantCharArrayHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantCharArrayHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantCharValueHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantCharValueHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantDoubleArrayHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantDoubleArrayHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantDoubleValueHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantDoubleValueHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantEnumArrayHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantEnumArrayHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantHandleArrayHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantHandleArrayHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantInt16ArrayHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantInt16ArrayHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantInt16ValueHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantInt16ValueHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantInt32ArrayHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantInt32ArrayHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantInt32ValueHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantInt32ValueHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantInt64ArrayHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantInt64ArrayHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantInt64ValueHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantInt64ValueHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantReferenceValueHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantReferenceValueHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantSByteArrayHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantSByteArrayHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantSByteValueHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantSByteValueHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantSingleArrayHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantSingleArrayHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantSingleValueHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantSingleValueHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantStringArrayHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantStringArrayHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantStringValueHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantStringValueHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantUInt16ArrayHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantUInt16ArrayHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantUInt16ValueHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantUInt16ValueHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantUInt32ArrayHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantUInt32ArrayHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantUInt32ValueHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantUInt32ValueHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantUInt64ArrayHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantUInt64ArrayHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantUInt64ValueHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantUInt64ValueHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out CustomAttributeHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new CustomAttributeHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out EventHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new EventHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out FieldHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new FieldHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out FieldSignatureHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new FieldSignatureHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out FunctionPointerSignatureHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new FunctionPointerSignatureHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out GenericParameterHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new GenericParameterHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out MemberReferenceHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new MemberReferenceHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out MethodHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new MethodHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out MethodInstantiationHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new MethodInstantiationHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out MethodSemanticsHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new MethodSemanticsHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out MethodSignatureHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new MethodSignatureHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out MethodTypeVariableSignatureHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new MethodTypeVariableSignatureHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ModifiedTypeHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ModifiedTypeHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out NamedArgumentHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new NamedArgumentHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out NamespaceDefinitionHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new NamespaceDefinitionHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out NamespaceReferenceHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new NamespaceReferenceHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ParameterHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ParameterHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out PointerSignatureHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new PointerSignatureHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out PropertyHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new PropertyHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out PropertySignatureHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new PropertySignatureHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out QualifiedFieldHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new QualifiedFieldHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out QualifiedMethodHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new QualifiedMethodHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out SZArraySignatureHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new SZArraySignatureHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ScopeDefinitionHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ScopeDefinitionHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ScopeReferenceHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ScopeReferenceHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out TypeDefinitionHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new TypeDefinitionHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out TypeForwarderHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new TypeForwarderHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out TypeInstantiationSignatureHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new TypeInstantiationSignatureHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out TypeReferenceHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new TypeReferenceHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out TypeSpecificationHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new TypeSpecificationHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out TypeVariableSignatureHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new TypeVariableSignatureHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out NamedArgumentHandleCollection values)
{
values = new NamedArgumentHandleCollection(reader, offset);
uint count;
offset = reader.DecodeUnsigned(offset, out count);
for (uint i = 0; i < count; ++i)
{
offset = reader.SkipInteger(offset);
}
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out MethodSemanticsHandleCollection values)
{
values = new MethodSemanticsHandleCollection(reader, offset);
uint count;
offset = reader.DecodeUnsigned(offset, out count);
for (uint i = 0; i < count; ++i)
{
offset = reader.SkipInteger(offset);
}
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out CustomAttributeHandleCollection values)
{
values = new CustomAttributeHandleCollection(reader, offset);
uint count;
offset = reader.DecodeUnsigned(offset, out count);
for (uint i = 0; i < count; ++i)
{
offset = reader.SkipInteger(offset);
}
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ParameterHandleCollection values)
{
values = new ParameterHandleCollection(reader, offset);
uint count;
offset = reader.DecodeUnsigned(offset, out count);
for (uint i = 0; i < count; ++i)
{
offset = reader.SkipInteger(offset);
}
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out GenericParameterHandleCollection values)
{
values = new GenericParameterHandleCollection(reader, offset);
uint count;
offset = reader.DecodeUnsigned(offset, out count);
for (uint i = 0; i < count; ++i)
{
offset = reader.SkipInteger(offset);
}
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out TypeDefinitionHandleCollection values)
{
values = new TypeDefinitionHandleCollection(reader, offset);
uint count;
offset = reader.DecodeUnsigned(offset, out count);
for (uint i = 0; i < count; ++i)
{
offset = reader.SkipInteger(offset);
}
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out TypeForwarderHandleCollection values)
{
values = new TypeForwarderHandleCollection(reader, offset);
uint count;
offset = reader.DecodeUnsigned(offset, out count);
for (uint i = 0; i < count; ++i)
{
offset = reader.SkipInteger(offset);
}
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out NamespaceDefinitionHandleCollection values)
{
values = new NamespaceDefinitionHandleCollection(reader, offset);
uint count;
offset = reader.DecodeUnsigned(offset, out count);
for (uint i = 0; i < count; ++i)
{
offset = reader.SkipInteger(offset);
}
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out MethodHandleCollection values)
{
values = new MethodHandleCollection(reader, offset);
uint count;
offset = reader.DecodeUnsigned(offset, out count);
for (uint i = 0; i < count; ++i)
{
offset = reader.SkipInteger(offset);
}
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out FieldHandleCollection values)
{
values = new FieldHandleCollection(reader, offset);
uint count;
offset = reader.DecodeUnsigned(offset, out count);
for (uint i = 0; i < count; ++i)
{
offset = reader.SkipInteger(offset);
}
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out PropertyHandleCollection values)
{
values = new PropertyHandleCollection(reader, offset);
uint count;
offset = reader.DecodeUnsigned(offset, out count);
for (uint i = 0; i < count; ++i)
{
offset = reader.SkipInteger(offset);
}
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out EventHandleCollection values)
{
values = new EventHandleCollection(reader, offset);
uint count;
offset = reader.DecodeUnsigned(offset, out count);
for (uint i = 0; i < count; ++i)
{
offset = reader.SkipInteger(offset);
}
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ScopeDefinitionHandleCollection values)
{
values = new ScopeDefinitionHandleCollection(reader, offset);
uint count;
offset = reader.DecodeUnsigned(offset, out count);
for (uint i = 0; i < count; ++i)
{
offset = reader.SkipInteger(offset);
}
return offset;
} // Read
} // MdBinaryReader
} // Internal.Metadata.NativeFormat
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// NOTE: This is a generated file - do not manually edit!
#pragma warning disable 649
using System;
using System.IO;
using System.Collections.Generic;
using System.Reflection;
using Internal.NativeFormat;
using Debug = System.Diagnostics.Debug;
namespace Internal.Metadata.NativeFormat
{
internal static partial class MdBinaryReader
{
public static unsafe uint Read(this NativeReader reader, uint offset, out BooleanCollection values)
{
values = new BooleanCollection(reader, offset);
uint count;
offset = reader.DecodeUnsigned(offset, out count);
offset = checked(offset + count * sizeof(bool));
return offset;
} // Read
public static unsafe uint Read(this NativeReader reader, uint offset, out CharCollection values)
{
values = new CharCollection(reader, offset);
uint count;
offset = reader.DecodeUnsigned(offset, out count);
offset = checked(offset + count * sizeof(char));
return offset;
} // Read
public static unsafe uint Read(this NativeReader reader, uint offset, out ByteCollection values)
{
values = new ByteCollection(reader, offset);
uint count;
offset = reader.DecodeUnsigned(offset, out count);
offset = checked(offset + count * sizeof(byte));
return offset;
} // Read
public static unsafe uint Read(this NativeReader reader, uint offset, out SByteCollection values)
{
values = new SByteCollection(reader, offset);
uint count;
offset = reader.DecodeUnsigned(offset, out count);
offset = checked(offset + count * sizeof(sbyte));
return offset;
} // Read
public static unsafe uint Read(this NativeReader reader, uint offset, out Int16Collection values)
{
values = new Int16Collection(reader, offset);
uint count;
offset = reader.DecodeUnsigned(offset, out count);
offset = checked(offset + count * sizeof(short));
return offset;
} // Read
public static unsafe uint Read(this NativeReader reader, uint offset, out UInt16Collection values)
{
values = new UInt16Collection(reader, offset);
uint count;
offset = reader.DecodeUnsigned(offset, out count);
offset = checked(offset + count * sizeof(ushort));
return offset;
} // Read
public static unsafe uint Read(this NativeReader reader, uint offset, out Int32Collection values)
{
values = new Int32Collection(reader, offset);
uint count;
offset = reader.DecodeUnsigned(offset, out count);
offset = checked(offset + count * sizeof(int));
return offset;
} // Read
public static unsafe uint Read(this NativeReader reader, uint offset, out UInt32Collection values)
{
values = new UInt32Collection(reader, offset);
uint count;
offset = reader.DecodeUnsigned(offset, out count);
offset = checked(offset + count * sizeof(uint));
return offset;
} // Read
public static unsafe uint Read(this NativeReader reader, uint offset, out Int64Collection values)
{
values = new Int64Collection(reader, offset);
uint count;
offset = reader.DecodeUnsigned(offset, out count);
offset = checked(offset + count * sizeof(long));
return offset;
} // Read
public static unsafe uint Read(this NativeReader reader, uint offset, out UInt64Collection values)
{
values = new UInt64Collection(reader, offset);
uint count;
offset = reader.DecodeUnsigned(offset, out count);
offset = checked(offset + count * sizeof(ulong));
return offset;
} // Read
public static unsafe uint Read(this NativeReader reader, uint offset, out SingleCollection values)
{
values = new SingleCollection(reader, offset);
uint count;
offset = reader.DecodeUnsigned(offset, out count);
offset = checked(offset + count * sizeof(float));
return offset;
} // Read
public static unsafe uint Read(this NativeReader reader, uint offset, out DoubleCollection values)
{
values = new DoubleCollection(reader, offset);
uint count;
offset = reader.DecodeUnsigned(offset, out count);
offset = checked(offset + count * sizeof(double));
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out AssemblyFlags value)
{
uint ivalue;
offset = reader.DecodeUnsigned(offset, out ivalue);
value = (AssemblyFlags)ivalue;
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out AssemblyHashAlgorithm value)
{
uint ivalue;
offset = reader.DecodeUnsigned(offset, out ivalue);
value = (AssemblyHashAlgorithm)ivalue;
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out CallingConventions value)
{
uint ivalue;
offset = reader.DecodeUnsigned(offset, out ivalue);
value = (CallingConventions)ivalue;
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out EventAttributes value)
{
uint ivalue;
offset = reader.DecodeUnsigned(offset, out ivalue);
value = (EventAttributes)ivalue;
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out FieldAttributes value)
{
uint ivalue;
offset = reader.DecodeUnsigned(offset, out ivalue);
value = (FieldAttributes)ivalue;
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out GenericParameterAttributes value)
{
uint ivalue;
offset = reader.DecodeUnsigned(offset, out ivalue);
value = (GenericParameterAttributes)ivalue;
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out GenericParameterKind value)
{
uint ivalue;
offset = reader.DecodeUnsigned(offset, out ivalue);
value = (GenericParameterKind)ivalue;
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out MethodAttributes value)
{
uint ivalue;
offset = reader.DecodeUnsigned(offset, out ivalue);
value = (MethodAttributes)ivalue;
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out MethodImplAttributes value)
{
uint ivalue;
offset = reader.DecodeUnsigned(offset, out ivalue);
value = (MethodImplAttributes)ivalue;
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out MethodSemanticsAttributes value)
{
uint ivalue;
offset = reader.DecodeUnsigned(offset, out ivalue);
value = (MethodSemanticsAttributes)ivalue;
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out NamedArgumentMemberKind value)
{
uint ivalue;
offset = reader.DecodeUnsigned(offset, out ivalue);
value = (NamedArgumentMemberKind)ivalue;
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ParameterAttributes value)
{
uint ivalue;
offset = reader.DecodeUnsigned(offset, out ivalue);
value = (ParameterAttributes)ivalue;
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out PInvokeAttributes value)
{
uint ivalue;
offset = reader.DecodeUnsigned(offset, out ivalue);
value = (PInvokeAttributes)ivalue;
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out PropertyAttributes value)
{
uint ivalue;
offset = reader.DecodeUnsigned(offset, out ivalue);
value = (PropertyAttributes)ivalue;
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out TypeAttributes value)
{
uint ivalue;
offset = reader.DecodeUnsigned(offset, out ivalue);
value = (TypeAttributes)ivalue;
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out HandleCollection values)
{
values = new HandleCollection(reader, offset);
uint count;
offset = reader.DecodeUnsigned(offset, out count);
for (uint i = 0; i < count; ++i)
{
offset = reader.SkipInteger(offset);
}
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ArraySignatureHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ArraySignatureHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ByReferenceSignatureHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ByReferenceSignatureHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantBooleanArrayHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantBooleanArrayHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantBooleanValueHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantBooleanValueHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantBoxedEnumValueHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantBoxedEnumValueHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantByteArrayHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantByteArrayHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantByteValueHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantByteValueHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantCharArrayHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantCharArrayHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantCharValueHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantCharValueHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantDoubleArrayHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantDoubleArrayHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantDoubleValueHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantDoubleValueHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantEnumArrayHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantEnumArrayHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantHandleArrayHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantHandleArrayHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantInt16ArrayHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantInt16ArrayHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantInt16ValueHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantInt16ValueHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantInt32ArrayHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantInt32ArrayHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantInt32ValueHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantInt32ValueHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantInt64ArrayHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantInt64ArrayHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantInt64ValueHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantInt64ValueHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantReferenceValueHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantReferenceValueHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantSByteArrayHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantSByteArrayHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantSByteValueHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantSByteValueHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantSingleArrayHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantSingleArrayHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantSingleValueHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantSingleValueHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantStringArrayHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantStringArrayHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantStringValueHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantStringValueHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantUInt16ArrayHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantUInt16ArrayHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantUInt16ValueHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantUInt16ValueHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantUInt32ArrayHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantUInt32ArrayHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantUInt32ValueHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantUInt32ValueHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantUInt64ArrayHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantUInt64ArrayHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ConstantUInt64ValueHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ConstantUInt64ValueHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out CustomAttributeHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new CustomAttributeHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out EventHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new EventHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out FieldHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new FieldHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out FieldSignatureHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new FieldSignatureHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out FunctionPointerSignatureHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new FunctionPointerSignatureHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out GenericParameterHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new GenericParameterHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out MemberReferenceHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new MemberReferenceHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out MethodHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new MethodHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out MethodInstantiationHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new MethodInstantiationHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out MethodSemanticsHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new MethodSemanticsHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out MethodSignatureHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new MethodSignatureHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out MethodTypeVariableSignatureHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new MethodTypeVariableSignatureHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ModifiedTypeHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ModifiedTypeHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out NamedArgumentHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new NamedArgumentHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out NamespaceDefinitionHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new NamespaceDefinitionHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out NamespaceReferenceHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new NamespaceReferenceHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ParameterHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ParameterHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out PointerSignatureHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new PointerSignatureHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out PropertyHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new PropertyHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out PropertySignatureHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new PropertySignatureHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out QualifiedFieldHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new QualifiedFieldHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out QualifiedMethodHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new QualifiedMethodHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out SZArraySignatureHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new SZArraySignatureHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ScopeDefinitionHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ScopeDefinitionHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ScopeReferenceHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new ScopeReferenceHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out TypeDefinitionHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new TypeDefinitionHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out TypeForwarderHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new TypeForwarderHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out TypeInstantiationSignatureHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new TypeInstantiationSignatureHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out TypeReferenceHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new TypeReferenceHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out TypeSpecificationHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new TypeSpecificationHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out TypeVariableSignatureHandle handle)
{
uint value;
offset = reader.DecodeUnsigned(offset, out value);
handle = new TypeVariableSignatureHandle((int)value);
handle._Validate();
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out NamedArgumentHandleCollection values)
{
values = new NamedArgumentHandleCollection(reader, offset);
uint count;
offset = reader.DecodeUnsigned(offset, out count);
for (uint i = 0; i < count; ++i)
{
offset = reader.SkipInteger(offset);
}
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out MethodSemanticsHandleCollection values)
{
values = new MethodSemanticsHandleCollection(reader, offset);
uint count;
offset = reader.DecodeUnsigned(offset, out count);
for (uint i = 0; i < count; ++i)
{
offset = reader.SkipInteger(offset);
}
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out CustomAttributeHandleCollection values)
{
values = new CustomAttributeHandleCollection(reader, offset);
uint count;
offset = reader.DecodeUnsigned(offset, out count);
for (uint i = 0; i < count; ++i)
{
offset = reader.SkipInteger(offset);
}
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ParameterHandleCollection values)
{
values = new ParameterHandleCollection(reader, offset);
uint count;
offset = reader.DecodeUnsigned(offset, out count);
for (uint i = 0; i < count; ++i)
{
offset = reader.SkipInteger(offset);
}
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out GenericParameterHandleCollection values)
{
values = new GenericParameterHandleCollection(reader, offset);
uint count;
offset = reader.DecodeUnsigned(offset, out count);
for (uint i = 0; i < count; ++i)
{
offset = reader.SkipInteger(offset);
}
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out TypeDefinitionHandleCollection values)
{
values = new TypeDefinitionHandleCollection(reader, offset);
uint count;
offset = reader.DecodeUnsigned(offset, out count);
for (uint i = 0; i < count; ++i)
{
offset = reader.SkipInteger(offset);
}
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out TypeForwarderHandleCollection values)
{
values = new TypeForwarderHandleCollection(reader, offset);
uint count;
offset = reader.DecodeUnsigned(offset, out count);
for (uint i = 0; i < count; ++i)
{
offset = reader.SkipInteger(offset);
}
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out NamespaceDefinitionHandleCollection values)
{
values = new NamespaceDefinitionHandleCollection(reader, offset);
uint count;
offset = reader.DecodeUnsigned(offset, out count);
for (uint i = 0; i < count; ++i)
{
offset = reader.SkipInteger(offset);
}
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out MethodHandleCollection values)
{
values = new MethodHandleCollection(reader, offset);
uint count;
offset = reader.DecodeUnsigned(offset, out count);
for (uint i = 0; i < count; ++i)
{
offset = reader.SkipInteger(offset);
}
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out FieldHandleCollection values)
{
values = new FieldHandleCollection(reader, offset);
uint count;
offset = reader.DecodeUnsigned(offset, out count);
for (uint i = 0; i < count; ++i)
{
offset = reader.SkipInteger(offset);
}
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out PropertyHandleCollection values)
{
values = new PropertyHandleCollection(reader, offset);
uint count;
offset = reader.DecodeUnsigned(offset, out count);
for (uint i = 0; i < count; ++i)
{
offset = reader.SkipInteger(offset);
}
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out EventHandleCollection values)
{
values = new EventHandleCollection(reader, offset);
uint count;
offset = reader.DecodeUnsigned(offset, out count);
for (uint i = 0; i < count; ++i)
{
offset = reader.SkipInteger(offset);
}
return offset;
} // Read
public static uint Read(this NativeReader reader, uint offset, out ScopeDefinitionHandleCollection values)
{
values = new ScopeDefinitionHandleCollection(reader, offset);
uint count;
offset = reader.DecodeUnsigned(offset, out count);
for (uint i = 0; i < count; ++i)
{
offset = reader.SkipInteger(offset);
}
return offset;
} // Read
} // MdBinaryReader
} // Internal.Metadata.NativeFormat
| -1 |
dotnet/runtime | 66,057 | Address TODO to switch to generated p/invoke | Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | elinor-fung | 2022-03-02T03:31:28Z | 2022-03-02T19:08:30Z | a4b8893a118357b55c0add9a39cc5aeb097a0bb8 | 1abbbb4adf6bf02549f4c6e021176534dcc4f974 | Address TODO to switch to generated p/invoke. Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | ./src/libraries/System.IO.Compression.Brotli/src/System/IO/Compression/enc/BrotliStream.Compress.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.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO.Compression
{
/// <summary>Provides methods and properties used to compress and decompress streams by using the Brotli data format specification.</summary>
public sealed partial class BrotliStream : Stream
{
private BrotliEncoder _encoder;
/// <summary>Initializes a new instance of the <see cref="System.IO.Compression.BrotliStream" /> class by using the specified stream and compression level.</summary>
/// <param name="stream">The stream to compress.</param>
/// <param name="compressionLevel">One of the enumeration values that indicates whether to emphasize speed or compression efficiency when compressing the stream.</param>
public BrotliStream(Stream stream, CompressionLevel compressionLevel) : this(stream, compressionLevel, leaveOpen: false) { }
/// <summary>Initializes a new instance of the <see cref="System.IO.Compression.BrotliStream" /> class by using the specified stream and compression level, and optionally leaves the stream open.</summary>
/// <param name="stream">The stream to compress.</param>
/// <param name="compressionLevel">One of the enumeration values that indicates whether to emphasize speed or compression efficiency when compressing the stream.</param>
/// <param name="leaveOpen"><see langword="true" /> to leave the stream open after disposing the <see cref="System.IO.Compression.BrotliStream" /> object; otherwise, <see langword="false" />.</param>
public BrotliStream(Stream stream, CompressionLevel compressionLevel, bool leaveOpen) : this(stream, CompressionMode.Compress, leaveOpen)
{
_encoder.SetQuality(BrotliUtils.GetQualityFromCompressionLevel(compressionLevel));
}
/// <summary>Writes compressed bytes to the underlying stream from the specified byte array.</summary>
/// <param name="buffer">The buffer containing the data to compress.</param>
/// <param name="offset">The byte offset in <paramref name="buffer" /> from which the bytes will be read.</param>
/// <param name="count">The maximum number of bytes to write.</param>
/// <exception cref="System.ObjectDisposedException">The write operation cannot be performed because the stream is closed.</exception>
public override void Write(byte[] buffer, int offset, int count)
{
ValidateBufferArguments(buffer, offset, count);
WriteCore(new ReadOnlySpan<byte>(buffer, offset, count));
}
/// <summary>
/// Writes a byte to the current position in the stream and advances the position within the stream by one byte.
/// </summary>
/// <param name="value">The byte to write to the stream.</param>
/// <exception cref="InvalidOperationException">Cannot perform write operations on a <see cref="BrotliStream" /> constructed with <see cref="CompressionMode.Decompress" />.
/// -or-
/// The encoder ran into invalid data.</exception>
public override void WriteByte(byte value)
{
WriteCore(MemoryMarshal.CreateReadOnlySpan(ref value, 1));
}
/// <summary>Writes a sequence of bytes to the current Brotli stream from a read-only byte span and advances the current position within this Brotli stream by the number of bytes written.</summary>
/// <param name="buffer">A region of memory. This method copies the contents of this region to the current Brotli stream.</param>
/// <remarks>Use the <see cref="System.IO.Compression.BrotliStream.CanWrite" /> property to determine whether the current instance supports writing. Use the <see langword="System.IO.Compression.BrotliStream.WriteAsync" /> method to write asynchronously to the current stream.
/// If the write operation is successful, the position within the Brotli stream advances by the number of bytes written. If an exception occurs, the position within the Brotli stream remains unchanged.</remarks>
public override void Write(ReadOnlySpan<byte> buffer)
{
WriteCore(buffer);
}
internal void WriteCore(ReadOnlySpan<byte> buffer, bool isFinalBlock = false)
{
if (_mode != CompressionMode.Compress)
throw new InvalidOperationException(SR.BrotliStream_Decompress_UnsupportedOperation);
EnsureNotDisposed();
OperationStatus lastResult = OperationStatus.DestinationTooSmall;
Span<byte> output = new Span<byte>(_buffer);
while (lastResult == OperationStatus.DestinationTooSmall)
{
int bytesConsumed;
int bytesWritten;
lastResult = _encoder.Compress(buffer, output, out bytesConsumed, out bytesWritten, isFinalBlock);
if (lastResult == OperationStatus.InvalidData)
throw new InvalidOperationException(SR.BrotliStream_Compress_InvalidData);
if (bytesWritten > 0)
_stream.Write(output.Slice(0, bytesWritten));
if (bytesConsumed > 0)
buffer = buffer.Slice(bytesConsumed);
}
}
/// <summary>Begins an asynchronous write operation. (Consider using the <see cref="System.IO.Stream.WriteAsync(byte[],int,int)" /> method instead.)</summary>
/// <param name="buffer">The buffer from which data will be written.</param>
/// <param name="offset">The byte offset in <paramref name="buffer" /> at which to begin writing data from the stream.</param>
/// <param name="count">The maximum number of bytes to write.</param>
/// <param name="asyncCallback">An optional asynchronous callback, to be called when the write operation is complete.</param>
/// <param name="asyncState">A user-provided object that distinguishes this particular asynchronous write request from other requests.</param>
/// <returns>An object that represents the asynchronous write operation, which could still be pending.</returns>
/// <exception cref="System.IO.IOException">The method tried to write asynchronously past the end of the stream, or a disk error occurred.</exception>
/// <exception cref="System.ArgumentException">One or more of the arguments is invalid.</exception>
/// <exception cref="System.ObjectDisposedException">Methods were called after the stream was closed.</exception>
/// <exception cref="System.NotSupportedException">The current <see cref="System.IO.Compression.BrotliStream" /> implementation does not support the write operation.</exception>
/// <exception cref="System.InvalidOperationException">The write operation cannot be performed because the stream is closed.</exception>
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback? asyncCallback, object? asyncState) =>
TaskToApm.Begin(WriteAsync(buffer, offset, count, CancellationToken.None), asyncCallback, asyncState);
/// <summary>Handles the end of an asynchronous write operation. (Consider using the <see cref="System.IO.Stream.WriteAsync(byte[],int,int)" /> method instead.)</summary>
/// <param name="asyncResult">The object that represents the asynchronous call.</param>
/// <exception cref="System.InvalidOperationException">The underlying stream is closed or <see langword="null" />.</exception>
public override void EndWrite(IAsyncResult asyncResult) =>
TaskToApm.End(asyncResult);
/// <summary>Asynchronously writes compressed bytes to the underlying Brotli stream from the specified byte array.</summary>
/// <param name="buffer">The buffer that contains the data to compress.</param>
/// <param name="offset">The zero-based byte offset in <paramref name="buffer" /> from which to begin copying bytes to the Brotli stream.</param>
/// <param name="count">The maximum number of bytes to write.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="System.Threading.CancellationToken.None" />.</param>
/// <returns>A task that represents the asynchronous write operation.</returns>
/// <remarks>The `WriteAsync` method enables you to perform resource-intensive I/O operations without blocking the main thread. This performance consideration is particularly important in a Windows 8.x Store app or desktop app where a time-consuming stream operation can block the UI thread and make your app appear as if it is not working. The async methods are used in conjunction with the <see langword="async" /> and <see langword="await" /> keywords in Visual Basic and C#.
/// Use the <see cref="System.IO.Compression.BrotliStream.CanWrite" /> property to determine whether the current instance supports writing.
/// If the operation is canceled before it completes, the returned task contains the <see cref="System.Threading.Tasks.TaskStatus.Canceled" /> value for the <see cref="System.Threading.Tasks.Task.Status" /> property.</remarks>
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
ValidateBufferArguments(buffer, offset, count);
return WriteAsync(new ReadOnlyMemory<byte>(buffer, offset, count), cancellationToken).AsTask();
}
/// <summary>Asynchronously writes compressed bytes to the underlying Brotli stream from the specified byte memory range.</summary>
/// <param name="buffer">The memory region to write data from.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="System.Threading.CancellationToken.None" />.</param>
/// <returns>A task that represents the asynchronous write operation.</returns>
/// <remarks>The `WriteAsync` method enables you to perform resource-intensive I/O operations without blocking the main thread. This performance consideration is particularly important in a Windows 8.x Store app or desktop app where a time-consuming stream operation can block the UI thread and make your app appear as if it is not working. The async methods are used in conjunction with the <see langword="async" /> and <see langword="await" /> keywords in Visual Basic and C#.
/// Use the <see cref="System.IO.Compression.BrotliStream.CanWrite" /> property to determine whether the current instance supports writing.
/// If the operation is canceled before it completes, the returned task contains the <see cref="System.Threading.Tasks.TaskStatus.Canceled" /> value for the <see cref="System.Threading.Tasks.Task.Status" /> property.</remarks>
public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default(CancellationToken))
{
if (_mode != CompressionMode.Compress)
throw new InvalidOperationException(SR.BrotliStream_Decompress_UnsupportedOperation);
EnsureNoActiveAsyncOperation();
EnsureNotDisposed();
return cancellationToken.IsCancellationRequested ?
ValueTask.FromCanceled(cancellationToken) :
WriteAsyncMemoryCore(buffer, cancellationToken);
}
private async ValueTask WriteAsyncMemoryCore(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken, bool isFinalBlock = false)
{
AsyncOperationStarting();
try
{
OperationStatus lastResult = OperationStatus.DestinationTooSmall;
while (lastResult == OperationStatus.DestinationTooSmall)
{
Memory<byte> output = new Memory<byte>(_buffer);
int bytesConsumed = 0;
int bytesWritten = 0;
lastResult = _encoder.Compress(buffer, output, out bytesConsumed, out bytesWritten, isFinalBlock);
if (lastResult == OperationStatus.InvalidData)
throw new InvalidOperationException(SR.BrotliStream_Compress_InvalidData);
if (bytesConsumed > 0)
buffer = buffer.Slice(bytesConsumed);
if (bytesWritten > 0)
await _stream.WriteAsync(new ReadOnlyMemory<byte>(_buffer, 0, bytesWritten), cancellationToken).ConfigureAwait(false);
}
}
finally
{
AsyncOperationCompleting();
}
}
/// <summary>If the stream is not disposed, and the compression mode is set to compress, writes all the remaining encoder's data into this stream.</summary>
/// <exception cref="InvalidDataException">The encoder ran into invalid data.</exception>
/// <exception cref="ObjectDisposedException">The stream is disposed.</exception>
public override void Flush()
{
EnsureNotDisposed();
if (_mode == CompressionMode.Compress)
{
if (_encoder._state == null || _encoder._state.IsClosed)
return;
OperationStatus lastResult = OperationStatus.DestinationTooSmall;
Span<byte> output = new Span<byte>(_buffer);
while (lastResult == OperationStatus.DestinationTooSmall)
{
int bytesWritten;
lastResult = _encoder.Flush(output, out bytesWritten);
if (lastResult == OperationStatus.InvalidData)
throw new InvalidDataException(SR.BrotliStream_Compress_InvalidData);
if (bytesWritten > 0)
{
_stream.Write(output.Slice(0, bytesWritten));
}
}
_stream.Flush();
}
}
/// <summary>Asynchronously clears all buffers for this Brotli stream, causes any buffered data to be written to the underlying device, and monitors cancellation requests.</summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="System.Threading.CancellationToken.None" />.</param>
/// <returns>A task that represents the asynchronous flush operation.</returns>
/// <remarks>If the operation is canceled before it completes, the returned task contains the <see cref="System.Threading.Tasks.TaskStatus.Canceled" /> value for the <see cref="System.Threading.Tasks.Task.Status" /> property.</remarks>
public override Task FlushAsync(CancellationToken cancellationToken)
{
EnsureNoActiveAsyncOperation();
EnsureNotDisposed();
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled(cancellationToken);
return _mode != CompressionMode.Compress ? Task.CompletedTask : FlushAsyncCore(cancellationToken);
}
private async Task FlushAsyncCore(CancellationToken cancellationToken)
{
AsyncOperationStarting();
try
{
if (_encoder._state == null || _encoder._state.IsClosed)
return;
OperationStatus lastResult = OperationStatus.DestinationTooSmall;
while (lastResult == OperationStatus.DestinationTooSmall)
{
Memory<byte> output = new Memory<byte>(_buffer);
int bytesWritten = 0;
lastResult = _encoder.Flush(output, out bytesWritten);
if (lastResult == OperationStatus.InvalidData)
throw new InvalidDataException(SR.BrotliStream_Compress_InvalidData);
if (bytesWritten > 0)
await _stream.WriteAsync(output.Slice(0, bytesWritten), cancellationToken).ConfigureAwait(false);
}
await _stream.FlushAsync(cancellationToken).ConfigureAwait(false);
}
finally
{
AsyncOperationCompleting();
}
}
}
}
| // 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.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO.Compression
{
/// <summary>Provides methods and properties used to compress and decompress streams by using the Brotli data format specification.</summary>
public sealed partial class BrotliStream : Stream
{
private BrotliEncoder _encoder;
/// <summary>Initializes a new instance of the <see cref="System.IO.Compression.BrotliStream" /> class by using the specified stream and compression level.</summary>
/// <param name="stream">The stream to compress.</param>
/// <param name="compressionLevel">One of the enumeration values that indicates whether to emphasize speed or compression efficiency when compressing the stream.</param>
public BrotliStream(Stream stream, CompressionLevel compressionLevel) : this(stream, compressionLevel, leaveOpen: false) { }
/// <summary>Initializes a new instance of the <see cref="System.IO.Compression.BrotliStream" /> class by using the specified stream and compression level, and optionally leaves the stream open.</summary>
/// <param name="stream">The stream to compress.</param>
/// <param name="compressionLevel">One of the enumeration values that indicates whether to emphasize speed or compression efficiency when compressing the stream.</param>
/// <param name="leaveOpen"><see langword="true" /> to leave the stream open after disposing the <see cref="System.IO.Compression.BrotliStream" /> object; otherwise, <see langword="false" />.</param>
public BrotliStream(Stream stream, CompressionLevel compressionLevel, bool leaveOpen) : this(stream, CompressionMode.Compress, leaveOpen)
{
_encoder.SetQuality(BrotliUtils.GetQualityFromCompressionLevel(compressionLevel));
}
/// <summary>Writes compressed bytes to the underlying stream from the specified byte array.</summary>
/// <param name="buffer">The buffer containing the data to compress.</param>
/// <param name="offset">The byte offset in <paramref name="buffer" /> from which the bytes will be read.</param>
/// <param name="count">The maximum number of bytes to write.</param>
/// <exception cref="System.ObjectDisposedException">The write operation cannot be performed because the stream is closed.</exception>
public override void Write(byte[] buffer, int offset, int count)
{
ValidateBufferArguments(buffer, offset, count);
WriteCore(new ReadOnlySpan<byte>(buffer, offset, count));
}
/// <summary>
/// Writes a byte to the current position in the stream and advances the position within the stream by one byte.
/// </summary>
/// <param name="value">The byte to write to the stream.</param>
/// <exception cref="InvalidOperationException">Cannot perform write operations on a <see cref="BrotliStream" /> constructed with <see cref="CompressionMode.Decompress" />.
/// -or-
/// The encoder ran into invalid data.</exception>
public override void WriteByte(byte value)
{
WriteCore(MemoryMarshal.CreateReadOnlySpan(ref value, 1));
}
/// <summary>Writes a sequence of bytes to the current Brotli stream from a read-only byte span and advances the current position within this Brotli stream by the number of bytes written.</summary>
/// <param name="buffer">A region of memory. This method copies the contents of this region to the current Brotli stream.</param>
/// <remarks>Use the <see cref="System.IO.Compression.BrotliStream.CanWrite" /> property to determine whether the current instance supports writing. Use the <see langword="System.IO.Compression.BrotliStream.WriteAsync" /> method to write asynchronously to the current stream.
/// If the write operation is successful, the position within the Brotli stream advances by the number of bytes written. If an exception occurs, the position within the Brotli stream remains unchanged.</remarks>
public override void Write(ReadOnlySpan<byte> buffer)
{
WriteCore(buffer);
}
internal void WriteCore(ReadOnlySpan<byte> buffer, bool isFinalBlock = false)
{
if (_mode != CompressionMode.Compress)
throw new InvalidOperationException(SR.BrotliStream_Decompress_UnsupportedOperation);
EnsureNotDisposed();
OperationStatus lastResult = OperationStatus.DestinationTooSmall;
Span<byte> output = new Span<byte>(_buffer);
while (lastResult == OperationStatus.DestinationTooSmall)
{
int bytesConsumed;
int bytesWritten;
lastResult = _encoder.Compress(buffer, output, out bytesConsumed, out bytesWritten, isFinalBlock);
if (lastResult == OperationStatus.InvalidData)
throw new InvalidOperationException(SR.BrotliStream_Compress_InvalidData);
if (bytesWritten > 0)
_stream.Write(output.Slice(0, bytesWritten));
if (bytesConsumed > 0)
buffer = buffer.Slice(bytesConsumed);
}
}
/// <summary>Begins an asynchronous write operation. (Consider using the <see cref="System.IO.Stream.WriteAsync(byte[],int,int)" /> method instead.)</summary>
/// <param name="buffer">The buffer from which data will be written.</param>
/// <param name="offset">The byte offset in <paramref name="buffer" /> at which to begin writing data from the stream.</param>
/// <param name="count">The maximum number of bytes to write.</param>
/// <param name="asyncCallback">An optional asynchronous callback, to be called when the write operation is complete.</param>
/// <param name="asyncState">A user-provided object that distinguishes this particular asynchronous write request from other requests.</param>
/// <returns>An object that represents the asynchronous write operation, which could still be pending.</returns>
/// <exception cref="System.IO.IOException">The method tried to write asynchronously past the end of the stream, or a disk error occurred.</exception>
/// <exception cref="System.ArgumentException">One or more of the arguments is invalid.</exception>
/// <exception cref="System.ObjectDisposedException">Methods were called after the stream was closed.</exception>
/// <exception cref="System.NotSupportedException">The current <see cref="System.IO.Compression.BrotliStream" /> implementation does not support the write operation.</exception>
/// <exception cref="System.InvalidOperationException">The write operation cannot be performed because the stream is closed.</exception>
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback? asyncCallback, object? asyncState) =>
TaskToApm.Begin(WriteAsync(buffer, offset, count, CancellationToken.None), asyncCallback, asyncState);
/// <summary>Handles the end of an asynchronous write operation. (Consider using the <see cref="System.IO.Stream.WriteAsync(byte[],int,int)" /> method instead.)</summary>
/// <param name="asyncResult">The object that represents the asynchronous call.</param>
/// <exception cref="System.InvalidOperationException">The underlying stream is closed or <see langword="null" />.</exception>
public override void EndWrite(IAsyncResult asyncResult) =>
TaskToApm.End(asyncResult);
/// <summary>Asynchronously writes compressed bytes to the underlying Brotli stream from the specified byte array.</summary>
/// <param name="buffer">The buffer that contains the data to compress.</param>
/// <param name="offset">The zero-based byte offset in <paramref name="buffer" /> from which to begin copying bytes to the Brotli stream.</param>
/// <param name="count">The maximum number of bytes to write.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="System.Threading.CancellationToken.None" />.</param>
/// <returns>A task that represents the asynchronous write operation.</returns>
/// <remarks>The `WriteAsync` method enables you to perform resource-intensive I/O operations without blocking the main thread. This performance consideration is particularly important in a Windows 8.x Store app or desktop app where a time-consuming stream operation can block the UI thread and make your app appear as if it is not working. The async methods are used in conjunction with the <see langword="async" /> and <see langword="await" /> keywords in Visual Basic and C#.
/// Use the <see cref="System.IO.Compression.BrotliStream.CanWrite" /> property to determine whether the current instance supports writing.
/// If the operation is canceled before it completes, the returned task contains the <see cref="System.Threading.Tasks.TaskStatus.Canceled" /> value for the <see cref="System.Threading.Tasks.Task.Status" /> property.</remarks>
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
ValidateBufferArguments(buffer, offset, count);
return WriteAsync(new ReadOnlyMemory<byte>(buffer, offset, count), cancellationToken).AsTask();
}
/// <summary>Asynchronously writes compressed bytes to the underlying Brotli stream from the specified byte memory range.</summary>
/// <param name="buffer">The memory region to write data from.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="System.Threading.CancellationToken.None" />.</param>
/// <returns>A task that represents the asynchronous write operation.</returns>
/// <remarks>The `WriteAsync` method enables you to perform resource-intensive I/O operations without blocking the main thread. This performance consideration is particularly important in a Windows 8.x Store app or desktop app where a time-consuming stream operation can block the UI thread and make your app appear as if it is not working. The async methods are used in conjunction with the <see langword="async" /> and <see langword="await" /> keywords in Visual Basic and C#.
/// Use the <see cref="System.IO.Compression.BrotliStream.CanWrite" /> property to determine whether the current instance supports writing.
/// If the operation is canceled before it completes, the returned task contains the <see cref="System.Threading.Tasks.TaskStatus.Canceled" /> value for the <see cref="System.Threading.Tasks.Task.Status" /> property.</remarks>
public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default(CancellationToken))
{
if (_mode != CompressionMode.Compress)
throw new InvalidOperationException(SR.BrotliStream_Decompress_UnsupportedOperation);
EnsureNoActiveAsyncOperation();
EnsureNotDisposed();
return cancellationToken.IsCancellationRequested ?
ValueTask.FromCanceled(cancellationToken) :
WriteAsyncMemoryCore(buffer, cancellationToken);
}
private async ValueTask WriteAsyncMemoryCore(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken, bool isFinalBlock = false)
{
AsyncOperationStarting();
try
{
OperationStatus lastResult = OperationStatus.DestinationTooSmall;
while (lastResult == OperationStatus.DestinationTooSmall)
{
Memory<byte> output = new Memory<byte>(_buffer);
int bytesConsumed = 0;
int bytesWritten = 0;
lastResult = _encoder.Compress(buffer, output, out bytesConsumed, out bytesWritten, isFinalBlock);
if (lastResult == OperationStatus.InvalidData)
throw new InvalidOperationException(SR.BrotliStream_Compress_InvalidData);
if (bytesConsumed > 0)
buffer = buffer.Slice(bytesConsumed);
if (bytesWritten > 0)
await _stream.WriteAsync(new ReadOnlyMemory<byte>(_buffer, 0, bytesWritten), cancellationToken).ConfigureAwait(false);
}
}
finally
{
AsyncOperationCompleting();
}
}
/// <summary>If the stream is not disposed, and the compression mode is set to compress, writes all the remaining encoder's data into this stream.</summary>
/// <exception cref="InvalidDataException">The encoder ran into invalid data.</exception>
/// <exception cref="ObjectDisposedException">The stream is disposed.</exception>
public override void Flush()
{
EnsureNotDisposed();
if (_mode == CompressionMode.Compress)
{
if (_encoder._state == null || _encoder._state.IsClosed)
return;
OperationStatus lastResult = OperationStatus.DestinationTooSmall;
Span<byte> output = new Span<byte>(_buffer);
while (lastResult == OperationStatus.DestinationTooSmall)
{
int bytesWritten;
lastResult = _encoder.Flush(output, out bytesWritten);
if (lastResult == OperationStatus.InvalidData)
throw new InvalidDataException(SR.BrotliStream_Compress_InvalidData);
if (bytesWritten > 0)
{
_stream.Write(output.Slice(0, bytesWritten));
}
}
_stream.Flush();
}
}
/// <summary>Asynchronously clears all buffers for this Brotli stream, causes any buffered data to be written to the underlying device, and monitors cancellation requests.</summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="System.Threading.CancellationToken.None" />.</param>
/// <returns>A task that represents the asynchronous flush operation.</returns>
/// <remarks>If the operation is canceled before it completes, the returned task contains the <see cref="System.Threading.Tasks.TaskStatus.Canceled" /> value for the <see cref="System.Threading.Tasks.Task.Status" /> property.</remarks>
public override Task FlushAsync(CancellationToken cancellationToken)
{
EnsureNoActiveAsyncOperation();
EnsureNotDisposed();
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled(cancellationToken);
return _mode != CompressionMode.Compress ? Task.CompletedTask : FlushAsyncCore(cancellationToken);
}
private async Task FlushAsyncCore(CancellationToken cancellationToken)
{
AsyncOperationStarting();
try
{
if (_encoder._state == null || _encoder._state.IsClosed)
return;
OperationStatus lastResult = OperationStatus.DestinationTooSmall;
while (lastResult == OperationStatus.DestinationTooSmall)
{
Memory<byte> output = new Memory<byte>(_buffer);
int bytesWritten = 0;
lastResult = _encoder.Flush(output, out bytesWritten);
if (lastResult == OperationStatus.InvalidData)
throw new InvalidDataException(SR.BrotliStream_Compress_InvalidData);
if (bytesWritten > 0)
await _stream.WriteAsync(output.Slice(0, bytesWritten), cancellationToken).ConfigureAwait(false);
}
await _stream.FlushAsync(cancellationToken).ConfigureAwait(false);
}
finally
{
AsyncOperationCompleting();
}
}
}
}
| -1 |
dotnet/runtime | 66,057 | Address TODO to switch to generated p/invoke | Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | elinor-fung | 2022-03-02T03:31:28Z | 2022-03-02T19:08:30Z | a4b8893a118357b55c0add9a39cc5aeb097a0bb8 | 1abbbb4adf6bf02549f4c6e021176534dcc4f974 | Address TODO to switch to generated p/invoke. Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | ./src/libraries/System.Threading.Overlapped/src/System.Threading.Overlapped.csproj | <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<IsPartialFacadeAssembly>true</IsPartialFacadeAssembly>
<TargetFramework>$(NetCoreAppCurrent)</TargetFramework>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="$(CoreLibProject)" />
</ItemGroup>
</Project> | <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<IsPartialFacadeAssembly>true</IsPartialFacadeAssembly>
<TargetFramework>$(NetCoreAppCurrent)</TargetFramework>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="$(CoreLibProject)" />
</ItemGroup>
</Project> | -1 |
dotnet/runtime | 66,057 | Address TODO to switch to generated p/invoke | Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | elinor-fung | 2022-03-02T03:31:28Z | 2022-03-02T19:08:30Z | a4b8893a118357b55c0add9a39cc5aeb097a0bb8 | 1abbbb4adf6bf02549f4c6e021176534dcc4f974 | Address TODO to switch to generated p/invoke. Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | ./src/libraries/Microsoft.Extensions.FileProviders.Composite/ref/Microsoft.Extensions.FileProviders.Composite.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 Microsoft.Extensions.FileProviders
{
public partial class CompositeFileProvider : Microsoft.Extensions.FileProviders.IFileProvider
{
public CompositeFileProvider(params Microsoft.Extensions.FileProviders.IFileProvider[]? fileProviders) { }
public CompositeFileProvider(System.Collections.Generic.IEnumerable<Microsoft.Extensions.FileProviders.IFileProvider> fileProviders) { }
public System.Collections.Generic.IEnumerable<Microsoft.Extensions.FileProviders.IFileProvider> FileProviders { get { throw null; } }
public Microsoft.Extensions.FileProviders.IDirectoryContents GetDirectoryContents(string subpath) { throw null; }
public Microsoft.Extensions.FileProviders.IFileInfo GetFileInfo(string subpath) { throw null; }
public Microsoft.Extensions.Primitives.IChangeToken Watch(string pattern) { throw null; }
}
}
namespace Microsoft.Extensions.FileProviders.Composite
{
public partial class CompositeDirectoryContents : Microsoft.Extensions.FileProviders.IDirectoryContents, System.Collections.Generic.IEnumerable<Microsoft.Extensions.FileProviders.IFileInfo>, System.Collections.IEnumerable
{
public CompositeDirectoryContents(System.Collections.Generic.IList<Microsoft.Extensions.FileProviders.IFileProvider> fileProviders, string subpath) { }
public bool Exists { get { throw null; } }
public System.Collections.Generic.IEnumerator<Microsoft.Extensions.FileProviders.IFileInfo> GetEnumerator() { throw null; }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { 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 Microsoft.Extensions.FileProviders
{
public partial class CompositeFileProvider : Microsoft.Extensions.FileProviders.IFileProvider
{
public CompositeFileProvider(params Microsoft.Extensions.FileProviders.IFileProvider[]? fileProviders) { }
public CompositeFileProvider(System.Collections.Generic.IEnumerable<Microsoft.Extensions.FileProviders.IFileProvider> fileProviders) { }
public System.Collections.Generic.IEnumerable<Microsoft.Extensions.FileProviders.IFileProvider> FileProviders { get { throw null; } }
public Microsoft.Extensions.FileProviders.IDirectoryContents GetDirectoryContents(string subpath) { throw null; }
public Microsoft.Extensions.FileProviders.IFileInfo GetFileInfo(string subpath) { throw null; }
public Microsoft.Extensions.Primitives.IChangeToken Watch(string pattern) { throw null; }
}
}
namespace Microsoft.Extensions.FileProviders.Composite
{
public partial class CompositeDirectoryContents : Microsoft.Extensions.FileProviders.IDirectoryContents, System.Collections.Generic.IEnumerable<Microsoft.Extensions.FileProviders.IFileInfo>, System.Collections.IEnumerable
{
public CompositeDirectoryContents(System.Collections.Generic.IList<Microsoft.Extensions.FileProviders.IFileProvider> fileProviders, string subpath) { }
public bool Exists { get { throw null; } }
public System.Collections.Generic.IEnumerator<Microsoft.Extensions.FileProviders.IFileInfo> GetEnumerator() { throw null; }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
}
}
| -1 |
dotnet/runtime | 66,057 | Address TODO to switch to generated p/invoke | Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | elinor-fung | 2022-03-02T03:31:28Z | 2022-03-02T19:08:30Z | a4b8893a118357b55c0add9a39cc5aeb097a0bb8 | 1abbbb4adf6bf02549f4c6e021176534dcc4f974 | Address TODO to switch to generated p/invoke. Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | ./src/tests/JIT/Regression/JitBlue/GitHub_11814/GitHub_11814.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// Repro case for a bug involving failure to rewrite all references
// to a promoted implicit byref struct parameter.
using System;
using System.Runtime.CompilerServices;
class MutateStructArg
{
public struct P
{
public string S;
public int X;
}
public static int Main()
{
P l1 = new P();
l1.S = "Hello World";
l1.X = 42;
P l2 = foo(l1);
Console.WriteLine(l2.S); // Print modified value "Goodbye World"
if ((l2.S == "Goodbye World") && (l2.X == 100))
{
return 100; // success
}
else
{
Console.WriteLine("**** Test FAILED ***");
return 1; // failure
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static P foo(P a)
{
Console.WriteLine(a.S); // Print the incoming value "Hello World"
a.S = "Goodbye World"; // Mutate the incoming value
a.X = 100;
return a; // Copy the modified value to the return value (bug was that this was returning original unmodified arg)
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// Repro case for a bug involving failure to rewrite all references
// to a promoted implicit byref struct parameter.
using System;
using System.Runtime.CompilerServices;
class MutateStructArg
{
public struct P
{
public string S;
public int X;
}
public static int Main()
{
P l1 = new P();
l1.S = "Hello World";
l1.X = 42;
P l2 = foo(l1);
Console.WriteLine(l2.S); // Print modified value "Goodbye World"
if ((l2.S == "Goodbye World") && (l2.X == 100))
{
return 100; // success
}
else
{
Console.WriteLine("**** Test FAILED ***");
return 1; // failure
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static P foo(P a)
{
Console.WriteLine(a.S); // Print the incoming value "Hello World"
a.S = "Goodbye World"; // Mutate the incoming value
a.X = 100;
return a; // Copy the modified value to the return value (bug was that this was returning original unmodified arg)
}
}
| -1 |
dotnet/runtime | 66,057 | Address TODO to switch to generated p/invoke | Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | elinor-fung | 2022-03-02T03:31:28Z | 2022-03-02T19:08:30Z | a4b8893a118357b55c0add9a39cc5aeb097a0bb8 | 1abbbb4adf6bf02549f4c6e021176534dcc4f974 | Address TODO to switch to generated p/invoke. Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | ./src/libraries/Common/src/Interop/Windows/Advapi32/Interop.IsWellKnownSid.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 Advapi32
{
[GeneratedDllImport(Interop.Libraries.Advapi32, EntryPoint = "IsWellKnownSid", SetLastError = true)]
internal static partial int IsWellKnownSid(
byte[] sid,
int type);
}
}
| // 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 Advapi32
{
[GeneratedDllImport(Interop.Libraries.Advapi32, EntryPoint = "IsWellKnownSid", SetLastError = true)]
internal static partial int IsWellKnownSid(
byte[] sid,
int type);
}
}
| -1 |
dotnet/runtime | 66,057 | Address TODO to switch to generated p/invoke | Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | elinor-fung | 2022-03-02T03:31:28Z | 2022-03-02T19:08:30Z | a4b8893a118357b55c0add9a39cc5aeb097a0bb8 | 1abbbb4adf6bf02549f4c6e021176534dcc4f974 | Address TODO to switch to generated p/invoke. Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | ./src/coreclr/tools/aot/ILCompiler.ReadyToRun/ObjectWriter/ProfileFileBuilder.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Internal.TypeSystem;
using ILCompiler.DependencyAnalysis;
using ILCompiler.DependencyAnalysis.ReadyToRun;
namespace ILCompiler.PEWriter
{
/// <summary>
/// Helper class used to calculate code layout quality heuristics w.r.t. given call chain profile.
/// </summary>
public class ProfileFileBuilder
{
private enum CrossPageCall : byte
{
No,
Yes,
Unresolved,
}
private class CallInfo
{
public readonly MethodDesc Caller;
public readonly OutputNode CallerNode;
public readonly int CallerRVA;
public readonly MethodDesc Callee;
public readonly OutputNode CalleeNode;
public readonly int CalleeRVA;
public readonly int CallCount;
public readonly CrossPageCall CallType;
public CallInfo(MethodDesc caller, OutputNode callerNode, int callerRVA, MethodDesc callee, OutputNode calleeNode, int calleeRVA, int callCount, CrossPageCall callType)
{
Caller = caller;
CallerNode = callerNode;
CallerRVA = callerRVA;
Callee = callee;
CalleeNode = calleeNode;
CalleeRVA = calleeRVA;
CallCount = callCount;
CallType = callType;
}
}
private readonly OutputInfoBuilder _outputInfoBuilder;
private readonly CallChainProfile _callChainProfile;
private readonly TargetDetails _targetDetails;
private readonly int _pageSize;
private Dictionary<MethodDesc, ISymbolDefinitionNode> _symbolMethodMap;
private List<CallInfo> _callInfo;
public ProfileFileBuilder(OutputInfoBuilder outputInfoBuilder, CallChainProfile callChainProfile, TargetDetails targetDetails)
{
_outputInfoBuilder = outputInfoBuilder;
_callChainProfile = callChainProfile;
_targetDetails = targetDetails;
_pageSize = _targetDetails.Architecture switch
{
TargetArchitecture.X86 => 0x00001000,
TargetArchitecture.X64 => 0x00010000,
TargetArchitecture.ARM => 0x00001000,
TargetArchitecture.ARM64 => 0x00010000,
_ => throw new NotImplementedException(_targetDetails.Architecture.ToString())
};
}
public void SaveProfile(string profileFileName)
{
Console.WriteLine("Emitting profile file: {0}", profileFileName);
CalculateCallInfo();
using (StreamWriter writer = new StreamWriter(profileFileName))
{
writer.WriteLine("CHARACTERISTIC | PAIR COUNT | CALL COUNT | PERCENTAGE");
writer.WriteLine("----------------------------------------------------------------");
int callCount = _callInfo.Sum(info => info.CallCount);
double percentFactor = 100.0 / Math.Max(callCount, 1);
writer.WriteLine("ENTRIES TOTAL | {0,10} | {1,10} | {2,10:F2}", _callInfo.Count, callCount, callCount * percentFactor);
int resolvedPairCount = _callInfo.Sum(info => info.CallType == CrossPageCall.Unresolved ? 0 : 1);
int resolvedCallCount = _callInfo.Sum(info => info.CallType == CrossPageCall.Unresolved ? 0 : info.CallCount);
writer.WriteLine("RESOLVED ENTRIES | {0,10} | {1,10} | {2,10:F2}", resolvedPairCount, resolvedCallCount, resolvedCallCount * percentFactor);
int unresolvedPairCount = _callInfo.Count - resolvedPairCount;
int unresolvedCallCount = callCount - resolvedCallCount;
writer.WriteLine("UNRESOLVED ENTRIES | {0,10} | {1,10} | {2,10:F2}", unresolvedPairCount, unresolvedCallCount, unresolvedCallCount * percentFactor);
int nearPairCount = _callInfo.Sum(info => info.CallType == CrossPageCall.No ? 1 : 0);
int nearCallCount = _callInfo.Sum(info => info.CallType == CrossPageCall.No ? info.CallCount : 0);
writer.WriteLine("NEAR (INTRA-PAGE) CALLS | {0,10} | {1,10} | {2,10:F2}", nearPairCount, nearCallCount, nearCallCount * percentFactor);
int farPairCount = _callInfo.Sum(info => info.CallType == CrossPageCall.Yes ? 1 : 0);
int farCallCount = _callInfo.Sum(info => info.CallType == CrossPageCall.Yes ? info.CallCount : 0);
writer.WriteLine("FAR (CROSS-PAGE) CALLS | {0,10} | {1,10} | {2,10:F2}", farPairCount, farCallCount, farCallCount * percentFactor);
writer.WriteLine();
writer.WriteLine("CALLER RVA | CALLER LEN | CALLEE RVA | CALLEE LEN | COUNT | FAR (CROSS-PAGE) CALLS (CALLER -> CALLEE)");
writer.WriteLine("----------------------------------------------------------------------------------------------------------");
DumpCallInfo(writer, _callInfo.Where(info => info.CallType == CrossPageCall.Yes).OrderByDescending(info => info.CallCount));
writer.WriteLine();
writer.WriteLine("CALLER RVA | CALLER LEN | CALLEE RVA | CALLEE LEN | COUNT | NEAR (INTRA-PAGE) CALLS (CALLER -> CALLEE)");
writer.WriteLine("-----------------------------------------------------------------------------------------------------------");
DumpCallInfo(writer, _callInfo.Where(info => info.CallType == CrossPageCall.No).OrderByDescending(info => info.CallCount));
}
}
private void DumpCallInfo(StreamWriter writer, IEnumerable<CallInfo> callInfos)
{
foreach (CallInfo callInfo in callInfos)
{
writer.Write($@"{callInfo.CallerRVA,10:X8} | ");
writer.Write($@"{callInfo.CallerNode.Length,10:X8} | ");
writer.Write($@"{callInfo.CalleeRVA,10:X8} | ");
writer.Write($@"{callInfo.CalleeNode.Length,10:X8} | ");
writer.Write($@"{callInfo.CallCount,10} | ");
writer.WriteLine($@"{callInfo.Caller.ToString()} -> {callInfo.Callee.ToString()}");
}
}
private void CalculateSymbolMethodMap()
{
if (_symbolMethodMap != null)
{
// Already calculated
return;
}
_symbolMethodMap = new Dictionary<MethodDesc, ISymbolDefinitionNode>();
foreach (KeyValuePair<ISymbolDefinitionNode, MethodWithGCInfo> kvpSymbolMethod in _outputInfoBuilder.MethodSymbolMap)
{
_symbolMethodMap.Add(kvpSymbolMethod.Value.Method, kvpSymbolMethod.Key);
}
}
private void CalculateCallInfo()
{
if (_callInfo != null)
{
// Already calculated
return;
}
CalculateSymbolMethodMap();
_callInfo = new List<CallInfo>();
foreach (KeyValuePair<MethodDesc, Dictionary<MethodDesc, int>> kvpCallerCalleeCount in _callChainProfile.ResolvedProfileData)
{
OutputNode callerNode = null;
int callerRVA = 0;
if (_symbolMethodMap.TryGetValue(kvpCallerCalleeCount.Key, out ISymbolDefinitionNode callerSymbol) &&
_outputInfoBuilder.NodeSymbolMap.TryGetValue(callerSymbol, out callerNode))
{
callerRVA = _outputInfoBuilder.Sections[callerNode.SectionIndex].RVAWhenPlaced + callerNode.Offset;
}
foreach (KeyValuePair<MethodDesc, int> kvpCalleeCount in kvpCallerCalleeCount.Value)
{
OutputNode calleeNode = null;
int calleeRVA = 0;
if (_symbolMethodMap.TryGetValue(kvpCalleeCount.Key, out ISymbolDefinitionNode calleeSymbol) &&
_outputInfoBuilder.NodeSymbolMap.TryGetValue(calleeSymbol, out calleeNode))
{
calleeRVA = _outputInfoBuilder.Sections[calleeNode.SectionIndex].RVAWhenPlaced + calleeNode.Offset;
}
_callInfo.Add(new CallInfo(
caller: kvpCallerCalleeCount.Key,
callerNode: callerNode,
callerRVA: callerRVA,
callee: kvpCalleeCount.Key,
calleeNode: calleeNode,
calleeRVA: calleeRVA,
callCount: kvpCalleeCount.Value,
callType: GetCallType(callerNode, callerRVA, calleeNode, calleeRVA)));
}
}
}
private CrossPageCall GetCallType(OutputNode caller, int callerRVA, OutputNode callee, int calleeRVA)
{
if (caller == null || callee == null)
{
return CrossPageCall.Unresolved;
}
int callerStartPage = callerRVA / _pageSize;
int callerEndPage = (callerRVA + caller.Length - 1) / _pageSize;
int calleePage = calleeRVA / _pageSize;
if (callerStartPage == calleePage && callerEndPage == calleePage)
{
// The entire caller and the callee entrypoint are on the same page, no cross-page call penalty
return CrossPageCall.No;
}
// Pessimistic estimate - we don't know where exactly the call is, we just know that it might cross a page.
return CrossPageCall.Yes;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Internal.TypeSystem;
using ILCompiler.DependencyAnalysis;
using ILCompiler.DependencyAnalysis.ReadyToRun;
namespace ILCompiler.PEWriter
{
/// <summary>
/// Helper class used to calculate code layout quality heuristics w.r.t. given call chain profile.
/// </summary>
public class ProfileFileBuilder
{
private enum CrossPageCall : byte
{
No,
Yes,
Unresolved,
}
private class CallInfo
{
public readonly MethodDesc Caller;
public readonly OutputNode CallerNode;
public readonly int CallerRVA;
public readonly MethodDesc Callee;
public readonly OutputNode CalleeNode;
public readonly int CalleeRVA;
public readonly int CallCount;
public readonly CrossPageCall CallType;
public CallInfo(MethodDesc caller, OutputNode callerNode, int callerRVA, MethodDesc callee, OutputNode calleeNode, int calleeRVA, int callCount, CrossPageCall callType)
{
Caller = caller;
CallerNode = callerNode;
CallerRVA = callerRVA;
Callee = callee;
CalleeNode = calleeNode;
CalleeRVA = calleeRVA;
CallCount = callCount;
CallType = callType;
}
}
private readonly OutputInfoBuilder _outputInfoBuilder;
private readonly CallChainProfile _callChainProfile;
private readonly TargetDetails _targetDetails;
private readonly int _pageSize;
private Dictionary<MethodDesc, ISymbolDefinitionNode> _symbolMethodMap;
private List<CallInfo> _callInfo;
public ProfileFileBuilder(OutputInfoBuilder outputInfoBuilder, CallChainProfile callChainProfile, TargetDetails targetDetails)
{
_outputInfoBuilder = outputInfoBuilder;
_callChainProfile = callChainProfile;
_targetDetails = targetDetails;
_pageSize = _targetDetails.Architecture switch
{
TargetArchitecture.X86 => 0x00001000,
TargetArchitecture.X64 => 0x00010000,
TargetArchitecture.ARM => 0x00001000,
TargetArchitecture.ARM64 => 0x00010000,
_ => throw new NotImplementedException(_targetDetails.Architecture.ToString())
};
}
public void SaveProfile(string profileFileName)
{
Console.WriteLine("Emitting profile file: {0}", profileFileName);
CalculateCallInfo();
using (StreamWriter writer = new StreamWriter(profileFileName))
{
writer.WriteLine("CHARACTERISTIC | PAIR COUNT | CALL COUNT | PERCENTAGE");
writer.WriteLine("----------------------------------------------------------------");
int callCount = _callInfo.Sum(info => info.CallCount);
double percentFactor = 100.0 / Math.Max(callCount, 1);
writer.WriteLine("ENTRIES TOTAL | {0,10} | {1,10} | {2,10:F2}", _callInfo.Count, callCount, callCount * percentFactor);
int resolvedPairCount = _callInfo.Sum(info => info.CallType == CrossPageCall.Unresolved ? 0 : 1);
int resolvedCallCount = _callInfo.Sum(info => info.CallType == CrossPageCall.Unresolved ? 0 : info.CallCount);
writer.WriteLine("RESOLVED ENTRIES | {0,10} | {1,10} | {2,10:F2}", resolvedPairCount, resolvedCallCount, resolvedCallCount * percentFactor);
int unresolvedPairCount = _callInfo.Count - resolvedPairCount;
int unresolvedCallCount = callCount - resolvedCallCount;
writer.WriteLine("UNRESOLVED ENTRIES | {0,10} | {1,10} | {2,10:F2}", unresolvedPairCount, unresolvedCallCount, unresolvedCallCount * percentFactor);
int nearPairCount = _callInfo.Sum(info => info.CallType == CrossPageCall.No ? 1 : 0);
int nearCallCount = _callInfo.Sum(info => info.CallType == CrossPageCall.No ? info.CallCount : 0);
writer.WriteLine("NEAR (INTRA-PAGE) CALLS | {0,10} | {1,10} | {2,10:F2}", nearPairCount, nearCallCount, nearCallCount * percentFactor);
int farPairCount = _callInfo.Sum(info => info.CallType == CrossPageCall.Yes ? 1 : 0);
int farCallCount = _callInfo.Sum(info => info.CallType == CrossPageCall.Yes ? info.CallCount : 0);
writer.WriteLine("FAR (CROSS-PAGE) CALLS | {0,10} | {1,10} | {2,10:F2}", farPairCount, farCallCount, farCallCount * percentFactor);
writer.WriteLine();
writer.WriteLine("CALLER RVA | CALLER LEN | CALLEE RVA | CALLEE LEN | COUNT | FAR (CROSS-PAGE) CALLS (CALLER -> CALLEE)");
writer.WriteLine("----------------------------------------------------------------------------------------------------------");
DumpCallInfo(writer, _callInfo.Where(info => info.CallType == CrossPageCall.Yes).OrderByDescending(info => info.CallCount));
writer.WriteLine();
writer.WriteLine("CALLER RVA | CALLER LEN | CALLEE RVA | CALLEE LEN | COUNT | NEAR (INTRA-PAGE) CALLS (CALLER -> CALLEE)");
writer.WriteLine("-----------------------------------------------------------------------------------------------------------");
DumpCallInfo(writer, _callInfo.Where(info => info.CallType == CrossPageCall.No).OrderByDescending(info => info.CallCount));
}
}
private void DumpCallInfo(StreamWriter writer, IEnumerable<CallInfo> callInfos)
{
foreach (CallInfo callInfo in callInfos)
{
writer.Write($@"{callInfo.CallerRVA,10:X8} | ");
writer.Write($@"{callInfo.CallerNode.Length,10:X8} | ");
writer.Write($@"{callInfo.CalleeRVA,10:X8} | ");
writer.Write($@"{callInfo.CalleeNode.Length,10:X8} | ");
writer.Write($@"{callInfo.CallCount,10} | ");
writer.WriteLine($@"{callInfo.Caller.ToString()} -> {callInfo.Callee.ToString()}");
}
}
private void CalculateSymbolMethodMap()
{
if (_symbolMethodMap != null)
{
// Already calculated
return;
}
_symbolMethodMap = new Dictionary<MethodDesc, ISymbolDefinitionNode>();
foreach (KeyValuePair<ISymbolDefinitionNode, MethodWithGCInfo> kvpSymbolMethod in _outputInfoBuilder.MethodSymbolMap)
{
_symbolMethodMap.Add(kvpSymbolMethod.Value.Method, kvpSymbolMethod.Key);
}
}
private void CalculateCallInfo()
{
if (_callInfo != null)
{
// Already calculated
return;
}
CalculateSymbolMethodMap();
_callInfo = new List<CallInfo>();
foreach (KeyValuePair<MethodDesc, Dictionary<MethodDesc, int>> kvpCallerCalleeCount in _callChainProfile.ResolvedProfileData)
{
OutputNode callerNode = null;
int callerRVA = 0;
if (_symbolMethodMap.TryGetValue(kvpCallerCalleeCount.Key, out ISymbolDefinitionNode callerSymbol) &&
_outputInfoBuilder.NodeSymbolMap.TryGetValue(callerSymbol, out callerNode))
{
callerRVA = _outputInfoBuilder.Sections[callerNode.SectionIndex].RVAWhenPlaced + callerNode.Offset;
}
foreach (KeyValuePair<MethodDesc, int> kvpCalleeCount in kvpCallerCalleeCount.Value)
{
OutputNode calleeNode = null;
int calleeRVA = 0;
if (_symbolMethodMap.TryGetValue(kvpCalleeCount.Key, out ISymbolDefinitionNode calleeSymbol) &&
_outputInfoBuilder.NodeSymbolMap.TryGetValue(calleeSymbol, out calleeNode))
{
calleeRVA = _outputInfoBuilder.Sections[calleeNode.SectionIndex].RVAWhenPlaced + calleeNode.Offset;
}
_callInfo.Add(new CallInfo(
caller: kvpCallerCalleeCount.Key,
callerNode: callerNode,
callerRVA: callerRVA,
callee: kvpCalleeCount.Key,
calleeNode: calleeNode,
calleeRVA: calleeRVA,
callCount: kvpCalleeCount.Value,
callType: GetCallType(callerNode, callerRVA, calleeNode, calleeRVA)));
}
}
}
private CrossPageCall GetCallType(OutputNode caller, int callerRVA, OutputNode callee, int calleeRVA)
{
if (caller == null || callee == null)
{
return CrossPageCall.Unresolved;
}
int callerStartPage = callerRVA / _pageSize;
int callerEndPage = (callerRVA + caller.Length - 1) / _pageSize;
int calleePage = calleeRVA / _pageSize;
if (callerStartPage == calleePage && callerEndPage == calleePage)
{
// The entire caller and the callee entrypoint are on the same page, no cross-page call penalty
return CrossPageCall.No;
}
// Pessimistic estimate - we don't know where exactly the call is, we just know that it might cross a page.
return CrossPageCall.Yes;
}
}
}
| -1 |
dotnet/runtime | 66,057 | Address TODO to switch to generated p/invoke | Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | elinor-fung | 2022-03-02T03:31:28Z | 2022-03-02T19:08:30Z | a4b8893a118357b55c0add9a39cc5aeb097a0bb8 | 1abbbb4adf6bf02549f4c6e021176534dcc4f974 | Address TODO to switch to generated p/invoke. Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | ./src/libraries/System.IO.Ports/tests/SerialPort/Write_char_int_int_Generic.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics;
using System.IO.PortsTests;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Legacy.Support;
using Xunit;
using Microsoft.DotNet.XUnitExtensions;
namespace System.IO.Ports.Tests
{
public class Write_char_int_int_generic : PortsTest
{
//Set bounds fore random timeout values.
//If the min is to low write will not timeout accurately and the testcase will fail
private const int minRandomTimeout = 250;
//If the max is to large then the testcase will take forever to run
private const int maxRandomTimeout = 2000;
//If the percentage difference between the expected timeout and the actual timeout
//found through Stopwatch is greater then 10% then the timeout value was not correctly
//to the write method and the testcase fails.
private static double s_maxPercentageDifference = .15;
//The char size used when veryifying exceptions that write will throw
private const int CHAR_SIZE_EXCEPTION = 4;
//The char size used when veryifying timeout
private const int CHAR_SIZE_TIMEOUT = 4;
//The char size used when veryifying BytesToWrite
private const int CHAR_SIZE_BYTES_TO_WRITE = 4;
//The char size used when veryifying Handshake
private const int CHAR_SIZE_HANDSHAKE = 8;
private const int NUM_TRYS = 5;
#region Test Cases
[Fact]
public void WriteWithoutOpen()
{
using (SerialPort com = new SerialPort())
{
Debug.WriteLine("Verifying write method throws exception without a call to Open()");
VerifyWriteException(com, typeof(InvalidOperationException));
}
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void WriteAfterFailedOpen()
{
using (SerialPort com = new SerialPort("BAD_PORT_NAME"))
{
Debug.WriteLine("Verifying write method throws exception with a failed call to Open()");
//Since the PortName is set to a bad port name Open will thrown an exception
//however we don't care what it is since we are verifying a write method
Assert.ThrowsAny<Exception>(() => com.Open());
VerifyWriteException(com, typeof(InvalidOperationException));
}
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void WriteAfterClose()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Debug.WriteLine("Verifying write method throws exception after a call to Cloes()");
com.Open();
com.Close();
VerifyWriteException(com, typeof(InvalidOperationException));
}
}
[KnownFailure]
[ConditionalFact(nameof(HasNullModem))]
public void Timeout()
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
Random rndGen = new Random(-55);
byte[] XOffBuffer = new byte[1];
XOffBuffer[0] = 19;
com1.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout);
com1.Handshake = Handshake.XOnXOff;
Debug.WriteLine("Verifying WriteTimeout={0}", com1.WriteTimeout);
com1.Open();
com2.Open();
com2.Write(XOffBuffer, 0, 1);
Thread.Sleep(250);
com2.Close();
VerifyTimeout(com1);
}
}
[Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // Timing-sensitive
[ConditionalFact(nameof(HasOneSerialPort), nameof(HasHardwareFlowControl))]
public void SuccessiveReadTimeout()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Random rndGen = new Random(-55);
com.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout);
com.Handshake = Handshake.RequestToSendXOnXOff;
// com.Encoding = new System.Text.UTF7Encoding();
com.Encoding = Encoding.Unicode;
Debug.WriteLine("Verifying WriteTimeout={0} with successive call to write method", com.WriteTimeout);
com.Open();
try
{
com.Write(new char[CHAR_SIZE_TIMEOUT], 0, CHAR_SIZE_TIMEOUT);
}
catch (TimeoutException)
{
}
VerifyTimeout(com);
}
}
[ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))]
public void SuccessiveReadTimeoutWithWriteSucceeding()
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Random rndGen = new Random(-55);
AsyncEnableRts asyncEnableRts = new AsyncEnableRts();
var t = new Task(asyncEnableRts.EnableRTS);
com1.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout);
com1.Handshake = Handshake.RequestToSend;
com1.Encoding = new UTF8Encoding();
Debug.WriteLine("Verifying WriteTimeout={0} with successive call to write method with the write succeeding sometime before its timeout", com1.WriteTimeout);
com1.Open();
//Call EnableRTS asynchronously this will enable RTS in the middle of the following write call allowing it to succeed
//before the timeout is reached
t.Start();
TCSupport.WaitForTaskToStart(t);
try
{
com1.Write(new char[CHAR_SIZE_TIMEOUT], 0, CHAR_SIZE_TIMEOUT);
}
catch (TimeoutException)
{
}
asyncEnableRts.Stop();
TCSupport.WaitForTaskCompletion(t);
VerifyTimeout(com1);
}
}
[ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))]
public void BytesToWrite()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
AsyncWriteRndCharArray asyncWriteRndCharArray = new AsyncWriteRndCharArray(com, CHAR_SIZE_BYTES_TO_WRITE);
var t = new Task(asyncWriteRndCharArray.WriteRndCharArray);
Debug.WriteLine("Verifying BytesToWrite with one call to Write");
com.Handshake = Handshake.RequestToSend;
com.Open();
com.WriteTimeout = 500;
//Write a random char[] asynchronously so we can verify some things while the write call is blocking
t.Start();
TCSupport.WaitForTaskToStart(t);
TCSupport.WaitForExactWriteBufferLoad(com, CHAR_SIZE_BYTES_TO_WRITE);
TCSupport.WaitForTaskCompletion(t);
}
}
[ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))]
public void BytesToWriteSuccessive()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
AsyncWriteRndCharArray asyncWriteRndCharArray = new AsyncWriteRndCharArray(com, CHAR_SIZE_BYTES_TO_WRITE);
var t1 = new Task(asyncWriteRndCharArray.WriteRndCharArray);
var t2 = new Task(asyncWriteRndCharArray.WriteRndCharArray);
Debug.WriteLine("Verifying BytesToWrite with successive calls to Write");
com.Handshake = Handshake.RequestToSend;
com.Open();
com.WriteTimeout = 4000;
//Write a random char[] asynchronously so we can verify some things while the write call is blocking
t1.Start();
TCSupport.WaitForTaskToStart(t1);
TCSupport.WaitForExactWriteBufferLoad(com, CHAR_SIZE_BYTES_TO_WRITE);
//Write a random char[] asynchronously so we can verify some things while the write call is blocking
t2.Start();
TCSupport.WaitForTaskToStart(t2);
TCSupport.WaitForExactWriteBufferLoad(com, CHAR_SIZE_BYTES_TO_WRITE * 2);
//Wait for both write methods to timeout
TCSupport.WaitForTaskCompletion(t1);
var aggregatedException = Assert.Throws<AggregateException>(() => TCSupport.WaitForTaskCompletion(t2));
Assert.IsType<IOException>(aggregatedException.InnerException);
}
}
[ConditionalFact(nameof(HasNullModem))]
public void Handshake_None()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
AsyncWriteRndCharArray asyncWriteRndCharArray = new AsyncWriteRndCharArray(com, CHAR_SIZE_HANDSHAKE);
var t = new Task(asyncWriteRndCharArray.WriteRndCharArray);
//Write a random char[] asynchronously so we can verify some things while the write call is blocking
Debug.WriteLine("Verifying Handshake=None");
com.Open();
t.Start();
TCSupport.WaitForTaskCompletion(t);
Assert.Equal(0, com.BytesToWrite);
}
}
[ConditionalFact(nameof(HasNullModem))]
public void Handshake_RequestToSend()
{
Verify_Handshake(Handshake.RequestToSend);
}
[KnownFailure]
[ConditionalFact(nameof(HasNullModem))]
public void Handshake_XOnXOff()
{
Verify_Handshake(Handshake.XOnXOff);
}
[KnownFailure]
[ConditionalFact(nameof(HasNullModem))]
public void Handshake_RequestToSendXOnXOff()
{
Verify_Handshake(Handshake.RequestToSendXOnXOff);
}
public class AsyncEnableRts
{
private bool _stop;
public void EnableRTS()
{
lock (this)
{
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
Random rndGen = new Random(-55);
int sleepPeriod = rndGen.Next(minRandomTimeout, maxRandomTimeout / 2);
//Sleep some random period with of a maximum duration of half the largest possible timeout value for a write method on COM1
Thread.Sleep(sleepPeriod);
com2.Open();
com2.RtsEnable = true;
while (!_stop)
Monitor.Wait(this);
com2.RtsEnable = false;
}
}
}
public void Stop()
{
lock (this)
{
_stop = true;
Monitor.Pulse(this);
}
}
}
public class AsyncWriteRndCharArray
{
private readonly SerialPort _com;
private readonly int _charLength;
public AsyncWriteRndCharArray(SerialPort com, int charLength)
{
_com = com;
_charLength = charLength;
}
public void WriteRndCharArray()
{
char[] buffer = TCSupport.GetRandomChars(_charLength, TCSupport.CharacterOptions.Surrogates);
try
{
_com.Write(buffer, 0, buffer.Length);
}
catch (TimeoutException)
{
}
}
}
#endregion
#region Verification for Test Cases
private static void VerifyWriteException(SerialPort com, Type expectedException)
{
Assert.Throws(expectedException, () => com.Write(new char[CHAR_SIZE_EXCEPTION], 0, CHAR_SIZE_EXCEPTION));
}
private void VerifyTimeout(SerialPort com)
{
Stopwatch timer = new Stopwatch();
int expectedTime = com.WriteTimeout;
int actualTime = 0;
double percentageDifference;
try
{
com.Write(new char[CHAR_SIZE_TIMEOUT], 0, CHAR_SIZE_TIMEOUT); //Warm up write method
}
catch (TimeoutException) { }
Thread.CurrentThread.Priority = ThreadPriority.Highest;
for (int i = 0; i < NUM_TRYS; i++)
{
timer.Start();
try
{
com.Write(new char[CHAR_SIZE_TIMEOUT], 0, CHAR_SIZE_TIMEOUT);
}
catch (TimeoutException) { }
timer.Stop();
actualTime += (int)timer.ElapsedMilliseconds;
timer.Reset();
}
Thread.CurrentThread.Priority = ThreadPriority.Normal;
actualTime /= NUM_TRYS;
percentageDifference = Math.Abs((expectedTime - actualTime) / (double)expectedTime);
//Verify that the percentage difference between the expected and actual timeout is less then maxPercentageDifference
if (s_maxPercentageDifference < percentageDifference)
{
Fail("ERROR!!!: The write method timedout in {0} expected {1} percentage difference: {2}", actualTime, expectedTime, percentageDifference);
}
}
private void Verify_Handshake(Handshake handshake)
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
bool rts = Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake;
bool xonxoff = Handshake.XOnXOff == handshake || Handshake.RequestToSendXOnXOff == handshake;
byte[] XOffBuffer = new byte[1];
byte[] XOnBuffer = new byte[1];
XOffBuffer[0] = 19;
XOnBuffer[0] = 17;
Debug.WriteLine("Verifying Handshake={0}", handshake);
com1.Handshake = handshake;
com1.Open();
com2.Open();
//Setup to ensure write will block with type of handshake method being used
if (rts)
{
com2.RtsEnable = false;
}
if (xonxoff)
{
com2.Write(XOffBuffer, 0, 1);
Thread.Sleep(250);
}
char[] writeArr = new char[] { 'A', 'B', 'C' };
Task writeTask = Task.Run(() => com1.Write(writeArr, 0, writeArr.Length));
CancellationTokenSource cts = new CancellationTokenSource();
Task<int> readTask = com2.BaseStream.ReadAsync(new byte[3], 0, 3, cts.Token);
// Give it some time to make sure transmission doesn't happen
Thread.Sleep(200);
Assert.False(readTask.IsCompleted);
cts.CancelAfter(500);
if (rts)
{
Assert.False(com1.CtsHolding);
com2.RtsEnable = true;
}
if (xonxoff)
{
com2.Write(XOnBuffer, 0, 1);
}
writeTask.Wait();
Assert.True(readTask.Result > 0);
//Verify that CtsHolding is true if the RequestToSend or RequestToSendXOnXOff handshake method is used
if (rts)
{
Assert.True(com1.CtsHolding);
}
}
}
#endregion
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics;
using System.IO.PortsTests;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Legacy.Support;
using Xunit;
using Microsoft.DotNet.XUnitExtensions;
namespace System.IO.Ports.Tests
{
public class Write_char_int_int_generic : PortsTest
{
//Set bounds fore random timeout values.
//If the min is to low write will not timeout accurately and the testcase will fail
private const int minRandomTimeout = 250;
//If the max is to large then the testcase will take forever to run
private const int maxRandomTimeout = 2000;
//If the percentage difference between the expected timeout and the actual timeout
//found through Stopwatch is greater then 10% then the timeout value was not correctly
//to the write method and the testcase fails.
private static double s_maxPercentageDifference = .15;
//The char size used when veryifying exceptions that write will throw
private const int CHAR_SIZE_EXCEPTION = 4;
//The char size used when veryifying timeout
private const int CHAR_SIZE_TIMEOUT = 4;
//The char size used when veryifying BytesToWrite
private const int CHAR_SIZE_BYTES_TO_WRITE = 4;
//The char size used when veryifying Handshake
private const int CHAR_SIZE_HANDSHAKE = 8;
private const int NUM_TRYS = 5;
#region Test Cases
[Fact]
public void WriteWithoutOpen()
{
using (SerialPort com = new SerialPort())
{
Debug.WriteLine("Verifying write method throws exception without a call to Open()");
VerifyWriteException(com, typeof(InvalidOperationException));
}
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void WriteAfterFailedOpen()
{
using (SerialPort com = new SerialPort("BAD_PORT_NAME"))
{
Debug.WriteLine("Verifying write method throws exception with a failed call to Open()");
//Since the PortName is set to a bad port name Open will thrown an exception
//however we don't care what it is since we are verifying a write method
Assert.ThrowsAny<Exception>(() => com.Open());
VerifyWriteException(com, typeof(InvalidOperationException));
}
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void WriteAfterClose()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Debug.WriteLine("Verifying write method throws exception after a call to Cloes()");
com.Open();
com.Close();
VerifyWriteException(com, typeof(InvalidOperationException));
}
}
[KnownFailure]
[ConditionalFact(nameof(HasNullModem))]
public void Timeout()
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
Random rndGen = new Random(-55);
byte[] XOffBuffer = new byte[1];
XOffBuffer[0] = 19;
com1.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout);
com1.Handshake = Handshake.XOnXOff;
Debug.WriteLine("Verifying WriteTimeout={0}", com1.WriteTimeout);
com1.Open();
com2.Open();
com2.Write(XOffBuffer, 0, 1);
Thread.Sleep(250);
com2.Close();
VerifyTimeout(com1);
}
}
[Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // Timing-sensitive
[ConditionalFact(nameof(HasOneSerialPort), nameof(HasHardwareFlowControl))]
public void SuccessiveReadTimeout()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Random rndGen = new Random(-55);
com.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout);
com.Handshake = Handshake.RequestToSendXOnXOff;
// com.Encoding = new System.Text.UTF7Encoding();
com.Encoding = Encoding.Unicode;
Debug.WriteLine("Verifying WriteTimeout={0} with successive call to write method", com.WriteTimeout);
com.Open();
try
{
com.Write(new char[CHAR_SIZE_TIMEOUT], 0, CHAR_SIZE_TIMEOUT);
}
catch (TimeoutException)
{
}
VerifyTimeout(com);
}
}
[ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))]
public void SuccessiveReadTimeoutWithWriteSucceeding()
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Random rndGen = new Random(-55);
AsyncEnableRts asyncEnableRts = new AsyncEnableRts();
var t = new Task(asyncEnableRts.EnableRTS);
com1.WriteTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout);
com1.Handshake = Handshake.RequestToSend;
com1.Encoding = new UTF8Encoding();
Debug.WriteLine("Verifying WriteTimeout={0} with successive call to write method with the write succeeding sometime before its timeout", com1.WriteTimeout);
com1.Open();
//Call EnableRTS asynchronously this will enable RTS in the middle of the following write call allowing it to succeed
//before the timeout is reached
t.Start();
TCSupport.WaitForTaskToStart(t);
try
{
com1.Write(new char[CHAR_SIZE_TIMEOUT], 0, CHAR_SIZE_TIMEOUT);
}
catch (TimeoutException)
{
}
asyncEnableRts.Stop();
TCSupport.WaitForTaskCompletion(t);
VerifyTimeout(com1);
}
}
[ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))]
public void BytesToWrite()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
AsyncWriteRndCharArray asyncWriteRndCharArray = new AsyncWriteRndCharArray(com, CHAR_SIZE_BYTES_TO_WRITE);
var t = new Task(asyncWriteRndCharArray.WriteRndCharArray);
Debug.WriteLine("Verifying BytesToWrite with one call to Write");
com.Handshake = Handshake.RequestToSend;
com.Open();
com.WriteTimeout = 500;
//Write a random char[] asynchronously so we can verify some things while the write call is blocking
t.Start();
TCSupport.WaitForTaskToStart(t);
TCSupport.WaitForExactWriteBufferLoad(com, CHAR_SIZE_BYTES_TO_WRITE);
TCSupport.WaitForTaskCompletion(t);
}
}
[ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))]
public void BytesToWriteSuccessive()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
AsyncWriteRndCharArray asyncWriteRndCharArray = new AsyncWriteRndCharArray(com, CHAR_SIZE_BYTES_TO_WRITE);
var t1 = new Task(asyncWriteRndCharArray.WriteRndCharArray);
var t2 = new Task(asyncWriteRndCharArray.WriteRndCharArray);
Debug.WriteLine("Verifying BytesToWrite with successive calls to Write");
com.Handshake = Handshake.RequestToSend;
com.Open();
com.WriteTimeout = 4000;
//Write a random char[] asynchronously so we can verify some things while the write call is blocking
t1.Start();
TCSupport.WaitForTaskToStart(t1);
TCSupport.WaitForExactWriteBufferLoad(com, CHAR_SIZE_BYTES_TO_WRITE);
//Write a random char[] asynchronously so we can verify some things while the write call is blocking
t2.Start();
TCSupport.WaitForTaskToStart(t2);
TCSupport.WaitForExactWriteBufferLoad(com, CHAR_SIZE_BYTES_TO_WRITE * 2);
//Wait for both write methods to timeout
TCSupport.WaitForTaskCompletion(t1);
var aggregatedException = Assert.Throws<AggregateException>(() => TCSupport.WaitForTaskCompletion(t2));
Assert.IsType<IOException>(aggregatedException.InnerException);
}
}
[ConditionalFact(nameof(HasNullModem))]
public void Handshake_None()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
AsyncWriteRndCharArray asyncWriteRndCharArray = new AsyncWriteRndCharArray(com, CHAR_SIZE_HANDSHAKE);
var t = new Task(asyncWriteRndCharArray.WriteRndCharArray);
//Write a random char[] asynchronously so we can verify some things while the write call is blocking
Debug.WriteLine("Verifying Handshake=None");
com.Open();
t.Start();
TCSupport.WaitForTaskCompletion(t);
Assert.Equal(0, com.BytesToWrite);
}
}
[ConditionalFact(nameof(HasNullModem))]
public void Handshake_RequestToSend()
{
Verify_Handshake(Handshake.RequestToSend);
}
[KnownFailure]
[ConditionalFact(nameof(HasNullModem))]
public void Handshake_XOnXOff()
{
Verify_Handshake(Handshake.XOnXOff);
}
[KnownFailure]
[ConditionalFact(nameof(HasNullModem))]
public void Handshake_RequestToSendXOnXOff()
{
Verify_Handshake(Handshake.RequestToSendXOnXOff);
}
public class AsyncEnableRts
{
private bool _stop;
public void EnableRTS()
{
lock (this)
{
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
Random rndGen = new Random(-55);
int sleepPeriod = rndGen.Next(minRandomTimeout, maxRandomTimeout / 2);
//Sleep some random period with of a maximum duration of half the largest possible timeout value for a write method on COM1
Thread.Sleep(sleepPeriod);
com2.Open();
com2.RtsEnable = true;
while (!_stop)
Monitor.Wait(this);
com2.RtsEnable = false;
}
}
}
public void Stop()
{
lock (this)
{
_stop = true;
Monitor.Pulse(this);
}
}
}
public class AsyncWriteRndCharArray
{
private readonly SerialPort _com;
private readonly int _charLength;
public AsyncWriteRndCharArray(SerialPort com, int charLength)
{
_com = com;
_charLength = charLength;
}
public void WriteRndCharArray()
{
char[] buffer = TCSupport.GetRandomChars(_charLength, TCSupport.CharacterOptions.Surrogates);
try
{
_com.Write(buffer, 0, buffer.Length);
}
catch (TimeoutException)
{
}
}
}
#endregion
#region Verification for Test Cases
private static void VerifyWriteException(SerialPort com, Type expectedException)
{
Assert.Throws(expectedException, () => com.Write(new char[CHAR_SIZE_EXCEPTION], 0, CHAR_SIZE_EXCEPTION));
}
private void VerifyTimeout(SerialPort com)
{
Stopwatch timer = new Stopwatch();
int expectedTime = com.WriteTimeout;
int actualTime = 0;
double percentageDifference;
try
{
com.Write(new char[CHAR_SIZE_TIMEOUT], 0, CHAR_SIZE_TIMEOUT); //Warm up write method
}
catch (TimeoutException) { }
Thread.CurrentThread.Priority = ThreadPriority.Highest;
for (int i = 0; i < NUM_TRYS; i++)
{
timer.Start();
try
{
com.Write(new char[CHAR_SIZE_TIMEOUT], 0, CHAR_SIZE_TIMEOUT);
}
catch (TimeoutException) { }
timer.Stop();
actualTime += (int)timer.ElapsedMilliseconds;
timer.Reset();
}
Thread.CurrentThread.Priority = ThreadPriority.Normal;
actualTime /= NUM_TRYS;
percentageDifference = Math.Abs((expectedTime - actualTime) / (double)expectedTime);
//Verify that the percentage difference between the expected and actual timeout is less then maxPercentageDifference
if (s_maxPercentageDifference < percentageDifference)
{
Fail("ERROR!!!: The write method timedout in {0} expected {1} percentage difference: {2}", actualTime, expectedTime, percentageDifference);
}
}
private void Verify_Handshake(Handshake handshake)
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
bool rts = Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake;
bool xonxoff = Handshake.XOnXOff == handshake || Handshake.RequestToSendXOnXOff == handshake;
byte[] XOffBuffer = new byte[1];
byte[] XOnBuffer = new byte[1];
XOffBuffer[0] = 19;
XOnBuffer[0] = 17;
Debug.WriteLine("Verifying Handshake={0}", handshake);
com1.Handshake = handshake;
com1.Open();
com2.Open();
//Setup to ensure write will block with type of handshake method being used
if (rts)
{
com2.RtsEnable = false;
}
if (xonxoff)
{
com2.Write(XOffBuffer, 0, 1);
Thread.Sleep(250);
}
char[] writeArr = new char[] { 'A', 'B', 'C' };
Task writeTask = Task.Run(() => com1.Write(writeArr, 0, writeArr.Length));
CancellationTokenSource cts = new CancellationTokenSource();
Task<int> readTask = com2.BaseStream.ReadAsync(new byte[3], 0, 3, cts.Token);
// Give it some time to make sure transmission doesn't happen
Thread.Sleep(200);
Assert.False(readTask.IsCompleted);
cts.CancelAfter(500);
if (rts)
{
Assert.False(com1.CtsHolding);
com2.RtsEnable = true;
}
if (xonxoff)
{
com2.Write(XOnBuffer, 0, 1);
}
writeTask.Wait();
Assert.True(readTask.Result > 0);
//Verify that CtsHolding is true if the RequestToSend or RequestToSendXOnXOff handshake method is used
if (rts)
{
Assert.True(com1.CtsHolding);
}
}
}
#endregion
}
}
| -1 |
dotnet/runtime | 66,057 | Address TODO to switch to generated p/invoke | Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | elinor-fung | 2022-03-02T03:31:28Z | 2022-03-02T19:08:30Z | a4b8893a118357b55c0add9a39cc5aeb097a0bb8 | 1abbbb4adf6bf02549f4c6e021176534dcc4f974 | Address TODO to switch to generated p/invoke. Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | ./src/libraries/System.Security.Permissions/src/System/Security/Policy/CodeConnectAccess.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.Policy
{
public partial class CodeConnectAccess
{
public static readonly string AnyScheme;
public static readonly int DefaultPort;
public static readonly int OriginPort;
public static readonly string OriginScheme;
public CodeConnectAccess(string allowScheme, int allowPort) { }
public int Port { get { return 0; } }
public string Scheme { get { return null; } }
public static CodeConnectAccess CreateAnySchemeAccess(int allowPort) { return default(CodeConnectAccess); }
public static CodeConnectAccess CreateOriginSchemeAccess(int allowPort) { return default(CodeConnectAccess); }
public override bool Equals(object o) => base.Equals(o);
public override int GetHashCode() => base.GetHashCode();
}
}
| // 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.Policy
{
public partial class CodeConnectAccess
{
public static readonly string AnyScheme;
public static readonly int DefaultPort;
public static readonly int OriginPort;
public static readonly string OriginScheme;
public CodeConnectAccess(string allowScheme, int allowPort) { }
public int Port { get { return 0; } }
public string Scheme { get { return null; } }
public static CodeConnectAccess CreateAnySchemeAccess(int allowPort) { return default(CodeConnectAccess); }
public static CodeConnectAccess CreateOriginSchemeAccess(int allowPort) { return default(CodeConnectAccess); }
public override bool Equals(object o) => base.Equals(o);
public override int GetHashCode() => base.GetHashCode();
}
}
| -1 |
dotnet/runtime | 66,057 | Address TODO to switch to generated p/invoke | Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | elinor-fung | 2022-03-02T03:31:28Z | 2022-03-02T19:08:30Z | a4b8893a118357b55c0add9a39cc5aeb097a0bb8 | 1abbbb4adf6bf02549f4c6e021176534dcc4f974 | Address TODO to switch to generated p/invoke. Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | ./src/libraries/System.Diagnostics.TraceSource/tests/DefaultTraceListenerClassTests.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.Reflection;
using System.Reflection.Emit;
using System.Linq;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
namespace System.Diagnostics.TraceSourceTests
{
public class DefaultTraceListenerClassTests : FileCleanupTestBase
{
private class TestDefaultTraceListener : DefaultTraceListener
{
private StringWriter _writer;
public bool ShouldOverrideWriteLine { get; set; } = true;
public TestDefaultTraceListener()
{
_writer = new StringWriter();
AssertUiEnabled = false;
}
public string Output
{
get { return _writer.ToString(); }
}
public override void Write(string message)
{
_writer.Write(message);
}
public override void WriteLine(string message)
{
if (ShouldOverrideWriteLine)
{
_writer.WriteLine(message);
}
else
{
base.WriteLine(message);
}
}
}
[Fact]
public void Constructor()
{
var listener = new DefaultTraceListener();
Assert.Equal("Default", listener.Name);
}
[Fact]
public void Fail()
{
var listener = new TestDefaultTraceListener();
listener.Fail("FAIL");
Assert.Contains("FAIL", listener.Output);
}
[Fact]
public void Fail_WithoutWriteLineOverride()
{
var listener = new TestDefaultTraceListener();
listener.ShouldOverrideWriteLine = false;
listener.Fail("FAIL");
Assert.DoesNotContain("FAIL", listener.Output);
}
[Fact]
public void Fail_WithLogFile()
{
var listener = new TestDefaultTraceListener();
string pathToLogFile = GetTestFilePath();
listener.LogFileName = pathToLogFile;
listener.ShouldOverrideWriteLine = false;
listener.Fail("FAIL");
Assert.True(File.Exists(pathToLogFile));
Assert.Contains("FAIL", File.ReadAllText(pathToLogFile));
}
[Fact]
public void Fail_LogFileDirectoryNotFound()
{
// Exception should be handled by DefaultTraceListener.WriteLine so no need to assert.
var listener = new TestDefaultTraceListener();
listener.LogFileName = $"{Guid.NewGuid().ToString("N")}\\LogFile.txt";
listener.ShouldOverrideWriteLine = false;
listener.Fail("FAIL");
}
[Fact]
public void TraceEvent()
{
var listener = new TestDefaultTraceListener();
listener.TraceEvent(new TraceEventCache(), "Test", TraceEventType.Critical, 1);
Assert.Contains("Test", listener.Output);
}
[Fact]
public void WriteNull()
{
var listener = new DefaultTraceListener();
// implied assert, does not throw
listener.Write(null);
}
[Fact]
public void WriteLongMessage()
{
var listener = new DefaultTraceListener();
var longString = new string('a', 0x40000);
listener.Write(longString);
// nothing to assert, the output is written to Debug.Write
// this simply provides code-coverage
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void AssertUiEnabledPropertyTest(bool expectedAssertUiEnabled)
{
var listener = new DefaultTraceListener() { AssertUiEnabled = expectedAssertUiEnabled };
Assert.Equal(expectedAssertUiEnabled, listener.AssertUiEnabled);
}
[Theory]
[InlineData("LogFile")]
public void LogFileNamePropertyTest(string expectedLogFileName)
{
var listener = new DefaultTraceListener();
//it should be initialized with the default
Assert.Equal(string.Empty, listener.LogFileName);
listener.LogFileName = expectedLogFileName;
Assert.Equal(expectedLogFileName, listener.LogFileName);
}
[ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
public void EntryAssemblyName_Default_IncludedInTrace()
{
RemoteExecutor.Invoke(() =>
{
var listener = new TestDefaultTraceListener();
Trace.Listeners.Add(listener);
Trace.TraceError("hello world");
Assert.Equal(Assembly.GetEntryAssembly()?.GetName().Name + " Error: 0 : hello world", listener.Output.Trim());
}).Dispose();
}
[ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
public void EntryAssemblyName_Null_NotIncludedInTrace()
{
RemoteExecutor.Invoke(() =>
{
MakeAssemblyGetEntryAssemblyReturnNull();
var listener = new TestDefaultTraceListener();
Trace.Listeners.Add(listener);
Trace.TraceError("hello world");
Assert.Equal("Error: 0 : hello world", listener.Output.Trim());
}).Dispose();
}
/// <summary>
/// Makes Assembly.GetEntryAssembly() return null using private reflection.
/// </summary>
private static void MakeAssemblyGetEntryAssemblyReturnNull()
{
typeof(Assembly)
.GetField("s_forceNullEntryPoint", BindingFlags.NonPublic | BindingFlags.Static)
.SetValue(null, true);
Assert.Null(Assembly.GetEntryAssembly());
}
}
}
| // 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.Reflection;
using System.Reflection.Emit;
using System.Linq;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
namespace System.Diagnostics.TraceSourceTests
{
public class DefaultTraceListenerClassTests : FileCleanupTestBase
{
private class TestDefaultTraceListener : DefaultTraceListener
{
private StringWriter _writer;
public bool ShouldOverrideWriteLine { get; set; } = true;
public TestDefaultTraceListener()
{
_writer = new StringWriter();
AssertUiEnabled = false;
}
public string Output
{
get { return _writer.ToString(); }
}
public override void Write(string message)
{
_writer.Write(message);
}
public override void WriteLine(string message)
{
if (ShouldOverrideWriteLine)
{
_writer.WriteLine(message);
}
else
{
base.WriteLine(message);
}
}
}
[Fact]
public void Constructor()
{
var listener = new DefaultTraceListener();
Assert.Equal("Default", listener.Name);
}
[Fact]
public void Fail()
{
var listener = new TestDefaultTraceListener();
listener.Fail("FAIL");
Assert.Contains("FAIL", listener.Output);
}
[Fact]
public void Fail_WithoutWriteLineOverride()
{
var listener = new TestDefaultTraceListener();
listener.ShouldOverrideWriteLine = false;
listener.Fail("FAIL");
Assert.DoesNotContain("FAIL", listener.Output);
}
[Fact]
public void Fail_WithLogFile()
{
var listener = new TestDefaultTraceListener();
string pathToLogFile = GetTestFilePath();
listener.LogFileName = pathToLogFile;
listener.ShouldOverrideWriteLine = false;
listener.Fail("FAIL");
Assert.True(File.Exists(pathToLogFile));
Assert.Contains("FAIL", File.ReadAllText(pathToLogFile));
}
[Fact]
public void Fail_LogFileDirectoryNotFound()
{
// Exception should be handled by DefaultTraceListener.WriteLine so no need to assert.
var listener = new TestDefaultTraceListener();
listener.LogFileName = $"{Guid.NewGuid().ToString("N")}\\LogFile.txt";
listener.ShouldOverrideWriteLine = false;
listener.Fail("FAIL");
}
[Fact]
public void TraceEvent()
{
var listener = new TestDefaultTraceListener();
listener.TraceEvent(new TraceEventCache(), "Test", TraceEventType.Critical, 1);
Assert.Contains("Test", listener.Output);
}
[Fact]
public void WriteNull()
{
var listener = new DefaultTraceListener();
// implied assert, does not throw
listener.Write(null);
}
[Fact]
public void WriteLongMessage()
{
var listener = new DefaultTraceListener();
var longString = new string('a', 0x40000);
listener.Write(longString);
// nothing to assert, the output is written to Debug.Write
// this simply provides code-coverage
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void AssertUiEnabledPropertyTest(bool expectedAssertUiEnabled)
{
var listener = new DefaultTraceListener() { AssertUiEnabled = expectedAssertUiEnabled };
Assert.Equal(expectedAssertUiEnabled, listener.AssertUiEnabled);
}
[Theory]
[InlineData("LogFile")]
public void LogFileNamePropertyTest(string expectedLogFileName)
{
var listener = new DefaultTraceListener();
//it should be initialized with the default
Assert.Equal(string.Empty, listener.LogFileName);
listener.LogFileName = expectedLogFileName;
Assert.Equal(expectedLogFileName, listener.LogFileName);
}
[ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
public void EntryAssemblyName_Default_IncludedInTrace()
{
RemoteExecutor.Invoke(() =>
{
var listener = new TestDefaultTraceListener();
Trace.Listeners.Add(listener);
Trace.TraceError("hello world");
Assert.Equal(Assembly.GetEntryAssembly()?.GetName().Name + " Error: 0 : hello world", listener.Output.Trim());
}).Dispose();
}
[ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
public void EntryAssemblyName_Null_NotIncludedInTrace()
{
RemoteExecutor.Invoke(() =>
{
MakeAssemblyGetEntryAssemblyReturnNull();
var listener = new TestDefaultTraceListener();
Trace.Listeners.Add(listener);
Trace.TraceError("hello world");
Assert.Equal("Error: 0 : hello world", listener.Output.Trim());
}).Dispose();
}
/// <summary>
/// Makes Assembly.GetEntryAssembly() return null using private reflection.
/// </summary>
private static void MakeAssemblyGetEntryAssemblyReturnNull()
{
typeof(Assembly)
.GetField("s_forceNullEntryPoint", BindingFlags.NonPublic | BindingFlags.Static)
.SetValue(null, true);
Assert.Null(Assembly.GetEntryAssembly());
}
}
}
| -1 |
dotnet/runtime | 66,057 | Address TODO to switch to generated p/invoke | Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | elinor-fung | 2022-03-02T03:31:28Z | 2022-03-02T19:08:30Z | a4b8893a118357b55c0add9a39cc5aeb097a0bb8 | 1abbbb4adf6bf02549f4c6e021176534dcc4f974 | Address TODO to switch to generated p/invoke. Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | ./src/tests/Loader/classloader/nesting/coreclr/VSW491577.csproj | <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<OutputType>Exe</OutputType>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<ItemGroup>
<Compile Include="vsw491577.cs" />
</ItemGroup>
</Project>
| <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<OutputType>Exe</OutputType>
<CLRTestPriority>1</CLRTestPriority>
</PropertyGroup>
<ItemGroup>
<Compile Include="vsw491577.cs" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime | 66,057 | Address TODO to switch to generated p/invoke | Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | elinor-fung | 2022-03-02T03:31:28Z | 2022-03-02T19:08:30Z | a4b8893a118357b55c0add9a39cc5aeb097a0bb8 | 1abbbb4adf6bf02549f4c6e021176534dcc4f974 | Address TODO to switch to generated p/invoke. Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | ./src/mono/mono/tests/inctest.cs | using System;
class Test {
int i;
int Foo ()
{
i = 3;
return (i++) + (i++);
}
public static int Main ()
{
Test t = new Test ();
if (t.Foo () != 7)
return 1;
return 0;
}
}
| using System;
class Test {
int i;
int Foo ()
{
i = 3;
return (i++) + (i++);
}
public static int Main ()
{
Test t = new Test ();
if (t.Foo () != 7)
return 1;
return 0;
}
}
| -1 |
dotnet/runtime | 66,057 | Address TODO to switch to generated p/invoke | Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | elinor-fung | 2022-03-02T03:31:28Z | 2022-03-02T19:08:30Z | a4b8893a118357b55c0add9a39cc5aeb097a0bb8 | 1abbbb4adf6bf02549f4c6e021176534dcc4f974 | Address TODO to switch to generated p/invoke. Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | ./src/tests/JIT/HardwareIntrinsics/X86/Sse2/Add.Int16.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void AddInt16()
{
var test = new SimpleBinaryOpTest__AddInt16();
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__AddInt16
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int16[] inArray1, Int16[] inArray2, Int16[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Int16> _fld1;
public Vector128<Int16> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__AddInt16 testClass)
{
var result = Sse2.Add(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__AddInt16 testClass)
{
fixed (Vector128<Int16>* pFld1 = &_fld1)
fixed (Vector128<Int16>* pFld2 = &_fld2)
{
var result = Sse2.Add(
Sse2.LoadVector128((Int16*)(pFld1)),
Sse2.LoadVector128((Int16*)(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<Int16>>() / sizeof(Int16);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16);
private static Int16[] _data1 = new Int16[Op1ElementCount];
private static Int16[] _data2 = new Int16[Op2ElementCount];
private static Vector128<Int16> _clsVar1;
private static Vector128<Int16> _clsVar2;
private Vector128<Int16> _fld1;
private Vector128<Int16> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__AddInt16()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
}
public SimpleBinaryOpTest__AddInt16()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
_dataTable = new DataTable(_data1, _data2, new Int16[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse2.Add(
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse2.Add(
Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int16*)(_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 = Sse2.Add(
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse2).GetMethod(nameof(Sse2.Add), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse2).GetMethod(nameof(Sse2.Add), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse2).GetMethod(nameof(Sse2.Add), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.Add(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Int16>* pClsVar1 = &_clsVar1)
fixed (Vector128<Int16>* pClsVar2 = &_clsVar2)
{
var result = Sse2.Add(
Sse2.LoadVector128((Int16*)(pClsVar1)),
Sse2.LoadVector128((Int16*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr);
var result = Sse2.Add(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((Int16*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr));
var result = Sse2.Add(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((Int16*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr));
var result = Sse2.Add(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__AddInt16();
var result = Sse2.Add(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__AddInt16();
fixed (Vector128<Int16>* pFld1 = &test._fld1)
fixed (Vector128<Int16>* pFld2 = &test._fld2)
{
var result = Sse2.Add(
Sse2.LoadVector128((Int16*)(pFld1)),
Sse2.LoadVector128((Int16*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.Add(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Int16>* pFld1 = &_fld1)
fixed (Vector128<Int16>* pFld2 = &_fld2)
{
var result = Sse2.Add(
Sse2.LoadVector128((Int16*)(pFld1)),
Sse2.LoadVector128((Int16*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse2.Add(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 = Sse2.Add(
Sse2.LoadVector128((Int16*)(&test._fld1)),
Sse2.LoadVector128((Int16*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Int16> op1, Vector128<Int16> op2, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int16[] left, Int16[] right, Int16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((short)(left[0] + right[0]) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((short)(left[i] + right[i]) != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.Add)}<Int16>(Vector128<Int16>, Vector128<Int16>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void AddInt16()
{
var test = new SimpleBinaryOpTest__AddInt16();
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__AddInt16
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int16[] inArray1, Int16[] inArray2, Int16[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Int16> _fld1;
public Vector128<Int16> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__AddInt16 testClass)
{
var result = Sse2.Add(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__AddInt16 testClass)
{
fixed (Vector128<Int16>* pFld1 = &_fld1)
fixed (Vector128<Int16>* pFld2 = &_fld2)
{
var result = Sse2.Add(
Sse2.LoadVector128((Int16*)(pFld1)),
Sse2.LoadVector128((Int16*)(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<Int16>>() / sizeof(Int16);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16);
private static Int16[] _data1 = new Int16[Op1ElementCount];
private static Int16[] _data2 = new Int16[Op2ElementCount];
private static Vector128<Int16> _clsVar1;
private static Vector128<Int16> _clsVar2;
private Vector128<Int16> _fld1;
private Vector128<Int16> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__AddInt16()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
}
public SimpleBinaryOpTest__AddInt16()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
_dataTable = new DataTable(_data1, _data2, new Int16[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse2.Add(
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse2.Add(
Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int16*)(_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 = Sse2.Add(
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse2).GetMethod(nameof(Sse2.Add), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse2).GetMethod(nameof(Sse2.Add), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse2).GetMethod(nameof(Sse2.Add), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.Add(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Int16>* pClsVar1 = &_clsVar1)
fixed (Vector128<Int16>* pClsVar2 = &_clsVar2)
{
var result = Sse2.Add(
Sse2.LoadVector128((Int16*)(pClsVar1)),
Sse2.LoadVector128((Int16*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr);
var result = Sse2.Add(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((Int16*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr));
var result = Sse2.Add(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((Int16*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr));
var result = Sse2.Add(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__AddInt16();
var result = Sse2.Add(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__AddInt16();
fixed (Vector128<Int16>* pFld1 = &test._fld1)
fixed (Vector128<Int16>* pFld2 = &test._fld2)
{
var result = Sse2.Add(
Sse2.LoadVector128((Int16*)(pFld1)),
Sse2.LoadVector128((Int16*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.Add(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Int16>* pFld1 = &_fld1)
fixed (Vector128<Int16>* pFld2 = &_fld2)
{
var result = Sse2.Add(
Sse2.LoadVector128((Int16*)(pFld1)),
Sse2.LoadVector128((Int16*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse2.Add(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 = Sse2.Add(
Sse2.LoadVector128((Int16*)(&test._fld1)),
Sse2.LoadVector128((Int16*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Int16> op1, Vector128<Int16> op2, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int16[] left, Int16[] right, Int16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((short)(left[0] + right[0]) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((short)(left[i] + right[i]) != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.Add)}<Int16>(Vector128<Int16>, Vector128<Int16>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
dotnet/runtime | 66,057 | Address TODO to switch to generated p/invoke | Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | elinor-fung | 2022-03-02T03:31:28Z | 2022-03-02T19:08:30Z | a4b8893a118357b55c0add9a39cc5aeb097a0bb8 | 1abbbb4adf6bf02549f4c6e021176534dcc4f974 | Address TODO to switch to generated p/invoke. Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | ./src/libraries/System.Private.CoreLib/src/System/Threading/PortableThreadPool.HillClimbing.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics;
using System.Diagnostics.Tracing;
namespace System.Threading
{
internal sealed partial class PortableThreadPool
{
/// <summary>
/// Hill climbing algorithm used for determining the number of threads needed for the thread pool.
/// </summary>
private sealed partial class HillClimbing
{
private const int LogCapacity = 200;
private const int DefaultSampleIntervalMsLow = 10;
private const int DefaultSampleIntervalMsHigh = 200;
public static readonly bool IsDisabled = AppContextConfigHelper.GetBooleanConfig("System.Threading.ThreadPool.HillClimbing.Disable", false);
// SOS's ThreadPool command depends on this name
public static readonly HillClimbing ThreadPoolHillClimber = new HillClimbing();
// SOS's ThreadPool command depends on the enum values
public enum StateOrTransition
{
Warmup,
Initializing,
RandomMove,
ClimbingMove,
ChangePoint,
Stabilizing,
Starvation,
ThreadTimedOut,
CooperativeBlocking,
}
// SOS's ThreadPool command depends on the names of all fields
private struct LogEntry
{
public int tickCount;
public StateOrTransition stateOrTransition;
public int newControlSetting;
public int lastHistoryCount;
public float lastHistoryMean;
}
private readonly int _wavePeriod;
private readonly int _samplesToMeasure;
private readonly double _targetThroughputRatio;
private readonly double _targetSignalToNoiseRatio;
private readonly double _maxChangePerSecond;
private readonly double _maxChangePerSample;
private readonly int _maxThreadWaveMagnitude;
private readonly int _sampleIntervalMsLow;
private readonly double _threadMagnitudeMultiplier;
private readonly int _sampleIntervalMsHigh;
private readonly double _throughputErrorSmoothingFactor;
private readonly double _gainExponent;
private readonly double _maxSampleError;
private double _currentControlSetting;
private long _totalSamples;
private int _lastThreadCount;
private double _averageThroughputNoise;
private double _secondsElapsedSinceLastChange;
private double _completionsSinceLastChange;
private int _accumulatedCompletionCount;
private double _accumulatedSampleDurationSeconds;
private readonly double[] _samples;
private readonly double[] _threadCounts;
private int _currentSampleMs;
private readonly Random _randomIntervalGenerator = new Random();
private readonly LogEntry[] _log = new LogEntry[LogCapacity]; // SOS's ThreadPool command depends on this name
private int _logStart; // SOS's ThreadPool command depends on this name
private int _logSize; // SOS's ThreadPool command depends on this name
public HillClimbing()
{
_wavePeriod = AppContextConfigHelper.GetInt32Config("System.Threading.ThreadPool.HillClimbing.WavePeriod", 4, false);
_maxThreadWaveMagnitude = AppContextConfigHelper.GetInt32Config("System.Threading.ThreadPool.HillClimbing.MaxWaveMagnitude", 20, false);
_threadMagnitudeMultiplier = AppContextConfigHelper.GetInt32Config("System.Threading.ThreadPool.HillClimbing.WaveMagnitudeMultiplier", 100, false) / 100.0;
_samplesToMeasure = _wavePeriod * AppContextConfigHelper.GetInt32Config("System.Threading.ThreadPool.HillClimbing.WaveHistorySize", 8, false);
_targetThroughputRatio = AppContextConfigHelper.GetInt32Config("System.Threading.ThreadPool.HillClimbing.Bias", 15, false) / 100.0;
_targetSignalToNoiseRatio = AppContextConfigHelper.GetInt32Config("System.Threading.ThreadPool.HillClimbing.TargetSignalToNoiseRatio", 300, false) / 100.0;
_maxChangePerSecond = AppContextConfigHelper.GetInt32Config("System.Threading.ThreadPool.HillClimbing.MaxChangePerSecond", 4, false);
_maxChangePerSample = AppContextConfigHelper.GetInt32Config("System.Threading.ThreadPool.HillClimbing.MaxChangePerSample", 20, false);
int sampleIntervalMsLow = AppContextConfigHelper.GetInt32Config("System.Threading.ThreadPool.HillClimbing.SampleIntervalLow", DefaultSampleIntervalMsLow, false);
int sampleIntervalMsHigh = AppContextConfigHelper.GetInt32Config("System.Threading.ThreadPool.HillClimbing.SampleIntervalHigh", DefaultSampleIntervalMsHigh, false);
if (sampleIntervalMsLow <= sampleIntervalMsHigh)
{
_sampleIntervalMsLow = sampleIntervalMsLow;
_sampleIntervalMsHigh = sampleIntervalMsHigh;
}
else
{
_sampleIntervalMsLow = DefaultSampleIntervalMsLow;
_sampleIntervalMsHigh = DefaultSampleIntervalMsHigh;
}
_throughputErrorSmoothingFactor = AppContextConfigHelper.GetInt32Config("System.Threading.ThreadPool.HillClimbing.ErrorSmoothingFactor", 1, false) / 100.0;
_gainExponent = AppContextConfigHelper.GetInt32Config("System.Threading.ThreadPool.HillClimbing.GainExponent", 200, false) / 100.0;
_maxSampleError = AppContextConfigHelper.GetInt32Config("System.Threading.ThreadPool.HillClimbing.MaxSampleErrorPercent", 15, false) / 100.0;
_samples = new double[_samplesToMeasure];
_threadCounts = new double[_samplesToMeasure];
_currentSampleMs = _randomIntervalGenerator.Next(_sampleIntervalMsLow, _sampleIntervalMsHigh + 1);
}
public (int newThreadCount, int newSampleMs) Update(int currentThreadCount, double sampleDurationSeconds, int numCompletions)
{
//
// If someone changed the thread count without telling us, update our records accordingly.
//
if (currentThreadCount != _lastThreadCount)
ForceChange(currentThreadCount, StateOrTransition.Initializing);
//
// Update the cumulative stats for this thread count
//
_secondsElapsedSinceLastChange += sampleDurationSeconds;
_completionsSinceLastChange += numCompletions;
//
// Add in any data we've already collected about this sample
//
sampleDurationSeconds += _accumulatedSampleDurationSeconds;
numCompletions += _accumulatedCompletionCount;
//
// We need to make sure we're collecting reasonably accurate data. Since we're just counting the end
// of each work item, we are goinng to be missing some data about what really happened during the
// sample interval. The count produced by each thread includes an initial work item that may have
// started well before the start of the interval, and each thread may have been running some new
// work item for some time before the end of the interval, which did not yet get counted. So
// our count is going to be off by +/- threadCount workitems.
//
// The exception is that the thread that reported to us last time definitely wasn't running any work
// at that time, and the thread that's reporting now definitely isn't running a work item now. So
// we really only need to consider threadCount-1 threads.
//
// Thus the percent error in our count is +/- (threadCount-1)/numCompletions.
//
// We cannot rely on the frequency-domain analysis we'll be doing later to filter out this error, because
// of the way it accumulates over time. If this sample is off by, say, 33% in the negative direction,
// then the next one likely will be too. The one after that will include the sum of the completions
// we missed in the previous samples, and so will be 33% positive. So every three samples we'll have
// two "low" samples and one "high" sample. This will appear as periodic variation right in the frequency
// range we're targeting, which will not be filtered by the frequency-domain translation.
//
if (_totalSamples > 0 && ((currentThreadCount - 1.0) / numCompletions) >= _maxSampleError)
{
// not accurate enough yet. Let's accumulate the data so far, and tell the ThreadPool
// to collect a little more.
_accumulatedSampleDurationSeconds = sampleDurationSeconds;
_accumulatedCompletionCount = numCompletions;
return (currentThreadCount, 10);
}
//
// We've got enouugh data for our sample; reset our accumulators for next time.
//
_accumulatedSampleDurationSeconds = 0;
_accumulatedCompletionCount = 0;
//
// Add the current thread count and throughput sample to our history
//
double throughput = numCompletions / sampleDurationSeconds;
if (NativeRuntimeEventSource.Log.IsEnabled())
{
NativeRuntimeEventSource.Log.ThreadPoolWorkerThreadAdjustmentSample(throughput);
}
int sampleIndex = (int)(_totalSamples % _samplesToMeasure);
_samples[sampleIndex] = throughput;
_threadCounts[sampleIndex] = currentThreadCount;
_totalSamples++;
//
// Set up defaults for our metrics
//
Complex threadWaveComponent = default;
Complex throughputWaveComponent = default;
double throughputErrorEstimate = 0;
Complex ratio = default;
double confidence = 0;
StateOrTransition state = StateOrTransition.Warmup;
//
// How many samples will we use? It must be at least the three wave periods we're looking for, and it must also be a whole
// multiple of the primary wave's period; otherwise the frequency we're looking for will fall between two frequency bands
// in the Fourier analysis, and we won't be able to measure it accurately.
//
int sampleCount = ((int)Math.Min(_totalSamples - 1, _samplesToMeasure)) / _wavePeriod * _wavePeriod;
if (sampleCount > _wavePeriod)
{
//
// Average the throughput and thread count samples, so we can scale the wave magnitudes later.
//
double sampleSum = 0;
double threadSum = 0;
for (int i = 0; i < sampleCount; i++)
{
sampleSum += _samples[(_totalSamples - sampleCount + i) % _samplesToMeasure];
threadSum += _threadCounts[(_totalSamples - sampleCount + i) % _samplesToMeasure];
}
double averageThroughput = sampleSum / sampleCount;
double averageThreadCount = threadSum / sampleCount;
if (averageThroughput > 0 && averageThreadCount > 0)
{
//
// Calculate the periods of the adjacent frequency bands we'll be using to measure noise levels.
// We want the two adjacent Fourier frequency bands.
//
double adjacentPeriod1 = sampleCount / (((double)sampleCount / _wavePeriod) + 1);
double adjacentPeriod2 = sampleCount / (((double)sampleCount / _wavePeriod) - 1);
//
// Get the the three different frequency components of the throughput (scaled by average
// throughput). Our "error" estimate (the amount of noise that might be present in the
// frequency band we're really interested in) is the average of the adjacent bands.
//
throughputWaveComponent = GetWaveComponent(_samples, sampleCount, _wavePeriod) / averageThroughput;
throughputErrorEstimate = (GetWaveComponent(_samples, sampleCount, adjacentPeriod1) / averageThroughput).Abs();
if (adjacentPeriod2 <= sampleCount)
{
throughputErrorEstimate = Math.Max(throughputErrorEstimate, (GetWaveComponent(_samples, sampleCount, adjacentPeriod2) / averageThroughput).Abs());
}
//
// Do the same for the thread counts, so we have something to compare to. We don't measure thread count
// noise, because there is none; these are exact measurements.
//
threadWaveComponent = GetWaveComponent(_threadCounts, sampleCount, _wavePeriod) / averageThreadCount;
//
// Update our moving average of the throughput noise. We'll use this later as feedback to
// determine the new size of the thread wave.
//
if (_averageThroughputNoise == 0)
_averageThroughputNoise = throughputErrorEstimate;
else
_averageThroughputNoise = (_throughputErrorSmoothingFactor * throughputErrorEstimate) + ((1.0 - _throughputErrorSmoothingFactor) * _averageThroughputNoise);
if (threadWaveComponent.Abs() > 0)
{
//
// Adjust the throughput wave so it's centered around the target wave, and then calculate the adjusted throughput/thread ratio.
//
ratio = (throughputWaveComponent - (_targetThroughputRatio * threadWaveComponent)) / threadWaveComponent;
state = StateOrTransition.ClimbingMove;
}
else
{
ratio = new Complex(0, 0);
state = StateOrTransition.Stabilizing;
}
//
// Calculate how confident we are in the ratio. More noise == less confident. This has
// the effect of slowing down movements that might be affected by random noise.
//
double noiseForConfidence = Math.Max(_averageThroughputNoise, throughputErrorEstimate);
if (noiseForConfidence > 0)
confidence = (threadWaveComponent.Abs() / noiseForConfidence) / _targetSignalToNoiseRatio;
else
confidence = 1.0; //there is no noise!
}
}
//
// We use just the real part of the complex ratio we just calculated. If the throughput signal
// is exactly in phase with the thread signal, this will be the same as taking the magnitude of
// the complex move and moving that far up. If they're 180 degrees out of phase, we'll move
// backward (because this indicates that our changes are having the opposite of the intended effect).
// If they're 90 degrees out of phase, we won't move at all, because we can't tell whether we're
// having a negative or positive effect on throughput.
//
double move = Math.Min(1.0, Math.Max(-1.0, ratio.Real));
//
// Apply our confidence multiplier.
//
move *= Math.Min(1.0, Math.Max(0.0, confidence));
//
// Now apply non-linear gain, such that values around zero are attenuated, while higher values
// are enhanced. This allows us to move quickly if we're far away from the target, but more slowly
// if we're getting close, giving us rapid ramp-up without wild oscillations around the target.
//
double gain = _maxChangePerSecond * sampleDurationSeconds;
move = Math.Pow(Math.Abs(move), _gainExponent) * (move >= 0.0 ? 1 : -1) * gain;
move = Math.Min(move, _maxChangePerSample);
//
// If the result was positive, and CPU is > 95%, refuse the move.
//
PortableThreadPool threadPoolInstance = ThreadPoolInstance;
if (move > 0.0 && threadPoolInstance._cpuUtilization > CpuUtilizationHigh)
move = 0.0;
//
// Apply the move to our control setting
//
_currentControlSetting += move;
//
// Calculate the new thread wave magnitude, which is based on the moving average we've been keeping of
// the throughput error. This average starts at zero, so we'll start with a nice safe little wave at first.
//
int newThreadWaveMagnitude = (int)(0.5 + (_currentControlSetting * _averageThroughputNoise * _targetSignalToNoiseRatio * _threadMagnitudeMultiplier * 2.0));
newThreadWaveMagnitude = Math.Min(newThreadWaveMagnitude, _maxThreadWaveMagnitude);
newThreadWaveMagnitude = Math.Max(newThreadWaveMagnitude, 1);
//
// Make sure our control setting is within the ThreadPool's limits. When some threads are blocked due to
// cooperative blocking, ensure that hill climbing does not decrease the thread count below the expected
// minimum.
//
int maxThreads = threadPoolInstance._maxThreads;
int minThreads = threadPoolInstance.MinThreadsGoal;
_currentControlSetting = Math.Min(maxThreads - newThreadWaveMagnitude, _currentControlSetting);
_currentControlSetting = Math.Max(minThreads, _currentControlSetting);
//
// Calculate the new thread count (control setting + square wave)
//
int newThreadCount = (int)(_currentControlSetting + newThreadWaveMagnitude * ((_totalSamples / (_wavePeriod / 2)) % 2));
//
// Make sure the new thread count doesn't exceed the ThreadPool's limits
//
newThreadCount = Math.Min(maxThreads, newThreadCount);
newThreadCount = Math.Max(minThreads, newThreadCount);
//
// Record these numbers for posterity
//
if (NativeRuntimeEventSource.Log.IsEnabled())
{
NativeRuntimeEventSource.Log.ThreadPoolWorkerThreadAdjustmentStats(sampleDurationSeconds, throughput, threadWaveComponent.Real, throughputWaveComponent.Real,
throughputErrorEstimate, _averageThroughputNoise, ratio.Real, confidence, _currentControlSetting, (ushort)newThreadWaveMagnitude);
}
//
// If all of this caused an actual change in thread count, log that as well.
//
if (newThreadCount != currentThreadCount)
{
ChangeThreadCount(newThreadCount, state);
_secondsElapsedSinceLastChange = 0;
_completionsSinceLastChange = 0;
}
//
// Return the new thread count and sample interval. This is randomized to prevent correlations with other periodic
// changes in throughput. Among other things, this prevents us from getting confused by Hill Climbing instances
// running in other processes.
//
// If we're at minThreads, and we seem to be hurting performance by going higher, we can't go any lower to fix this. So
// we'll simply stay at minThreads much longer, and only occasionally try a higher value.
//
int newSampleInterval;
if (ratio.Real < 0.0 && newThreadCount == minThreads)
newSampleInterval = (int)(0.5 + _currentSampleMs * (10.0 * Math.Min(-ratio.Real, 1.0)));
else
newSampleInterval = _currentSampleMs;
return (newThreadCount, newSampleInterval);
}
private void ChangeThreadCount(int newThreadCount, StateOrTransition state)
{
_lastThreadCount = newThreadCount;
if (state != StateOrTransition.CooperativeBlocking) // this can be noisy
{
_currentSampleMs = _randomIntervalGenerator.Next(_sampleIntervalMsLow, _sampleIntervalMsHigh + 1);
}
double throughput = _secondsElapsedSinceLastChange > 0 ? _completionsSinceLastChange / _secondsElapsedSinceLastChange : 0;
LogTransition(newThreadCount, throughput, state);
}
private void LogTransition(int newThreadCount, double throughput, StateOrTransition stateOrTransition)
{
// Use the _log array as a circular array for log entries
int index = (_logStart + _logSize) % LogCapacity;
if (_logSize == LogCapacity)
{
_logStart = (_logStart + 1) % LogCapacity;
_logSize--; // hide this slot while we update it
}
ref LogEntry entry = ref _log[index];
entry.tickCount = Environment.TickCount;
entry.stateOrTransition = stateOrTransition;
entry.newControlSetting = newThreadCount;
entry.lastHistoryCount = (int)(Math.Min(_totalSamples, _samplesToMeasure) / _wavePeriod) * _wavePeriod;
entry.lastHistoryMean = (float)throughput;
_logSize++;
if (NativeRuntimeEventSource.Log.IsEnabled())
{
NativeRuntimeEventSource.Log.ThreadPoolWorkerThreadAdjustmentAdjustment(
throughput,
(uint)newThreadCount,
(NativeRuntimeEventSource.ThreadAdjustmentReasonMap)stateOrTransition);
}
}
public void ForceChange(int newThreadCount, StateOrTransition state)
{
if (_lastThreadCount != newThreadCount)
{
_currentControlSetting += newThreadCount - _lastThreadCount;
ChangeThreadCount(newThreadCount, state);
}
}
private Complex GetWaveComponent(double[] samples, int numSamples, double period)
{
Debug.Assert(numSamples >= period); // can't measure a wave that doesn't fit
Debug.Assert(period >= 2); // can't measure above the Nyquist frequency
Debug.Assert(numSamples <= samples.Length); // can't measure more samples than we have
//
// Calculate the sinusoid with the given period.
// We're using the Goertzel algorithm for this. See http://en.wikipedia.org/wiki/Goertzel_algorithm.
//
double w = 2 * Math.PI / period;
double cos = Math.Cos(w);
double coeff = 2 * cos;
double q0, q1 = 0, q2 = 0;
for (int i = 0; i < numSamples; ++i)
{
q0 = coeff * q1 - q2 + samples[(_totalSamples - numSamples + i) % _samplesToMeasure];
q2 = q1;
q1 = q0;
}
return new Complex(q1 - q2 * cos, q2 * Math.Sin(w)) / numSamples;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics;
using System.Diagnostics.Tracing;
namespace System.Threading
{
internal sealed partial class PortableThreadPool
{
/// <summary>
/// Hill climbing algorithm used for determining the number of threads needed for the thread pool.
/// </summary>
private sealed partial class HillClimbing
{
private const int LogCapacity = 200;
private const int DefaultSampleIntervalMsLow = 10;
private const int DefaultSampleIntervalMsHigh = 200;
public static readonly bool IsDisabled = AppContextConfigHelper.GetBooleanConfig("System.Threading.ThreadPool.HillClimbing.Disable", false);
// SOS's ThreadPool command depends on this name
public static readonly HillClimbing ThreadPoolHillClimber = new HillClimbing();
// SOS's ThreadPool command depends on the enum values
public enum StateOrTransition
{
Warmup,
Initializing,
RandomMove,
ClimbingMove,
ChangePoint,
Stabilizing,
Starvation,
ThreadTimedOut,
CooperativeBlocking,
}
// SOS's ThreadPool command depends on the names of all fields
private struct LogEntry
{
public int tickCount;
public StateOrTransition stateOrTransition;
public int newControlSetting;
public int lastHistoryCount;
public float lastHistoryMean;
}
private readonly int _wavePeriod;
private readonly int _samplesToMeasure;
private readonly double _targetThroughputRatio;
private readonly double _targetSignalToNoiseRatio;
private readonly double _maxChangePerSecond;
private readonly double _maxChangePerSample;
private readonly int _maxThreadWaveMagnitude;
private readonly int _sampleIntervalMsLow;
private readonly double _threadMagnitudeMultiplier;
private readonly int _sampleIntervalMsHigh;
private readonly double _throughputErrorSmoothingFactor;
private readonly double _gainExponent;
private readonly double _maxSampleError;
private double _currentControlSetting;
private long _totalSamples;
private int _lastThreadCount;
private double _averageThroughputNoise;
private double _secondsElapsedSinceLastChange;
private double _completionsSinceLastChange;
private int _accumulatedCompletionCount;
private double _accumulatedSampleDurationSeconds;
private readonly double[] _samples;
private readonly double[] _threadCounts;
private int _currentSampleMs;
private readonly Random _randomIntervalGenerator = new Random();
private readonly LogEntry[] _log = new LogEntry[LogCapacity]; // SOS's ThreadPool command depends on this name
private int _logStart; // SOS's ThreadPool command depends on this name
private int _logSize; // SOS's ThreadPool command depends on this name
public HillClimbing()
{
_wavePeriod = AppContextConfigHelper.GetInt32Config("System.Threading.ThreadPool.HillClimbing.WavePeriod", 4, false);
_maxThreadWaveMagnitude = AppContextConfigHelper.GetInt32Config("System.Threading.ThreadPool.HillClimbing.MaxWaveMagnitude", 20, false);
_threadMagnitudeMultiplier = AppContextConfigHelper.GetInt32Config("System.Threading.ThreadPool.HillClimbing.WaveMagnitudeMultiplier", 100, false) / 100.0;
_samplesToMeasure = _wavePeriod * AppContextConfigHelper.GetInt32Config("System.Threading.ThreadPool.HillClimbing.WaveHistorySize", 8, false);
_targetThroughputRatio = AppContextConfigHelper.GetInt32Config("System.Threading.ThreadPool.HillClimbing.Bias", 15, false) / 100.0;
_targetSignalToNoiseRatio = AppContextConfigHelper.GetInt32Config("System.Threading.ThreadPool.HillClimbing.TargetSignalToNoiseRatio", 300, false) / 100.0;
_maxChangePerSecond = AppContextConfigHelper.GetInt32Config("System.Threading.ThreadPool.HillClimbing.MaxChangePerSecond", 4, false);
_maxChangePerSample = AppContextConfigHelper.GetInt32Config("System.Threading.ThreadPool.HillClimbing.MaxChangePerSample", 20, false);
int sampleIntervalMsLow = AppContextConfigHelper.GetInt32Config("System.Threading.ThreadPool.HillClimbing.SampleIntervalLow", DefaultSampleIntervalMsLow, false);
int sampleIntervalMsHigh = AppContextConfigHelper.GetInt32Config("System.Threading.ThreadPool.HillClimbing.SampleIntervalHigh", DefaultSampleIntervalMsHigh, false);
if (sampleIntervalMsLow <= sampleIntervalMsHigh)
{
_sampleIntervalMsLow = sampleIntervalMsLow;
_sampleIntervalMsHigh = sampleIntervalMsHigh;
}
else
{
_sampleIntervalMsLow = DefaultSampleIntervalMsLow;
_sampleIntervalMsHigh = DefaultSampleIntervalMsHigh;
}
_throughputErrorSmoothingFactor = AppContextConfigHelper.GetInt32Config("System.Threading.ThreadPool.HillClimbing.ErrorSmoothingFactor", 1, false) / 100.0;
_gainExponent = AppContextConfigHelper.GetInt32Config("System.Threading.ThreadPool.HillClimbing.GainExponent", 200, false) / 100.0;
_maxSampleError = AppContextConfigHelper.GetInt32Config("System.Threading.ThreadPool.HillClimbing.MaxSampleErrorPercent", 15, false) / 100.0;
_samples = new double[_samplesToMeasure];
_threadCounts = new double[_samplesToMeasure];
_currentSampleMs = _randomIntervalGenerator.Next(_sampleIntervalMsLow, _sampleIntervalMsHigh + 1);
}
public (int newThreadCount, int newSampleMs) Update(int currentThreadCount, double sampleDurationSeconds, int numCompletions)
{
//
// If someone changed the thread count without telling us, update our records accordingly.
//
if (currentThreadCount != _lastThreadCount)
ForceChange(currentThreadCount, StateOrTransition.Initializing);
//
// Update the cumulative stats for this thread count
//
_secondsElapsedSinceLastChange += sampleDurationSeconds;
_completionsSinceLastChange += numCompletions;
//
// Add in any data we've already collected about this sample
//
sampleDurationSeconds += _accumulatedSampleDurationSeconds;
numCompletions += _accumulatedCompletionCount;
//
// We need to make sure we're collecting reasonably accurate data. Since we're just counting the end
// of each work item, we are goinng to be missing some data about what really happened during the
// sample interval. The count produced by each thread includes an initial work item that may have
// started well before the start of the interval, and each thread may have been running some new
// work item for some time before the end of the interval, which did not yet get counted. So
// our count is going to be off by +/- threadCount workitems.
//
// The exception is that the thread that reported to us last time definitely wasn't running any work
// at that time, and the thread that's reporting now definitely isn't running a work item now. So
// we really only need to consider threadCount-1 threads.
//
// Thus the percent error in our count is +/- (threadCount-1)/numCompletions.
//
// We cannot rely on the frequency-domain analysis we'll be doing later to filter out this error, because
// of the way it accumulates over time. If this sample is off by, say, 33% in the negative direction,
// then the next one likely will be too. The one after that will include the sum of the completions
// we missed in the previous samples, and so will be 33% positive. So every three samples we'll have
// two "low" samples and one "high" sample. This will appear as periodic variation right in the frequency
// range we're targeting, which will not be filtered by the frequency-domain translation.
//
if (_totalSamples > 0 && ((currentThreadCount - 1.0) / numCompletions) >= _maxSampleError)
{
// not accurate enough yet. Let's accumulate the data so far, and tell the ThreadPool
// to collect a little more.
_accumulatedSampleDurationSeconds = sampleDurationSeconds;
_accumulatedCompletionCount = numCompletions;
return (currentThreadCount, 10);
}
//
// We've got enouugh data for our sample; reset our accumulators for next time.
//
_accumulatedSampleDurationSeconds = 0;
_accumulatedCompletionCount = 0;
//
// Add the current thread count and throughput sample to our history
//
double throughput = numCompletions / sampleDurationSeconds;
if (NativeRuntimeEventSource.Log.IsEnabled())
{
NativeRuntimeEventSource.Log.ThreadPoolWorkerThreadAdjustmentSample(throughput);
}
int sampleIndex = (int)(_totalSamples % _samplesToMeasure);
_samples[sampleIndex] = throughput;
_threadCounts[sampleIndex] = currentThreadCount;
_totalSamples++;
//
// Set up defaults for our metrics
//
Complex threadWaveComponent = default;
Complex throughputWaveComponent = default;
double throughputErrorEstimate = 0;
Complex ratio = default;
double confidence = 0;
StateOrTransition state = StateOrTransition.Warmup;
//
// How many samples will we use? It must be at least the three wave periods we're looking for, and it must also be a whole
// multiple of the primary wave's period; otherwise the frequency we're looking for will fall between two frequency bands
// in the Fourier analysis, and we won't be able to measure it accurately.
//
int sampleCount = ((int)Math.Min(_totalSamples - 1, _samplesToMeasure)) / _wavePeriod * _wavePeriod;
if (sampleCount > _wavePeriod)
{
//
// Average the throughput and thread count samples, so we can scale the wave magnitudes later.
//
double sampleSum = 0;
double threadSum = 0;
for (int i = 0; i < sampleCount; i++)
{
sampleSum += _samples[(_totalSamples - sampleCount + i) % _samplesToMeasure];
threadSum += _threadCounts[(_totalSamples - sampleCount + i) % _samplesToMeasure];
}
double averageThroughput = sampleSum / sampleCount;
double averageThreadCount = threadSum / sampleCount;
if (averageThroughput > 0 && averageThreadCount > 0)
{
//
// Calculate the periods of the adjacent frequency bands we'll be using to measure noise levels.
// We want the two adjacent Fourier frequency bands.
//
double adjacentPeriod1 = sampleCount / (((double)sampleCount / _wavePeriod) + 1);
double adjacentPeriod2 = sampleCount / (((double)sampleCount / _wavePeriod) - 1);
//
// Get the the three different frequency components of the throughput (scaled by average
// throughput). Our "error" estimate (the amount of noise that might be present in the
// frequency band we're really interested in) is the average of the adjacent bands.
//
throughputWaveComponent = GetWaveComponent(_samples, sampleCount, _wavePeriod) / averageThroughput;
throughputErrorEstimate = (GetWaveComponent(_samples, sampleCount, adjacentPeriod1) / averageThroughput).Abs();
if (adjacentPeriod2 <= sampleCount)
{
throughputErrorEstimate = Math.Max(throughputErrorEstimate, (GetWaveComponent(_samples, sampleCount, adjacentPeriod2) / averageThroughput).Abs());
}
//
// Do the same for the thread counts, so we have something to compare to. We don't measure thread count
// noise, because there is none; these are exact measurements.
//
threadWaveComponent = GetWaveComponent(_threadCounts, sampleCount, _wavePeriod) / averageThreadCount;
//
// Update our moving average of the throughput noise. We'll use this later as feedback to
// determine the new size of the thread wave.
//
if (_averageThroughputNoise == 0)
_averageThroughputNoise = throughputErrorEstimate;
else
_averageThroughputNoise = (_throughputErrorSmoothingFactor * throughputErrorEstimate) + ((1.0 - _throughputErrorSmoothingFactor) * _averageThroughputNoise);
if (threadWaveComponent.Abs() > 0)
{
//
// Adjust the throughput wave so it's centered around the target wave, and then calculate the adjusted throughput/thread ratio.
//
ratio = (throughputWaveComponent - (_targetThroughputRatio * threadWaveComponent)) / threadWaveComponent;
state = StateOrTransition.ClimbingMove;
}
else
{
ratio = new Complex(0, 0);
state = StateOrTransition.Stabilizing;
}
//
// Calculate how confident we are in the ratio. More noise == less confident. This has
// the effect of slowing down movements that might be affected by random noise.
//
double noiseForConfidence = Math.Max(_averageThroughputNoise, throughputErrorEstimate);
if (noiseForConfidence > 0)
confidence = (threadWaveComponent.Abs() / noiseForConfidence) / _targetSignalToNoiseRatio;
else
confidence = 1.0; //there is no noise!
}
}
//
// We use just the real part of the complex ratio we just calculated. If the throughput signal
// is exactly in phase with the thread signal, this will be the same as taking the magnitude of
// the complex move and moving that far up. If they're 180 degrees out of phase, we'll move
// backward (because this indicates that our changes are having the opposite of the intended effect).
// If they're 90 degrees out of phase, we won't move at all, because we can't tell whether we're
// having a negative or positive effect on throughput.
//
double move = Math.Min(1.0, Math.Max(-1.0, ratio.Real));
//
// Apply our confidence multiplier.
//
move *= Math.Min(1.0, Math.Max(0.0, confidence));
//
// Now apply non-linear gain, such that values around zero are attenuated, while higher values
// are enhanced. This allows us to move quickly if we're far away from the target, but more slowly
// if we're getting close, giving us rapid ramp-up without wild oscillations around the target.
//
double gain = _maxChangePerSecond * sampleDurationSeconds;
move = Math.Pow(Math.Abs(move), _gainExponent) * (move >= 0.0 ? 1 : -1) * gain;
move = Math.Min(move, _maxChangePerSample);
//
// If the result was positive, and CPU is > 95%, refuse the move.
//
PortableThreadPool threadPoolInstance = ThreadPoolInstance;
if (move > 0.0 && threadPoolInstance._cpuUtilization > CpuUtilizationHigh)
move = 0.0;
//
// Apply the move to our control setting
//
_currentControlSetting += move;
//
// Calculate the new thread wave magnitude, which is based on the moving average we've been keeping of
// the throughput error. This average starts at zero, so we'll start with a nice safe little wave at first.
//
int newThreadWaveMagnitude = (int)(0.5 + (_currentControlSetting * _averageThroughputNoise * _targetSignalToNoiseRatio * _threadMagnitudeMultiplier * 2.0));
newThreadWaveMagnitude = Math.Min(newThreadWaveMagnitude, _maxThreadWaveMagnitude);
newThreadWaveMagnitude = Math.Max(newThreadWaveMagnitude, 1);
//
// Make sure our control setting is within the ThreadPool's limits. When some threads are blocked due to
// cooperative blocking, ensure that hill climbing does not decrease the thread count below the expected
// minimum.
//
int maxThreads = threadPoolInstance._maxThreads;
int minThreads = threadPoolInstance.MinThreadsGoal;
_currentControlSetting = Math.Min(maxThreads - newThreadWaveMagnitude, _currentControlSetting);
_currentControlSetting = Math.Max(minThreads, _currentControlSetting);
//
// Calculate the new thread count (control setting + square wave)
//
int newThreadCount = (int)(_currentControlSetting + newThreadWaveMagnitude * ((_totalSamples / (_wavePeriod / 2)) % 2));
//
// Make sure the new thread count doesn't exceed the ThreadPool's limits
//
newThreadCount = Math.Min(maxThreads, newThreadCount);
newThreadCount = Math.Max(minThreads, newThreadCount);
//
// Record these numbers for posterity
//
if (NativeRuntimeEventSource.Log.IsEnabled())
{
NativeRuntimeEventSource.Log.ThreadPoolWorkerThreadAdjustmentStats(sampleDurationSeconds, throughput, threadWaveComponent.Real, throughputWaveComponent.Real,
throughputErrorEstimate, _averageThroughputNoise, ratio.Real, confidence, _currentControlSetting, (ushort)newThreadWaveMagnitude);
}
//
// If all of this caused an actual change in thread count, log that as well.
//
if (newThreadCount != currentThreadCount)
{
ChangeThreadCount(newThreadCount, state);
_secondsElapsedSinceLastChange = 0;
_completionsSinceLastChange = 0;
}
//
// Return the new thread count and sample interval. This is randomized to prevent correlations with other periodic
// changes in throughput. Among other things, this prevents us from getting confused by Hill Climbing instances
// running in other processes.
//
// If we're at minThreads, and we seem to be hurting performance by going higher, we can't go any lower to fix this. So
// we'll simply stay at minThreads much longer, and only occasionally try a higher value.
//
int newSampleInterval;
if (ratio.Real < 0.0 && newThreadCount == minThreads)
newSampleInterval = (int)(0.5 + _currentSampleMs * (10.0 * Math.Min(-ratio.Real, 1.0)));
else
newSampleInterval = _currentSampleMs;
return (newThreadCount, newSampleInterval);
}
private void ChangeThreadCount(int newThreadCount, StateOrTransition state)
{
_lastThreadCount = newThreadCount;
if (state != StateOrTransition.CooperativeBlocking) // this can be noisy
{
_currentSampleMs = _randomIntervalGenerator.Next(_sampleIntervalMsLow, _sampleIntervalMsHigh + 1);
}
double throughput = _secondsElapsedSinceLastChange > 0 ? _completionsSinceLastChange / _secondsElapsedSinceLastChange : 0;
LogTransition(newThreadCount, throughput, state);
}
private void LogTransition(int newThreadCount, double throughput, StateOrTransition stateOrTransition)
{
// Use the _log array as a circular array for log entries
int index = (_logStart + _logSize) % LogCapacity;
if (_logSize == LogCapacity)
{
_logStart = (_logStart + 1) % LogCapacity;
_logSize--; // hide this slot while we update it
}
ref LogEntry entry = ref _log[index];
entry.tickCount = Environment.TickCount;
entry.stateOrTransition = stateOrTransition;
entry.newControlSetting = newThreadCount;
entry.lastHistoryCount = (int)(Math.Min(_totalSamples, _samplesToMeasure) / _wavePeriod) * _wavePeriod;
entry.lastHistoryMean = (float)throughput;
_logSize++;
if (NativeRuntimeEventSource.Log.IsEnabled())
{
NativeRuntimeEventSource.Log.ThreadPoolWorkerThreadAdjustmentAdjustment(
throughput,
(uint)newThreadCount,
(NativeRuntimeEventSource.ThreadAdjustmentReasonMap)stateOrTransition);
}
}
public void ForceChange(int newThreadCount, StateOrTransition state)
{
if (_lastThreadCount != newThreadCount)
{
_currentControlSetting += newThreadCount - _lastThreadCount;
ChangeThreadCount(newThreadCount, state);
}
}
private Complex GetWaveComponent(double[] samples, int numSamples, double period)
{
Debug.Assert(numSamples >= period); // can't measure a wave that doesn't fit
Debug.Assert(period >= 2); // can't measure above the Nyquist frequency
Debug.Assert(numSamples <= samples.Length); // can't measure more samples than we have
//
// Calculate the sinusoid with the given period.
// We're using the Goertzel algorithm for this. See http://en.wikipedia.org/wiki/Goertzel_algorithm.
//
double w = 2 * Math.PI / period;
double cos = Math.Cos(w);
double coeff = 2 * cos;
double q0, q1 = 0, q2 = 0;
for (int i = 0; i < numSamples; ++i)
{
q0 = coeff * q1 - q2 + samples[(_totalSamples - numSamples + i) % _samplesToMeasure];
q2 = q1;
q1 = q0;
}
return new Complex(q1 - q2 * cos, q2 * Math.Sin(w)) / numSamples;
}
}
}
}
| -1 |
dotnet/runtime | 66,057 | Address TODO to switch to generated p/invoke | Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | elinor-fung | 2022-03-02T03:31:28Z | 2022-03-02T19:08:30Z | a4b8893a118357b55c0add9a39cc5aeb097a0bb8 | 1abbbb4adf6bf02549f4c6e021176534dcc4f974 | Address TODO to switch to generated p/invoke. Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | ./src/tests/JIT/Methodical/AsgOp/r8/r8flat.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
internal class test
{
public static int Main()
{
double x;
double y;
bool pass = true;
x = -10.0;
y = 4.0;
x = x + y;
if (x != -6)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x = x + y failed. x: {0}, \texpected: -6\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x = x - y;
if (x != -14)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x = x - y failed. x: {0}, \texpected: -14\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x = x * y;
if (x != -40)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x = x * y failed. x: {0}, \texpected: -40\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x = x / y;
if (x != -2.5)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x = x / y failed. x: {0}, \texpected: -2.5\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x = x % y;
if (x != -2)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x = x % y failed. x: {0}, \texpected: -2\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x += x + y;
if (x != -16)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x += x + y failed. x: {0}, \texpected: -16\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x += x - y;
if (x != -24)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x += x - y failed. x: {0}, \texpected: -24\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x += x * y;
if (x != -50)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x += x * y failed. x: {0}, \texpected: -50\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x += x / y;
if (x != -12.5)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x += x / y failed. x: {0}, \texpected: -12.5\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x += x % y;
if (x != -12)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x += x % y failed. x: {0}, \texpected: -12\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x -= x + y;
if (x != -4)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x -= x + y failed. x: {0}, \texpected: -4\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x -= x - y;
if (x != 4)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x -= x - y failed. x: {0}, \texpected: 4\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x -= x * y;
if (x != 30)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x -= x * y failed. x: {0}, \texpected: 30\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x -= x / y;
if (x != -7.5)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x -= x / y failed. x: {0}, \texpected: -7.5\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x -= x % y;
if (x != -8)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x -= x % y failed. x: {0}, \texpected: -8\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x *= x + y;
if (x != 60)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x *= x + y failed. x: {0}, \texpected: 60\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x *= x - y;
if (x != 140)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x *= x - y failed. x: {0}, \texpected: 140\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x *= x * y;
if (x != 400)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x *= x * y failed. x: {0}, \texpected: 400\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x *= x / y;
if (x != 25)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x *= x / y failed. x: {0}, \texpected: 25\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x *= x % y;
if (x != 20)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x *= x % y failed. x: {0}, \texpected: 20\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x /= x + y;
if (x != 1.6666666666666667)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x /= x + y failed. x: {0}, \texpected: 1.6666666666666667\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x /= x - y;
if (x != 0.7142857142857143)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x /= x - y failed. x: {0}, \texpected: 0.7142857142857143\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x /= x * y;
if (x != 0.25)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x /= x * y failed. x: {0}, \texpected: 0.25\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x /= x / y;
if (x != 4)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x /= x / y failed. x: {0}, \texpected: 4\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x /= x % y;
if (x != 5)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x /= x % y failed. x: {0}, \texpected: 5\n", x);
pass = false;
}
if (pass)
{
Console.WriteLine("PASSED");
return 100;
}
else
return 1;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
internal class test
{
public static int Main()
{
double x;
double y;
bool pass = true;
x = -10.0;
y = 4.0;
x = x + y;
if (x != -6)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x = x + y failed. x: {0}, \texpected: -6\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x = x - y;
if (x != -14)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x = x - y failed. x: {0}, \texpected: -14\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x = x * y;
if (x != -40)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x = x * y failed. x: {0}, \texpected: -40\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x = x / y;
if (x != -2.5)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x = x / y failed. x: {0}, \texpected: -2.5\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x = x % y;
if (x != -2)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x = x % y failed. x: {0}, \texpected: -2\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x += x + y;
if (x != -16)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x += x + y failed. x: {0}, \texpected: -16\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x += x - y;
if (x != -24)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x += x - y failed. x: {0}, \texpected: -24\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x += x * y;
if (x != -50)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x += x * y failed. x: {0}, \texpected: -50\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x += x / y;
if (x != -12.5)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x += x / y failed. x: {0}, \texpected: -12.5\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x += x % y;
if (x != -12)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x += x % y failed. x: {0}, \texpected: -12\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x -= x + y;
if (x != -4)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x -= x + y failed. x: {0}, \texpected: -4\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x -= x - y;
if (x != 4)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x -= x - y failed. x: {0}, \texpected: 4\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x -= x * y;
if (x != 30)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x -= x * y failed. x: {0}, \texpected: 30\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x -= x / y;
if (x != -7.5)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x -= x / y failed. x: {0}, \texpected: -7.5\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x -= x % y;
if (x != -8)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x -= x % y failed. x: {0}, \texpected: -8\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x *= x + y;
if (x != 60)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x *= x + y failed. x: {0}, \texpected: 60\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x *= x - y;
if (x != 140)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x *= x - y failed. x: {0}, \texpected: 140\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x *= x * y;
if (x != 400)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x *= x * y failed. x: {0}, \texpected: 400\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x *= x / y;
if (x != 25)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x *= x / y failed. x: {0}, \texpected: 25\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x *= x % y;
if (x != 20)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x *= x % y failed. x: {0}, \texpected: 20\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x /= x + y;
if (x != 1.6666666666666667)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x /= x + y failed. x: {0}, \texpected: 1.6666666666666667\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x /= x - y;
if (x != 0.7142857142857143)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x /= x - y failed. x: {0}, \texpected: 0.7142857142857143\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x /= x * y;
if (x != 0.25)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x /= x * y failed. x: {0}, \texpected: 0.25\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x /= x / y;
if (x != 4)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x /= x / y failed. x: {0}, \texpected: 4\n", x);
pass = false;
}
x = -10.0;
y = 4.0;
x /= x % y;
if (x != 5)
{
Console.WriteLine("\nInitial parameters: x is -10.0 and y is 4.0");
Console.WriteLine("x /= x % y failed. x: {0}, \texpected: 5\n", x);
pass = false;
}
if (pass)
{
Console.WriteLine("PASSED");
return 100;
}
else
return 1;
}
}
| -1 |
dotnet/runtime | 66,057 | Address TODO to switch to generated p/invoke | Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | elinor-fung | 2022-03-02T03:31:28Z | 2022-03-02T19:08:30Z | a4b8893a118357b55c0add9a39cc5aeb097a0bb8 | 1abbbb4adf6bf02549f4c6e021176534dcc4f974 | Address TODO to switch to generated p/invoke. Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | ./src/tests/JIT/Methodical/fp/exgen/5w1d-03.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
internal unsafe class testout1
{
public class CL_0
{
public Decimal[,,] arr3d_0 = new Decimal[5, 6, 4];
public Decimal a1_0 = -3.0476190476190476190476190476M;
public ulong a2_0 = 4096UL;
}
public static CL_0 clstatic_0 = new CL_0();
public static int Func_0()
{
CL_0 cl_0 = new CL_0();
cl_0.arr3d_0[4, 0, 3] = 16M;
int retval_0 = Convert.ToInt32(Convert.ToInt32(cl_0.arr3d_0[4, 0, 3] - ((Convert.ToDecimal((Convert.ToUInt64(clstatic_0.a2_0 / 16UL))) / clstatic_0.a1_0))));
return retval_0;
}
public static int Main()
{
int retval;
retval = Convert.ToInt32(Func_0());
if ((retval >= 99) && (retval < 100))
retval = 100;
if ((retval > 100) && (retval <= 101))
retval = 100;
Console.WriteLine(retval);
return retval;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
internal unsafe class testout1
{
public class CL_0
{
public Decimal[,,] arr3d_0 = new Decimal[5, 6, 4];
public Decimal a1_0 = -3.0476190476190476190476190476M;
public ulong a2_0 = 4096UL;
}
public static CL_0 clstatic_0 = new CL_0();
public static int Func_0()
{
CL_0 cl_0 = new CL_0();
cl_0.arr3d_0[4, 0, 3] = 16M;
int retval_0 = Convert.ToInt32(Convert.ToInt32(cl_0.arr3d_0[4, 0, 3] - ((Convert.ToDecimal((Convert.ToUInt64(clstatic_0.a2_0 / 16UL))) / clstatic_0.a1_0))));
return retval_0;
}
public static int Main()
{
int retval;
retval = Convert.ToInt32(Func_0());
if ((retval >= 99) && (retval < 100))
retval = 100;
if ((retval > 100) && (retval <= 101))
retval = 100;
Console.WriteLine(retval);
return retval;
}
}
| -1 |
dotnet/runtime | 66,057 | Address TODO to switch to generated p/invoke | Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | elinor-fung | 2022-03-02T03:31:28Z | 2022-03-02T19:08:30Z | a4b8893a118357b55c0add9a39cc5aeb097a0bb8 | 1abbbb4adf6bf02549f4c6e021176534dcc4f974 | Address TODO to switch to generated p/invoke. Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | ./src/libraries/Common/src/Interop/Windows/Crypt32/Interop.CryptQueryObject.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
internal static partial class Interop
{
internal static partial class Crypt32
{
[GeneratedDllImport(Libraries.Crypt32, SetLastError = true)]
internal static unsafe partial bool CryptQueryObject(
CertQueryObjectType dwObjectType,
void* pvObject,
ExpectedContentTypeFlags dwExpectedContentTypeFlags,
ExpectedFormatTypeFlags dwExpectedFormatTypeFlags,
int dwFlags, // reserved - always pass 0
out CertEncodingType pdwMsgAndCertEncodingType,
out ContentType pdwContentType,
out FormatType pdwFormatType,
out SafeCertStoreHandle phCertStore,
out SafeCryptMsgHandle phMsg,
out SafeCertContextHandle ppvContext
);
[GeneratedDllImport(Libraries.Crypt32, SetLastError = true)]
internal static unsafe partial bool CryptQueryObject(
CertQueryObjectType dwObjectType,
void* pvObject,
ExpectedContentTypeFlags dwExpectedContentTypeFlags,
ExpectedFormatTypeFlags dwExpectedFormatTypeFlags,
int dwFlags, // reserved - always pass 0
IntPtr pdwMsgAndCertEncodingType,
out ContentType pdwContentType,
IntPtr pdwFormatType,
IntPtr phCertStore,
IntPtr phMsg,
IntPtr ppvContext
);
[GeneratedDllImport(Libraries.Crypt32, SetLastError = true)]
internal static unsafe partial bool CryptQueryObject(
CertQueryObjectType dwObjectType,
void* pvObject,
ExpectedContentTypeFlags dwExpectedContentTypeFlags,
ExpectedFormatTypeFlags dwExpectedFormatTypeFlags,
int dwFlags, // reserved - always pass 0
IntPtr pdwMsgAndCertEncodingType,
out ContentType pdwContentType,
IntPtr pdwFormatType,
out SafeCertStoreHandle phCertStore,
IntPtr phMsg,
IntPtr ppvContext
);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
internal static partial class Interop
{
internal static partial class Crypt32
{
[GeneratedDllImport(Libraries.Crypt32, SetLastError = true)]
internal static unsafe partial bool CryptQueryObject(
CertQueryObjectType dwObjectType,
void* pvObject,
ExpectedContentTypeFlags dwExpectedContentTypeFlags,
ExpectedFormatTypeFlags dwExpectedFormatTypeFlags,
int dwFlags, // reserved - always pass 0
out CertEncodingType pdwMsgAndCertEncodingType,
out ContentType pdwContentType,
out FormatType pdwFormatType,
out SafeCertStoreHandle phCertStore,
out SafeCryptMsgHandle phMsg,
out SafeCertContextHandle ppvContext
);
[GeneratedDllImport(Libraries.Crypt32, SetLastError = true)]
internal static unsafe partial bool CryptQueryObject(
CertQueryObjectType dwObjectType,
void* pvObject,
ExpectedContentTypeFlags dwExpectedContentTypeFlags,
ExpectedFormatTypeFlags dwExpectedFormatTypeFlags,
int dwFlags, // reserved - always pass 0
IntPtr pdwMsgAndCertEncodingType,
out ContentType pdwContentType,
IntPtr pdwFormatType,
IntPtr phCertStore,
IntPtr phMsg,
IntPtr ppvContext
);
[GeneratedDllImport(Libraries.Crypt32, SetLastError = true)]
internal static unsafe partial bool CryptQueryObject(
CertQueryObjectType dwObjectType,
void* pvObject,
ExpectedContentTypeFlags dwExpectedContentTypeFlags,
ExpectedFormatTypeFlags dwExpectedFormatTypeFlags,
int dwFlags, // reserved - always pass 0
IntPtr pdwMsgAndCertEncodingType,
out ContentType pdwContentType,
IntPtr pdwFormatType,
out SafeCertStoreHandle phCertStore,
IntPtr phMsg,
IntPtr ppvContext
);
}
}
| -1 |
dotnet/runtime | 66,057 | Address TODO to switch to generated p/invoke | Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | elinor-fung | 2022-03-02T03:31:28Z | 2022-03-02T19:08:30Z | a4b8893a118357b55c0add9a39cc5aeb097a0bb8 | 1abbbb4adf6bf02549f4c6e021176534dcc4f974 | Address TODO to switch to generated p/invoke. Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | ./src/tests/JIT/HardwareIntrinsics/General/Vector128/BitwiseOr.Byte.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void BitwiseOrByte()
{
var test = new VectorBinaryOpTest__BitwiseOrByte();
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorBinaryOpTest__BitwiseOrByte
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Byte[] inArray1, Byte[] inArray2, Byte[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>();
if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public 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(VectorBinaryOpTest__BitwiseOrByte testClass)
{
var result = Vector128.BitwiseOr(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<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 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 VectorBinaryOpTest__BitwiseOrByte()
{
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 VectorBinaryOpTest__BitwiseOrByte()
{
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 Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Vector128.BitwiseOr(
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var method = typeof(Vector128).GetMethod(nameof(Vector128.BitwiseOr), new Type[] {
typeof(Vector128<Byte>),
typeof(Vector128<Byte>)
});
if (method is null)
{
method = typeof(Vector128).GetMethod(nameof(Vector128.BitwiseOr), 1, new Type[] {
typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)),
typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0))
});
}
if (method.IsGenericMethodDefinition)
{
method = method.MakeGenericMethod(typeof(Byte));
}
var result = method.Invoke(null, new object[] {
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Vector128.BitwiseOr(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr);
var result = Vector128.BitwiseOr(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new VectorBinaryOpTest__BitwiseOrByte();
var result = Vector128.BitwiseOr(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Vector128.BitwiseOr(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Vector128.BitwiseOr(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
private void ValidateResult(Vector128<Byte> op1, Vector128<Byte> op2, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Byte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (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[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != (byte)(left[0] | right[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != (byte)(left[i] | right[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Vector128)}.{nameof(Vector128.BitwiseOr)}<Byte>(Vector128<Byte>, Vector128<Byte>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({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 BitwiseOrByte()
{
var test = new VectorBinaryOpTest__BitwiseOrByte();
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorBinaryOpTest__BitwiseOrByte
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Byte[] inArray1, Byte[] inArray2, Byte[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>();
if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public 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(VectorBinaryOpTest__BitwiseOrByte testClass)
{
var result = Vector128.BitwiseOr(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<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 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 VectorBinaryOpTest__BitwiseOrByte()
{
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 VectorBinaryOpTest__BitwiseOrByte()
{
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 Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Vector128.BitwiseOr(
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var method = typeof(Vector128).GetMethod(nameof(Vector128.BitwiseOr), new Type[] {
typeof(Vector128<Byte>),
typeof(Vector128<Byte>)
});
if (method is null)
{
method = typeof(Vector128).GetMethod(nameof(Vector128.BitwiseOr), 1, new Type[] {
typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)),
typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0))
});
}
if (method.IsGenericMethodDefinition)
{
method = method.MakeGenericMethod(typeof(Byte));
}
var result = method.Invoke(null, new object[] {
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Vector128.BitwiseOr(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr);
var result = Vector128.BitwiseOr(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new VectorBinaryOpTest__BitwiseOrByte();
var result = Vector128.BitwiseOr(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Vector128.BitwiseOr(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Vector128.BitwiseOr(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
private void ValidateResult(Vector128<Byte> op1, Vector128<Byte> op2, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Byte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (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[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != (byte)(left[0] | right[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != (byte)(left[i] | right[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Vector128)}.{nameof(Vector128.BitwiseOr)}<Byte>(Vector128<Byte>, Vector128<Byte>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| -1 |
dotnet/runtime | 66,057 | Address TODO to switch to generated p/invoke | Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | elinor-fung | 2022-03-02T03:31:28Z | 2022-03-02T19:08:30Z | a4b8893a118357b55c0add9a39cc5aeb097a0bb8 | 1abbbb4adf6bf02549f4c6e021176534dcc4f974 | Address TODO to switch to generated p/invoke. Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | ./src/libraries/System.Net.Http.WinHttpHandler/tests/UnitTests/FakeRegistry.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.Http.WinHttpHandlerUnitTests
{
public static class FakeRegistry
{
public static void Reset()
{
WinInetProxySettings.RegistryKeyMissing = false;
WinInetProxySettings.AutoDetect = false;
WinInetProxySettings.AutoConfigUrl = null;
WinInetProxySettings.Proxy = null;
WinInetProxySettings.ProxyBypass = null;
}
public static class WinInetProxySettings
{
public static bool RegistryKeyMissing { get; set; }
public static bool AutoDetect { get; set; }
public static string AutoConfigUrl { get; set; }
public static string Proxy { get; set; }
public static string ProxyBypass { get; set; }
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace System.Net.Http.WinHttpHandlerUnitTests
{
public static class FakeRegistry
{
public static void Reset()
{
WinInetProxySettings.RegistryKeyMissing = false;
WinInetProxySettings.AutoDetect = false;
WinInetProxySettings.AutoConfigUrl = null;
WinInetProxySettings.Proxy = null;
WinInetProxySettings.ProxyBypass = null;
}
public static class WinInetProxySettings
{
public static bool RegistryKeyMissing { get; set; }
public static bool AutoDetect { get; set; }
public static string AutoConfigUrl { get; set; }
public static string Proxy { get; set; }
public static string ProxyBypass { get; set; }
}
}
}
| -1 |
dotnet/runtime | 66,057 | Address TODO to switch to generated p/invoke | Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | elinor-fung | 2022-03-02T03:31:28Z | 2022-03-02T19:08:30Z | a4b8893a118357b55c0add9a39cc5aeb097a0bb8 | 1abbbb4adf6bf02549f4c6e021176534dcc4f974 | Address TODO to switch to generated p/invoke. Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | ./src/libraries/System.Runtime.Serialization.Formatters/tests/FormatterTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections;
using System.Collections.Generic;
using System.IO;
using Xunit;
namespace System.Runtime.Serialization.Formatters.Tests
{
public class FormatterTests
{
[Fact]
public void DefaultCtor_ObjectsInitialized()
{
var f = new TestFormatter();
Assert.NotNull(f.m_idGenerator);
Assert.NotNull(f.m_objectQueue);
Assert.Equal(0, f.m_objectQueue.Count);
bool firstTime;
AssertExtensions.Throws<ArgumentNullException>("obj", () => f.m_idGenerator.GetId(null, out firstTime));
AssertExtensions.Throws<ArgumentNullException>("obj", () => f.m_idGenerator.HasId(null, out firstTime));
}
[Fact]
public void ScheduleAndGetObjects_ExpectedIDsAndOrder()
{
var f = new TestFormatter();
// null values don't count
long actualId;
Assert.Equal(0, f.Schedule(null));
Assert.Equal(0, f.Schedule(null));
Assert.Null(f.GetNext(out actualId));
Assert.Equal(0, actualId);
var objects = new object[] { new object(), new object(), new object() };
// Add each object for the first time
long nextExpectedId = 1;
foreach (var obj in objects)
{
Assert.Equal(nextExpectedId++, f.Schedule(obj));
}
// Adding them again should produce the same IDs
nextExpectedId = 1;
foreach (var obj in objects)
{
Assert.Equal(nextExpectedId++, f.Schedule(obj));
}
// Now retrieve them all
nextExpectedId = 1;
foreach (var obj in objects)
{
var actualObj = f.GetNext(out actualId);
Assert.Same(obj, actualObj);
Assert.Equal(nextExpectedId++, actualId);
}
}
[Fact]
public void GetNext_UnexpectedObject_ThrowsException()
{
var f = new TestFormatter();
f.m_objectQueue.Enqueue(new object());
long id;
Assert.Throws<SerializationException>(() => f.GetNext(out id));
}
[Fact]
public void WriteMember_InvokesProperMethod()
{
string calledMethod = null;
object result = null;
var f = new TestFormatter { WriteCallback = (name, val) => { calledMethod = name; result = val; } };
Action<string, object> verify = (expectedMember, expectedValue) =>
{
f.WriteMember("Member", expectedValue);
Assert.Equal(expectedMember, calledMethod);
Assert.Equal(expectedValue, result);
};
verify("WriteBoolean", true);
verify("WriteByte", (byte)42);
verify("WriteChar", 'c');
verify("WriteDateTime", DateTime.Now);
verify("WriteDecimal", 42m);
verify("WriteDouble", 1.2);
verify("WriteInt16", (short)42);
verify("WriteInt32", 42);
verify("WriteInt64", (long)42);
verify("WriteSByte", (sbyte)42);
verify("WriteSingle", 1.2f);
verify("WriteUInt16", (ushort)42);
verify("WriteUInt32", (uint)42);
verify("WriteUInt64", (ulong)42);
verify("WriteValueType", new KeyValuePair<int, int>(1, 2));
// verify("WriteTimeSpan", TimeSpan.FromSeconds(42)); // Fails on both .NET Framework and core, getting routed as a normal ValueType:
verify("WriteValueType", TimeSpan.FromSeconds(42));
verify("WriteObjectRef", new ObjectWithIntStringUShortUIntULongAndCustomObjectFields());
verify("WriteObjectRef", null);
f.WriteMember("Member", new[] { 1, 2, 3, 4, 5 });
Assert.Equal("WriteArray", calledMethod);
Assert.Equal<int>(new[] { 1, 2, 3, 4, 5 }, (int[])result);
}
private sealed class TestFormatter : Formatter
{
public new object GetNext(out long objID) => base.GetNext(out objID);
public new long Schedule(object obj) => base.Schedule(obj);
public new void WriteMember(string memberName, object data) => base.WriteMember(memberName, data);
public new ObjectIDGenerator m_idGenerator => base.m_idGenerator;
public new Queue m_objectQueue => base.m_objectQueue;
public Action<string, object> WriteCallback;
protected override void WriteArray(object obj, string name, Type memberType) => WriteCallback?.Invoke("WriteArray", obj);
protected override void WriteBoolean(bool val, string name) => WriteCallback?.Invoke("WriteBoolean", val);
protected override void WriteByte(byte val, string name) => WriteCallback?.Invoke("WriteByte", val);
protected override void WriteChar(char val, string name) => WriteCallback?.Invoke("WriteChar", val);
protected override void WriteDateTime(DateTime val, string name) => WriteCallback?.Invoke("WriteDateTime", val);
protected override void WriteDecimal(decimal val, string name) => WriteCallback?.Invoke("WriteDecimal", val);
protected override void WriteDouble(double val, string name) => WriteCallback?.Invoke("WriteDouble", val);
protected override void WriteInt16(short val, string name) => WriteCallback?.Invoke("WriteInt16", val);
protected override void WriteInt32(int val, string name) => WriteCallback?.Invoke("WriteInt32", val);
protected override void WriteInt64(long val, string name) => WriteCallback?.Invoke("WriteInt64", val);
protected override void WriteObjectRef(object obj, string name, Type memberType) => WriteCallback?.Invoke("WriteObjectRef", obj);
protected override void WriteSByte(sbyte val, string name) => WriteCallback?.Invoke("WriteSByte", val);
protected override void WriteSingle(float val, string name) => WriteCallback?.Invoke("WriteSingle", val);
protected override void WriteTimeSpan(TimeSpan val, string name) => WriteCallback?.Invoke("WriteTimeSpan", val);
protected override void WriteUInt16(ushort val, string name) => WriteCallback?.Invoke("WriteUInt16", val);
protected override void WriteUInt32(uint val, string name) => WriteCallback?.Invoke("WriteUInt32", val);
protected override void WriteUInt64(ulong val, string name) => WriteCallback?.Invoke("WriteUInt64", val);
protected override void WriteValueType(object obj, string name, Type memberType) => WriteCallback?.Invoke("WriteValueType", obj);
public override SerializationBinder Binder { get; set; }
public override StreamingContext Context { get; set; }
public override ISurrogateSelector SurrogateSelector { get; set; }
#pragma warning disable CS0672 // Member overrides obsolete member
public override object Deserialize(Stream serializationStream) => null;
public override void Serialize(Stream serializationStream, object graph) { }
#pragma warning restore CS0672 // Member overrides obsolete member
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections;
using System.Collections.Generic;
using System.IO;
using Xunit;
namespace System.Runtime.Serialization.Formatters.Tests
{
public class FormatterTests
{
[Fact]
public void DefaultCtor_ObjectsInitialized()
{
var f = new TestFormatter();
Assert.NotNull(f.m_idGenerator);
Assert.NotNull(f.m_objectQueue);
Assert.Equal(0, f.m_objectQueue.Count);
bool firstTime;
AssertExtensions.Throws<ArgumentNullException>("obj", () => f.m_idGenerator.GetId(null, out firstTime));
AssertExtensions.Throws<ArgumentNullException>("obj", () => f.m_idGenerator.HasId(null, out firstTime));
}
[Fact]
public void ScheduleAndGetObjects_ExpectedIDsAndOrder()
{
var f = new TestFormatter();
// null values don't count
long actualId;
Assert.Equal(0, f.Schedule(null));
Assert.Equal(0, f.Schedule(null));
Assert.Null(f.GetNext(out actualId));
Assert.Equal(0, actualId);
var objects = new object[] { new object(), new object(), new object() };
// Add each object for the first time
long nextExpectedId = 1;
foreach (var obj in objects)
{
Assert.Equal(nextExpectedId++, f.Schedule(obj));
}
// Adding them again should produce the same IDs
nextExpectedId = 1;
foreach (var obj in objects)
{
Assert.Equal(nextExpectedId++, f.Schedule(obj));
}
// Now retrieve them all
nextExpectedId = 1;
foreach (var obj in objects)
{
var actualObj = f.GetNext(out actualId);
Assert.Same(obj, actualObj);
Assert.Equal(nextExpectedId++, actualId);
}
}
[Fact]
public void GetNext_UnexpectedObject_ThrowsException()
{
var f = new TestFormatter();
f.m_objectQueue.Enqueue(new object());
long id;
Assert.Throws<SerializationException>(() => f.GetNext(out id));
}
[Fact]
public void WriteMember_InvokesProperMethod()
{
string calledMethod = null;
object result = null;
var f = new TestFormatter { WriteCallback = (name, val) => { calledMethod = name; result = val; } };
Action<string, object> verify = (expectedMember, expectedValue) =>
{
f.WriteMember("Member", expectedValue);
Assert.Equal(expectedMember, calledMethod);
Assert.Equal(expectedValue, result);
};
verify("WriteBoolean", true);
verify("WriteByte", (byte)42);
verify("WriteChar", 'c');
verify("WriteDateTime", DateTime.Now);
verify("WriteDecimal", 42m);
verify("WriteDouble", 1.2);
verify("WriteInt16", (short)42);
verify("WriteInt32", 42);
verify("WriteInt64", (long)42);
verify("WriteSByte", (sbyte)42);
verify("WriteSingle", 1.2f);
verify("WriteUInt16", (ushort)42);
verify("WriteUInt32", (uint)42);
verify("WriteUInt64", (ulong)42);
verify("WriteValueType", new KeyValuePair<int, int>(1, 2));
// verify("WriteTimeSpan", TimeSpan.FromSeconds(42)); // Fails on both .NET Framework and core, getting routed as a normal ValueType:
verify("WriteValueType", TimeSpan.FromSeconds(42));
verify("WriteObjectRef", new ObjectWithIntStringUShortUIntULongAndCustomObjectFields());
verify("WriteObjectRef", null);
f.WriteMember("Member", new[] { 1, 2, 3, 4, 5 });
Assert.Equal("WriteArray", calledMethod);
Assert.Equal<int>(new[] { 1, 2, 3, 4, 5 }, (int[])result);
}
private sealed class TestFormatter : Formatter
{
public new object GetNext(out long objID) => base.GetNext(out objID);
public new long Schedule(object obj) => base.Schedule(obj);
public new void WriteMember(string memberName, object data) => base.WriteMember(memberName, data);
public new ObjectIDGenerator m_idGenerator => base.m_idGenerator;
public new Queue m_objectQueue => base.m_objectQueue;
public Action<string, object> WriteCallback;
protected override void WriteArray(object obj, string name, Type memberType) => WriteCallback?.Invoke("WriteArray", obj);
protected override void WriteBoolean(bool val, string name) => WriteCallback?.Invoke("WriteBoolean", val);
protected override void WriteByte(byte val, string name) => WriteCallback?.Invoke("WriteByte", val);
protected override void WriteChar(char val, string name) => WriteCallback?.Invoke("WriteChar", val);
protected override void WriteDateTime(DateTime val, string name) => WriteCallback?.Invoke("WriteDateTime", val);
protected override void WriteDecimal(decimal val, string name) => WriteCallback?.Invoke("WriteDecimal", val);
protected override void WriteDouble(double val, string name) => WriteCallback?.Invoke("WriteDouble", val);
protected override void WriteInt16(short val, string name) => WriteCallback?.Invoke("WriteInt16", val);
protected override void WriteInt32(int val, string name) => WriteCallback?.Invoke("WriteInt32", val);
protected override void WriteInt64(long val, string name) => WriteCallback?.Invoke("WriteInt64", val);
protected override void WriteObjectRef(object obj, string name, Type memberType) => WriteCallback?.Invoke("WriteObjectRef", obj);
protected override void WriteSByte(sbyte val, string name) => WriteCallback?.Invoke("WriteSByte", val);
protected override void WriteSingle(float val, string name) => WriteCallback?.Invoke("WriteSingle", val);
protected override void WriteTimeSpan(TimeSpan val, string name) => WriteCallback?.Invoke("WriteTimeSpan", val);
protected override void WriteUInt16(ushort val, string name) => WriteCallback?.Invoke("WriteUInt16", val);
protected override void WriteUInt32(uint val, string name) => WriteCallback?.Invoke("WriteUInt32", val);
protected override void WriteUInt64(ulong val, string name) => WriteCallback?.Invoke("WriteUInt64", val);
protected override void WriteValueType(object obj, string name, Type memberType) => WriteCallback?.Invoke("WriteValueType", obj);
public override SerializationBinder Binder { get; set; }
public override StreamingContext Context { get; set; }
public override ISurrogateSelector SurrogateSelector { get; set; }
#pragma warning disable CS0672 // Member overrides obsolete member
public override object Deserialize(Stream serializationStream) => null;
public override void Serialize(Stream serializationStream, object graph) { }
#pragma warning restore CS0672 // Member overrides obsolete member
}
}
}
| -1 |
dotnet/runtime | 66,057 | Address TODO to switch to generated p/invoke | Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | elinor-fung | 2022-03-02T03:31:28Z | 2022-03-02T19:08:30Z | a4b8893a118357b55c0add9a39cc5aeb097a0bb8 | 1abbbb4adf6bf02549f4c6e021176534dcc4f974 | Address TODO to switch to generated p/invoke. Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | ./src/coreclr/md/enc/metamodelenc.cpp | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//*****************************************************************************
// MetaModelENC.cpp
//
//
// Implementation for applying ENC deltas to a MiniMd.
//
//*****************************************************************************
#include "stdafx.h"
#include <limits.h>
#include <posterror.h>
#include <metamodelrw.h>
#include <stgio.h>
#include <stgtiggerstorage.h>
#include "mdlog.h"
#include "rwutil.h"
ULONG CMiniMdRW::m_SuppressedDeltaColumns[TBL_COUNT] = {0};
//*****************************************************************************
// Copy the data from one MiniMd to another.
//*****************************************************************************
__checkReturn
HRESULT
CMiniMdRW::ApplyRecordDelta(
CMiniMdRW &mdDelta, // The delta MetaData.
ULONG ixTbl, // The table with the data.
void *pDelta, // The delta MetaData record.
void *pRecord) // The record to update.
{
HRESULT hr = S_OK;
ULONG mask = m_SuppressedDeltaColumns[ixTbl];
for (ULONG ixCol = 0; ixCol<m_TableDefs[ixTbl].m_cCols; ++ixCol, mask >>= 1)
{ // Skip certain pointer columns.
if (mask & 0x01)
continue;
ULONG val = mdDelta.GetCol(ixTbl, ixCol, pDelta);
IfFailRet(PutCol(ixTbl, ixCol, pRecord, val));
}
return hr;
} // CMiniMdRW::ApplyRecordDelta
//*****************************************************************************
// Apply a delta record to a table, generically.
//*****************************************************************************
__checkReturn
HRESULT
CMiniMdRW::ApplyTableDelta(
CMiniMdRW &mdDelta, // Interface to MD with the ENC delta.
ULONG ixTbl, // Table index to update.
RID iRid, // RID of the changed item.
int fc) // Function code of update.
{
HRESULT hr = S_OK;
void *pRec; // Record in existing MetaData.
void *pDeltaRec; // Record if Delta MetaData.
RID newRid; // Rid of new record.
// Get the delta record.
IfFailGo(mdDelta.GetDeltaRecord(ixTbl, iRid, &pDeltaRec));
// Get the record from the base metadata.
if (iRid > m_Schema.m_cRecs[ixTbl])
{ // Added record. Each addition is the next one.
_ASSERTE(iRid == m_Schema.m_cRecs[ixTbl] + 1);
switch (ixTbl)
{
case TBL_TypeDef:
IfFailGo(AddTypeDefRecord(reinterpret_cast<TypeDefRec **>(&pRec), &newRid));
break;
case TBL_Method:
IfFailGo(AddMethodRecord(reinterpret_cast<MethodRec **>(&pRec), &newRid));
break;
case TBL_EventMap:
IfFailGo(AddEventMapRecord(reinterpret_cast<EventMapRec **>(&pRec), &newRid));
break;
case TBL_PropertyMap:
IfFailGo(AddPropertyMapRecord(reinterpret_cast<PropertyMapRec **>(&pRec), &newRid));
break;
default:
IfFailGo(AddRecord(ixTbl, &pRec, &newRid));
break;
}
IfNullGo(pRec);
_ASSERTE(iRid == newRid);
}
else
{ // Updated record.
IfFailGo(getRow(ixTbl, iRid, &pRec));
}
// Copy the record info.
IfFailGo(ApplyRecordDelta(mdDelta, ixTbl, pDeltaRec, pRec));
ErrExit:
return hr;
} // CMiniMdRW::ApplyTableDelta
//*****************************************************************************
// Get the record from a Delta MetaData that corresponds to the actual record.
//*****************************************************************************
__checkReturn
HRESULT
CMiniMdRW::GetDeltaRecord(
ULONG ixTbl, // Table.
ULONG iRid, // Record in the table.
void **ppRecord)
{
HRESULT hr;
ULONG iMap; // RID in map table.
ENCMapRec *pMap; // Row in map table.
*ppRecord = NULL;
// If no remap, just return record directly.
if ((m_Schema.m_cRecs[TBL_ENCMap] == 0) || (ixTbl == TBL_Module) || !IsMinimalDelta())
{
return getRow(ixTbl, iRid, ppRecord);
}
// Use the remap table to find the physical row containing this logical row.
iMap = (*m_rENCRecs)[ixTbl];
IfFailRet(GetENCMapRecord(iMap, &pMap));
// Search for desired record.
while ((TblFromRecId(pMap->GetToken()) == ixTbl) && (RidFromRecId(pMap->GetToken()) < iRid))
{
IfFailRet(GetENCMapRecord(++iMap, &pMap));
}
_ASSERTE((TblFromRecId(pMap->GetToken()) == ixTbl) && (RidFromRecId(pMap->GetToken()) == iRid));
// Relative position within table's group in map is physical rid.
iRid = iMap - (*m_rENCRecs)[ixTbl] + 1;
return getRow(ixTbl, iRid, ppRecord);
} // CMiniMdRW::GetDeltaRecord
//*****************************************************************************
// Given a MetaData with ENC changes, apply those changes to this MetaData.
//*****************************************************************************
__checkReturn
HRESULT
CMiniMdRW::ApplyHeapDeltas(
CMiniMdRW &mdDelta) // Interface to MD with the ENC delta.
{
if (mdDelta.IsMinimalDelta())
{
return ApplyHeapDeltasWithMinimalDelta(mdDelta);
}
else
{
return ApplyHeapDeltasWithFullDelta(mdDelta);
}
}// CMiniMdRW::ApplyHeapDeltas
__checkReturn
HRESULT
CMiniMdRW::ApplyHeapDeltasWithMinimalDelta(
CMiniMdRW &mdDelta) // Interface to MD with the ENC delta.
{
HRESULT hr = S_OK;
// Extend the heaps with EnC minimal delta
IfFailGo(m_StringHeap.AddStringHeap(
&(mdDelta.m_StringHeap),
0)); // Start offset in the mdDelta
IfFailGo(m_BlobHeap.AddBlobHeap(
&(mdDelta.m_BlobHeap),
0)); // Start offset in the mdDelta
IfFailGo(m_UserStringHeap.AddBlobHeap(
&(mdDelta.m_UserStringHeap),
0)); // Start offset in the mdDelta
// We never do a minimal delta with the guid heap
IfFailGo(m_GuidHeap.AddGuidHeap(
&(mdDelta.m_GuidHeap),
m_GuidHeap.GetSize())); // Starting offset in the full delta guid heap
ErrExit:
return hr;
} // CMiniMdRW::ApplyHeapDeltasWithMinimalDelta
__checkReturn
HRESULT
CMiniMdRW::ApplyHeapDeltasWithFullDelta(
CMiniMdRW &mdDelta) // Interface to MD with the ENC delta.
{
HRESULT hr = S_OK;
// Extend the heaps with EnC full delta
IfFailRet(m_StringHeap.AddStringHeap(
&(mdDelta.m_StringHeap),
m_StringHeap.GetUnalignedSize())); // Starting offset in the full delta string heap
IfFailRet(m_BlobHeap.AddBlobHeap(
&(mdDelta.m_BlobHeap),
m_BlobHeap.GetUnalignedSize())); // Starting offset in the full delta blob heap
IfFailRet(m_UserStringHeap.AddBlobHeap(
&(mdDelta.m_UserStringHeap),
m_UserStringHeap.GetUnalignedSize())); // Starting offset in the full delta user string heap
IfFailRet(m_GuidHeap.AddGuidHeap(
&(mdDelta.m_GuidHeap),
m_GuidHeap.GetSize())); // Starting offset in the full delta guid heap
return hr;
} // CMiniMdRW::ApplyHeapDeltasWithFullDelta
//*****************************************************************************
// Driver for the delta process.
//*****************************************************************************
__checkReturn
HRESULT
CMiniMdRW::ApplyDelta(
CMiniMdRW &mdDelta) // Interface to MD with the ENC delta.
{
HRESULT hr = S_OK;
ULONG iENC; // Loop control.
RID iRid; // RID of some record.
RID iNew; // RID of a new record.
int i; // Loop control.
ULONG ixTbl; // A table.
#ifdef _DEBUG
if (CLRConfig::GetConfigValue(CLRConfig::INTERNAL_MD_ApplyDeltaBreak))
{
_ASSERTE(!"CMiniMDRW::ApplyDelta()");
}
#endif // _DEBUG
// Init the suppressed column table. We know this one isn't zero...
if (m_SuppressedDeltaColumns[TBL_TypeDef] == 0)
{
m_SuppressedDeltaColumns[TBL_EventMap] = (1 << EventMapRec::COL_EventList);
m_SuppressedDeltaColumns[TBL_PropertyMap] = (1 << PropertyMapRec::COL_PropertyList);
m_SuppressedDeltaColumns[TBL_EventMap] = (1 << EventMapRec::COL_EventList);
m_SuppressedDeltaColumns[TBL_Method] = (1 << MethodRec::COL_ParamList);
m_SuppressedDeltaColumns[TBL_TypeDef] = (1 << TypeDefRec::COL_FieldList)|(1<<TypeDefRec::COL_MethodList);
}
// Verify the version of the MD.
if (m_Schema.m_major != mdDelta.m_Schema.m_major ||
m_Schema.m_minor != mdDelta.m_Schema.m_minor)
{
_ASSERTE(!"Version of Delta MetaData is a incompatible with current MetaData.");
//<TODO>@FUTURE: unique error in the future since we are not shipping ENC.</TODO>
return E_INVALIDARG;
}
// verify MVIDs.
ModuleRec *pModDelta;
ModuleRec *pModBase;
IfFailGo(mdDelta.GetModuleRecord(1, &pModDelta));
IfFailGo(GetModuleRecord(1, &pModBase));
GUID GuidDelta;
GUID GuidBase;
IfFailGo(mdDelta.getMvidOfModule(pModDelta, &GuidDelta));
IfFailGo(getMvidOfModule(pModBase, &GuidBase));
if (CLRConfig::GetConfigValue(CLRConfig::INTERNAL_MD_DeltaCheck) && (GuidDelta != GuidBase))
{
_ASSERTE(!"Delta MetaData has different base than current MetaData.");
return E_INVALIDARG;
}
// Let the other md prepare for sparse records.
IfFailGo(mdDelta.StartENCMap());
// Fix the heaps.
IfFailGo(ApplyHeapDeltas(mdDelta));
// Truncate some tables in preparation to copy in new ENCLog data.
for (i = 0; (ixTbl = m_TruncatedEncTables[i]) != (ULONG)-1; ++i)
{
m_Tables[ixTbl].Delete();
IfFailGo(m_Tables[ixTbl].InitializeEmpty_WithRecordCount(
m_TableDefs[ixTbl].m_cbRec,
mdDelta.m_Schema.m_cRecs[ixTbl]
COMMA_INDEBUG_MD(TRUE))); // fIsReadWrite
INDEBUG_MD(m_Tables[ixTbl].Debug_SetTableInfo(NULL, ixTbl));
m_Schema.m_cRecs[ixTbl] = 0;
}
// For each record in the ENC log...
for (iENC = 1; iENC <= mdDelta.m_Schema.m_cRecs[TBL_ENCLog]; ++iENC)
{
// Get the record, and the updated token.
ENCLogRec *pENC;
IfFailGo(mdDelta.GetENCLogRecord(iENC, &pENC));
ENCLogRec *pENC2;
IfFailGo(AddENCLogRecord(&pENC2, &iNew));
IfNullGo(pENC2);
ENCLogRec *pENC3;
_ASSERTE(iNew == iENC);
ULONG func = pENC->GetFuncCode();
pENC2->SetFuncCode(pENC->GetFuncCode());
pENC2->SetToken(pENC->GetToken());
// What kind of record is this?
if (IsRecId(pENC->GetToken()))
{ // Non-token table
iRid = RidFromRecId(pENC->GetToken());
ixTbl = TblFromRecId(pENC->GetToken());
}
else
{ // Token table.
iRid = RidFromToken(pENC->GetToken());
ixTbl = GetTableForToken(pENC->GetToken());
}
RID rid_Ignore;
// Switch based on the function code.
switch (func)
{
case eDeltaMethodCreate:
// Next ENC record will define the new Method.
MethodRec *pMethodRecord;
IfFailGo(AddMethodRecord(&pMethodRecord, &rid_Ignore));
IfFailGo(AddMethodToTypeDef(iRid, m_Schema.m_cRecs[TBL_Method]));
break;
case eDeltaParamCreate:
// Next ENC record will define the new Param. This record is
// tricky because params will be re-ordered based on their sequence,
// but the sequence isn't set until the NEXT record is applied.
// So, for ParamCreate only, apply the param record delta before
// adding the parent-child linkage.
ParamRec *pParamRecord;
IfFailGo(AddParamRecord(&pParamRecord, &rid_Ignore));
// Should have recorded a Param delta after the Param add.
_ASSERTE(iENC<mdDelta.m_Schema.m_cRecs[TBL_ENCLog]);
IfFailGo(mdDelta.GetENCLogRecord(iENC+1, &pENC3));
_ASSERTE(pENC3->GetFuncCode() == 0);
_ASSERTE(GetTableForToken(pENC3->GetToken()) == TBL_Param);
IfFailGo(ApplyTableDelta(mdDelta, TBL_Param, RidFromToken(pENC3->GetToken()), eDeltaFuncDefault));
// Now that Param record is OK, set up linkage.
IfFailGo(AddParamToMethod(iRid, m_Schema.m_cRecs[TBL_Param]));
break;
case eDeltaFieldCreate:
// Next ENC record will define the new Field.
FieldRec *pFieldRecord;
IfFailGo(AddFieldRecord(&pFieldRecord, &rid_Ignore));
IfFailGo(AddFieldToTypeDef(iRid, m_Schema.m_cRecs[TBL_Field]));
break;
case eDeltaPropertyCreate:
// Next ENC record will define the new Property.
PropertyRec *pPropertyRecord;
IfFailGo(AddPropertyRecord(&pPropertyRecord, &rid_Ignore));
IfFailGo(AddPropertyToPropertyMap(iRid, m_Schema.m_cRecs[TBL_Property]));
break;
case eDeltaEventCreate:
// Next ENC record will define the new Event.
EventRec *pEventRecord;
IfFailGo(AddEventRecord(&pEventRecord, &rid_Ignore));
IfFailGo(AddEventToEventMap(iRid, m_Schema.m_cRecs[TBL_Event]));
break;
case eDeltaFuncDefault:
IfFailGo(ApplyTableDelta(mdDelta, ixTbl, iRid, func));
break;
default:
_ASSERTE(!"Unexpected function in ApplyDelta");
IfFailGo(E_UNEXPECTED);
break;
}
}
m_Schema.m_cRecs[TBL_ENCLog] = mdDelta.m_Schema.m_cRecs[TBL_ENCLog];
ErrExit:
// Store the result for returning (IfFailRet will modify hr)
HRESULT hrReturn = hr;
IfFailRet(mdDelta.EndENCMap());
return hrReturn;
} // CMiniMdRW::ApplyDelta
//*****************************************************************************
//*****************************************************************************
__checkReturn
HRESULT
CMiniMdRW::StartENCMap() // S_OK or error.
{
HRESULT hr = S_OK;
ULONG iENC; // Loop control.
ULONG ixTbl; // A table.
int ixTblPrev = -1; // Table previously seen.
_ASSERTE(m_rENCRecs == 0);
if (m_Schema.m_cRecs[TBL_ENCMap] == 0)
return S_OK;
// Build an array of pointers into the ENCMap table for fast access to the ENCMap
// for each table.
m_rENCRecs = new (nothrow) ULONGARRAY;
IfNullGo(m_rENCRecs);
if (!m_rENCRecs->AllocateBlock(TBL_COUNT))
IfFailGo(E_OUTOFMEMORY);
for (iENC = 1; iENC <= m_Schema.m_cRecs[TBL_ENCMap]; ++iENC)
{
ENCMapRec *pMap;
IfFailGo(GetENCMapRecord(iENC, &pMap));
ixTbl = TblFromRecId(pMap->GetToken());
_ASSERTE((int)ixTbl >= ixTblPrev);
_ASSERTE(ixTbl < TBL_COUNT);
_ASSERTE(ixTbl != TBL_ENCMap);
_ASSERTE(ixTbl != TBL_ENCLog);
if ((int)ixTbl == ixTblPrev)
continue;
// Catch up on any skipped tables.
while (ixTblPrev < (int)ixTbl)
{
(*m_rENCRecs)[++ixTblPrev] = iENC;
}
}
while (ixTblPrev < TBL_COUNT-1)
{
(*m_rENCRecs)[++ixTblPrev] = iENC;
}
ErrExit:
return hr;
} // CMiniMdRW::StartENCMap
//*****************************************************************************
//*****************************************************************************
__checkReturn
HRESULT
CMiniMdRW::EndENCMap()
{
if (m_rENCRecs != NULL)
{
delete m_rENCRecs;
m_rENCRecs = NULL;
}
return S_OK;
} // CMiniMdRW::EndENCMap
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//*****************************************************************************
// MetaModelENC.cpp
//
//
// Implementation for applying ENC deltas to a MiniMd.
//
//*****************************************************************************
#include "stdafx.h"
#include <limits.h>
#include <posterror.h>
#include <metamodelrw.h>
#include <stgio.h>
#include <stgtiggerstorage.h>
#include "mdlog.h"
#include "rwutil.h"
ULONG CMiniMdRW::m_SuppressedDeltaColumns[TBL_COUNT] = {0};
//*****************************************************************************
// Copy the data from one MiniMd to another.
//*****************************************************************************
__checkReturn
HRESULT
CMiniMdRW::ApplyRecordDelta(
CMiniMdRW &mdDelta, // The delta MetaData.
ULONG ixTbl, // The table with the data.
void *pDelta, // The delta MetaData record.
void *pRecord) // The record to update.
{
HRESULT hr = S_OK;
ULONG mask = m_SuppressedDeltaColumns[ixTbl];
for (ULONG ixCol = 0; ixCol<m_TableDefs[ixTbl].m_cCols; ++ixCol, mask >>= 1)
{ // Skip certain pointer columns.
if (mask & 0x01)
continue;
ULONG val = mdDelta.GetCol(ixTbl, ixCol, pDelta);
IfFailRet(PutCol(ixTbl, ixCol, pRecord, val));
}
return hr;
} // CMiniMdRW::ApplyRecordDelta
//*****************************************************************************
// Apply a delta record to a table, generically.
//*****************************************************************************
__checkReturn
HRESULT
CMiniMdRW::ApplyTableDelta(
CMiniMdRW &mdDelta, // Interface to MD with the ENC delta.
ULONG ixTbl, // Table index to update.
RID iRid, // RID of the changed item.
int fc) // Function code of update.
{
HRESULT hr = S_OK;
void *pRec; // Record in existing MetaData.
void *pDeltaRec; // Record if Delta MetaData.
RID newRid; // Rid of new record.
// Get the delta record.
IfFailGo(mdDelta.GetDeltaRecord(ixTbl, iRid, &pDeltaRec));
// Get the record from the base metadata.
if (iRid > m_Schema.m_cRecs[ixTbl])
{ // Added record. Each addition is the next one.
_ASSERTE(iRid == m_Schema.m_cRecs[ixTbl] + 1);
switch (ixTbl)
{
case TBL_TypeDef:
IfFailGo(AddTypeDefRecord(reinterpret_cast<TypeDefRec **>(&pRec), &newRid));
break;
case TBL_Method:
IfFailGo(AddMethodRecord(reinterpret_cast<MethodRec **>(&pRec), &newRid));
break;
case TBL_EventMap:
IfFailGo(AddEventMapRecord(reinterpret_cast<EventMapRec **>(&pRec), &newRid));
break;
case TBL_PropertyMap:
IfFailGo(AddPropertyMapRecord(reinterpret_cast<PropertyMapRec **>(&pRec), &newRid));
break;
default:
IfFailGo(AddRecord(ixTbl, &pRec, &newRid));
break;
}
IfNullGo(pRec);
_ASSERTE(iRid == newRid);
}
else
{ // Updated record.
IfFailGo(getRow(ixTbl, iRid, &pRec));
}
// Copy the record info.
IfFailGo(ApplyRecordDelta(mdDelta, ixTbl, pDeltaRec, pRec));
ErrExit:
return hr;
} // CMiniMdRW::ApplyTableDelta
//*****************************************************************************
// Get the record from a Delta MetaData that corresponds to the actual record.
//*****************************************************************************
__checkReturn
HRESULT
CMiniMdRW::GetDeltaRecord(
ULONG ixTbl, // Table.
ULONG iRid, // Record in the table.
void **ppRecord)
{
HRESULT hr;
ULONG iMap; // RID in map table.
ENCMapRec *pMap; // Row in map table.
*ppRecord = NULL;
// If no remap, just return record directly.
if ((m_Schema.m_cRecs[TBL_ENCMap] == 0) || (ixTbl == TBL_Module) || !IsMinimalDelta())
{
return getRow(ixTbl, iRid, ppRecord);
}
// Use the remap table to find the physical row containing this logical row.
iMap = (*m_rENCRecs)[ixTbl];
IfFailRet(GetENCMapRecord(iMap, &pMap));
// Search for desired record.
while ((TblFromRecId(pMap->GetToken()) == ixTbl) && (RidFromRecId(pMap->GetToken()) < iRid))
{
IfFailRet(GetENCMapRecord(++iMap, &pMap));
}
_ASSERTE((TblFromRecId(pMap->GetToken()) == ixTbl) && (RidFromRecId(pMap->GetToken()) == iRid));
// Relative position within table's group in map is physical rid.
iRid = iMap - (*m_rENCRecs)[ixTbl] + 1;
return getRow(ixTbl, iRid, ppRecord);
} // CMiniMdRW::GetDeltaRecord
//*****************************************************************************
// Given a MetaData with ENC changes, apply those changes to this MetaData.
//*****************************************************************************
__checkReturn
HRESULT
CMiniMdRW::ApplyHeapDeltas(
CMiniMdRW &mdDelta) // Interface to MD with the ENC delta.
{
if (mdDelta.IsMinimalDelta())
{
return ApplyHeapDeltasWithMinimalDelta(mdDelta);
}
else
{
return ApplyHeapDeltasWithFullDelta(mdDelta);
}
}// CMiniMdRW::ApplyHeapDeltas
__checkReturn
HRESULT
CMiniMdRW::ApplyHeapDeltasWithMinimalDelta(
CMiniMdRW &mdDelta) // Interface to MD with the ENC delta.
{
HRESULT hr = S_OK;
// Extend the heaps with EnC minimal delta
IfFailGo(m_StringHeap.AddStringHeap(
&(mdDelta.m_StringHeap),
0)); // Start offset in the mdDelta
IfFailGo(m_BlobHeap.AddBlobHeap(
&(mdDelta.m_BlobHeap),
0)); // Start offset in the mdDelta
IfFailGo(m_UserStringHeap.AddBlobHeap(
&(mdDelta.m_UserStringHeap),
0)); // Start offset in the mdDelta
// We never do a minimal delta with the guid heap
IfFailGo(m_GuidHeap.AddGuidHeap(
&(mdDelta.m_GuidHeap),
m_GuidHeap.GetSize())); // Starting offset in the full delta guid heap
ErrExit:
return hr;
} // CMiniMdRW::ApplyHeapDeltasWithMinimalDelta
__checkReturn
HRESULT
CMiniMdRW::ApplyHeapDeltasWithFullDelta(
CMiniMdRW &mdDelta) // Interface to MD with the ENC delta.
{
HRESULT hr = S_OK;
// Extend the heaps with EnC full delta
IfFailRet(m_StringHeap.AddStringHeap(
&(mdDelta.m_StringHeap),
m_StringHeap.GetUnalignedSize())); // Starting offset in the full delta string heap
IfFailRet(m_BlobHeap.AddBlobHeap(
&(mdDelta.m_BlobHeap),
m_BlobHeap.GetUnalignedSize())); // Starting offset in the full delta blob heap
IfFailRet(m_UserStringHeap.AddBlobHeap(
&(mdDelta.m_UserStringHeap),
m_UserStringHeap.GetUnalignedSize())); // Starting offset in the full delta user string heap
IfFailRet(m_GuidHeap.AddGuidHeap(
&(mdDelta.m_GuidHeap),
m_GuidHeap.GetSize())); // Starting offset in the full delta guid heap
return hr;
} // CMiniMdRW::ApplyHeapDeltasWithFullDelta
//*****************************************************************************
// Driver for the delta process.
//*****************************************************************************
__checkReturn
HRESULT
CMiniMdRW::ApplyDelta(
CMiniMdRW &mdDelta) // Interface to MD with the ENC delta.
{
HRESULT hr = S_OK;
ULONG iENC; // Loop control.
RID iRid; // RID of some record.
RID iNew; // RID of a new record.
int i; // Loop control.
ULONG ixTbl; // A table.
#ifdef _DEBUG
if (CLRConfig::GetConfigValue(CLRConfig::INTERNAL_MD_ApplyDeltaBreak))
{
_ASSERTE(!"CMiniMDRW::ApplyDelta()");
}
#endif // _DEBUG
// Init the suppressed column table. We know this one isn't zero...
if (m_SuppressedDeltaColumns[TBL_TypeDef] == 0)
{
m_SuppressedDeltaColumns[TBL_EventMap] = (1 << EventMapRec::COL_EventList);
m_SuppressedDeltaColumns[TBL_PropertyMap] = (1 << PropertyMapRec::COL_PropertyList);
m_SuppressedDeltaColumns[TBL_EventMap] = (1 << EventMapRec::COL_EventList);
m_SuppressedDeltaColumns[TBL_Method] = (1 << MethodRec::COL_ParamList);
m_SuppressedDeltaColumns[TBL_TypeDef] = (1 << TypeDefRec::COL_FieldList)|(1<<TypeDefRec::COL_MethodList);
}
// Verify the version of the MD.
if (m_Schema.m_major != mdDelta.m_Schema.m_major ||
m_Schema.m_minor != mdDelta.m_Schema.m_minor)
{
_ASSERTE(!"Version of Delta MetaData is a incompatible with current MetaData.");
//<TODO>@FUTURE: unique error in the future since we are not shipping ENC.</TODO>
return E_INVALIDARG;
}
// verify MVIDs.
ModuleRec *pModDelta;
ModuleRec *pModBase;
IfFailGo(mdDelta.GetModuleRecord(1, &pModDelta));
IfFailGo(GetModuleRecord(1, &pModBase));
GUID GuidDelta;
GUID GuidBase;
IfFailGo(mdDelta.getMvidOfModule(pModDelta, &GuidDelta));
IfFailGo(getMvidOfModule(pModBase, &GuidBase));
if (CLRConfig::GetConfigValue(CLRConfig::INTERNAL_MD_DeltaCheck) && (GuidDelta != GuidBase))
{
_ASSERTE(!"Delta MetaData has different base than current MetaData.");
return E_INVALIDARG;
}
// Let the other md prepare for sparse records.
IfFailGo(mdDelta.StartENCMap());
// Fix the heaps.
IfFailGo(ApplyHeapDeltas(mdDelta));
// Truncate some tables in preparation to copy in new ENCLog data.
for (i = 0; (ixTbl = m_TruncatedEncTables[i]) != (ULONG)-1; ++i)
{
m_Tables[ixTbl].Delete();
IfFailGo(m_Tables[ixTbl].InitializeEmpty_WithRecordCount(
m_TableDefs[ixTbl].m_cbRec,
mdDelta.m_Schema.m_cRecs[ixTbl]
COMMA_INDEBUG_MD(TRUE))); // fIsReadWrite
INDEBUG_MD(m_Tables[ixTbl].Debug_SetTableInfo(NULL, ixTbl));
m_Schema.m_cRecs[ixTbl] = 0;
}
// For each record in the ENC log...
for (iENC = 1; iENC <= mdDelta.m_Schema.m_cRecs[TBL_ENCLog]; ++iENC)
{
// Get the record, and the updated token.
ENCLogRec *pENC;
IfFailGo(mdDelta.GetENCLogRecord(iENC, &pENC));
ENCLogRec *pENC2;
IfFailGo(AddENCLogRecord(&pENC2, &iNew));
IfNullGo(pENC2);
ENCLogRec *pENC3;
_ASSERTE(iNew == iENC);
ULONG func = pENC->GetFuncCode();
pENC2->SetFuncCode(pENC->GetFuncCode());
pENC2->SetToken(pENC->GetToken());
// What kind of record is this?
if (IsRecId(pENC->GetToken()))
{ // Non-token table
iRid = RidFromRecId(pENC->GetToken());
ixTbl = TblFromRecId(pENC->GetToken());
}
else
{ // Token table.
iRid = RidFromToken(pENC->GetToken());
ixTbl = GetTableForToken(pENC->GetToken());
}
RID rid_Ignore;
// Switch based on the function code.
switch (func)
{
case eDeltaMethodCreate:
// Next ENC record will define the new Method.
MethodRec *pMethodRecord;
IfFailGo(AddMethodRecord(&pMethodRecord, &rid_Ignore));
IfFailGo(AddMethodToTypeDef(iRid, m_Schema.m_cRecs[TBL_Method]));
break;
case eDeltaParamCreate:
// Next ENC record will define the new Param. This record is
// tricky because params will be re-ordered based on their sequence,
// but the sequence isn't set until the NEXT record is applied.
// So, for ParamCreate only, apply the param record delta before
// adding the parent-child linkage.
ParamRec *pParamRecord;
IfFailGo(AddParamRecord(&pParamRecord, &rid_Ignore));
// Should have recorded a Param delta after the Param add.
_ASSERTE(iENC<mdDelta.m_Schema.m_cRecs[TBL_ENCLog]);
IfFailGo(mdDelta.GetENCLogRecord(iENC+1, &pENC3));
_ASSERTE(pENC3->GetFuncCode() == 0);
_ASSERTE(GetTableForToken(pENC3->GetToken()) == TBL_Param);
IfFailGo(ApplyTableDelta(mdDelta, TBL_Param, RidFromToken(pENC3->GetToken()), eDeltaFuncDefault));
// Now that Param record is OK, set up linkage.
IfFailGo(AddParamToMethod(iRid, m_Schema.m_cRecs[TBL_Param]));
break;
case eDeltaFieldCreate:
// Next ENC record will define the new Field.
FieldRec *pFieldRecord;
IfFailGo(AddFieldRecord(&pFieldRecord, &rid_Ignore));
IfFailGo(AddFieldToTypeDef(iRid, m_Schema.m_cRecs[TBL_Field]));
break;
case eDeltaPropertyCreate:
// Next ENC record will define the new Property.
PropertyRec *pPropertyRecord;
IfFailGo(AddPropertyRecord(&pPropertyRecord, &rid_Ignore));
IfFailGo(AddPropertyToPropertyMap(iRid, m_Schema.m_cRecs[TBL_Property]));
break;
case eDeltaEventCreate:
// Next ENC record will define the new Event.
EventRec *pEventRecord;
IfFailGo(AddEventRecord(&pEventRecord, &rid_Ignore));
IfFailGo(AddEventToEventMap(iRid, m_Schema.m_cRecs[TBL_Event]));
break;
case eDeltaFuncDefault:
IfFailGo(ApplyTableDelta(mdDelta, ixTbl, iRid, func));
break;
default:
_ASSERTE(!"Unexpected function in ApplyDelta");
IfFailGo(E_UNEXPECTED);
break;
}
}
m_Schema.m_cRecs[TBL_ENCLog] = mdDelta.m_Schema.m_cRecs[TBL_ENCLog];
ErrExit:
// Store the result for returning (IfFailRet will modify hr)
HRESULT hrReturn = hr;
IfFailRet(mdDelta.EndENCMap());
return hrReturn;
} // CMiniMdRW::ApplyDelta
//*****************************************************************************
//*****************************************************************************
__checkReturn
HRESULT
CMiniMdRW::StartENCMap() // S_OK or error.
{
HRESULT hr = S_OK;
ULONG iENC; // Loop control.
ULONG ixTbl; // A table.
int ixTblPrev = -1; // Table previously seen.
_ASSERTE(m_rENCRecs == 0);
if (m_Schema.m_cRecs[TBL_ENCMap] == 0)
return S_OK;
// Build an array of pointers into the ENCMap table for fast access to the ENCMap
// for each table.
m_rENCRecs = new (nothrow) ULONGARRAY;
IfNullGo(m_rENCRecs);
if (!m_rENCRecs->AllocateBlock(TBL_COUNT))
IfFailGo(E_OUTOFMEMORY);
for (iENC = 1; iENC <= m_Schema.m_cRecs[TBL_ENCMap]; ++iENC)
{
ENCMapRec *pMap;
IfFailGo(GetENCMapRecord(iENC, &pMap));
ixTbl = TblFromRecId(pMap->GetToken());
_ASSERTE((int)ixTbl >= ixTblPrev);
_ASSERTE(ixTbl < TBL_COUNT);
_ASSERTE(ixTbl != TBL_ENCMap);
_ASSERTE(ixTbl != TBL_ENCLog);
if ((int)ixTbl == ixTblPrev)
continue;
// Catch up on any skipped tables.
while (ixTblPrev < (int)ixTbl)
{
(*m_rENCRecs)[++ixTblPrev] = iENC;
}
}
while (ixTblPrev < TBL_COUNT-1)
{
(*m_rENCRecs)[++ixTblPrev] = iENC;
}
ErrExit:
return hr;
} // CMiniMdRW::StartENCMap
//*****************************************************************************
//*****************************************************************************
__checkReturn
HRESULT
CMiniMdRW::EndENCMap()
{
if (m_rENCRecs != NULL)
{
delete m_rENCRecs;
m_rENCRecs = NULL;
}
return S_OK;
} // CMiniMdRW::EndENCMap
| -1 |
dotnet/runtime | 66,057 | Address TODO to switch to generated p/invoke | Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | elinor-fung | 2022-03-02T03:31:28Z | 2022-03-02T19:08:30Z | a4b8893a118357b55c0add9a39cc5aeb097a0bb8 | 1abbbb4adf6bf02549f4c6e021176534dcc4f974 | Address TODO to switch to generated p/invoke. Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | ./src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/SpecialNames.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace Microsoft.CSharp.RuntimeBinder
{
internal static class SpecialNames
{
public const string ImplicitConversion = "op_Implicit";
public const string ExplicitConversion = "op_Explicit";
public const string Invoke = "Invoke";
public const string Constructor = ".ctor";
public const string Indexer = "$Item$";
// Binary Operators
public const string CLR_Add = "op_Addition";
public const string CLR_Subtract = "op_Subtraction";
public const string CLR_Multiply = "op_Multiply";
public const string CLR_Division = "op_Division";
public const string CLR_Modulus = "op_Modulus";
public const string CLR_LShift = "op_LeftShift";
public const string CLR_RShift = "op_RightShift";
public const string CLR_LT = "op_LessThan";
public const string CLR_GT = "op_GreaterThan";
public const string CLR_LTE = "op_LessThanOrEqual";
public const string CLR_GTE = "op_GreaterThanOrEqual";
public const string CLR_Equality = "op_Equality";
public const string CLR_Inequality = "op_Inequality";
public const string CLR_BitwiseAnd = "op_BitwiseAnd";
public const string CLR_ExclusiveOr = "op_ExclusiveOr";
public const string CLR_BitwiseOr = "op_BitwiseOr";
public const string CLR_LogicalNot = "op_LogicalNot";
// In place binary operators.
public const string CLR_InPlaceAdd = "op_Addition";
public const string CLR_InPlaceSubtract = "op_Subtraction";
public const string CLR_InPlaceMultiply = "op_Multiply";
public const string CLR_InPlaceDivide = "op_Division";
public const string CLR_InPlaceModulus = "op_Modulus";
public const string CLR_InPlaceBitwiseAnd = "op_BitwiseAnd";
public const string CLR_InPlaceExclusiveOr = "op_ExclusiveOr";
public const string CLR_InPlaceBitwiseOr = "op_BitwiseOr";
public const string CLR_InPlaceLShift = "op_LeftShift";
public const string CLR_InPlaceRShift = "op_RightShift";
// Unary Operators
public const string CLR_UnaryNegation = "op_UnaryNegation";
public const string CLR_UnaryPlus = "op_UnaryPlus";
public const string CLR_OnesComplement = "op_OnesComplement";
public const string CLR_True = "op_True";
public const string CLR_False = "op_False";
public const string CLR_Increment = "op_Increment";
public const string CLR_Decrement = "op_Decrement";
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace Microsoft.CSharp.RuntimeBinder
{
internal static class SpecialNames
{
public const string ImplicitConversion = "op_Implicit";
public const string ExplicitConversion = "op_Explicit";
public const string Invoke = "Invoke";
public const string Constructor = ".ctor";
public const string Indexer = "$Item$";
// Binary Operators
public const string CLR_Add = "op_Addition";
public const string CLR_Subtract = "op_Subtraction";
public const string CLR_Multiply = "op_Multiply";
public const string CLR_Division = "op_Division";
public const string CLR_Modulus = "op_Modulus";
public const string CLR_LShift = "op_LeftShift";
public const string CLR_RShift = "op_RightShift";
public const string CLR_LT = "op_LessThan";
public const string CLR_GT = "op_GreaterThan";
public const string CLR_LTE = "op_LessThanOrEqual";
public const string CLR_GTE = "op_GreaterThanOrEqual";
public const string CLR_Equality = "op_Equality";
public const string CLR_Inequality = "op_Inequality";
public const string CLR_BitwiseAnd = "op_BitwiseAnd";
public const string CLR_ExclusiveOr = "op_ExclusiveOr";
public const string CLR_BitwiseOr = "op_BitwiseOr";
public const string CLR_LogicalNot = "op_LogicalNot";
// In place binary operators.
public const string CLR_InPlaceAdd = "op_Addition";
public const string CLR_InPlaceSubtract = "op_Subtraction";
public const string CLR_InPlaceMultiply = "op_Multiply";
public const string CLR_InPlaceDivide = "op_Division";
public const string CLR_InPlaceModulus = "op_Modulus";
public const string CLR_InPlaceBitwiseAnd = "op_BitwiseAnd";
public const string CLR_InPlaceExclusiveOr = "op_ExclusiveOr";
public const string CLR_InPlaceBitwiseOr = "op_BitwiseOr";
public const string CLR_InPlaceLShift = "op_LeftShift";
public const string CLR_InPlaceRShift = "op_RightShift";
// Unary Operators
public const string CLR_UnaryNegation = "op_UnaryNegation";
public const string CLR_UnaryPlus = "op_UnaryPlus";
public const string CLR_OnesComplement = "op_OnesComplement";
public const string CLR_True = "op_True";
public const string CLR_False = "op_False";
public const string CLR_Increment = "op_Increment";
public const string CLR_Decrement = "op_Decrement";
}
}
| -1 |
dotnet/runtime | 66,057 | Address TODO to switch to generated p/invoke | Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | elinor-fung | 2022-03-02T03:31:28Z | 2022-03-02T19:08:30Z | a4b8893a118357b55c0add9a39cc5aeb097a0bb8 | 1abbbb4adf6bf02549f4c6e021176534dcc4f974 | Address TODO to switch to generated p/invoke. Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | ./src/libraries/System.Linq/tests/SumTests.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.Linq.Tests
{
public class SumTests : EnumerableTests
{
#region SourceIsNull - ArgumentNullExceptionThrown
[Fact]
public void SumOfInt_SourceIsNull_ArgumentNullExceptionThrown()
{
IEnumerable<int> sourceInt = null;
AssertExtensions.Throws<ArgumentNullException>("source", () => sourceInt.Sum());
AssertExtensions.Throws<ArgumentNullException>("source", () => sourceInt.Sum(x => x));
}
[Fact]
public void SumOfNullableOfInt_SourceIsNull_ArgumentNullExceptionThrown()
{
IEnumerable<int?> sourceNullableInt = null;
AssertExtensions.Throws<ArgumentNullException>("source", () => sourceNullableInt.Sum());
AssertExtensions.Throws<ArgumentNullException>("source", () => sourceNullableInt.Sum(x => x));
}
[Fact]
public void SumOfLong_SourceIsNull_ArgumentNullExceptionThrown()
{
IEnumerable<long> sourceLong = null;
AssertExtensions.Throws<ArgumentNullException>("source", () => sourceLong.Sum());
AssertExtensions.Throws<ArgumentNullException>("source", () => sourceLong.Sum(x => x));
}
[Fact]
public void SumOfNullableOfLong_SourceIsNull_ArgumentNullExceptionThrown()
{
IEnumerable<long?> sourceNullableLong = null;
AssertExtensions.Throws<ArgumentNullException>("source", () => sourceNullableLong.Sum());
AssertExtensions.Throws<ArgumentNullException>("source", () => sourceNullableLong.Sum(x => x));
}
[Fact]
public void SumOfFloat_SourceIsNull_ArgumentNullExceptionThrown()
{
IEnumerable<float> sourceFloat = null;
AssertExtensions.Throws<ArgumentNullException>("source", () => sourceFloat.Sum());
AssertExtensions.Throws<ArgumentNullException>("source", () => sourceFloat.Sum(x => x));
}
[Fact]
public void SumOfNullableOfFloat_SourceIsNull_ArgumentNullExceptionThrown()
{
IEnumerable<float?> sourceNullableFloat = null;
AssertExtensions.Throws<ArgumentNullException>("source", () => sourceNullableFloat.Sum());
AssertExtensions.Throws<ArgumentNullException>("source", () => sourceNullableFloat.Sum(x => x));
}
[Fact]
public void SumOfDouble_SourceIsNull_ArgumentNullExceptionThrown()
{
IEnumerable<double> sourceDouble = null;
AssertExtensions.Throws<ArgumentNullException>("source", () => sourceDouble.Sum());
AssertExtensions.Throws<ArgumentNullException>("source", () => sourceDouble.Sum(x => x));
}
[Fact]
public void SumOfNullableOfDouble_SourceIsNull_ArgumentNullExceptionThrown()
{
IEnumerable<double?> sourceNullableDouble = null;
AssertExtensions.Throws<ArgumentNullException>("source", () => sourceNullableDouble.Sum());
AssertExtensions.Throws<ArgumentNullException>("source", () => sourceNullableDouble.Sum(x => x));
}
[Fact]
public void SumOfDecimal_SourceIsNull_ArgumentNullExceptionThrown()
{
IEnumerable<decimal> sourceDecimal = null;
AssertExtensions.Throws<ArgumentNullException>("source", () => sourceDecimal.Sum());
AssertExtensions.Throws<ArgumentNullException>("source", () => sourceDecimal.Sum(x => x));
}
[Fact]
public void SumOfNullableOfDecimal_SourceIsNull_ArgumentNullExceptionThrown()
{
IEnumerable<decimal?> sourceNullableDecimal = null;
AssertExtensions.Throws<ArgumentNullException>("source", () => sourceNullableDecimal.Sum());
AssertExtensions.Throws<ArgumentNullException>("source", () => sourceNullableDecimal.Sum(x => x));
}
#endregion
#region SelectionIsNull - ArgumentNullExceptionThrown
[Fact]
public void SumOfInt_SelectorIsNull_ArgumentNullExceptionThrown()
{
IEnumerable<int> sourceInt = Enumerable.Empty<int>();
Func<int, int> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => sourceInt.Sum(selector));
}
[Fact]
public void SumOfNullableOfInt_SelectorIsNull_ArgumentNullExceptionThrown()
{
IEnumerable<int?> sourceNullableInt = Enumerable.Empty<int?>();
Func<int?, int?> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => sourceNullableInt.Sum(selector));
}
[Fact]
public void SumOfLong_SelectorIsNull_ArgumentNullExceptionThrown()
{
IEnumerable<long> sourceLong = Enumerable.Empty<long>();
Func<long, long> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => sourceLong.Sum(selector));
}
[Fact]
public void SumOfNullableOfLong_SelectorIsNull_ArgumentNullExceptionThrown()
{
IEnumerable<long?> sourceNullableLong = Enumerable.Empty<long?>();
Func<long?, long?> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => sourceNullableLong.Sum(selector));
}
[Fact]
public void SumOfFloat_SelectorIsNull_ArgumentNullExceptionThrown()
{
IEnumerable<float> sourceFloat = Enumerable.Empty<float>();
Func<float, float> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => sourceFloat.Sum(selector));
}
[Fact]
public void SumOfNullableOfFloat_SelectorIsNull_ArgumentNullExceptionThrown()
{
IEnumerable<float?> sourceNullableFloat = Enumerable.Empty<float?>();
Func<float?, float?> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => sourceNullableFloat.Sum(selector));
}
[Fact]
public void SumOfDouble_SelectorIsNull_ArgumentNullExceptionThrown()
{
IEnumerable<double> sourceDouble = Enumerable.Empty<double>();
Func<double, double> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => sourceDouble.Sum(selector));
}
[Fact]
public void SumOfNullableOfDouble_SelectorIsNull_ArgumentNullExceptionThrown()
{
IEnumerable<double?> sourceNullableDouble = Enumerable.Empty<double?>();
Func<double?, double?> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => sourceNullableDouble.Sum(selector));
}
[Fact]
public void SumOfDecimal_SelectorIsNull_ArgumentNullExceptionThrown()
{
IEnumerable<decimal> sourceDecimal = Enumerable.Empty<decimal>();
Func<decimal, decimal> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => sourceDecimal.Sum(selector));
}
[Fact]
public void SumOfNullableOfDecimal_SelectorIsNull_ArgumentNullExceptionThrown()
{
IEnumerable<decimal?> sourceNullableDecimal = Enumerable.Empty<decimal?>();
Func<decimal?, decimal?> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => sourceNullableDecimal.Sum(selector));
}
#endregion
#region SourceIsEmptyCollection - ZeroReturned
[Fact]
public void SumOfInt_SourceIsEmptyCollection_ZeroReturned()
{
IEnumerable<int> sourceInt = Enumerable.Empty<int>();
Assert.Equal(0, sourceInt.Sum());
Assert.Equal(0, sourceInt.Sum(x => x));
}
[Fact]
public void SumOfNullableOfInt_SourceIsEmptyCollection_ZeroReturned()
{
IEnumerable<int?> sourceNullableInt = Enumerable.Empty<int?>();
Assert.Equal(0, sourceNullableInt.Sum());
Assert.Equal(0, sourceNullableInt.Sum(x => x));
}
[Fact]
public void SumOfLong_SourceIsEmptyCollection_ZeroReturned()
{
IEnumerable<long> sourceLong = Enumerable.Empty<long>();
Assert.Equal(0L, sourceLong.Sum());
Assert.Equal(0L, sourceLong.Sum(x => x));
}
[Fact]
public void SumOfNullableOfLong_SourceIsEmptyCollection_ZeroReturned()
{
IEnumerable<long?> sourceNullableLong = Enumerable.Empty<long?>();
Assert.Equal(0L, sourceNullableLong.Sum());
Assert.Equal(0L, sourceNullableLong.Sum(x => x));
}
[Fact]
public void SumOfFloat_SourceIsEmptyCollection_ZeroReturned()
{
IEnumerable<float> sourceFloat = Enumerable.Empty<float>();
Assert.Equal(0f, sourceFloat.Sum());
Assert.Equal(0f, sourceFloat.Sum(x => x));
}
[Fact]
public void SumOfNullableOfFloat_SourceIsEmptyCollection_ZeroReturned()
{
IEnumerable<float?> sourceNullableFloat = Enumerable.Empty<float?>();
Assert.Equal(0f, sourceNullableFloat.Sum());
Assert.Equal(0f, sourceNullableFloat.Sum(x => x));
}
[Fact]
public void SumOfDouble_SourceIsEmptyCollection_ZeroReturned()
{
IEnumerable<double> sourceDouble = Enumerable.Empty<double>();
Assert.Equal(0d, sourceDouble.Sum());
Assert.Equal(0d, sourceDouble.Sum(x => x));
}
[Fact]
public void SumOfNullableOfDouble_SourceIsEmptyCollection_ZeroReturned()
{
IEnumerable<double?> sourceNullableDouble = Enumerable.Empty<double?>();
Assert.Equal(0d, sourceNullableDouble.Sum());
Assert.Equal(0d, sourceNullableDouble.Sum(x => x));
}
[Fact]
public void SumOfDecimal_SourceIsEmptyCollection_ZeroReturned()
{
IEnumerable<decimal> sourceDecimal = Enumerable.Empty<decimal>();
Assert.Equal(0m, sourceDecimal.Sum());
Assert.Equal(0m, sourceDecimal.Sum(x => x));
}
[Fact]
public void SumOfNullableOfDecimal_SourceIsEmptyCollection_ZeroReturned()
{
IEnumerable<decimal?> sourceNullableDecimal = Enumerable.Empty<decimal?>();
Assert.Equal(0m, sourceNullableDecimal.Sum());
Assert.Equal(0m, sourceNullableDecimal.Sum(x => x));
}
#endregion
#region SourceIsNotEmpty - ProperSumReturned
[Fact]
public void SumOfInt_SourceIsNotEmpty_ProperSumReturned()
{
IEnumerable<int> sourceInt = new int[] { 1, -2, 3, -4 };
Assert.Equal(-2, sourceInt.Sum());
Assert.Equal(-2, sourceInt.Sum(x => x));
}
[Fact]
public void SumOfNullableOfInt_SourceIsNotEmpty_ProperSumReturned()
{
IEnumerable<int?> sourceNullableInt = new int?[] { 1, -2, null, 3, -4, null };
Assert.Equal(-2, sourceNullableInt.Sum());
Assert.Equal(-2, sourceNullableInt.Sum(x => x));
}
[Fact]
public void SumOfLong_SourceIsNotEmpty_ProperSumReturned()
{
IEnumerable<long> sourceLong = new long[] { 1L, -2L, 3L, -4L };
Assert.Equal(-2L, sourceLong.Sum());
Assert.Equal(-2L, sourceLong.Sum(x => x));
}
[Fact]
public void SumOfNullableOfLong_SourceIsNotEmpty_ProperSumReturned()
{
IEnumerable<long?> sourceNullableLong = new long?[] { 1L, -2L, null, 3L, -4L, null };
Assert.Equal(-2L, sourceNullableLong.Sum());
Assert.Equal(-2L, sourceNullableLong.Sum(x => x));
}
[Fact]
public void SumOfFloat_SourceIsNotEmpty_ProperSumReturned()
{
IEnumerable<float> sourceFloat = new float[] { 1f, 0.5f, -1f, 0.5f };
Assert.Equal(1f, sourceFloat.Sum());
Assert.Equal(1f, sourceFloat.Sum(x => x));
}
[Fact]
public void SumOfNullableOfFloat_SourceIsNotEmpty_ProperSumReturned()
{
IEnumerable<float?> sourceNullableFloat = new float?[] { 1f, 0.5f, null, -1f, 0.5f, null };
Assert.Equal(1f, sourceNullableFloat.Sum());
Assert.Equal(1f, sourceNullableFloat.Sum(x => x));
}
[Fact]
public void SumOfDouble_SourceIsNotEmpty_ProperSumReturned()
{
IEnumerable<double> sourceDouble = new double[] { 1d, 0.5d, -1d, 0.5d };
Assert.Equal(1d, sourceDouble.Sum());
Assert.Equal(1d, sourceDouble.Sum(x => x));
}
[Fact]
public void SumOfNullableOfDouble_SourceIsNotEmpty_ProperSumReturned()
{
IEnumerable<double?> sourceNullableDouble = new double?[] { 1d, 0.5d, null, -1d, 0.5d, null };
Assert.Equal(1d, sourceNullableDouble.Sum());
Assert.Equal(1d, sourceNullableDouble.Sum(x => x));
}
[Fact]
public void SumOfDecimal_SourceIsNotEmpty_ProperSumReturned()
{
IEnumerable<decimal> sourceDecimal = new decimal[] { 1m, 0.5m, -1m, 0.5m };
Assert.Equal(1m, sourceDecimal.Sum());
Assert.Equal(1m, sourceDecimal.Sum(x => x));
}
[Fact]
public void SumOfNullableOfDecimal_SourceIsNotEmpty_ProperSumReturned()
{
IEnumerable<decimal?> sourceNullableDecimal = new decimal?[] { 1m, 0.5m, null, -1m, 0.5m, null };
Assert.Equal(1m, sourceNullableDecimal.Sum());
Assert.Equal(1m, sourceNullableDecimal.Sum(x => x));
}
#endregion
#region SourceSumsToOverflow - OverflowExceptionThrown or Infinity returned
[Fact]
public void SumOfInt_SourceSumsToOverflow_OverflowExceptionThrown()
{
IEnumerable<int> sourceInt = new int[] { int.MaxValue, 1 };
Assert.Throws<OverflowException>(() => sourceInt.Sum());
Assert.Throws<OverflowException>(() => sourceInt.Sum(x => x));
}
[Fact]
public void SumOfNullableOfInt_SourceSumsToOverflow_OverflowExceptionThrown()
{
IEnumerable<int?> sourceNullableInt = new int?[] { int.MaxValue, null, 1 };
Assert.Throws<OverflowException>(() => sourceNullableInt.Sum());
Assert.Throws<OverflowException>(() => sourceNullableInt.Sum(x => x));
}
[Fact]
public void SumOfLong_SourceSumsToOverflow_OverflowExceptionThrown()
{
IEnumerable<long> sourceLong = new long[] { long.MaxValue, 1L };
Assert.Throws<OverflowException>(() => sourceLong.Sum());
Assert.Throws<OverflowException>(() => sourceLong.Sum(x => x));
}
[Fact]
public void SumOfNullableOfLong_SourceSumsToOverflow_OverflowExceptionThrown()
{
IEnumerable<long?> sourceNullableLong = new long?[] { long.MaxValue, null, 1 };
Assert.Throws<OverflowException>(() => sourceNullableLong.Sum());
Assert.Throws<OverflowException>(() => sourceNullableLong.Sum(x => x));
}
[Fact]
public void SumOfFloat_SourceSumsToOverflow_InfinityReturned()
{
IEnumerable<float> sourceFloat = new float[] { float.MaxValue, float.MaxValue };
Assert.True(float.IsPositiveInfinity(sourceFloat.Sum()));
Assert.True(float.IsPositiveInfinity(sourceFloat.Sum(x => x)));
}
[Fact]
public void SumOfNullableOfFloat_SourceSumsToOverflow_InfinityReturned()
{
IEnumerable<float?> sourceNullableFloat = new float?[] { float.MaxValue, null, float.MaxValue };
Assert.True(float.IsPositiveInfinity(sourceNullableFloat.Sum().Value));
Assert.True(float.IsPositiveInfinity(sourceNullableFloat.Sum(x => x).Value));
}
[Fact]
public void SumOfDouble_SourceSumsToOverflow_InfinityReturned()
{
IEnumerable<double> sourceDouble = new double[] { double.MaxValue, double.MaxValue };
Assert.True(double.IsPositiveInfinity(sourceDouble.Sum()));
Assert.True(double.IsPositiveInfinity(sourceDouble.Sum(x => x)));
}
[Fact]
public void SumOfNullableOfDouble_SourceSumsToOverflow_InfinityReturned()
{
IEnumerable<double?> sourceNullableDouble = new double?[] { double.MaxValue, null, double.MaxValue };
Assert.True(double.IsPositiveInfinity(sourceNullableDouble.Sum().Value));
Assert.True(double.IsPositiveInfinity(sourceNullableDouble.Sum(x => x).Value));
}
[Fact]
public void SumOfDecimal_SourceSumsToOverflow_OverflowExceptionThrown()
{
IEnumerable<decimal> sourceDecimal = new decimal[] { decimal.MaxValue, 1m };
Assert.Throws<OverflowException>(() => sourceDecimal.Sum());
Assert.Throws<OverflowException>(() => sourceDecimal.Sum(x => x));
}
[Fact]
public void SumOfNullableOfDecimal_SourceSumsToOverflow_OverflowExceptionThrown()
{
IEnumerable<decimal?> sourceNullableDecimal = new decimal?[] { decimal.MaxValue, null, 1m };
Assert.Throws<OverflowException>(() => sourceNullableDecimal.Sum());
Assert.Throws<OverflowException>(() => sourceNullableDecimal.Sum(x => x));
}
#endregion
[Fact]
public void SameResultsRepeatCallsIntQuery()
{
var q = from x in new int?[] { 9999, 0, 888, -1, 66, null, -777, 1, 2, -12345 }
where x > int.MinValue
select x;
Assert.Equal(q.Sum(), q.Sum());
}
[Fact]
public void SolitaryNullableSingle()
{
float?[] source = { 20.51f };
Assert.Equal(source.FirstOrDefault(), source.Sum());
}
[Fact]
public void NaNFromSingles()
{
float?[] source = { 20.45f, 0f, -10.55f, float.NaN };
Assert.True(float.IsNaN(source.Sum().Value));
}
[Fact]
public void NullableSingleAllNull()
{
Assert.Equal(0, Enumerable.Repeat(default(float?), 4).Sum().Value);
}
[Fact]
public void NullableSingleToNegativeInfinity()
{
float?[] source = { -float.MaxValue, -float.MaxValue };
Assert.True(float.IsNegativeInfinity(source.Sum().Value));
}
[Fact]
public void NullableSingleFromSelector()
{
var source = new[]{
new { name="Tim", num=(float?)9.5f },
new { name="John", num=default(float?) },
new { name="Bob", num=(float?)8.5f }
};
Assert.Equal(18.0f, source.Sum(e => e.num).Value);
}
[Fact]
public void SolitaryInt32()
{
int[] source = { 20 };
Assert.Equal(source.FirstOrDefault(), source.Sum());
}
[Fact]
public void OverflowInt32Negative()
{
int[] source = { -int.MaxValue, 0, -5, -20 };
Assert.Throws<OverflowException>(() => source.Sum());
}
[Fact]
public void Int32FromSelector()
{
var source = new[]
{
new { name="Tim", num=10 },
new { name="John", num=50 },
new { name="Bob", num=-30 }
};
Assert.Equal(30, source.Sum(e => e.num));
}
[Fact]
public void SolitaryNullableInt32()
{
int?[] source = { -9 };
Assert.Equal(source.FirstOrDefault(), source.Sum());
}
[Fact]
public void NullableInt32AllNull()
{
Assert.Equal(0, Enumerable.Repeat(default(int?), 5).Sum().Value);
}
[Fact]
public void NullableInt32NegativeOverflow()
{
int?[] source = { -int.MaxValue, 0, -5, null, null, -20 };
Assert.Throws<OverflowException>(() => source.Sum());
}
[Fact]
public void NullableInt32FromSelector()
{
var source = new[]
{
new { name="Tim", num=(int?)10 },
new { name="John", num=default(int?) },
new { name="Bob", num=(int?)-30 }
};
Assert.Equal(-20, source.Sum(e => e.num));
}
[Fact]
public void RunOnce()
{
var source = new[]
{
new { name="Tim", num=(int?)10 },
new { name="John", num=default(int?) },
new { name="Bob", num=(int?)-30 }
};
Assert.Equal(-20, source.RunOnce().Sum(e => e.num));
}
[Fact]
public void SolitaryInt64()
{
long[] source = { int.MaxValue + 20L };
Assert.Equal(source.FirstOrDefault(), source.Sum());
}
[Fact]
public void NullableInt64NegativeOverflow()
{
long[] source = { -long.MaxValue, 0, -5, 20, -16 };
Assert.Throws<OverflowException>(() => source.Sum());
}
[Fact]
public void Int64FromSelector()
{
var source = new[]{
new { name="Tim", num=10L },
new { name="John", num=(long)int.MaxValue },
new { name="Bob", num=40L }
};
Assert.Equal(int.MaxValue + 50L, source.Sum(e => e.num));
}
[Fact]
public void SolitaryNullableInt64()
{
long?[] source = { -int.MaxValue - 20L };
Assert.Equal(source.FirstOrDefault(), source.Sum());
}
[Fact]
public void NullableInt64AllNull()
{
Assert.Equal(0, Enumerable.Repeat(default(long?), 5).Sum().Value);
}
[Fact]
public void Int64NegativeOverflow()
{
long?[] source = { -long.MaxValue, 0, -5, -20, null, null };
Assert.Throws<OverflowException>(() => source.Sum());
}
[Fact]
public void NullableInt64FromSelector()
{
var source = new[]{
new { name="Tim", num=(long?)10L },
new { name="John", num=(long?)int.MaxValue },
new { name="Bob", num=default(long?) }
};
Assert.Equal(int.MaxValue + 10L, source.Sum(e => e.num));
}
[Fact]
public void SolitaryDouble()
{
double[] source = { 20.51 };
Assert.Equal(source.FirstOrDefault(), source.Sum());
}
[Fact]
public void DoubleWithNaN()
{
double[] source = { 20.45, 0, -10.55, double.NaN };
Assert.True(double.IsNaN(source.Sum()));
}
[Fact]
public void DoubleToNegativeInfinity()
{
double[] source = { -double.MaxValue, -double.MaxValue };
Assert.True(double.IsNegativeInfinity(source.Sum()));
}
[Fact]
public void DoubleFromSelector()
{
var source = new[]
{
new { name="Tim", num=9.5 },
new { name="John", num=10.5 },
new { name="Bob", num=3.5 }
};
Assert.Equal(23.5, source.Sum(e => e.num));
}
[Fact]
public void SolitaryNullableDouble()
{
double?[] source = { 20.51 };
Assert.Equal(source.FirstOrDefault(), source.Sum());
}
[Fact]
public void NullableDoubleAllNull()
{
Assert.Equal(0, Enumerable.Repeat(default(double?), 4).Sum().Value);
}
[Fact]
public void NullableDoubleToNegativeInfinity()
{
double?[] source = { -double.MaxValue, -double.MaxValue };
Assert.True(double.IsNegativeInfinity(source.Sum().Value));
}
[Fact]
public void NullableDoubleFromSelector()
{
var source = new[]
{
new { name="Tim", num=(double?)9.5 },
new { name="John", num=default(double?) },
new { name="Bob", num=(double?)8.5 }
};
Assert.Equal(18.0, source.Sum(e => e.num).Value);
}
[Fact]
public void SolitaryDecimal()
{
decimal[] source = { 20.51m };
Assert.Equal(source.FirstOrDefault(), source.Sum());
}
[Fact]
public void DecimalNegativeOverflow()
{
decimal[] source = { -decimal.MaxValue, -decimal.MaxValue };
Assert.Throws<OverflowException>(() => source.Sum());
}
[Fact]
public void DecimalFromSelector()
{
var source = new[]
{
new {name="Tim", num=20.51m},
new {name="John", num=10m},
new {name="Bob", num=2.33m}
};
Assert.Equal(32.84m, source.Sum(e => e.num));
}
[Fact]
public void SolitaryNullableDecimal()
{
decimal?[] source = { 20.51m };
Assert.Equal(source.FirstOrDefault(), source.Sum());
}
[Fact]
public void NullableDecimalAllNull()
{
Assert.Equal(0, Enumerable.Repeat(default(long?), 3).Sum().Value);
}
[Fact]
public void NullableDecimalNegativeOverflow()
{
decimal?[] source = { -decimal.MaxValue, -decimal.MaxValue };
Assert.Throws<OverflowException>(() => source.Sum());
}
[Fact]
public void NullableDecimalFromSelector()
{
var source = new[]
{
new { name="Tim", num=(decimal?)20.51m },
new { name="John", num=default(decimal?) },
new { name="Bob", num=(decimal?)2.33m }
};
Assert.Equal(22.84m, source.Sum(e => e.num));
}
[Fact]
public void SolitarySingle()
{
float[] source = { 20.51f };
Assert.Equal(source.FirstOrDefault(), source.Sum());
}
[Fact]
public void SingleToNegativeInfinity()
{
float[] source = { -float.MaxValue, -float.MaxValue };
Assert.True(float.IsNegativeInfinity(source.Sum()));
}
[Fact]
public void SingleFromSelector()
{
var source = new[]
{
new { name="Tim", num=9.5f },
new { name="John", num=10.5f },
new { name="Bob", num=3.5f }
};
Assert.Equal(23.5f, source.Sum(e => e.num));
}
}
}
| // 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.Linq.Tests
{
public class SumTests : EnumerableTests
{
#region SourceIsNull - ArgumentNullExceptionThrown
[Fact]
public void SumOfInt_SourceIsNull_ArgumentNullExceptionThrown()
{
IEnumerable<int> sourceInt = null;
AssertExtensions.Throws<ArgumentNullException>("source", () => sourceInt.Sum());
AssertExtensions.Throws<ArgumentNullException>("source", () => sourceInt.Sum(x => x));
}
[Fact]
public void SumOfNullableOfInt_SourceIsNull_ArgumentNullExceptionThrown()
{
IEnumerable<int?> sourceNullableInt = null;
AssertExtensions.Throws<ArgumentNullException>("source", () => sourceNullableInt.Sum());
AssertExtensions.Throws<ArgumentNullException>("source", () => sourceNullableInt.Sum(x => x));
}
[Fact]
public void SumOfLong_SourceIsNull_ArgumentNullExceptionThrown()
{
IEnumerable<long> sourceLong = null;
AssertExtensions.Throws<ArgumentNullException>("source", () => sourceLong.Sum());
AssertExtensions.Throws<ArgumentNullException>("source", () => sourceLong.Sum(x => x));
}
[Fact]
public void SumOfNullableOfLong_SourceIsNull_ArgumentNullExceptionThrown()
{
IEnumerable<long?> sourceNullableLong = null;
AssertExtensions.Throws<ArgumentNullException>("source", () => sourceNullableLong.Sum());
AssertExtensions.Throws<ArgumentNullException>("source", () => sourceNullableLong.Sum(x => x));
}
[Fact]
public void SumOfFloat_SourceIsNull_ArgumentNullExceptionThrown()
{
IEnumerable<float> sourceFloat = null;
AssertExtensions.Throws<ArgumentNullException>("source", () => sourceFloat.Sum());
AssertExtensions.Throws<ArgumentNullException>("source", () => sourceFloat.Sum(x => x));
}
[Fact]
public void SumOfNullableOfFloat_SourceIsNull_ArgumentNullExceptionThrown()
{
IEnumerable<float?> sourceNullableFloat = null;
AssertExtensions.Throws<ArgumentNullException>("source", () => sourceNullableFloat.Sum());
AssertExtensions.Throws<ArgumentNullException>("source", () => sourceNullableFloat.Sum(x => x));
}
[Fact]
public void SumOfDouble_SourceIsNull_ArgumentNullExceptionThrown()
{
IEnumerable<double> sourceDouble = null;
AssertExtensions.Throws<ArgumentNullException>("source", () => sourceDouble.Sum());
AssertExtensions.Throws<ArgumentNullException>("source", () => sourceDouble.Sum(x => x));
}
[Fact]
public void SumOfNullableOfDouble_SourceIsNull_ArgumentNullExceptionThrown()
{
IEnumerable<double?> sourceNullableDouble = null;
AssertExtensions.Throws<ArgumentNullException>("source", () => sourceNullableDouble.Sum());
AssertExtensions.Throws<ArgumentNullException>("source", () => sourceNullableDouble.Sum(x => x));
}
[Fact]
public void SumOfDecimal_SourceIsNull_ArgumentNullExceptionThrown()
{
IEnumerable<decimal> sourceDecimal = null;
AssertExtensions.Throws<ArgumentNullException>("source", () => sourceDecimal.Sum());
AssertExtensions.Throws<ArgumentNullException>("source", () => sourceDecimal.Sum(x => x));
}
[Fact]
public void SumOfNullableOfDecimal_SourceIsNull_ArgumentNullExceptionThrown()
{
IEnumerable<decimal?> sourceNullableDecimal = null;
AssertExtensions.Throws<ArgumentNullException>("source", () => sourceNullableDecimal.Sum());
AssertExtensions.Throws<ArgumentNullException>("source", () => sourceNullableDecimal.Sum(x => x));
}
#endregion
#region SelectionIsNull - ArgumentNullExceptionThrown
[Fact]
public void SumOfInt_SelectorIsNull_ArgumentNullExceptionThrown()
{
IEnumerable<int> sourceInt = Enumerable.Empty<int>();
Func<int, int> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => sourceInt.Sum(selector));
}
[Fact]
public void SumOfNullableOfInt_SelectorIsNull_ArgumentNullExceptionThrown()
{
IEnumerable<int?> sourceNullableInt = Enumerable.Empty<int?>();
Func<int?, int?> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => sourceNullableInt.Sum(selector));
}
[Fact]
public void SumOfLong_SelectorIsNull_ArgumentNullExceptionThrown()
{
IEnumerable<long> sourceLong = Enumerable.Empty<long>();
Func<long, long> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => sourceLong.Sum(selector));
}
[Fact]
public void SumOfNullableOfLong_SelectorIsNull_ArgumentNullExceptionThrown()
{
IEnumerable<long?> sourceNullableLong = Enumerable.Empty<long?>();
Func<long?, long?> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => sourceNullableLong.Sum(selector));
}
[Fact]
public void SumOfFloat_SelectorIsNull_ArgumentNullExceptionThrown()
{
IEnumerable<float> sourceFloat = Enumerable.Empty<float>();
Func<float, float> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => sourceFloat.Sum(selector));
}
[Fact]
public void SumOfNullableOfFloat_SelectorIsNull_ArgumentNullExceptionThrown()
{
IEnumerable<float?> sourceNullableFloat = Enumerable.Empty<float?>();
Func<float?, float?> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => sourceNullableFloat.Sum(selector));
}
[Fact]
public void SumOfDouble_SelectorIsNull_ArgumentNullExceptionThrown()
{
IEnumerable<double> sourceDouble = Enumerable.Empty<double>();
Func<double, double> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => sourceDouble.Sum(selector));
}
[Fact]
public void SumOfNullableOfDouble_SelectorIsNull_ArgumentNullExceptionThrown()
{
IEnumerable<double?> sourceNullableDouble = Enumerable.Empty<double?>();
Func<double?, double?> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => sourceNullableDouble.Sum(selector));
}
[Fact]
public void SumOfDecimal_SelectorIsNull_ArgumentNullExceptionThrown()
{
IEnumerable<decimal> sourceDecimal = Enumerable.Empty<decimal>();
Func<decimal, decimal> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => sourceDecimal.Sum(selector));
}
[Fact]
public void SumOfNullableOfDecimal_SelectorIsNull_ArgumentNullExceptionThrown()
{
IEnumerable<decimal?> sourceNullableDecimal = Enumerable.Empty<decimal?>();
Func<decimal?, decimal?> selector = null;
AssertExtensions.Throws<ArgumentNullException>("selector", () => sourceNullableDecimal.Sum(selector));
}
#endregion
#region SourceIsEmptyCollection - ZeroReturned
[Fact]
public void SumOfInt_SourceIsEmptyCollection_ZeroReturned()
{
IEnumerable<int> sourceInt = Enumerable.Empty<int>();
Assert.Equal(0, sourceInt.Sum());
Assert.Equal(0, sourceInt.Sum(x => x));
}
[Fact]
public void SumOfNullableOfInt_SourceIsEmptyCollection_ZeroReturned()
{
IEnumerable<int?> sourceNullableInt = Enumerable.Empty<int?>();
Assert.Equal(0, sourceNullableInt.Sum());
Assert.Equal(0, sourceNullableInt.Sum(x => x));
}
[Fact]
public void SumOfLong_SourceIsEmptyCollection_ZeroReturned()
{
IEnumerable<long> sourceLong = Enumerable.Empty<long>();
Assert.Equal(0L, sourceLong.Sum());
Assert.Equal(0L, sourceLong.Sum(x => x));
}
[Fact]
public void SumOfNullableOfLong_SourceIsEmptyCollection_ZeroReturned()
{
IEnumerable<long?> sourceNullableLong = Enumerable.Empty<long?>();
Assert.Equal(0L, sourceNullableLong.Sum());
Assert.Equal(0L, sourceNullableLong.Sum(x => x));
}
[Fact]
public void SumOfFloat_SourceIsEmptyCollection_ZeroReturned()
{
IEnumerable<float> sourceFloat = Enumerable.Empty<float>();
Assert.Equal(0f, sourceFloat.Sum());
Assert.Equal(0f, sourceFloat.Sum(x => x));
}
[Fact]
public void SumOfNullableOfFloat_SourceIsEmptyCollection_ZeroReturned()
{
IEnumerable<float?> sourceNullableFloat = Enumerable.Empty<float?>();
Assert.Equal(0f, sourceNullableFloat.Sum());
Assert.Equal(0f, sourceNullableFloat.Sum(x => x));
}
[Fact]
public void SumOfDouble_SourceIsEmptyCollection_ZeroReturned()
{
IEnumerable<double> sourceDouble = Enumerable.Empty<double>();
Assert.Equal(0d, sourceDouble.Sum());
Assert.Equal(0d, sourceDouble.Sum(x => x));
}
[Fact]
public void SumOfNullableOfDouble_SourceIsEmptyCollection_ZeroReturned()
{
IEnumerable<double?> sourceNullableDouble = Enumerable.Empty<double?>();
Assert.Equal(0d, sourceNullableDouble.Sum());
Assert.Equal(0d, sourceNullableDouble.Sum(x => x));
}
[Fact]
public void SumOfDecimal_SourceIsEmptyCollection_ZeroReturned()
{
IEnumerable<decimal> sourceDecimal = Enumerable.Empty<decimal>();
Assert.Equal(0m, sourceDecimal.Sum());
Assert.Equal(0m, sourceDecimal.Sum(x => x));
}
[Fact]
public void SumOfNullableOfDecimal_SourceIsEmptyCollection_ZeroReturned()
{
IEnumerable<decimal?> sourceNullableDecimal = Enumerable.Empty<decimal?>();
Assert.Equal(0m, sourceNullableDecimal.Sum());
Assert.Equal(0m, sourceNullableDecimal.Sum(x => x));
}
#endregion
#region SourceIsNotEmpty - ProperSumReturned
[Fact]
public void SumOfInt_SourceIsNotEmpty_ProperSumReturned()
{
IEnumerable<int> sourceInt = new int[] { 1, -2, 3, -4 };
Assert.Equal(-2, sourceInt.Sum());
Assert.Equal(-2, sourceInt.Sum(x => x));
}
[Fact]
public void SumOfNullableOfInt_SourceIsNotEmpty_ProperSumReturned()
{
IEnumerable<int?> sourceNullableInt = new int?[] { 1, -2, null, 3, -4, null };
Assert.Equal(-2, sourceNullableInt.Sum());
Assert.Equal(-2, sourceNullableInt.Sum(x => x));
}
[Fact]
public void SumOfLong_SourceIsNotEmpty_ProperSumReturned()
{
IEnumerable<long> sourceLong = new long[] { 1L, -2L, 3L, -4L };
Assert.Equal(-2L, sourceLong.Sum());
Assert.Equal(-2L, sourceLong.Sum(x => x));
}
[Fact]
public void SumOfNullableOfLong_SourceIsNotEmpty_ProperSumReturned()
{
IEnumerable<long?> sourceNullableLong = new long?[] { 1L, -2L, null, 3L, -4L, null };
Assert.Equal(-2L, sourceNullableLong.Sum());
Assert.Equal(-2L, sourceNullableLong.Sum(x => x));
}
[Fact]
public void SumOfFloat_SourceIsNotEmpty_ProperSumReturned()
{
IEnumerable<float> sourceFloat = new float[] { 1f, 0.5f, -1f, 0.5f };
Assert.Equal(1f, sourceFloat.Sum());
Assert.Equal(1f, sourceFloat.Sum(x => x));
}
[Fact]
public void SumOfNullableOfFloat_SourceIsNotEmpty_ProperSumReturned()
{
IEnumerable<float?> sourceNullableFloat = new float?[] { 1f, 0.5f, null, -1f, 0.5f, null };
Assert.Equal(1f, sourceNullableFloat.Sum());
Assert.Equal(1f, sourceNullableFloat.Sum(x => x));
}
[Fact]
public void SumOfDouble_SourceIsNotEmpty_ProperSumReturned()
{
IEnumerable<double> sourceDouble = new double[] { 1d, 0.5d, -1d, 0.5d };
Assert.Equal(1d, sourceDouble.Sum());
Assert.Equal(1d, sourceDouble.Sum(x => x));
}
[Fact]
public void SumOfNullableOfDouble_SourceIsNotEmpty_ProperSumReturned()
{
IEnumerable<double?> sourceNullableDouble = new double?[] { 1d, 0.5d, null, -1d, 0.5d, null };
Assert.Equal(1d, sourceNullableDouble.Sum());
Assert.Equal(1d, sourceNullableDouble.Sum(x => x));
}
[Fact]
public void SumOfDecimal_SourceIsNotEmpty_ProperSumReturned()
{
IEnumerable<decimal> sourceDecimal = new decimal[] { 1m, 0.5m, -1m, 0.5m };
Assert.Equal(1m, sourceDecimal.Sum());
Assert.Equal(1m, sourceDecimal.Sum(x => x));
}
[Fact]
public void SumOfNullableOfDecimal_SourceIsNotEmpty_ProperSumReturned()
{
IEnumerable<decimal?> sourceNullableDecimal = new decimal?[] { 1m, 0.5m, null, -1m, 0.5m, null };
Assert.Equal(1m, sourceNullableDecimal.Sum());
Assert.Equal(1m, sourceNullableDecimal.Sum(x => x));
}
#endregion
#region SourceSumsToOverflow - OverflowExceptionThrown or Infinity returned
[Fact]
public void SumOfInt_SourceSumsToOverflow_OverflowExceptionThrown()
{
IEnumerable<int> sourceInt = new int[] { int.MaxValue, 1 };
Assert.Throws<OverflowException>(() => sourceInt.Sum());
Assert.Throws<OverflowException>(() => sourceInt.Sum(x => x));
}
[Fact]
public void SumOfNullableOfInt_SourceSumsToOverflow_OverflowExceptionThrown()
{
IEnumerable<int?> sourceNullableInt = new int?[] { int.MaxValue, null, 1 };
Assert.Throws<OverflowException>(() => sourceNullableInt.Sum());
Assert.Throws<OverflowException>(() => sourceNullableInt.Sum(x => x));
}
[Fact]
public void SumOfLong_SourceSumsToOverflow_OverflowExceptionThrown()
{
IEnumerable<long> sourceLong = new long[] { long.MaxValue, 1L };
Assert.Throws<OverflowException>(() => sourceLong.Sum());
Assert.Throws<OverflowException>(() => sourceLong.Sum(x => x));
}
[Fact]
public void SumOfNullableOfLong_SourceSumsToOverflow_OverflowExceptionThrown()
{
IEnumerable<long?> sourceNullableLong = new long?[] { long.MaxValue, null, 1 };
Assert.Throws<OverflowException>(() => sourceNullableLong.Sum());
Assert.Throws<OverflowException>(() => sourceNullableLong.Sum(x => x));
}
[Fact]
public void SumOfFloat_SourceSumsToOverflow_InfinityReturned()
{
IEnumerable<float> sourceFloat = new float[] { float.MaxValue, float.MaxValue };
Assert.True(float.IsPositiveInfinity(sourceFloat.Sum()));
Assert.True(float.IsPositiveInfinity(sourceFloat.Sum(x => x)));
}
[Fact]
public void SumOfNullableOfFloat_SourceSumsToOverflow_InfinityReturned()
{
IEnumerable<float?> sourceNullableFloat = new float?[] { float.MaxValue, null, float.MaxValue };
Assert.True(float.IsPositiveInfinity(sourceNullableFloat.Sum().Value));
Assert.True(float.IsPositiveInfinity(sourceNullableFloat.Sum(x => x).Value));
}
[Fact]
public void SumOfDouble_SourceSumsToOverflow_InfinityReturned()
{
IEnumerable<double> sourceDouble = new double[] { double.MaxValue, double.MaxValue };
Assert.True(double.IsPositiveInfinity(sourceDouble.Sum()));
Assert.True(double.IsPositiveInfinity(sourceDouble.Sum(x => x)));
}
[Fact]
public void SumOfNullableOfDouble_SourceSumsToOverflow_InfinityReturned()
{
IEnumerable<double?> sourceNullableDouble = new double?[] { double.MaxValue, null, double.MaxValue };
Assert.True(double.IsPositiveInfinity(sourceNullableDouble.Sum().Value));
Assert.True(double.IsPositiveInfinity(sourceNullableDouble.Sum(x => x).Value));
}
[Fact]
public void SumOfDecimal_SourceSumsToOverflow_OverflowExceptionThrown()
{
IEnumerable<decimal> sourceDecimal = new decimal[] { decimal.MaxValue, 1m };
Assert.Throws<OverflowException>(() => sourceDecimal.Sum());
Assert.Throws<OverflowException>(() => sourceDecimal.Sum(x => x));
}
[Fact]
public void SumOfNullableOfDecimal_SourceSumsToOverflow_OverflowExceptionThrown()
{
IEnumerable<decimal?> sourceNullableDecimal = new decimal?[] { decimal.MaxValue, null, 1m };
Assert.Throws<OverflowException>(() => sourceNullableDecimal.Sum());
Assert.Throws<OverflowException>(() => sourceNullableDecimal.Sum(x => x));
}
#endregion
[Fact]
public void SameResultsRepeatCallsIntQuery()
{
var q = from x in new int?[] { 9999, 0, 888, -1, 66, null, -777, 1, 2, -12345 }
where x > int.MinValue
select x;
Assert.Equal(q.Sum(), q.Sum());
}
[Fact]
public void SolitaryNullableSingle()
{
float?[] source = { 20.51f };
Assert.Equal(source.FirstOrDefault(), source.Sum());
}
[Fact]
public void NaNFromSingles()
{
float?[] source = { 20.45f, 0f, -10.55f, float.NaN };
Assert.True(float.IsNaN(source.Sum().Value));
}
[Fact]
public void NullableSingleAllNull()
{
Assert.Equal(0, Enumerable.Repeat(default(float?), 4).Sum().Value);
}
[Fact]
public void NullableSingleToNegativeInfinity()
{
float?[] source = { -float.MaxValue, -float.MaxValue };
Assert.True(float.IsNegativeInfinity(source.Sum().Value));
}
[Fact]
public void NullableSingleFromSelector()
{
var source = new[]{
new { name="Tim", num=(float?)9.5f },
new { name="John", num=default(float?) },
new { name="Bob", num=(float?)8.5f }
};
Assert.Equal(18.0f, source.Sum(e => e.num).Value);
}
[Fact]
public void SolitaryInt32()
{
int[] source = { 20 };
Assert.Equal(source.FirstOrDefault(), source.Sum());
}
[Fact]
public void OverflowInt32Negative()
{
int[] source = { -int.MaxValue, 0, -5, -20 };
Assert.Throws<OverflowException>(() => source.Sum());
}
[Fact]
public void Int32FromSelector()
{
var source = new[]
{
new { name="Tim", num=10 },
new { name="John", num=50 },
new { name="Bob", num=-30 }
};
Assert.Equal(30, source.Sum(e => e.num));
}
[Fact]
public void SolitaryNullableInt32()
{
int?[] source = { -9 };
Assert.Equal(source.FirstOrDefault(), source.Sum());
}
[Fact]
public void NullableInt32AllNull()
{
Assert.Equal(0, Enumerable.Repeat(default(int?), 5).Sum().Value);
}
[Fact]
public void NullableInt32NegativeOverflow()
{
int?[] source = { -int.MaxValue, 0, -5, null, null, -20 };
Assert.Throws<OverflowException>(() => source.Sum());
}
[Fact]
public void NullableInt32FromSelector()
{
var source = new[]
{
new { name="Tim", num=(int?)10 },
new { name="John", num=default(int?) },
new { name="Bob", num=(int?)-30 }
};
Assert.Equal(-20, source.Sum(e => e.num));
}
[Fact]
public void RunOnce()
{
var source = new[]
{
new { name="Tim", num=(int?)10 },
new { name="John", num=default(int?) },
new { name="Bob", num=(int?)-30 }
};
Assert.Equal(-20, source.RunOnce().Sum(e => e.num));
}
[Fact]
public void SolitaryInt64()
{
long[] source = { int.MaxValue + 20L };
Assert.Equal(source.FirstOrDefault(), source.Sum());
}
[Fact]
public void NullableInt64NegativeOverflow()
{
long[] source = { -long.MaxValue, 0, -5, 20, -16 };
Assert.Throws<OverflowException>(() => source.Sum());
}
[Fact]
public void Int64FromSelector()
{
var source = new[]{
new { name="Tim", num=10L },
new { name="John", num=(long)int.MaxValue },
new { name="Bob", num=40L }
};
Assert.Equal(int.MaxValue + 50L, source.Sum(e => e.num));
}
[Fact]
public void SolitaryNullableInt64()
{
long?[] source = { -int.MaxValue - 20L };
Assert.Equal(source.FirstOrDefault(), source.Sum());
}
[Fact]
public void NullableInt64AllNull()
{
Assert.Equal(0, Enumerable.Repeat(default(long?), 5).Sum().Value);
}
[Fact]
public void Int64NegativeOverflow()
{
long?[] source = { -long.MaxValue, 0, -5, -20, null, null };
Assert.Throws<OverflowException>(() => source.Sum());
}
[Fact]
public void NullableInt64FromSelector()
{
var source = new[]{
new { name="Tim", num=(long?)10L },
new { name="John", num=(long?)int.MaxValue },
new { name="Bob", num=default(long?) }
};
Assert.Equal(int.MaxValue + 10L, source.Sum(e => e.num));
}
[Fact]
public void SolitaryDouble()
{
double[] source = { 20.51 };
Assert.Equal(source.FirstOrDefault(), source.Sum());
}
[Fact]
public void DoubleWithNaN()
{
double[] source = { 20.45, 0, -10.55, double.NaN };
Assert.True(double.IsNaN(source.Sum()));
}
[Fact]
public void DoubleToNegativeInfinity()
{
double[] source = { -double.MaxValue, -double.MaxValue };
Assert.True(double.IsNegativeInfinity(source.Sum()));
}
[Fact]
public void DoubleFromSelector()
{
var source = new[]
{
new { name="Tim", num=9.5 },
new { name="John", num=10.5 },
new { name="Bob", num=3.5 }
};
Assert.Equal(23.5, source.Sum(e => e.num));
}
[Fact]
public void SolitaryNullableDouble()
{
double?[] source = { 20.51 };
Assert.Equal(source.FirstOrDefault(), source.Sum());
}
[Fact]
public void NullableDoubleAllNull()
{
Assert.Equal(0, Enumerable.Repeat(default(double?), 4).Sum().Value);
}
[Fact]
public void NullableDoubleToNegativeInfinity()
{
double?[] source = { -double.MaxValue, -double.MaxValue };
Assert.True(double.IsNegativeInfinity(source.Sum().Value));
}
[Fact]
public void NullableDoubleFromSelector()
{
var source = new[]
{
new { name="Tim", num=(double?)9.5 },
new { name="John", num=default(double?) },
new { name="Bob", num=(double?)8.5 }
};
Assert.Equal(18.0, source.Sum(e => e.num).Value);
}
[Fact]
public void SolitaryDecimal()
{
decimal[] source = { 20.51m };
Assert.Equal(source.FirstOrDefault(), source.Sum());
}
[Fact]
public void DecimalNegativeOverflow()
{
decimal[] source = { -decimal.MaxValue, -decimal.MaxValue };
Assert.Throws<OverflowException>(() => source.Sum());
}
[Fact]
public void DecimalFromSelector()
{
var source = new[]
{
new {name="Tim", num=20.51m},
new {name="John", num=10m},
new {name="Bob", num=2.33m}
};
Assert.Equal(32.84m, source.Sum(e => e.num));
}
[Fact]
public void SolitaryNullableDecimal()
{
decimal?[] source = { 20.51m };
Assert.Equal(source.FirstOrDefault(), source.Sum());
}
[Fact]
public void NullableDecimalAllNull()
{
Assert.Equal(0, Enumerable.Repeat(default(long?), 3).Sum().Value);
}
[Fact]
public void NullableDecimalNegativeOverflow()
{
decimal?[] source = { -decimal.MaxValue, -decimal.MaxValue };
Assert.Throws<OverflowException>(() => source.Sum());
}
[Fact]
public void NullableDecimalFromSelector()
{
var source = new[]
{
new { name="Tim", num=(decimal?)20.51m },
new { name="John", num=default(decimal?) },
new { name="Bob", num=(decimal?)2.33m }
};
Assert.Equal(22.84m, source.Sum(e => e.num));
}
[Fact]
public void SolitarySingle()
{
float[] source = { 20.51f };
Assert.Equal(source.FirstOrDefault(), source.Sum());
}
[Fact]
public void SingleToNegativeInfinity()
{
float[] source = { -float.MaxValue, -float.MaxValue };
Assert.True(float.IsNegativeInfinity(source.Sum()));
}
[Fact]
public void SingleFromSelector()
{
var source = new[]
{
new { name="Tim", num=9.5f },
new { name="John", num=10.5f },
new { name="Bob", num=3.5f }
};
Assert.Equal(23.5f, source.Sum(e => e.num));
}
}
}
| -1 |
dotnet/runtime | 66,057 | Address TODO to switch to generated p/invoke | Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | elinor-fung | 2022-03-02T03:31:28Z | 2022-03-02T19:08:30Z | a4b8893a118357b55c0add9a39cc5aeb097a0bb8 | 1abbbb4adf6bf02549f4c6e021176534dcc4f974 | Address TODO to switch to generated p/invoke. Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | ./src/coreclr/System.Private.CoreLib/src/System/Reflection/RuntimeLocalVariableInfo.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.Reflection
{
internal sealed class RuntimeLocalVariableInfo : LocalVariableInfo
{
private RuntimeType? _type;
private int _localIndex;
private bool _isPinned;
private RuntimeLocalVariableInfo() { }
public override Type LocalType { get { Debug.Assert(_type != null, "type must be set!"); return _type; } }
public override int LocalIndex => _localIndex;
public override bool IsPinned => _isPinned;
}
}
| // 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.Reflection
{
internal sealed class RuntimeLocalVariableInfo : LocalVariableInfo
{
private RuntimeType? _type;
private int _localIndex;
private bool _isPinned;
private RuntimeLocalVariableInfo() { }
public override Type LocalType { get { Debug.Assert(_type != null, "type must be set!"); return _type; } }
public override int LocalIndex => _localIndex;
public override bool IsPinned => _isPinned;
}
}
| -1 |
dotnet/runtime | 66,057 | Address TODO to switch to generated p/invoke | Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | elinor-fung | 2022-03-02T03:31:28Z | 2022-03-02T19:08:30Z | a4b8893a118357b55c0add9a39cc5aeb097a0bb8 | 1abbbb4adf6bf02549f4c6e021176534dcc4f974 | Address TODO to switch to generated p/invoke. Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | ./src/libraries/sendtohelix.proj | <!-- This project constructs the Helix "correlation payload", the set of files needed to run a set of tests,
and then invokes sendtohelixhelp.proj for each test assembly and scenario combination to get Helix to
invoke the tests.
In the simple case, no scenarios are specified and the default CoreCLR optimization configuration
is used to run the tests. If a set of comma-separated scenarios are specified in the `_Scenarios`
property, then each test is run for each of the specified CoreCLR scenarios (e.g., COMPlus_JitStress=1;
COMPlus_JitStressRegs=4; COMPlus_JitStress=2 + COMPlus_JitStressRegs=0x1000). The set of acceptable
scenario names is defined and interpreted by src\tests\Common\testenvironment.proj.
"RunInParallelForEachScenario" is the "root" target for this Project. It first creates the
"correlation payload", which is the set of files used by all Helix submissions
(which we compress into a single file).
-->
<Project Sdk="Microsoft.Build.NoTargets" InitialTargets="_SetTestArchiveRuntimeFile">
<PropertyGroup>
<BuildTargetFramework Condition="'$(BuildTargetFramework)' == ''">$(NetCoreAppCurrent)</BuildTargetFramework>
<!-- Set the name of the scenario file. Note that this is only used in invocations where $(Scenario) is set
(which is when this project is invoked to call the "CreateOneScenarioTestEnvFile" target). -->
<TestEnvFileName Condition=" '$(TargetOS)' == 'windows' ">SetStressModes_$(Scenario).cmd</TestEnvFileName>
<TestEnvFileName Condition=" '$(TargetOS)' != 'windows' ">SetStressModes_$(Scenario).sh</TestEnvFileName>
</PropertyGroup>
<!-- The Helix correlation payload file -->
<Target Name="_SetTestArchiveRuntimeFile"
Condition="'$(BuildTargetFramework)' == '$(NetCoreAppCurrent)'">
<PropertyGroup>
<TestArchiveRuntimeFile>$(TestArchiveRuntimeRoot)test-runtime-$(NetCoreAppCurrentBuildSettings).zip</TestArchiveRuntimeFile>
</PropertyGroup>
</Target>
<Target Name="RunInParallelForEachScenario"
AfterTargets="Build">
<PropertyGroup>
<!-- This specifies what properties are needed to be passed down as global properties to a child project invocation. -->
<_PropertiesToPass>
RuntimeFlavor=$(RuntimeFlavor);
TargetArchitecture=$(TargetArchitecture);
Configuration=$(Configuration);
TargetOS=$(TargetOS);
TargetRuntimeIdentifier=$(TargetRuntimeIdentifier);
TestRunNamePrefixSuffix=$(TestRunNamePrefixSuffix);
Creator=$(Creator);
HelixAccessToken=$(HelixAccessToken);
HelixTargetQueues=$(HelixTargetQueues);
BuildTargetFramework=$(BuildTargetFramework)
</_PropertiesToPass>
</PropertyGroup>
<Message Condition="'$(_Scenarios)' != ''" Importance="High" Text="Using _Scenarios: $(_Scenarios)" />
<Message Importance="High" Text="Using Queues: $(HelixTargetQueues)" />
<Message Importance="High" Text="BuildTargetFramework: $(BuildTargetFramework)" />
<Message Importance="High" Text="TestArchiveTestsRoot: $(TestArchiveTestsRoot)" />
<Message Importance="High" Text="TestArchiveRoot: $(TestArchiveRoot)" />
<Message Importance="High" Text="TestArchiveRuntimeRoot: $(TestArchiveRuntimeRoot)" />
<Message Condition="'$(TestArchiveRuntimeFile)' != ''" Importance="High" Text="TestArchiveRuntimeFile: $(TestArchiveRuntimeFile)" />
<!-- Re-invoke MSBuild on this project to create the correlation payload -->
<MSBuild Projects="$(MSBuildProjectFile)" Targets="PrepareCorrelationPayloadDirectory" Properties="Scenarios=$(_Scenarios)" />
<PropertyGroup>
<PerScenarioProjectFile>$(MSBuildThisFileDirectory)sendtohelixhelp.proj</PerScenarioProjectFile>
</PropertyGroup>
<ItemGroup>
<_Scenarios Include="$(_Scenarios.Split(','))" />
<!-- MSBuild creates a new instance of the project for each %(_Scenarios.Identity) and can build them in parallel. -->
<_BaseProjectsToBuild Include="$(PerScenarioProjectFile)" Condition="'%(_Scenarios.Identity)' != 'buildwasmapps' and '%(_Scenarios.Identity)' != 'buildiosapps'">
<AdditionalProperties>$(_PropertiesToPass);Scenario=%(_Scenarios.Identity);TestArchiveRuntimeFile=$(TestArchiveRuntimeFile)</AdditionalProperties>
<AdditionalProperties Condition="'$(NeedsToBuildWasmAppsOnHelix)' != ''">%(_BaseProjectsToBuild.AdditionalProperties);NeedsToBuildWasmAppsOnHelix=$(NeedsToBuildWasmAppsOnHelix)</AdditionalProperties>
</_BaseProjectsToBuild>
</ItemGroup>
<!-- For BuildWasmApps we want to build the project twice, with: TestUsingWorkloads=true, and TestUsingWorkloads=false -->
<ItemGroup Condition="'@(_Scenarios -> AnyHaveMetadataValue('Identity', 'buildwasmapps'))' == 'true'">
<_TestUsingWorkloadsValues Include="true;false" />
<_BuildWasmAppsProjectsToBuild Include="$(PerScenarioProjectFile)">
<AdditionalProperties>$(_PropertiesToPass);Scenario=BuildWasmApps;TestArchiveRuntimeFile=$(TestArchiveRuntimeFile);TestUsingWorkloads=%(_TestUsingWorkloadsValues.Identity)</AdditionalProperties>
<AdditionalProperties Condition="'$(NeedsToBuildWasmAppsOnHelix)' != ''">%(_BuildWasmAppsProjectsToBuild.AdditionalProperties);NeedsToBuildWasmAppsOnHelix=$(NeedsToBuildWasmAppsOnHelix)</AdditionalProperties>
</_BuildWasmAppsProjectsToBuild>
</ItemGroup>
<!-- For BuildWasmApps we want to build the project twice, with: TestUsingWorkloads=true, and TestUsingWorkloads=false -->
<ItemGroup Condition="'@(_Scenarios -> AnyHaveMetadataValue('Identity', 'buildiosapps'))' == 'true'">
<_TestUsingWorkloadsValues Include="false" />
<_BuildiOSAppsProjectsToBuild Include="$(PerScenarioProjectFile)">
<AdditionalProperties>$(_PropertiesToPass);Scenario=BuildiOSApps;TestArchiveRuntimeFile=$(TestArchiveRuntimeFile);TestUsingWorkloads=%(_TestUsingWorkloadsValues.Identity)</AdditionalProperties>
<AdditionalProperties Condition="'$(NeedsToBuildAppsOnHelix)' != ''">%(_BuildiOSAppsProjectsToBuild.AdditionalProperties);NeedsToBuildAppsOnHelix=$(NeedsToBuildAppsOnHelix)</AdditionalProperties>
</_BuildiOSAppsProjectsToBuild>
</ItemGroup>
<ItemGroup>
<_ProjectsToBuild Include="@(_BuildWasmAppsProjectsToBuild);@(_BuildiOSAppsProjectsToBuild);@(_BaseProjectsToBuild)" />
</ItemGroup>
<PropertyGroup>
<_BuildInParallel>false</_BuildInParallel>
<_BuildInParallel Condition=" '@(_ProjectsToBuild->Count())' > '1' ">true</_BuildInParallel>
</PropertyGroup>
<!-- Invoke MSBuild once for each Scenario (because of the "batching" defined in "_ProjectsToBuild").
Create the Helix work items and start the jobs. This is done by invoking the "Test" Helix target.
-->
<MSBuild Projects="@(_ProjectsToBuild)" Targets="Test" BuildInParallel="$(_BuildInParallel)" StopOnFirstFailure="false" />
</Target>
<Target Name="CreateOneScenarioTestEnvFile">
<!-- This target creates one __TestEnv file for the single $(Scenario). -->
<Error Condition="'$(Scenario)' == ''" Text="No Scenario specified" />
<PropertyGroup>
<TestEnvFilePath>$(NetCoreAppCurrentTestHostPath)$(TestEnvFileName)</TestEnvFilePath>
<_targetsWindows Condition="'$(TargetOS)' == 'windows'">true</_targetsWindows>
</PropertyGroup>
<ItemGroup>
<_ProjectsToBuild Include="$(RepoRoot)\src\tests\Common\testenvironment.proj">
<Properties>Scenario=$(Scenario);TestEnvFileName=$(TestEnvFilePath);TargetsWindows=$(_targetsWindows)</Properties>
</_ProjectsToBuild>
</ItemGroup>
<Message Importance="High" Text="Creating $(TestEnvFilePath) for scenario $(Scenario)" />
<MSBuild Projects="@(_ProjectsToBuild)" Targets="CreateTestEnvFile" StopOnFirstFailure="true" />
<Error Condition="!Exists('$(TestEnvFilePath)')" Text="File $(TestEnvFilePath) not found!" />
</Target>
<Target Condition="'$(Scenarios)' != '' and '$(TargetOS)' != 'Browser' and '$(TargetOS)' != 'iOS' and '$(TargetOS)' != 'iOSSimulator'" Name="CreateAllScenarioTestEnvFiles">
<!-- This target creates one __TestEnv file for each of the scenarios in the $(Scenarios) comma-separated list. -->
<Message Importance="High" Text="Creating per-scenario TestEnv files for scenarios $(Scenarios)" />
<ItemGroup>
<_Scenario Include="$(Scenarios.Split(','))" />
<_ProjectsToBuild Include="$(MSBuildProjectFile)">
<AdditionalProperties>Scenario=%(_Scenario.Identity)</AdditionalProperties>
</_ProjectsToBuild>
</ItemGroup>
<MSBuild Projects="@(_ProjectsToBuild)" Targets="CreateOneScenarioTestEnvFile" StopOnFirstFailure="true" />
</Target>
<Target Name="_CollectRuntimeInputs">
<!--
We need to include all dlls in the runtime path as inputs to make it really incremental. If we use the root folder,
if a dll is updated, the folder's timestamp is not updated, therefore skipped.
-->
<ItemGroup>
<_RuntimeInput Include="$(NetCoreAppCurrentTestHostPath)**\*.dll" />
<!-- Add the scenario TestEnv batch files -->
<_RuntimeInput Condition="'$(Scenarios)' != '' and '$(TargetOS)' == 'windows'" Include="$(NetCoreAppCurrentTestHostPath)**\*.cmd" />
<_RuntimeInput Condition="'$(Scenarios)' != '' and '$(TargetOS)' != 'windows'" Include="$(NetCoreAppCurrentTestHostPath)**\*.sh" />
</ItemGroup>
</Target>
<Target Name="IncludeDumpDocsInTesthost"
Condition="'$(RuntimeFlavor)' == 'CoreCLR'">
<ItemGroup>
<DebugDocsFiles Include="$(RepositoryEngineeringDir)testing\debug-dump-template.md" />
<DebugDocsFiles Include="$(RepositoryEngineeringDir)testing\gen-debug-dump-docs.py" />
<_RuntimeInputs Include="@(DebugDocsFiles)" />
</ItemGroup>
<Copy SourceFiles="@(DebugDocsFiles)"
DestinationFolder="$(NetCoreAppCurrentTestHostPath)"
SkipUnchangedFiles="true" />
</Target>
<Target Name="CompressRuntimeDirectory"
DependsOnTargets="IncludeDumpDocsInTesthost;_CollectRuntimeInputs"
Inputs="@(_RuntimeInput);@(TestArchiveRuntimeDependency)"
Outputs="$(TestArchiveRuntimeFile)"
Condition="'$(TargetsMobile)' != 'true' and
'$(TestArchiveRuntimeFile)' != ''">
<!-- Compress the test files, testhost, and per-scenario scripts into a single ZIP file for sending to the Helix machines. -->
<Message Importance="High" Text="Compressing runtime directory" />
<Message Importance="High" Text="Creating directory $(TestArchiveRuntimeRoot)" />
<MakeDir Directories="$(TestArchiveRuntimeRoot)" />
<ZipDirectory SourceDirectory="$(NetCoreAppCurrentTestHostPath)"
DestinationFile="$(TestArchiveRuntimeFile)"
Overwrite="true" />
</Target>
<!--
Collect all the tasks needed to be run once, to prepare the Helix correlation payload directory.
There's no actual work here; this target just causes its dependent targets to be run.
-->
<Target Name="PrepareCorrelationPayloadDirectory"
DependsOnTargets="CreateAllScenarioTestEnvFiles;CompressRuntimeDirectory" >
<Message Importance="High" Text="Correlation directory prepared" />
</Target>
</Project>
| <!-- This project constructs the Helix "correlation payload", the set of files needed to run a set of tests,
and then invokes sendtohelixhelp.proj for each test assembly and scenario combination to get Helix to
invoke the tests.
In the simple case, no scenarios are specified and the default CoreCLR optimization configuration
is used to run the tests. If a set of comma-separated scenarios are specified in the `_Scenarios`
property, then each test is run for each of the specified CoreCLR scenarios (e.g., COMPlus_JitStress=1;
COMPlus_JitStressRegs=4; COMPlus_JitStress=2 + COMPlus_JitStressRegs=0x1000). The set of acceptable
scenario names is defined and interpreted by src\tests\Common\testenvironment.proj.
"RunInParallelForEachScenario" is the "root" target for this Project. It first creates the
"correlation payload", which is the set of files used by all Helix submissions
(which we compress into a single file).
-->
<Project Sdk="Microsoft.Build.NoTargets" InitialTargets="_SetTestArchiveRuntimeFile">
<PropertyGroup>
<BuildTargetFramework Condition="'$(BuildTargetFramework)' == ''">$(NetCoreAppCurrent)</BuildTargetFramework>
<!-- Set the name of the scenario file. Note that this is only used in invocations where $(Scenario) is set
(which is when this project is invoked to call the "CreateOneScenarioTestEnvFile" target). -->
<TestEnvFileName Condition=" '$(TargetOS)' == 'windows' ">SetStressModes_$(Scenario).cmd</TestEnvFileName>
<TestEnvFileName Condition=" '$(TargetOS)' != 'windows' ">SetStressModes_$(Scenario).sh</TestEnvFileName>
</PropertyGroup>
<!-- The Helix correlation payload file -->
<Target Name="_SetTestArchiveRuntimeFile"
Condition="'$(BuildTargetFramework)' == '$(NetCoreAppCurrent)'">
<PropertyGroup>
<TestArchiveRuntimeFile>$(TestArchiveRuntimeRoot)test-runtime-$(NetCoreAppCurrentBuildSettings).zip</TestArchiveRuntimeFile>
</PropertyGroup>
</Target>
<Target Name="RunInParallelForEachScenario"
AfterTargets="Build">
<PropertyGroup>
<!-- This specifies what properties are needed to be passed down as global properties to a child project invocation. -->
<_PropertiesToPass>
RuntimeFlavor=$(RuntimeFlavor);
TargetArchitecture=$(TargetArchitecture);
Configuration=$(Configuration);
TargetOS=$(TargetOS);
TargetRuntimeIdentifier=$(TargetRuntimeIdentifier);
TestRunNamePrefixSuffix=$(TestRunNamePrefixSuffix);
Creator=$(Creator);
HelixAccessToken=$(HelixAccessToken);
HelixTargetQueues=$(HelixTargetQueues);
BuildTargetFramework=$(BuildTargetFramework)
</_PropertiesToPass>
</PropertyGroup>
<Message Condition="'$(_Scenarios)' != ''" Importance="High" Text="Using _Scenarios: $(_Scenarios)" />
<Message Importance="High" Text="Using Queues: $(HelixTargetQueues)" />
<Message Importance="High" Text="BuildTargetFramework: $(BuildTargetFramework)" />
<Message Importance="High" Text="TestArchiveTestsRoot: $(TestArchiveTestsRoot)" />
<Message Importance="High" Text="TestArchiveRoot: $(TestArchiveRoot)" />
<Message Importance="High" Text="TestArchiveRuntimeRoot: $(TestArchiveRuntimeRoot)" />
<Message Condition="'$(TestArchiveRuntimeFile)' != ''" Importance="High" Text="TestArchiveRuntimeFile: $(TestArchiveRuntimeFile)" />
<!-- Re-invoke MSBuild on this project to create the correlation payload -->
<MSBuild Projects="$(MSBuildProjectFile)" Targets="PrepareCorrelationPayloadDirectory" Properties="Scenarios=$(_Scenarios)" />
<PropertyGroup>
<PerScenarioProjectFile>$(MSBuildThisFileDirectory)sendtohelixhelp.proj</PerScenarioProjectFile>
</PropertyGroup>
<ItemGroup>
<_Scenarios Include="$(_Scenarios.Split(','))" />
<!-- MSBuild creates a new instance of the project for each %(_Scenarios.Identity) and can build them in parallel. -->
<_BaseProjectsToBuild Include="$(PerScenarioProjectFile)" Condition="'%(_Scenarios.Identity)' != 'buildwasmapps' and '%(_Scenarios.Identity)' != 'buildiosapps'">
<AdditionalProperties>$(_PropertiesToPass);Scenario=%(_Scenarios.Identity);TestArchiveRuntimeFile=$(TestArchiveRuntimeFile)</AdditionalProperties>
<AdditionalProperties Condition="'$(NeedsToBuildWasmAppsOnHelix)' != ''">%(_BaseProjectsToBuild.AdditionalProperties);NeedsToBuildWasmAppsOnHelix=$(NeedsToBuildWasmAppsOnHelix)</AdditionalProperties>
</_BaseProjectsToBuild>
</ItemGroup>
<!-- For BuildWasmApps we want to build the project twice, with: TestUsingWorkloads=true, and TestUsingWorkloads=false -->
<ItemGroup Condition="'@(_Scenarios -> AnyHaveMetadataValue('Identity', 'buildwasmapps'))' == 'true'">
<_TestUsingWorkloadsValues Include="true;false" />
<_BuildWasmAppsProjectsToBuild Include="$(PerScenarioProjectFile)">
<AdditionalProperties>$(_PropertiesToPass);Scenario=BuildWasmApps;TestArchiveRuntimeFile=$(TestArchiveRuntimeFile);TestUsingWorkloads=%(_TestUsingWorkloadsValues.Identity)</AdditionalProperties>
<AdditionalProperties Condition="'$(NeedsToBuildWasmAppsOnHelix)' != ''">%(_BuildWasmAppsProjectsToBuild.AdditionalProperties);NeedsToBuildWasmAppsOnHelix=$(NeedsToBuildWasmAppsOnHelix)</AdditionalProperties>
</_BuildWasmAppsProjectsToBuild>
</ItemGroup>
<!-- For BuildWasmApps we want to build the project twice, with: TestUsingWorkloads=true, and TestUsingWorkloads=false -->
<ItemGroup Condition="'@(_Scenarios -> AnyHaveMetadataValue('Identity', 'buildiosapps'))' == 'true'">
<_TestUsingWorkloadsValues Include="false" />
<_BuildiOSAppsProjectsToBuild Include="$(PerScenarioProjectFile)">
<AdditionalProperties>$(_PropertiesToPass);Scenario=BuildiOSApps;TestArchiveRuntimeFile=$(TestArchiveRuntimeFile);TestUsingWorkloads=%(_TestUsingWorkloadsValues.Identity)</AdditionalProperties>
<AdditionalProperties Condition="'$(NeedsToBuildAppsOnHelix)' != ''">%(_BuildiOSAppsProjectsToBuild.AdditionalProperties);NeedsToBuildAppsOnHelix=$(NeedsToBuildAppsOnHelix)</AdditionalProperties>
</_BuildiOSAppsProjectsToBuild>
</ItemGroup>
<ItemGroup>
<_ProjectsToBuild Include="@(_BuildWasmAppsProjectsToBuild);@(_BuildiOSAppsProjectsToBuild);@(_BaseProjectsToBuild)" />
</ItemGroup>
<PropertyGroup>
<_BuildInParallel>false</_BuildInParallel>
<_BuildInParallel Condition=" '@(_ProjectsToBuild->Count())' > '1' ">true</_BuildInParallel>
</PropertyGroup>
<!-- Invoke MSBuild once for each Scenario (because of the "batching" defined in "_ProjectsToBuild").
Create the Helix work items and start the jobs. This is done by invoking the "Test" Helix target.
-->
<MSBuild Projects="@(_ProjectsToBuild)" Targets="Test" BuildInParallel="$(_BuildInParallel)" StopOnFirstFailure="false" />
</Target>
<Target Name="CreateOneScenarioTestEnvFile">
<!-- This target creates one __TestEnv file for the single $(Scenario). -->
<Error Condition="'$(Scenario)' == ''" Text="No Scenario specified" />
<PropertyGroup>
<TestEnvFilePath>$(NetCoreAppCurrentTestHostPath)$(TestEnvFileName)</TestEnvFilePath>
<_targetsWindows Condition="'$(TargetOS)' == 'windows'">true</_targetsWindows>
</PropertyGroup>
<ItemGroup>
<_ProjectsToBuild Include="$(RepoRoot)\src\tests\Common\testenvironment.proj">
<Properties>Scenario=$(Scenario);TestEnvFileName=$(TestEnvFilePath);TargetsWindows=$(_targetsWindows)</Properties>
</_ProjectsToBuild>
</ItemGroup>
<Message Importance="High" Text="Creating $(TestEnvFilePath) for scenario $(Scenario)" />
<MSBuild Projects="@(_ProjectsToBuild)" Targets="CreateTestEnvFile" StopOnFirstFailure="true" />
<Error Condition="!Exists('$(TestEnvFilePath)')" Text="File $(TestEnvFilePath) not found!" />
</Target>
<Target Condition="'$(Scenarios)' != '' and '$(TargetOS)' != 'Browser' and '$(TargetOS)' != 'iOS' and '$(TargetOS)' != 'iOSSimulator'" Name="CreateAllScenarioTestEnvFiles">
<!-- This target creates one __TestEnv file for each of the scenarios in the $(Scenarios) comma-separated list. -->
<Message Importance="High" Text="Creating per-scenario TestEnv files for scenarios $(Scenarios)" />
<ItemGroup>
<_Scenario Include="$(Scenarios.Split(','))" />
<_ProjectsToBuild Include="$(MSBuildProjectFile)">
<AdditionalProperties>Scenario=%(_Scenario.Identity)</AdditionalProperties>
</_ProjectsToBuild>
</ItemGroup>
<MSBuild Projects="@(_ProjectsToBuild)" Targets="CreateOneScenarioTestEnvFile" StopOnFirstFailure="true" />
</Target>
<Target Name="_CollectRuntimeInputs">
<!--
We need to include all dlls in the runtime path as inputs to make it really incremental. If we use the root folder,
if a dll is updated, the folder's timestamp is not updated, therefore skipped.
-->
<ItemGroup>
<_RuntimeInput Include="$(NetCoreAppCurrentTestHostPath)**\*.dll" />
<!-- Add the scenario TestEnv batch files -->
<_RuntimeInput Condition="'$(Scenarios)' != '' and '$(TargetOS)' == 'windows'" Include="$(NetCoreAppCurrentTestHostPath)**\*.cmd" />
<_RuntimeInput Condition="'$(Scenarios)' != '' and '$(TargetOS)' != 'windows'" Include="$(NetCoreAppCurrentTestHostPath)**\*.sh" />
</ItemGroup>
</Target>
<Target Name="IncludeDumpDocsInTesthost"
Condition="'$(RuntimeFlavor)' == 'CoreCLR'">
<ItemGroup>
<DebugDocsFiles Include="$(RepositoryEngineeringDir)testing\debug-dump-template.md" />
<DebugDocsFiles Include="$(RepositoryEngineeringDir)testing\gen-debug-dump-docs.py" />
<_RuntimeInputs Include="@(DebugDocsFiles)" />
</ItemGroup>
<Copy SourceFiles="@(DebugDocsFiles)"
DestinationFolder="$(NetCoreAppCurrentTestHostPath)"
SkipUnchangedFiles="true" />
</Target>
<Target Name="CompressRuntimeDirectory"
DependsOnTargets="IncludeDumpDocsInTesthost;_CollectRuntimeInputs"
Inputs="@(_RuntimeInput);@(TestArchiveRuntimeDependency)"
Outputs="$(TestArchiveRuntimeFile)"
Condition="'$(TargetsMobile)' != 'true' and
'$(TestArchiveRuntimeFile)' != ''">
<!-- Compress the test files, testhost, and per-scenario scripts into a single ZIP file for sending to the Helix machines. -->
<Message Importance="High" Text="Compressing runtime directory" />
<Message Importance="High" Text="Creating directory $(TestArchiveRuntimeRoot)" />
<MakeDir Directories="$(TestArchiveRuntimeRoot)" />
<ZipDirectory SourceDirectory="$(NetCoreAppCurrentTestHostPath)"
DestinationFile="$(TestArchiveRuntimeFile)"
Overwrite="true" />
</Target>
<!--
Collect all the tasks needed to be run once, to prepare the Helix correlation payload directory.
There's no actual work here; this target just causes its dependent targets to be run.
-->
<Target Name="PrepareCorrelationPayloadDirectory"
DependsOnTargets="CreateAllScenarioTestEnvFiles;CompressRuntimeDirectory" >
<Message Importance="High" Text="Correlation directory prepared" />
</Target>
</Project>
| -1 |
dotnet/runtime | 66,057 | Address TODO to switch to generated p/invoke | Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | elinor-fung | 2022-03-02T03:31:28Z | 2022-03-02T19:08:30Z | a4b8893a118357b55c0add9a39cc5aeb097a0bb8 | 1abbbb4adf6bf02549f4c6e021176534dcc4f974 | Address TODO to switch to generated p/invoke. Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | ./src/mono/mono/utils/parse.h | /**
* \file
* Parsing for GC options.
*
* Licensed under the MIT license. See LICENSE file in the project root for full license information.
*/
#ifndef __MONO_UTILS_PARSE_H__
#define __MONO_UTILS_PARSE_H__
#include <glib.h>
#include <stdlib.h>
gboolean mono_gc_parse_environment_string_extract_number (const char *str, size_t *out);
#endif
| /**
* \file
* Parsing for GC options.
*
* Licensed under the MIT license. See LICENSE file in the project root for full license information.
*/
#ifndef __MONO_UTILS_PARSE_H__
#define __MONO_UTILS_PARSE_H__
#include <glib.h>
#include <stdlib.h>
gboolean mono_gc_parse_environment_string_extract_number (const char *str, size_t *out);
#endif
| -1 |
dotnet/runtime | 66,057 | Address TODO to switch to generated p/invoke | Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | elinor-fung | 2022-03-02T03:31:28Z | 2022-03-02T19:08:30Z | a4b8893a118357b55c0add9a39cc5aeb097a0bb8 | 1abbbb4adf6bf02549f4c6e021176534dcc4f974 | Address TODO to switch to generated p/invoke. Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | ./src/libraries/System.Reflection.Primitives/src/System.Reflection.Primitives.csproj | <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<IsPartialFacadeAssembly>true</IsPartialFacadeAssembly>
<TargetFramework>$(NetCoreAppCurrent)</TargetFramework>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="$(CoreLibProject)" />
</ItemGroup>
</Project> | <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<IsPartialFacadeAssembly>true</IsPartialFacadeAssembly>
<TargetFramework>$(NetCoreAppCurrent)</TargetFramework>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="$(CoreLibProject)" />
</ItemGroup>
</Project> | -1 |
dotnet/runtime | 66,057 | Address TODO to switch to generated p/invoke | Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | elinor-fung | 2022-03-02T03:31:28Z | 2022-03-02T19:08:30Z | a4b8893a118357b55c0add9a39cc5aeb097a0bb8 | 1abbbb4adf6bf02549f4c6e021176534dcc4f974 | Address TODO to switch to generated p/invoke. Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | ./src/libraries/System.Linq.Expressions/tests/Variables/VariableTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Xunit;
namespace System.Linq.Expressions.Tests
{
public class VariableTests : ParameterExpressionTests
{
[Theory]
[MemberData(nameof(ValidTypeData))]
public void CreateVariableForValidTypeNoName(Type type)
{
ParameterExpression variable = Expression.Variable(type);
Assert.Equal(type, variable.Type);
Assert.False(variable.IsByRef);
Assert.Null(variable.Name);
}
[Theory]
[MemberData(nameof(ValidTypeData))]
public void CrateVariableForValidTypeWithName(Type type)
{
ParameterExpression variable = Expression.Variable(type, "name");
Assert.Equal(type, variable.Type);
Assert.False(variable.IsByRef);
Assert.Equal("name", variable.Name);
}
[Fact]
public void NameNeedNotBeCSharpValid()
{
ParameterExpression variable = Expression.Variable(typeof(int), "a name with characters not allowed in C# <, >, !, =, \0, \uFFFF, &c.");
Assert.Equal("a name with characters not allowed in C# <, >, !, =, \0, \uFFFF, &c.", variable.Name);
}
[Fact]
public void VariableCannotBeTypeVoid()
{
AssertExtensions.Throws<ArgumentException>("type", () => Expression.Variable(typeof(void)));
AssertExtensions.Throws<ArgumentException>("type", () => Expression.Variable(typeof(void), "var"));
}
[Fact]
public void NullType()
{
AssertExtensions.Throws<ArgumentNullException>("type", () => Expression.Variable(null));
AssertExtensions.Throws<ArgumentNullException>("type", () => Expression.Variable(null, "var"));
}
[Theory]
[MemberData(nameof(ByRefTypeData))]
public void VariableCannotBeByRef(Type type)
{
AssertExtensions.Throws<ArgumentException>("type", () => Expression.Variable(type));
AssertExtensions.Throws<ArgumentException>("type", () => Expression.Variable(type, "var"));
}
[Theory]
[PerCompilationType(nameof(ValueData))]
public void CanWriteAndReadBack(object value, bool useInterpreter)
{
Type type = value.GetType();
ParameterExpression variable = Expression.Variable(type);
Assert.True(
Expression.Lambda<Func<bool>>(
Expression.Equal(
Expression.Constant(value),
Expression.Block(
type,
new[] { variable },
Expression.Assign(variable, Expression.Constant(value)),
variable
)
)
).Compile(useInterpreter)()
);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void CanUseAsLambdaParameter(bool useInterpreter)
{
ParameterExpression variable = Expression.Variable(typeof(int));
Func<int, int> addOne = Expression.Lambda<Func<int, int>>(
Expression.Add(variable, Expression.Constant(1)),
variable
).Compile(useInterpreter);
Assert.Equal(3, addOne(2));
}
[Fact]
public void CannotReduce()
{
ParameterExpression variable = Expression.Variable(typeof(int));
Assert.False(variable.CanReduce);
Assert.Same(variable, variable.Reduce());
AssertExtensions.Throws<ArgumentException>(null, () => variable.ReduceAndCheck());
}
[Theory]
[ClassData(typeof(InvalidTypesData))]
public void OpenGenericType_ThrowsArgumentException(Type type)
{
AssertExtensions.Throws<ArgumentException>("type", () => Expression.Variable(type));
AssertExtensions.Throws<ArgumentException>("type", () => Expression.Variable(type, "name"));
}
[Fact]
public void CannotBePointerType()
{
AssertExtensions.Throws<ArgumentException>("type", () => Expression.Variable(typeof(int*)));
AssertExtensions.Throws<ArgumentException>("type", () => Expression.Variable(typeof(int*), "pointer"));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Xunit;
namespace System.Linq.Expressions.Tests
{
public class VariableTests : ParameterExpressionTests
{
[Theory]
[MemberData(nameof(ValidTypeData))]
public void CreateVariableForValidTypeNoName(Type type)
{
ParameterExpression variable = Expression.Variable(type);
Assert.Equal(type, variable.Type);
Assert.False(variable.IsByRef);
Assert.Null(variable.Name);
}
[Theory]
[MemberData(nameof(ValidTypeData))]
public void CrateVariableForValidTypeWithName(Type type)
{
ParameterExpression variable = Expression.Variable(type, "name");
Assert.Equal(type, variable.Type);
Assert.False(variable.IsByRef);
Assert.Equal("name", variable.Name);
}
[Fact]
public void NameNeedNotBeCSharpValid()
{
ParameterExpression variable = Expression.Variable(typeof(int), "a name with characters not allowed in C# <, >, !, =, \0, \uFFFF, &c.");
Assert.Equal("a name with characters not allowed in C# <, >, !, =, \0, \uFFFF, &c.", variable.Name);
}
[Fact]
public void VariableCannotBeTypeVoid()
{
AssertExtensions.Throws<ArgumentException>("type", () => Expression.Variable(typeof(void)));
AssertExtensions.Throws<ArgumentException>("type", () => Expression.Variable(typeof(void), "var"));
}
[Fact]
public void NullType()
{
AssertExtensions.Throws<ArgumentNullException>("type", () => Expression.Variable(null));
AssertExtensions.Throws<ArgumentNullException>("type", () => Expression.Variable(null, "var"));
}
[Theory]
[MemberData(nameof(ByRefTypeData))]
public void VariableCannotBeByRef(Type type)
{
AssertExtensions.Throws<ArgumentException>("type", () => Expression.Variable(type));
AssertExtensions.Throws<ArgumentException>("type", () => Expression.Variable(type, "var"));
}
[Theory]
[PerCompilationType(nameof(ValueData))]
public void CanWriteAndReadBack(object value, bool useInterpreter)
{
Type type = value.GetType();
ParameterExpression variable = Expression.Variable(type);
Assert.True(
Expression.Lambda<Func<bool>>(
Expression.Equal(
Expression.Constant(value),
Expression.Block(
type,
new[] { variable },
Expression.Assign(variable, Expression.Constant(value)),
variable
)
)
).Compile(useInterpreter)()
);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void CanUseAsLambdaParameter(bool useInterpreter)
{
ParameterExpression variable = Expression.Variable(typeof(int));
Func<int, int> addOne = Expression.Lambda<Func<int, int>>(
Expression.Add(variable, Expression.Constant(1)),
variable
).Compile(useInterpreter);
Assert.Equal(3, addOne(2));
}
[Fact]
public void CannotReduce()
{
ParameterExpression variable = Expression.Variable(typeof(int));
Assert.False(variable.CanReduce);
Assert.Same(variable, variable.Reduce());
AssertExtensions.Throws<ArgumentException>(null, () => variable.ReduceAndCheck());
}
[Theory]
[ClassData(typeof(InvalidTypesData))]
public void OpenGenericType_ThrowsArgumentException(Type type)
{
AssertExtensions.Throws<ArgumentException>("type", () => Expression.Variable(type));
AssertExtensions.Throws<ArgumentException>("type", () => Expression.Variable(type, "name"));
}
[Fact]
public void CannotBePointerType()
{
AssertExtensions.Throws<ArgumentException>("type", () => Expression.Variable(typeof(int*)));
AssertExtensions.Throws<ArgumentException>("type", () => Expression.Variable(typeof(int*), "pointer"));
}
}
}
| -1 |
dotnet/runtime | 66,057 | Address TODO to switch to generated p/invoke | Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | elinor-fung | 2022-03-02T03:31:28Z | 2022-03-02T19:08:30Z | a4b8893a118357b55c0add9a39cc5aeb097a0bb8 | 1abbbb4adf6bf02549f4c6e021176534dcc4f974 | Address TODO to switch to generated p/invoke. Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | ./src/tests/Common/XUnitWrapperGenerator/RuntimeTestModes.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 Xunit
{
[Flags]
public enum RuntimeTestModes
{
// Disable always when using coreclr runtime.
Any = ~0,
// We're running regular tests with no runtime stress modes
RegularRun = 1,
// JitStress, JitStressRegs, JitMinOpts and TailcallStress enable
// various modes in the JIT that cause us to exercise more code paths,
// and generate different kinds of code
JitStress = 1 << 1, // COMPlus_JitStress is set.
JitStressRegs = 1 << 2, // COMPlus_JitStressRegs is set.
JitMinOpts = 1 << 3, // COMPlus_JITMinOpts is set.
TailcallStress = 1 << 4, // COMPlus_TailcallStress is set.
// ZapDisable says to not use NGEN or ReadyToRun images.
// This means we JIT everything.
ZapDisable = 1 << 5, // COMPlus_ZapDisable is set.
// GCStress3 forces a GC at various locations, typically transitions
// to/from the VM from managed code.
GCStress3 = 1 << 6, // COMPlus_GCStress includes mode 0x3.
// GCStressC forces a GC at every JIT-generated code instruction,
// including in NGEN/ReadyToRun code.
GCStressC = 1 << 7, // COMPlus_GCStress includes mode 0xC.
AnyGCStress = GCStress3 | GCStressC // Disable when any GCStress is exercised.
}
}
| // 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 Xunit
{
[Flags]
public enum RuntimeTestModes
{
// Disable always when using coreclr runtime.
Any = ~0,
// We're running regular tests with no runtime stress modes
RegularRun = 1,
// JitStress, JitStressRegs, JitMinOpts and TailcallStress enable
// various modes in the JIT that cause us to exercise more code paths,
// and generate different kinds of code
JitStress = 1 << 1, // COMPlus_JitStress is set.
JitStressRegs = 1 << 2, // COMPlus_JitStressRegs is set.
JitMinOpts = 1 << 3, // COMPlus_JITMinOpts is set.
TailcallStress = 1 << 4, // COMPlus_TailcallStress is set.
// ZapDisable says to not use NGEN or ReadyToRun images.
// This means we JIT everything.
ZapDisable = 1 << 5, // COMPlus_ZapDisable is set.
// GCStress3 forces a GC at various locations, typically transitions
// to/from the VM from managed code.
GCStress3 = 1 << 6, // COMPlus_GCStress includes mode 0x3.
// GCStressC forces a GC at every JIT-generated code instruction,
// including in NGEN/ReadyToRun code.
GCStressC = 1 << 7, // COMPlus_GCStress includes mode 0xC.
AnyGCStress = GCStress3 | GCStressC // Disable when any GCStress is exercised.
}
}
| -1 |
dotnet/runtime | 66,057 | Address TODO to switch to generated p/invoke | Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | elinor-fung | 2022-03-02T03:31:28Z | 2022-03-02T19:08:30Z | a4b8893a118357b55c0add9a39cc5aeb097a0bb8 | 1abbbb4adf6bf02549f4c6e021176534dcc4f974 | Address TODO to switch to generated p/invoke. Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | ./src/libraries/System.Private.Xml/tests/Xslt/TestFiles/TestData/XsltApi/fruits.xml | <?xml version='1.0'?>
<FruitRack>
<apple>
<color>Red</color>
<calories>50</calories>
</apple>
<orange>
<color>Orange</color>
<calories>25</calories>
</orange>
</FruitRack> | <?xml version='1.0'?>
<FruitRack>
<apple>
<color>Red</color>
<calories>50</calories>
</apple>
<orange>
<color>Orange</color>
<calories>25</calories>
</orange>
</FruitRack> | -1 |
dotnet/runtime | 66,057 | Address TODO to switch to generated p/invoke | Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | elinor-fung | 2022-03-02T03:31:28Z | 2022-03-02T19:08:30Z | a4b8893a118357b55c0add9a39cc5aeb097a0bb8 | 1abbbb4adf6bf02549f4c6e021176534dcc4f974 | Address TODO to switch to generated p/invoke. Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | ./src/coreclr/inc/readytoruninstructionset.h | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// DO NOT EDIT THIS FILE! IT IS AUTOGENERATED
// FROM /src/coreclr/tools/Common/JitInterface/ThunkGenerator/InstructionSetDesc.txt
// using /src/coreclr/tools/Common/JitInterface/ThunkGenerator/gen.bat
#ifndef READYTORUNINSTRUCTIONSET_H
#define READYTORUNINSTRUCTIONSET_H
enum ReadyToRunInstructionSet
{
READYTORUN_INSTRUCTION_Sse=1,
READYTORUN_INSTRUCTION_Sse2=2,
READYTORUN_INSTRUCTION_Sse3=3,
READYTORUN_INSTRUCTION_Ssse3=4,
READYTORUN_INSTRUCTION_Sse41=5,
READYTORUN_INSTRUCTION_Sse42=6,
READYTORUN_INSTRUCTION_Avx=7,
READYTORUN_INSTRUCTION_Avx2=8,
READYTORUN_INSTRUCTION_Aes=9,
READYTORUN_INSTRUCTION_Bmi1=10,
READYTORUN_INSTRUCTION_Bmi2=11,
READYTORUN_INSTRUCTION_Fma=12,
READYTORUN_INSTRUCTION_Lzcnt=13,
READYTORUN_INSTRUCTION_Pclmulqdq=14,
READYTORUN_INSTRUCTION_Popcnt=15,
READYTORUN_INSTRUCTION_ArmBase=16,
READYTORUN_INSTRUCTION_AdvSimd=17,
READYTORUN_INSTRUCTION_Crc32=18,
READYTORUN_INSTRUCTION_Sha1=19,
READYTORUN_INSTRUCTION_Sha256=20,
READYTORUN_INSTRUCTION_Atomics=21,
READYTORUN_INSTRUCTION_X86Base=22,
READYTORUN_INSTRUCTION_Dp=23,
READYTORUN_INSTRUCTION_Rdm=24,
READYTORUN_INSTRUCTION_AvxVnni=25,
};
#endif // READYTORUNINSTRUCTIONSET_H
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// DO NOT EDIT THIS FILE! IT IS AUTOGENERATED
// FROM /src/coreclr/tools/Common/JitInterface/ThunkGenerator/InstructionSetDesc.txt
// using /src/coreclr/tools/Common/JitInterface/ThunkGenerator/gen.bat
#ifndef READYTORUNINSTRUCTIONSET_H
#define READYTORUNINSTRUCTIONSET_H
enum ReadyToRunInstructionSet
{
READYTORUN_INSTRUCTION_Sse=1,
READYTORUN_INSTRUCTION_Sse2=2,
READYTORUN_INSTRUCTION_Sse3=3,
READYTORUN_INSTRUCTION_Ssse3=4,
READYTORUN_INSTRUCTION_Sse41=5,
READYTORUN_INSTRUCTION_Sse42=6,
READYTORUN_INSTRUCTION_Avx=7,
READYTORUN_INSTRUCTION_Avx2=8,
READYTORUN_INSTRUCTION_Aes=9,
READYTORUN_INSTRUCTION_Bmi1=10,
READYTORUN_INSTRUCTION_Bmi2=11,
READYTORUN_INSTRUCTION_Fma=12,
READYTORUN_INSTRUCTION_Lzcnt=13,
READYTORUN_INSTRUCTION_Pclmulqdq=14,
READYTORUN_INSTRUCTION_Popcnt=15,
READYTORUN_INSTRUCTION_ArmBase=16,
READYTORUN_INSTRUCTION_AdvSimd=17,
READYTORUN_INSTRUCTION_Crc32=18,
READYTORUN_INSTRUCTION_Sha1=19,
READYTORUN_INSTRUCTION_Sha256=20,
READYTORUN_INSTRUCTION_Atomics=21,
READYTORUN_INSTRUCTION_X86Base=22,
READYTORUN_INSTRUCTION_Dp=23,
READYTORUN_INSTRUCTION_Rdm=24,
READYTORUN_INSTRUCTION_AvxVnni=25,
};
#endif // READYTORUNINSTRUCTIONSET_H
| -1 |
dotnet/runtime | 66,057 | Address TODO to switch to generated p/invoke | Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | elinor-fung | 2022-03-02T03:31:28Z | 2022-03-02T19:08:30Z | a4b8893a118357b55c0add9a39cc5aeb097a0bb8 | 1abbbb4adf6bf02549f4c6e021176534dcc4f974 | Address TODO to switch to generated p/invoke. Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | ./src/tests/JIT/Regression/JitBlue/GitHub_22583/base.csproj | <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<CLRTestKind>SharedLibrary</CLRTestKind>
</PropertyGroup>
<PropertyGroup>
<DebugType />
<Optimize>True</Optimize>
</PropertyGroup>
<ItemGroup>
<Compile Include="base.cs" />
</ItemGroup>
</Project>
| <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<CLRTestKind>SharedLibrary</CLRTestKind>
</PropertyGroup>
<PropertyGroup>
<DebugType />
<Optimize>True</Optimize>
</PropertyGroup>
<ItemGroup>
<Compile Include="base.cs" />
</ItemGroup>
</Project>
| -1 |
dotnet/runtime | 66,057 | Address TODO to switch to generated p/invoke | Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | elinor-fung | 2022-03-02T03:31:28Z | 2022-03-02T19:08:30Z | a4b8893a118357b55c0add9a39cc5aeb097a0bb8 | 1abbbb4adf6bf02549f4c6e021176534dcc4f974 | Address TODO to switch to generated p/invoke. Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | ./src/tests/JIT/Regression/CLR-x86-JIT/V1.2-Beta1/b178128/hugestruct.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
using System;
struct Big10DW
{
#pragma warning disable 0414
public Int64 i1;
public Int64 i2;
public Int64 i3;
public Int64 i4;
public Int64 i5;
public void Zero()
{
i1 = 0;
i2 = 0;
i3 = 0;
i4 = 0;
i5 = 0;
}
#pragma warning restore 0414
}
struct Big100DW
{
public Big10DW b1;
public Big10DW b2;
public Big10DW b3;
public Big10DW b4;
public Big10DW b5;
public Big10DW b6;
public Big10DW b7;
public Big10DW b8;
public Big10DW b9;
public Big10DW b10;
public void Zero()
{
b1.Zero();
b2.Zero();
b3.Zero();
b4.Zero();
b5.Zero();
b6.Zero();
b7.Zero();
b8.Zero();
b9.Zero();
b10.Zero();
}
}
struct Big1000DW
{
public Big100DW b1;
public Big100DW b2;
public Big100DW b3;
public Big100DW b4;
public Big100DW b5;
public Big100DW b6;
public Big100DW b7;
public Big100DW b8;
public Big100DW b9;
public Big100DW b10;
public void Zero()
{
b1.Zero();
b2.Zero();
b3.Zero();
b4.Zero();
b5.Zero();
b6.Zero();
b7.Zero();
b8.Zero();
b9.Zero();
b10.Zero();
}
}
struct Big10000DW
{
public Big1000DW b1;
public Big1000DW b2;
public Big1000DW b3;
public Big1000DW b4;
public Big1000DW b5;
public Big1000DW b6;
public Big1000DW b7;
public Big1000DW b8;
public Big1000DW b9;
public Big1000DW b10;
public void Zero()
{
b1.Zero();
b2.Zero();
b3.Zero();
b4.Zero();
b5.Zero();
b6.Zero();
b7.Zero();
b8.Zero();
b9.Zero();
b10.Zero();
}
}
struct Big100000DW
{
public Big10000DW b1;
public Big10000DW b2;
public Big10000DW b3;
public Big10000DW b4;
public Big10000DW b5;
public Big10000DW b6;
public Big10000DW b7;
public Big10000DW b8;
public Big10000DW b9;
public Big10000DW b10;
public void Zero()
{
b1.Zero();
b2.Zero();
b3.Zero();
b4.Zero();
b5.Zero();
b6.Zero();
b7.Zero();
b8.Zero();
b9.Zero();
b10.Zero();
}
}
class Test_hugestruct
{
static int Main()
{
Big100000DW b = new Big100000DW();
b.b10.b10.b10.b10.i5 = 0;
GC.Collect();
return 100;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
using System;
struct Big10DW
{
#pragma warning disable 0414
public Int64 i1;
public Int64 i2;
public Int64 i3;
public Int64 i4;
public Int64 i5;
public void Zero()
{
i1 = 0;
i2 = 0;
i3 = 0;
i4 = 0;
i5 = 0;
}
#pragma warning restore 0414
}
struct Big100DW
{
public Big10DW b1;
public Big10DW b2;
public Big10DW b3;
public Big10DW b4;
public Big10DW b5;
public Big10DW b6;
public Big10DW b7;
public Big10DW b8;
public Big10DW b9;
public Big10DW b10;
public void Zero()
{
b1.Zero();
b2.Zero();
b3.Zero();
b4.Zero();
b5.Zero();
b6.Zero();
b7.Zero();
b8.Zero();
b9.Zero();
b10.Zero();
}
}
struct Big1000DW
{
public Big100DW b1;
public Big100DW b2;
public Big100DW b3;
public Big100DW b4;
public Big100DW b5;
public Big100DW b6;
public Big100DW b7;
public Big100DW b8;
public Big100DW b9;
public Big100DW b10;
public void Zero()
{
b1.Zero();
b2.Zero();
b3.Zero();
b4.Zero();
b5.Zero();
b6.Zero();
b7.Zero();
b8.Zero();
b9.Zero();
b10.Zero();
}
}
struct Big10000DW
{
public Big1000DW b1;
public Big1000DW b2;
public Big1000DW b3;
public Big1000DW b4;
public Big1000DW b5;
public Big1000DW b6;
public Big1000DW b7;
public Big1000DW b8;
public Big1000DW b9;
public Big1000DW b10;
public void Zero()
{
b1.Zero();
b2.Zero();
b3.Zero();
b4.Zero();
b5.Zero();
b6.Zero();
b7.Zero();
b8.Zero();
b9.Zero();
b10.Zero();
}
}
struct Big100000DW
{
public Big10000DW b1;
public Big10000DW b2;
public Big10000DW b3;
public Big10000DW b4;
public Big10000DW b5;
public Big10000DW b6;
public Big10000DW b7;
public Big10000DW b8;
public Big10000DW b9;
public Big10000DW b10;
public void Zero()
{
b1.Zero();
b2.Zero();
b3.Zero();
b4.Zero();
b5.Zero();
b6.Zero();
b7.Zero();
b8.Zero();
b9.Zero();
b10.Zero();
}
}
class Test_hugestruct
{
static int Main()
{
Big100000DW b = new Big100000DW();
b.b10.b10.b10.b10.i5 = 0;
GC.Collect();
return 100;
}
}
| -1 |
dotnet/runtime | 66,057 | Address TODO to switch to generated p/invoke | Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | elinor-fung | 2022-03-02T03:31:28Z | 2022-03-02T19:08:30Z | a4b8893a118357b55c0add9a39cc5aeb097a0bb8 | 1abbbb4adf6bf02549f4c6e021176534dcc4f974 | Address TODO to switch to generated p/invoke. Found a few more `TODO: [DllImportGenerator]` from before the blittable/unmanaged reconciliation. | ./src/native/libs/Common/pal_ssl_types.h | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#pragma once
#include <stdint.h>
// Matches managed System.Security.Authentication.SslProtocols
enum
{
PAL_SslProtocol_None = 0,
PAL_SslProtocol_Ssl2 = 12,
PAL_SslProtocol_Ssl3 = 48,
PAL_SslProtocol_Tls10 = 192,
PAL_SslProtocol_Tls11 = 768,
PAL_SslProtocol_Tls12 = 3072,
PAL_SslProtocol_Tls13 = 12288,
};
typedef int32_t PAL_SslProtocol;
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#pragma once
#include <stdint.h>
// Matches managed System.Security.Authentication.SslProtocols
enum
{
PAL_SslProtocol_None = 0,
PAL_SslProtocol_Ssl2 = 12,
PAL_SslProtocol_Ssl3 = 48,
PAL_SslProtocol_Tls10 = 192,
PAL_SslProtocol_Tls11 = 768,
PAL_SslProtocol_Tls12 = 3072,
PAL_SslProtocol_Tls13 = 12288,
};
typedef int32_t PAL_SslProtocol;
| -1 |
dotnet/runtime | 66,046 | Fix handling of atomic nodes in RegexCompiler / source generator | We weren't properly resetting the stack position, so if we had an atomic group that contained something that backtracked, any backtracking positions left on the stack by that nested construct would then be consumed by a previous backtracking construct and lead to it reading the wrong state. | stephentoub | 2022-03-02T01:17:05Z | 2022-03-03T16:24:40Z | fdbdb9a81d2974b38c4c6c3dea9c3d2bf1d4b7d8 | b410984a6287b722b7bd215441504fe78ecb2ca0 | Fix handling of atomic nodes in RegexCompiler / source generator. We weren't properly resetting the stack position, so if we had an atomic group that contained something that backtracked, any backtracking positions left on the stack by that nested construct would then be consumed by a previous backtracking construct and lead to it reading the wrong state. | ./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)
{
RegexNode root = rm.Tree.Root;
if (!root.SupportsCompilation())
{
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.
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))
{
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, end = base.runtextend;");
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 <= end)",
1 => "if (pos < end)",
_ => $"if (pos < end - {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 = end;");
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");
additionalDeclarations.Add("int beginning = base.runtextbeg;");
using (EmitBlock(writer, "if (pos > beginning)"))
{
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 < end - 1)"))
{
writer.WriteLine("base.runtextpos = end - 1;");
}
writer.WriteLine("return true;");
return true;
case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_End:
writer.WriteLine("// Leading end \\z anchor");
using (EmitBlock(writer, "if (pos < end)"))
{
writer.WriteLine("base.runtextpos = end;");
}
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 < end - {regexTree.FindOptimizations.MinRequiredLength + 1})"))
{
writer.WriteLine($"base.runtextpos = end - {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 < end - {regexTree.FindOptimizations.MinRequiredLength})"))
{
writer.WriteLine($"base.runtextpos = end - {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");
additionalDeclarations.Add("int beginning = base.runtextbeg;");
using (EmitBlock(writer, "if (pos > beginning && inputSpan[pos - 1] != '\\n')"))
{
writer.WriteLine("int newlinePos = global::System.MemoryExtensions.IndexOf(inputSpan.Slice(pos), '\\n');");
using (EmitBlock(writer, "if (newlinePos < 0 || newlinePos + pos + 1 > end)"))
{
Goto(NoStartingPositionFound);
}
writer.WriteLine("pos = newlinePos + pos + 1;");
}
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 < end - {maxLength})"))
{
writer.WriteLine($"pos = end - {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 < end - {maxLength + 1})"))
{
writer.WriteLine($"pos = end - {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, end - 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, end - 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, end - 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, end - 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, end = base.runtextend;");
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, end - 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()}");
// Lookarounds are implicitly atomic. Store the original done label to reset at the end.
string originalDoneLabel = doneLabel;
// 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.
EmitNode(node.Child(0));
// 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;
doneLabel = originalDoneLabel;
}
// 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()}");
// Lookarounds are implicitly atomic. Store the original done label to reset at the end.
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.
EmitNode(node.Child(0));
// 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;
// Atomic is invisible in the generated source, other than its impact on the targets of jumps
case RegexNodeKind.Atomic:
EmitAtomic(node, subsequent);
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.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, $"Unexpected type: {node.Kind}");
Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}");
// Atomic simply outputs the code for the child, but it ensures that any done label left
// set by the child is reset to what it was prior to the node's processing. That way,
// anything later that tries to jump back won't see labels set inside the atomic.
string originalDoneLabel = doneLabel;
EmitNode(node.Child(0), subsequent);
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
{
additionalDeclarations.Add(node.Kind == RegexNodeKind.Beginning ? "int beginning = base.runtextbeg;" : "int start = base.runtextstart;");
using (EmitBlock(writer, node.Kind == RegexNodeKind.Beginning ? "if (pos != beginning)" : "if (pos != start)"))
{
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:
additionalDeclarations.Add("int beginning = base.runtextbeg;");
using (EmitBlock(writer, $"if (pos > beginning && 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 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.
// int i = end - pos;
TransferSliceStaticPosToPos();
writer.WriteLine($"int {iterationLocal} = end - 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>Gets whether a given regular expression method is supported by the code generator.</summary>
private static bool SupportsCodeGeneration(RegexMethod rm)
{
RegexNode root = rm.Tree.Root;
if (!root.SupportsCompilation())
{
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.
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))
{
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, end = base.runtextend;");
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 <= end)",
1 => "if (pos < end)",
_ => $"if (pos < end - {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 = end;");
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");
additionalDeclarations.Add("int beginning = base.runtextbeg;");
using (EmitBlock(writer, "if (pos > beginning)"))
{
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 < end - 1)"))
{
writer.WriteLine("base.runtextpos = end - 1;");
}
writer.WriteLine("return true;");
return true;
case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_End:
writer.WriteLine("// Leading end \\z anchor");
using (EmitBlock(writer, "if (pos < end)"))
{
writer.WriteLine("base.runtextpos = end;");
}
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 < end - {regexTree.FindOptimizations.MinRequiredLength + 1})"))
{
writer.WriteLine($"base.runtextpos = end - {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 < end - {regexTree.FindOptimizations.MinRequiredLength})"))
{
writer.WriteLine($"base.runtextpos = end - {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");
additionalDeclarations.Add("int beginning = base.runtextbeg;");
using (EmitBlock(writer, "if (pos > beginning && inputSpan[pos - 1] != '\\n')"))
{
writer.WriteLine("int newlinePos = global::System.MemoryExtensions.IndexOf(inputSpan.Slice(pos), '\\n');");
using (EmitBlock(writer, "if (newlinePos < 0 || newlinePos + pos + 1 > end)"))
{
Goto(NoStartingPositionFound);
}
writer.WriteLine("pos = newlinePos + pos + 1;");
}
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 < end - {maxLength})"))
{
writer.WriteLine($"pos = end - {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 < end - {maxLength + 1})"))
{
writer.WriteLine($"pos = end - {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, end - 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, end - 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, end - 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, end - 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, end = base.runtextend;");
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, end - 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
{
additionalDeclarations.Add(node.Kind == RegexNodeKind.Beginning ? "int beginning = base.runtextbeg;" : "int start = base.runtextstart;");
using (EmitBlock(writer, node.Kind == RegexNodeKind.Beginning ? "if (pos != beginning)" : "if (pos != start)"))
{
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:
additionalDeclarations.Add("int beginning = base.runtextbeg;");
using (EmitBlock(writer, $"if (pos > beginning && 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 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.
// int i = end - pos;
TransferSliceStaticPosToPos();
writer.WriteLine($"int {iterationLocal} = end - 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
}
}
}
| 1 |
dotnet/runtime | 66,046 | Fix handling of atomic nodes in RegexCompiler / source generator | We weren't properly resetting the stack position, so if we had an atomic group that contained something that backtracked, any backtracking positions left on the stack by that nested construct would then be consumed by a previous backtracking construct and lead to it reading the wrong state. | stephentoub | 2022-03-02T01:17:05Z | 2022-03-03T16:24:40Z | fdbdb9a81d2974b38c4c6c3dea9c3d2bf1d4b7d8 | b410984a6287b722b7bd215441504fe78ecb2ca0 | Fix handling of atomic nodes in RegexCompiler / source generator. We weren't properly resetting the stack position, so if we had an atomic group that contained something that backtracked, any backtracking positions left on the stack by that nested construct would then be consumed by a previous backtracking construct and lead to it reading the wrong state. | ./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_runtextbegField = RegexRunnerField("runtextbeg");
private static readonly FieldInfo s_runtextendField = RegexRunnerField("runtextend");
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();
LocalBuilder end = 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;
// int end = base.runtextend;
// ReadOnlySpan<char> inputSpan = input;
Mvfldloc(s_runtextposField, pos);
Mvfldloc(s_runtextendField, end);
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 > end - _code.Tree.MinRequiredLength)
// {
// base.runtextpos = end;
// return false;
// }
Ldloc(pos);
Ldloc(end);
if (minRequiredLength > 0)
{
Ldc(minRequiredLength);
Sub();
}
Ble(finishedLengthCheck);
MarkLabel(returnFalse);
Ldthis();
Ldloc(end);
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);
Ldthisfld(s_runtextbegField);
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);
Ldloc(end);
Ldc(1);
Sub();
Bge(label);
Ldthis();
Ldloc(end);
Ldc(1);
Sub();
Stfld(s_runtextposField);
MarkLabel(label);
Ldc(1);
Ret();
return true;
case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_End:
label = DefineLabel();
Ldloc(pos);
Ldloc(end);
Bge(label);
Ldthis();
Ldloc(end);
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);
Ldloc(end);
Ldc(_regexTree.FindOptimizations.MinRequiredLength + extraNewlineBump);
Sub();
Bge(label);
Ldthis();
Ldloc(end);
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 > runtextbeg...
Ldloc(pos!);
Ldthisfld(s_runtextbegField);
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 > end)
// {
// base.runtextpos = end;
// return false;
// }
Ldloc(newlinePos);
Ldc(0);
Blt(returnFalse);
Ldloc(newlinePos);
Ldloc(pos);
Add();
Ldc(1);
Add();
Ldloc(end);
Bgt(returnFalse);
// pos += newlinePos + 1;
Ldloc(pos);
Ldloc(newlinePos);
Add();
Ldc(1);
Add();
Stloc(pos);
}
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);
Ldloc(end);
Ldc(maxLength + extraNewlineBump);
Sub();
Bge(label);
Ldloc(end);
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, end - pos).IndexOf(prefix);
Ldloca(inputSpan);
Ldloc(pos);
Ldloc(end);
Ldloc(pos);
Sub();
Call(s_spanSliceIntIntMethod);
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, end - pos);
Ldloca(inputSpan);
Ldloc(pos);
Ldloc(end);
Ldloc(pos);
Sub();
Call(s_spanSliceIntIntMethod);
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 = end;
// 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, end - pos);
using RentedLocalBuilder slice = RentReadOnlySpanCharLocal();
Ldloca(inputSpan);
Ldloc(pos);
Ldloc(end);
Ldloc(pos);
Sub();
Call(s_spanSliceIntIntMethod);
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 = end;
// 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();
LocalBuilder end = DeclareInt32();
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;
// int end = base.runtextend;
Ldarg_1();
Stloc(inputSpan);
Mvfldloc(s_runtextendField, end);
// 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, end - pos);
Ldloca(inputSpan);
Ldloc(pos);
Ldloc(end);
Ldloc(pos);
Sub();
Call(s_spanSliceIntIntMethod);
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, end - 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, end - 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()}");
// Lookarounds are implicitly atomic. Store the original done label to reset at the end.
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;
// Emit the child.
EmitNode(node.Child(0));
// After the child completes successfully, reset the text positions.
// Do not reset captures, which persist beyond the lookahead.
// pos = startingPos;
// slice = inputSpan.Slice(pos, end - pos);
Ldloc(startingPos);
Stloc(pos);
SliceInputSpan();
sliceStaticPos = startingTextSpanPos;
doneLabel = originalDoneLabel;
}
// 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()}");
// Lookarounds are implicitly atomic. Store the original done label to reset at the end.
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.
EmitNode(node.Child(0));
// 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, $"Unexpected type: {node.Kind}");
Debug.Assert(node.ChildCount() == 1, $"Expected 1 child, found {node.ChildCount()}");
// Atomic simply outputs the code for the child, but it ensures that any done label left
// set by the child is reset to what it was prior to the node's processing. That way,
// anything later that tries to jump back won't see labels set inside the atomic.
Label originalDoneLabel = doneLabel;
EmitNode(node.Child(0), subsequent);
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 > base.runtextbeg/start) goto doneLabel;
Ldloc(pos);
Ldthisfld(node.Kind == RegexNodeKind.Beginning ? s_runtextbegField : 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 > base.runtextbeg && base.runtext[pos - 1] != '\n') goto doneLabel;
Label success = DefineLabel();
Ldloc(pos);
Ldthisfld(s_runtextbegField);
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 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, end - 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, end - 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, end - 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 = end - pos;
TransferSliceStaticPosToPos();
Ldloc(end);
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_runtextbegField = RegexRunnerField("runtextbeg");
private static readonly FieldInfo s_runtextendField = RegexRunnerField("runtextend");
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();
LocalBuilder end = 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;
// int end = base.runtextend;
// ReadOnlySpan<char> inputSpan = input;
Mvfldloc(s_runtextposField, pos);
Mvfldloc(s_runtextendField, end);
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 > end - _code.Tree.MinRequiredLength)
// {
// base.runtextpos = end;
// return false;
// }
Ldloc(pos);
Ldloc(end);
if (minRequiredLength > 0)
{
Ldc(minRequiredLength);
Sub();
}
Ble(finishedLengthCheck);
MarkLabel(returnFalse);
Ldthis();
Ldloc(end);
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);
Ldthisfld(s_runtextbegField);
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);
Ldloc(end);
Ldc(1);
Sub();
Bge(label);
Ldthis();
Ldloc(end);
Ldc(1);
Sub();
Stfld(s_runtextposField);
MarkLabel(label);
Ldc(1);
Ret();
return true;
case FindNextStartingPositionMode.LeadingAnchor_LeftToRight_End:
label = DefineLabel();
Ldloc(pos);
Ldloc(end);
Bge(label);
Ldthis();
Ldloc(end);
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);
Ldloc(end);
Ldc(_regexTree.FindOptimizations.MinRequiredLength + extraNewlineBump);
Sub();
Bge(label);
Ldthis();
Ldloc(end);
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 > runtextbeg...
Ldloc(pos!);
Ldthisfld(s_runtextbegField);
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 > end)
// {
// base.runtextpos = end;
// return false;
// }
Ldloc(newlinePos);
Ldc(0);
Blt(returnFalse);
Ldloc(newlinePos);
Ldloc(pos);
Add();
Ldc(1);
Add();
Ldloc(end);
Bgt(returnFalse);
// pos += newlinePos + 1;
Ldloc(pos);
Ldloc(newlinePos);
Add();
Ldc(1);
Add();
Stloc(pos);
}
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);
Ldloc(end);
Ldc(maxLength + extraNewlineBump);
Sub();
Bge(label);
Ldloc(end);
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, end - pos).IndexOf(prefix);
Ldloca(inputSpan);
Ldloc(pos);
Ldloc(end);
Ldloc(pos);
Sub();
Call(s_spanSliceIntIntMethod);
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, end - pos);
Ldloca(inputSpan);
Ldloc(pos);
Ldloc(end);
Ldloc(pos);
Sub();
Call(s_spanSliceIntIntMethod);
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 = end;
// 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, end - pos);
using RentedLocalBuilder slice = RentReadOnlySpanCharLocal();
Ldloca(inputSpan);
Ldloc(pos);
Ldloc(end);
Ldloc(pos);
Sub();
Call(s_spanSliceIntIntMethod);
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 = end;
// 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();
LocalBuilder end = DeclareInt32();
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;
// int end = base.runtextend;
Ldarg_1();
Stloc(inputSpan);
Mvfldloc(s_runtextendField, end);
// 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, end - pos);
Ldloca(inputSpan);
Ldloc(pos);
Ldloc(end);
Ldloc(pos);
Sub();
Call(s_spanSliceIntIntMethod);
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, end - 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, end - 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, end - 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 > base.runtextbeg/start) goto doneLabel;
Ldloc(pos);
Ldthisfld(node.Kind == RegexNodeKind.Beginning ? s_runtextbegField : 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 > base.runtextbeg && base.runtext[pos - 1] != '\n') goto doneLabel;
Label success = DefineLabel();
Ldloc(pos);
Ldthisfld(s_runtextbegField);
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 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, end - 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, end - 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, end - 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 = end - pos;
TransferSliceStaticPosToPos();
Ldloc(end);
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);
}
}
}
| 1 |
dotnet/runtime | 66,046 | Fix handling of atomic nodes in RegexCompiler / source generator | We weren't properly resetting the stack position, so if we had an atomic group that contained something that backtracked, any backtracking positions left on the stack by that nested construct would then be consumed by a previous backtracking construct and lead to it reading the wrong state. | stephentoub | 2022-03-02T01:17:05Z | 2022-03-03T16:24:40Z | fdbdb9a81d2974b38c4c6c3dea9c3d2bf1d4b7d8 | b410984a6287b722b7bd215441504fe78ecb2ca0 | Fix handling of atomic nodes in RegexCompiler / source generator. We weren't properly resetting the stack position, so if we had an atomic group that contained something that backtracked, any backtracking positions left on the stack by that nested construct would then be consumed by a previous backtracking construct and lead to it reading the wrong state. | ./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");
// 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: 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) } };
}
}
}
}
| 1 |
dotnet/runtime | 66,046 | Fix handling of atomic nodes in RegexCompiler / source generator | We weren't properly resetting the stack position, so if we had an atomic group that contained something that backtracked, any backtracking positions left on the stack by that nested construct would then be consumed by a previous backtracking construct and lead to it reading the wrong state. | stephentoub | 2022-03-02T01:17:05Z | 2022-03-03T16:24:40Z | fdbdb9a81d2974b38c4c6c3dea9c3d2bf1d4b7d8 | b410984a6287b722b7bd215441504fe78ecb2ca0 | Fix handling of atomic nodes in RegexCompiler / source generator. We weren't properly resetting the stack position, so if we had an atomic group that contained something that backtracked, any backtracking positions left on the stack by that nested construct would then be consumed by a previous backtracking construct and lead to it reading the wrong state. | ./src/libraries/System.Net.Security/tests/FunctionalTests/TestHelper.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 System.Net.Sockets;
using System.Net.Test.Common;
using System.Security.Authentication;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography.X509Certificates.Tests.Common;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Security.Tests
{
public static class TestHelper
{
private static readonly X509KeyUsageExtension s_eeKeyUsage =
new X509KeyUsageExtension(
X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.KeyEncipherment | X509KeyUsageFlags.DataEncipherment,
critical: false);
private static readonly X509EnhancedKeyUsageExtension s_tlsServerEku =
new X509EnhancedKeyUsageExtension(
new OidCollection
{
new Oid("1.3.6.1.5.5.7.3.1", null)
},
false);
private static readonly X509EnhancedKeyUsageExtension s_tlsClientEku =
new X509EnhancedKeyUsageExtension(
new OidCollection
{
new Oid("1.3.6.1.5.5.7.3.2", null)
},
false);
private static readonly X509BasicConstraintsExtension s_eeConstraints =
new X509BasicConstraintsExtension(false, false, 0, false);
public static readonly byte[] s_ping = Encoding.UTF8.GetBytes("PING");
public static readonly byte[] s_pong = Encoding.UTF8.GetBytes("PONG");
public static (SslStream ClientStream, SslStream ServerStream) GetConnectedSslStreams()
{
(Stream clientStream, Stream serverStream) = GetConnectedStreams();
return (new SslStream(clientStream), new SslStream(serverStream));
}
public static (Stream ClientStream, Stream ServerStream) GetConnectedStreams()
{
if (Capability.SecurityForceSocketStreams())
{
// DOTNET_TEST_NET_SECURITY_FORCE_SOCKET_STREAMS is set.
return GetConnectedTcpStreams();
}
return ConnectedStreams.CreateBidirectional(initialBufferSize: 4096, maxBufferSize: int.MaxValue);
}
internal static (NetworkStream ClientStream, NetworkStream ServerStream) GetConnectedTcpStreams()
{
using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
listener.Listen(1);
var clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
clientSocket.Connect(listener.LocalEndPoint);
Socket serverSocket = listener.Accept();
serverSocket.NoDelay = true;
clientSocket.NoDelay = true;
return (new NetworkStream(clientSocket, ownsSocket: true), new NetworkStream(serverSocket, ownsSocket: true));
}
}
internal static void CleanupCertificates([CallerMemberName] string? testName = null)
{
string caName = $"O={testName}";
try
{
using (X509Store store = new X509Store(StoreName.CertificateAuthority, StoreLocation.LocalMachine))
{
store.Open(OpenFlags.ReadWrite);
foreach (X509Certificate2 cert in store.Certificates)
{
if (cert.Subject.Contains(caName))
{
store.Remove(cert);
}
}
}
}
catch { };
try
{
using (X509Store store = new X509Store(StoreName.CertificateAuthority, StoreLocation.CurrentUser))
{
store.Open(OpenFlags.ReadWrite);
foreach (X509Certificate2 cert in store.Certificates)
{
if (cert.Subject.Contains(caName))
{
store.Remove(cert);
}
}
}
}
catch { };
}
internal static (X509Certificate2 certificate, X509Certificate2Collection) GenerateCertificates(string targetName, [CallerMemberName] string? testName = null, bool longChain = false, bool serverCertificate = true)
{
const int keySize = 2048;
if (PlatformDetection.IsWindows && testName != null)
{
CleanupCertificates(testName);
}
X509Certificate2Collection chain = new X509Certificate2Collection();
X509ExtensionCollection extensions = new X509ExtensionCollection();
SubjectAlternativeNameBuilder builder = new SubjectAlternativeNameBuilder();
builder.AddDnsName(targetName);
extensions.Add(builder.Build());
extensions.Add(s_eeConstraints);
extensions.Add(s_eeKeyUsage);
extensions.Add(serverCertificate ? s_tlsServerEku : s_tlsClientEku);
CertificateAuthority.BuildPrivatePki(
PkiOptions.IssuerRevocationViaCrl,
out RevocationResponder responder,
out CertificateAuthority root,
out CertificateAuthority[] intermediates,
out X509Certificate2 endEntity,
intermediateAuthorityCount: longChain ? 3 : 1,
subjectName: targetName,
testName: testName,
keySize: keySize,
extensions: extensions);
// Walk the intermediates backwards so we build the chain collection as
// Issuer3
// Issuer2
// Issuer1
// Root
for (int i = intermediates.Length - 1; i >= 0; i--)
{
CertificateAuthority authority = intermediates[i];
chain.Add(authority.CloneIssuerCert());
authority.Dispose();
}
chain.Add(root.CloneIssuerCert());
responder.Dispose();
root.Dispose();
if (PlatformDetection.IsWindows)
{
X509Certificate2 ephemeral = endEntity;
endEntity = new X509Certificate2(endEntity.Export(X509ContentType.Pfx));
ephemeral.Dispose();
}
return (endEntity, chain);
}
internal static async Task PingPong(SslStream client, SslStream server, CancellationToken cancellationToken = default)
{
byte[] buffer = new byte[s_ping.Length];
ValueTask t = client.WriteAsync(s_ping, cancellationToken);
int remains = s_ping.Length;
while (remains > 0)
{
int readLength = await server.ReadAsync(buffer, buffer.Length - remains, remains, cancellationToken);
Assert.True(readLength > 0);
remains -= readLength;
}
Assert.Equal(s_ping, buffer);
await t;
t = server.WriteAsync(s_pong, cancellationToken);
remains = s_pong.Length;
while (remains > 0)
{
int readLength = await client.ReadAsync(buffer, buffer.Length - remains, remains, cancellationToken);
Assert.True(readLength > 0);
remains -= readLength;
}
Assert.Equal(s_pong, buffer);
await t;
}
internal static string GetTestSNIName(string testMethodName, params SslProtocols?[] protocols)
{
static string ProtocolToString(SslProtocols? protocol)
{
return (protocol?.ToString() ?? "null").Replace(", ", "-");
}
var args = string.Join(".", protocols.Select(p => ProtocolToString(p)));
var name = testMethodName.Length > 63 ? testMethodName.Substring(0, 63) : testMethodName;
name = $"{name}.{args}";
if (PlatformDetection.IsAndroid)
{
// Android does not support underscores in host names
name = name.Replace("_", string.Empty);
}
return name;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Net.Test.Common;
using System.Security.Authentication;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography.X509Certificates.Tests.Common;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Security.Tests
{
public static class TestHelper
{
private static readonly X509KeyUsageExtension s_eeKeyUsage =
new X509KeyUsageExtension(
X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.KeyEncipherment | X509KeyUsageFlags.DataEncipherment,
critical: false);
private static readonly X509EnhancedKeyUsageExtension s_tlsServerEku =
new X509EnhancedKeyUsageExtension(
new OidCollection
{
new Oid("1.3.6.1.5.5.7.3.1", null)
},
false);
private static readonly X509EnhancedKeyUsageExtension s_tlsClientEku =
new X509EnhancedKeyUsageExtension(
new OidCollection
{
new Oid("1.3.6.1.5.5.7.3.2", null)
},
false);
private static readonly X509BasicConstraintsExtension s_eeConstraints =
new X509BasicConstraintsExtension(false, false, 0, false);
public static readonly byte[] s_ping = Encoding.UTF8.GetBytes("PING");
public static readonly byte[] s_pong = Encoding.UTF8.GetBytes("PONG");
public static (SslStream ClientStream, SslStream ServerStream) GetConnectedSslStreams()
{
(Stream clientStream, Stream serverStream) = GetConnectedStreams();
return (new SslStream(clientStream), new SslStream(serverStream));
}
public static (Stream ClientStream, Stream ServerStream) GetConnectedStreams()
{
if (Capability.SecurityForceSocketStreams())
{
// DOTNET_TEST_NET_SECURITY_FORCE_SOCKET_STREAMS is set.
return GetConnectedTcpStreams();
}
return ConnectedStreams.CreateBidirectional(initialBufferSize: 4096, maxBufferSize: int.MaxValue);
}
internal static (NetworkStream ClientStream, NetworkStream ServerStream) GetConnectedTcpStreams()
{
using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
listener.Listen(1);
var clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
clientSocket.Connect(listener.LocalEndPoint);
Socket serverSocket = listener.Accept();
serverSocket.NoDelay = true;
clientSocket.NoDelay = true;
return (new NetworkStream(clientSocket, ownsSocket: true), new NetworkStream(serverSocket, ownsSocket: true));
}
}
internal static void CleanupCertificates([CallerMemberName] string? testName = null)
{
string caName = $"O={testName}";
try
{
using (X509Store store = new X509Store(StoreName.CertificateAuthority, StoreLocation.LocalMachine))
{
store.Open(OpenFlags.ReadWrite);
foreach (X509Certificate2 cert in store.Certificates)
{
if (cert.Subject.Contains(caName))
{
store.Remove(cert);
}
}
}
}
catch { };
try
{
using (X509Store store = new X509Store(StoreName.CertificateAuthority, StoreLocation.CurrentUser))
{
store.Open(OpenFlags.ReadWrite);
foreach (X509Certificate2 cert in store.Certificates)
{
if (cert.Subject.Contains(caName))
{
store.Remove(cert);
}
}
}
}
catch { };
}
internal static (X509Certificate2 certificate, X509Certificate2Collection) GenerateCertificates(string targetName, [CallerMemberName] string? testName = null, bool longChain = false, bool serverCertificate = true)
{
const int keySize = 2048;
if (PlatformDetection.IsWindows && testName != null)
{
CleanupCertificates(testName);
}
X509Certificate2Collection chain = new X509Certificate2Collection();
X509ExtensionCollection extensions = new X509ExtensionCollection();
SubjectAlternativeNameBuilder builder = new SubjectAlternativeNameBuilder();
builder.AddDnsName(targetName);
extensions.Add(builder.Build());
extensions.Add(s_eeConstraints);
extensions.Add(s_eeKeyUsage);
extensions.Add(serverCertificate ? s_tlsServerEku : s_tlsClientEku);
CertificateAuthority.BuildPrivatePki(
PkiOptions.IssuerRevocationViaCrl,
out RevocationResponder responder,
out CertificateAuthority root,
out CertificateAuthority[] intermediates,
out X509Certificate2 endEntity,
intermediateAuthorityCount: longChain ? 3 : 1,
subjectName: targetName,
testName: testName,
keySize: keySize,
extensions: extensions);
// Walk the intermediates backwards so we build the chain collection as
// Issuer3
// Issuer2
// Issuer1
// Root
for (int i = intermediates.Length - 1; i >= 0; i--)
{
CertificateAuthority authority = intermediates[i];
chain.Add(authority.CloneIssuerCert());
authority.Dispose();
}
chain.Add(root.CloneIssuerCert());
responder.Dispose();
root.Dispose();
if (PlatformDetection.IsWindows)
{
X509Certificate2 ephemeral = endEntity;
endEntity = new X509Certificate2(endEntity.Export(X509ContentType.Pfx));
ephemeral.Dispose();
}
return (endEntity, chain);
}
internal static async Task PingPong(SslStream client, SslStream server, CancellationToken cancellationToken = default)
{
byte[] buffer = new byte[s_ping.Length];
ValueTask t = client.WriteAsync(s_ping, cancellationToken);
int remains = s_ping.Length;
while (remains > 0)
{
int readLength = await server.ReadAsync(buffer, buffer.Length - remains, remains, cancellationToken);
Assert.True(readLength > 0);
remains -= readLength;
}
Assert.Equal(s_ping, buffer);
await t;
t = server.WriteAsync(s_pong, cancellationToken);
remains = s_pong.Length;
while (remains > 0)
{
int readLength = await client.ReadAsync(buffer, buffer.Length - remains, remains, cancellationToken);
Assert.True(readLength > 0);
remains -= readLength;
}
Assert.Equal(s_pong, buffer);
await t;
}
internal static string GetTestSNIName(string testMethodName, params SslProtocols?[] protocols)
{
static string ProtocolToString(SslProtocols? protocol)
{
return (protocol?.ToString() ?? "null").Replace(", ", "-");
}
var args = string.Join(".", protocols.Select(p => ProtocolToString(p)));
var name = testMethodName.Length > 63 ? testMethodName.Substring(0, 63) : testMethodName;
name = $"{name}.{args}";
if (PlatformDetection.IsAndroid)
{
// Android does not support underscores in host names
name = name.Replace("_", string.Empty);
}
return name;
}
}
}
| -1 |
dotnet/runtime | 66,046 | Fix handling of atomic nodes in RegexCompiler / source generator | We weren't properly resetting the stack position, so if we had an atomic group that contained something that backtracked, any backtracking positions left on the stack by that nested construct would then be consumed by a previous backtracking construct and lead to it reading the wrong state. | stephentoub | 2022-03-02T01:17:05Z | 2022-03-03T16:24:40Z | fdbdb9a81d2974b38c4c6c3dea9c3d2bf1d4b7d8 | b410984a6287b722b7bd215441504fe78ecb2ca0 | Fix handling of atomic nodes in RegexCompiler / source generator. We weren't properly resetting the stack position, so if we had an atomic group that contained something that backtracked, any backtracking positions left on the stack by that nested construct would then be consumed by a previous backtracking construct and lead to it reading the wrong state. | ./src/libraries/System.Private.DataContractSerialization/src/System/Text/Base64Encoding.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.Diagnostics;
using System.Runtime.Serialization; //For SR
using System.Globalization;
namespace System.Text
{
internal sealed class Base64Encoding : Encoding
{
private static ReadOnlySpan<byte> Char2val => new byte[128] // rely on C# compiler optimization to eliminate allocation
{
/* 0-15 */ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
/* 16-31 */ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
/* 32-47 */ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 62, 0xFF, 0xFF, 0xFF, 63,
/* 48-63 */ 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 0xFF, 0xFF, 0xFF, 64, 0xFF, 0xFF,
/* 64-79 */ 0xFF, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
/* 80-95 */ 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
/* 96-111 */ 0xFF, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
/* 112-127 */ 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
};
private const string Val2Char = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
private static ReadOnlySpan<byte> Val2byte => new byte[]
{
(byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N', (byte)'O', (byte)'P',
(byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f',
(byte)'g', (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', (byte)'v',
(byte)'w', (byte)'x', (byte)'y', (byte)'z', (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'+', (byte)'/'
};
public override int GetMaxByteCount(int charCount)
{
if (charCount < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charCount), SR.ValueMustBeNonNegative));
if ((charCount % 4) != 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.XmlInvalidBase64Length, charCount.ToString())));
return charCount / 4 * 3;
}
private bool IsValidLeadBytes(int v1, int v2, int v3, int v4)
{
// First two chars of a four char base64 sequence can't be ==, and must be valid
return ((v1 | v2) < 64) && ((v3 | v4) != 0xFF);
}
private bool IsValidTailBytes(int v3, int v4)
{
// If the third char is = then the fourth char must be =
return !(v3 == 64 && v4 != 64);
}
public unsafe override int GetByteCount(char[] chars!!, int index, int count)
{
if (index < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(index), SR.ValueMustBeNonNegative));
if (index > chars.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(index), SR.Format(SR.OffsetExceedsBufferSize, chars.Length)));
if (count < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.ValueMustBeNonNegative));
if (count > chars.Length - index)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.SizeExceedsRemainingBufferSpace, chars.Length - index)));
if (count == 0)
return 0;
if ((count % 4) != 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.XmlInvalidBase64Length, count.ToString())));
fixed (byte* _char2val = &Char2val[0])
{
fixed (char* _chars = &chars[index])
{
int totalCount = 0;
char* pch = _chars;
char* pchMax = _chars + count;
while (pch < pchMax)
{
DiagnosticUtility.DebugAssert(pch + 4 <= pchMax, "");
char pch0 = pch[0];
char pch1 = pch[1];
char pch2 = pch[2];
char pch3 = pch[3];
if ((pch0 | pch1 | pch2 | pch3) >= 128)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.XmlInvalidBase64Sequence, new string(pch, 0, 4), index + (int)(pch - _chars))));
// xx765432 xx107654 xx321076 xx543210
// 76543210 76543210 76543210
int v1 = _char2val[pch0];
int v2 = _char2val[pch1];
int v3 = _char2val[pch2];
int v4 = _char2val[pch3];
if (!IsValidLeadBytes(v1, v2, v3, v4) || !IsValidTailBytes(v3, v4))
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.XmlInvalidBase64Sequence, new string(pch, 0, 4), index + (int)(pch - _chars))));
int byteCount = (v4 != 64 ? 3 : (v3 != 64 ? 2 : 1));
totalCount += byteCount;
pch += 4;
}
return totalCount;
}
}
}
public unsafe override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex)
{
ArgumentNullException.ThrowIfNull(chars);
if (charIndex < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charIndex), SR.ValueMustBeNonNegative));
if (charIndex > chars.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charIndex), SR.Format(SR.OffsetExceedsBufferSize, chars.Length)));
if (charCount < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charCount), SR.ValueMustBeNonNegative));
if (charCount > chars.Length - charIndex)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charCount), SR.Format(SR.SizeExceedsRemainingBufferSpace, chars.Length - charIndex)));
ArgumentNullException.ThrowIfNull(bytes);
if (byteIndex < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteIndex), SR.ValueMustBeNonNegative));
if (byteIndex > bytes.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteIndex), SR.Format(SR.OffsetExceedsBufferSize, bytes.Length)));
if (charCount == 0)
return 0;
if ((charCount % 4) != 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.XmlInvalidBase64Length, charCount.ToString())));
fixed (byte* _char2val = &Char2val[0])
{
fixed (char* _chars = &chars[charIndex])
{
fixed (byte* _bytes = &bytes[byteIndex])
{
char* pch = _chars;
char* pchMax = _chars + charCount;
byte* pb = _bytes;
byte* pbMax = _bytes + bytes.Length - byteIndex;
while (pch < pchMax)
{
DiagnosticUtility.DebugAssert(pch + 4 <= pchMax, "");
char pch0 = pch[0];
char pch1 = pch[1];
char pch2 = pch[2];
char pch3 = pch[3];
if ((pch0 | pch1 | pch2 | pch3) >= 128)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.XmlInvalidBase64Sequence, new string(pch, 0, 4), charIndex + (int)(pch - _chars))));
// xx765432 xx107654 xx321076 xx543210
// 76543210 76543210 76543210
int v1 = _char2val[pch0];
int v2 = _char2val[pch1];
int v3 = _char2val[pch2];
int v4 = _char2val[pch3];
if (!IsValidLeadBytes(v1, v2, v3, v4) || !IsValidTailBytes(v3, v4))
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.XmlInvalidBase64Sequence, new string(pch, 0, 4), charIndex + (int)(pch - _chars))));
int byteCount = (v4 != 64 ? 3 : (v3 != 64 ? 2 : 1));
if (pb + byteCount > pbMax)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.XmlArrayTooSmall, nameof(bytes)));
pb[0] = (byte)((v1 << 2) | ((v2 >> 4) & 0x03));
if (byteCount > 1)
{
pb[1] = (byte)((v2 << 4) | ((v3 >> 2) & 0x0F));
if (byteCount > 2)
{
pb[2] = (byte)((v3 << 6) | ((v4 >> 0) & 0x3F));
}
}
pb += byteCount;
pch += 4;
}
return (int)(pb - _bytes);
}
}
}
}
public unsafe int GetBytes(byte[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex)
{
ArgumentNullException.ThrowIfNull(chars);
if (charIndex < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charIndex), SR.ValueMustBeNonNegative));
if (charIndex > chars.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charIndex), SR.Format(SR.OffsetExceedsBufferSize, chars.Length)));
if (charCount < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charCount), SR.ValueMustBeNonNegative));
if (charCount > chars.Length - charIndex)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charCount), SR.Format(SR.SizeExceedsRemainingBufferSpace, chars.Length - charIndex)));
ArgumentNullException.ThrowIfNull(bytes);
if (byteIndex < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteIndex), SR.ValueMustBeNonNegative));
if (byteIndex > bytes.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteIndex), SR.Format(SR.OffsetExceedsBufferSize, bytes.Length)));
if (charCount == 0)
return 0;
if ((charCount % 4) != 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.XmlInvalidBase64Length, charCount.ToString())));
fixed (byte* _char2val = &Char2val[0])
{
fixed (byte* _chars = &chars[charIndex])
{
fixed (byte* _bytes = &bytes[byteIndex])
{
byte* pch = _chars;
byte* pchMax = _chars + charCount;
byte* pb = _bytes;
byte* pbMax = _bytes + bytes.Length - byteIndex;
while (pch < pchMax)
{
DiagnosticUtility.DebugAssert(pch + 4 <= pchMax, "");
byte pch0 = pch[0];
byte pch1 = pch[1];
byte pch2 = pch[2];
byte pch3 = pch[3];
if ((pch0 | pch1 | pch2 | pch3) >= 128)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.XmlInvalidBase64Sequence, "?", charIndex + (int)(pch - _chars))));
// xx765432 xx107654 xx321076 xx543210
// 76543210 76543210 76543210
int v1 = _char2val[pch0];
int v2 = _char2val[pch1];
int v3 = _char2val[pch2];
int v4 = _char2val[pch3];
if (!IsValidLeadBytes(v1, v2, v3, v4) || !IsValidTailBytes(v3, v4))
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.XmlInvalidBase64Sequence, "?", charIndex + (int)(pch - _chars))));
int byteCount = (v4 != 64 ? 3 : (v3 != 64 ? 2 : 1));
if (pb + byteCount > pbMax)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.XmlArrayTooSmall, nameof(bytes)));
pb[0] = (byte)((v1 << 2) | ((v2 >> 4) & 0x03));
if (byteCount > 1)
{
pb[1] = unchecked((byte)((v2 << 4) | ((v3 >> 2) & 0x0F)));
if (byteCount > 2)
{
pb[2] = unchecked((byte)((v3 << 6) | ((v4 >> 0) & 0x3F)));
}
}
pb += byteCount;
pch += 4;
}
return (int)(pb - _bytes);
}
}
}
}
public override int GetMaxCharCount(int byteCount)
{
if (byteCount < 0 || byteCount > int.MaxValue / 4 * 3 - 2)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteCount), SR.Format(SR.ValueMustBeInRange, 0, int.MaxValue / 4 * 3 - 2)));
return ((byteCount + 2) / 3) * 4;
}
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 System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteIndex), SR.ValueMustBeNonNegative));
if (byteIndex > bytes.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteIndex), SR.Format(SR.OffsetExceedsBufferSize, bytes.Length)));
if (byteCount < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteCount), SR.ValueMustBeNonNegative));
if (byteCount > bytes.Length - byteIndex)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteCount), SR.Format(SR.SizeExceedsRemainingBufferSpace, bytes.Length - byteIndex)));
int charCount = GetCharCount(bytes, byteIndex, byteCount);
ArgumentNullException.ThrowIfNull(chars);
if (charIndex < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charIndex), SR.ValueMustBeNonNegative));
if (charIndex > chars.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charIndex), SR.Format(SR.OffsetExceedsBufferSize, chars.Length)));
if (charCount < 0 || charCount > chars.Length - charIndex)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.XmlArrayTooSmall, nameof(chars)));
// We've computed exactly how many chars there are and verified that
// there's enough space in the char buffer, so we can proceed without
// checking the charCount.
if (byteCount > 0)
{
fixed (char* _val2char = Val2Char)
{
fixed (byte* _bytes = &bytes[byteIndex])
{
fixed (char* _chars = &chars[charIndex])
{
byte* pb = _bytes;
byte* pbMax = pb + byteCount - 3;
char* pch = _chars;
// Convert chunks of 3 bytes to 4 chars
while (pb <= pbMax)
{
// 76543210 76543210 76543210
// xx765432 xx107654 xx321076 xx543210
// Inspect the code carefully before you change this
pch[0] = _val2char[(pb[0] >> 2)];
pch[1] = _val2char[((pb[0] & 0x03) << 4) | (pb[1] >> 4)];
pch[2] = _val2char[((pb[1] & 0x0F) << 2) | (pb[2] >> 6)];
pch[3] = _val2char[pb[2] & 0x3F];
pb += 3;
pch += 4;
}
// Handle 1 or 2 trailing bytes
if (pb - pbMax == 2)
{
// 1 trailing byte
// 76543210 xxxxxxxx xxxxxxxx
// xx765432 xx10xxxx xxxxxxxx xxxxxxxx
pch[0] = _val2char[(pb[0] >> 2)];
pch[1] = _val2char[((pb[0] & 0x03) << 4)];
pch[2] = '=';
pch[3] = '=';
}
else if (pb - pbMax == 1)
{
// 2 trailing bytes
// 76543210 76543210 xxxxxxxx
// xx765432 xx107654 xx3210xx xxxxxxxx
pch[0] = _val2char[(pb[0] >> 2)];
pch[1] = _val2char[((pb[0] & 0x03) << 4) | (pb[1] >> 4)];
pch[2] = _val2char[((pb[1] & 0x0F) << 2)];
pch[3] = '=';
}
else
{
// 0 trailing bytes
DiagnosticUtility.DebugAssert(pb - pbMax == 3, "");
}
}
}
}
}
return charCount;
}
public unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, byte[] chars, int charIndex)
{
ArgumentNullException.ThrowIfNull(bytes);
if (byteIndex < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteIndex), SR.ValueMustBeNonNegative));
if (byteIndex > bytes.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteIndex), SR.Format(SR.OffsetExceedsBufferSize, bytes.Length)));
if (byteCount < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteCount), SR.ValueMustBeNonNegative));
if (byteCount > bytes.Length - byteIndex)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteCount), SR.Format(SR.SizeExceedsRemainingBufferSpace, bytes.Length - byteIndex)));
int charCount = GetCharCount(bytes, byteIndex, byteCount);
ArgumentNullException.ThrowIfNull(chars);
if (charIndex < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charIndex), SR.ValueMustBeNonNegative));
if (charIndex > chars.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charIndex), SR.Format(SR.OffsetExceedsBufferSize, chars.Length)));
if (charCount < 0 || charCount > chars.Length - charIndex)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.XmlArrayTooSmall, nameof(chars)));
// We've computed exactly how many chars there are and verified that
// there's enough space in the char buffer, so we can proceed without
// checking the charCount.
if (byteCount > 0)
{
fixed (byte* _val2byte = &Val2byte[0])
{
fixed (byte* _bytes = &bytes[byteIndex])
{
fixed (byte* _chars = &chars[charIndex])
{
byte* pb = _bytes;
byte* pbMax = pb + byteCount - 3;
byte* pch = _chars;
// Convert chunks of 3 bytes to 4 chars
while (pb <= pbMax)
{
// 76543210 76543210 76543210
// xx765432 xx107654 xx321076 xx543210
// Inspect the code carefully before you change this
pch[0] = _val2byte[(pb[0] >> 2)];
pch[1] = _val2byte[((pb[0] & 0x03) << 4) | (pb[1] >> 4)];
pch[2] = _val2byte[((pb[1] & 0x0F) << 2) | (pb[2] >> 6)];
pch[3] = _val2byte[pb[2] & 0x3F];
pb += 3;
pch += 4;
}
// Handle 1 or 2 trailing bytes
if (pb - pbMax == 2)
{
// 1 trailing byte
// 76543210 xxxxxxxx xxxxxxxx
// xx765432 xx10xxxx xxxxxxxx xxxxxxxx
pch[0] = _val2byte[(pb[0] >> 2)];
pch[1] = _val2byte[((pb[0] & 0x03) << 4)];
pch[2] = (byte)'=';
pch[3] = (byte)'=';
}
else if (pb - pbMax == 1)
{
// 2 trailing bytes
// 76543210 76543210 xxxxxxxx
// xx765432 xx107654 xx3210xx xxxxxxxx
pch[0] = _val2byte[(pb[0] >> 2)];
pch[1] = _val2byte[((pb[0] & 0x03) << 4) | (pb[1] >> 4)];
pch[2] = _val2byte[((pb[1] & 0x0F) << 2)];
pch[3] = (byte)'=';
}
else
{
// 0 trailing bytes
DiagnosticUtility.DebugAssert(pb - pbMax == 3, "");
}
}
}
}
}
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.Text;
using System.Diagnostics;
using System.Runtime.Serialization; //For SR
using System.Globalization;
namespace System.Text
{
internal sealed class Base64Encoding : Encoding
{
private static ReadOnlySpan<byte> Char2val => new byte[128] // rely on C# compiler optimization to eliminate allocation
{
/* 0-15 */ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
/* 16-31 */ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
/* 32-47 */ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 62, 0xFF, 0xFF, 0xFF, 63,
/* 48-63 */ 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 0xFF, 0xFF, 0xFF, 64, 0xFF, 0xFF,
/* 64-79 */ 0xFF, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
/* 80-95 */ 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
/* 96-111 */ 0xFF, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
/* 112-127 */ 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
};
private const string Val2Char = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
private static ReadOnlySpan<byte> Val2byte => new byte[]
{
(byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N', (byte)'O', (byte)'P',
(byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f',
(byte)'g', (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', (byte)'v',
(byte)'w', (byte)'x', (byte)'y', (byte)'z', (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'+', (byte)'/'
};
public override int GetMaxByteCount(int charCount)
{
if (charCount < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charCount), SR.ValueMustBeNonNegative));
if ((charCount % 4) != 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.XmlInvalidBase64Length, charCount.ToString())));
return charCount / 4 * 3;
}
private bool IsValidLeadBytes(int v1, int v2, int v3, int v4)
{
// First two chars of a four char base64 sequence can't be ==, and must be valid
return ((v1 | v2) < 64) && ((v3 | v4) != 0xFF);
}
private bool IsValidTailBytes(int v3, int v4)
{
// If the third char is = then the fourth char must be =
return !(v3 == 64 && v4 != 64);
}
public unsafe override int GetByteCount(char[] chars!!, int index, int count)
{
if (index < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(index), SR.ValueMustBeNonNegative));
if (index > chars.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(index), SR.Format(SR.OffsetExceedsBufferSize, chars.Length)));
if (count < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.ValueMustBeNonNegative));
if (count > chars.Length - index)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.SizeExceedsRemainingBufferSpace, chars.Length - index)));
if (count == 0)
return 0;
if ((count % 4) != 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.XmlInvalidBase64Length, count.ToString())));
fixed (byte* _char2val = &Char2val[0])
{
fixed (char* _chars = &chars[index])
{
int totalCount = 0;
char* pch = _chars;
char* pchMax = _chars + count;
while (pch < pchMax)
{
DiagnosticUtility.DebugAssert(pch + 4 <= pchMax, "");
char pch0 = pch[0];
char pch1 = pch[1];
char pch2 = pch[2];
char pch3 = pch[3];
if ((pch0 | pch1 | pch2 | pch3) >= 128)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.XmlInvalidBase64Sequence, new string(pch, 0, 4), index + (int)(pch - _chars))));
// xx765432 xx107654 xx321076 xx543210
// 76543210 76543210 76543210
int v1 = _char2val[pch0];
int v2 = _char2val[pch1];
int v3 = _char2val[pch2];
int v4 = _char2val[pch3];
if (!IsValidLeadBytes(v1, v2, v3, v4) || !IsValidTailBytes(v3, v4))
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.XmlInvalidBase64Sequence, new string(pch, 0, 4), index + (int)(pch - _chars))));
int byteCount = (v4 != 64 ? 3 : (v3 != 64 ? 2 : 1));
totalCount += byteCount;
pch += 4;
}
return totalCount;
}
}
}
public unsafe override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex)
{
ArgumentNullException.ThrowIfNull(chars);
if (charIndex < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charIndex), SR.ValueMustBeNonNegative));
if (charIndex > chars.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charIndex), SR.Format(SR.OffsetExceedsBufferSize, chars.Length)));
if (charCount < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charCount), SR.ValueMustBeNonNegative));
if (charCount > chars.Length - charIndex)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charCount), SR.Format(SR.SizeExceedsRemainingBufferSpace, chars.Length - charIndex)));
ArgumentNullException.ThrowIfNull(bytes);
if (byteIndex < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteIndex), SR.ValueMustBeNonNegative));
if (byteIndex > bytes.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteIndex), SR.Format(SR.OffsetExceedsBufferSize, bytes.Length)));
if (charCount == 0)
return 0;
if ((charCount % 4) != 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.XmlInvalidBase64Length, charCount.ToString())));
fixed (byte* _char2val = &Char2val[0])
{
fixed (char* _chars = &chars[charIndex])
{
fixed (byte* _bytes = &bytes[byteIndex])
{
char* pch = _chars;
char* pchMax = _chars + charCount;
byte* pb = _bytes;
byte* pbMax = _bytes + bytes.Length - byteIndex;
while (pch < pchMax)
{
DiagnosticUtility.DebugAssert(pch + 4 <= pchMax, "");
char pch0 = pch[0];
char pch1 = pch[1];
char pch2 = pch[2];
char pch3 = pch[3];
if ((pch0 | pch1 | pch2 | pch3) >= 128)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.XmlInvalidBase64Sequence, new string(pch, 0, 4), charIndex + (int)(pch - _chars))));
// xx765432 xx107654 xx321076 xx543210
// 76543210 76543210 76543210
int v1 = _char2val[pch0];
int v2 = _char2val[pch1];
int v3 = _char2val[pch2];
int v4 = _char2val[pch3];
if (!IsValidLeadBytes(v1, v2, v3, v4) || !IsValidTailBytes(v3, v4))
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.XmlInvalidBase64Sequence, new string(pch, 0, 4), charIndex + (int)(pch - _chars))));
int byteCount = (v4 != 64 ? 3 : (v3 != 64 ? 2 : 1));
if (pb + byteCount > pbMax)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.XmlArrayTooSmall, nameof(bytes)));
pb[0] = (byte)((v1 << 2) | ((v2 >> 4) & 0x03));
if (byteCount > 1)
{
pb[1] = (byte)((v2 << 4) | ((v3 >> 2) & 0x0F));
if (byteCount > 2)
{
pb[2] = (byte)((v3 << 6) | ((v4 >> 0) & 0x3F));
}
}
pb += byteCount;
pch += 4;
}
return (int)(pb - _bytes);
}
}
}
}
public unsafe int GetBytes(byte[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex)
{
ArgumentNullException.ThrowIfNull(chars);
if (charIndex < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charIndex), SR.ValueMustBeNonNegative));
if (charIndex > chars.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charIndex), SR.Format(SR.OffsetExceedsBufferSize, chars.Length)));
if (charCount < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charCount), SR.ValueMustBeNonNegative));
if (charCount > chars.Length - charIndex)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charCount), SR.Format(SR.SizeExceedsRemainingBufferSpace, chars.Length - charIndex)));
ArgumentNullException.ThrowIfNull(bytes);
if (byteIndex < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteIndex), SR.ValueMustBeNonNegative));
if (byteIndex > bytes.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteIndex), SR.Format(SR.OffsetExceedsBufferSize, bytes.Length)));
if (charCount == 0)
return 0;
if ((charCount % 4) != 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.XmlInvalidBase64Length, charCount.ToString())));
fixed (byte* _char2val = &Char2val[0])
{
fixed (byte* _chars = &chars[charIndex])
{
fixed (byte* _bytes = &bytes[byteIndex])
{
byte* pch = _chars;
byte* pchMax = _chars + charCount;
byte* pb = _bytes;
byte* pbMax = _bytes + bytes.Length - byteIndex;
while (pch < pchMax)
{
DiagnosticUtility.DebugAssert(pch + 4 <= pchMax, "");
byte pch0 = pch[0];
byte pch1 = pch[1];
byte pch2 = pch[2];
byte pch3 = pch[3];
if ((pch0 | pch1 | pch2 | pch3) >= 128)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.XmlInvalidBase64Sequence, "?", charIndex + (int)(pch - _chars))));
// xx765432 xx107654 xx321076 xx543210
// 76543210 76543210 76543210
int v1 = _char2val[pch0];
int v2 = _char2val[pch1];
int v3 = _char2val[pch2];
int v4 = _char2val[pch3];
if (!IsValidLeadBytes(v1, v2, v3, v4) || !IsValidTailBytes(v3, v4))
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.XmlInvalidBase64Sequence, "?", charIndex + (int)(pch - _chars))));
int byteCount = (v4 != 64 ? 3 : (v3 != 64 ? 2 : 1));
if (pb + byteCount > pbMax)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.XmlArrayTooSmall, nameof(bytes)));
pb[0] = (byte)((v1 << 2) | ((v2 >> 4) & 0x03));
if (byteCount > 1)
{
pb[1] = unchecked((byte)((v2 << 4) | ((v3 >> 2) & 0x0F)));
if (byteCount > 2)
{
pb[2] = unchecked((byte)((v3 << 6) | ((v4 >> 0) & 0x3F)));
}
}
pb += byteCount;
pch += 4;
}
return (int)(pb - _bytes);
}
}
}
}
public override int GetMaxCharCount(int byteCount)
{
if (byteCount < 0 || byteCount > int.MaxValue / 4 * 3 - 2)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteCount), SR.Format(SR.ValueMustBeInRange, 0, int.MaxValue / 4 * 3 - 2)));
return ((byteCount + 2) / 3) * 4;
}
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 System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteIndex), SR.ValueMustBeNonNegative));
if (byteIndex > bytes.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteIndex), SR.Format(SR.OffsetExceedsBufferSize, bytes.Length)));
if (byteCount < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteCount), SR.ValueMustBeNonNegative));
if (byteCount > bytes.Length - byteIndex)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteCount), SR.Format(SR.SizeExceedsRemainingBufferSpace, bytes.Length - byteIndex)));
int charCount = GetCharCount(bytes, byteIndex, byteCount);
ArgumentNullException.ThrowIfNull(chars);
if (charIndex < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charIndex), SR.ValueMustBeNonNegative));
if (charIndex > chars.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charIndex), SR.Format(SR.OffsetExceedsBufferSize, chars.Length)));
if (charCount < 0 || charCount > chars.Length - charIndex)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.XmlArrayTooSmall, nameof(chars)));
// We've computed exactly how many chars there are and verified that
// there's enough space in the char buffer, so we can proceed without
// checking the charCount.
if (byteCount > 0)
{
fixed (char* _val2char = Val2Char)
{
fixed (byte* _bytes = &bytes[byteIndex])
{
fixed (char* _chars = &chars[charIndex])
{
byte* pb = _bytes;
byte* pbMax = pb + byteCount - 3;
char* pch = _chars;
// Convert chunks of 3 bytes to 4 chars
while (pb <= pbMax)
{
// 76543210 76543210 76543210
// xx765432 xx107654 xx321076 xx543210
// Inspect the code carefully before you change this
pch[0] = _val2char[(pb[0] >> 2)];
pch[1] = _val2char[((pb[0] & 0x03) << 4) | (pb[1] >> 4)];
pch[2] = _val2char[((pb[1] & 0x0F) << 2) | (pb[2] >> 6)];
pch[3] = _val2char[pb[2] & 0x3F];
pb += 3;
pch += 4;
}
// Handle 1 or 2 trailing bytes
if (pb - pbMax == 2)
{
// 1 trailing byte
// 76543210 xxxxxxxx xxxxxxxx
// xx765432 xx10xxxx xxxxxxxx xxxxxxxx
pch[0] = _val2char[(pb[0] >> 2)];
pch[1] = _val2char[((pb[0] & 0x03) << 4)];
pch[2] = '=';
pch[3] = '=';
}
else if (pb - pbMax == 1)
{
// 2 trailing bytes
// 76543210 76543210 xxxxxxxx
// xx765432 xx107654 xx3210xx xxxxxxxx
pch[0] = _val2char[(pb[0] >> 2)];
pch[1] = _val2char[((pb[0] & 0x03) << 4) | (pb[1] >> 4)];
pch[2] = _val2char[((pb[1] & 0x0F) << 2)];
pch[3] = '=';
}
else
{
// 0 trailing bytes
DiagnosticUtility.DebugAssert(pb - pbMax == 3, "");
}
}
}
}
}
return charCount;
}
public unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, byte[] chars, int charIndex)
{
ArgumentNullException.ThrowIfNull(bytes);
if (byteIndex < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteIndex), SR.ValueMustBeNonNegative));
if (byteIndex > bytes.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteIndex), SR.Format(SR.OffsetExceedsBufferSize, bytes.Length)));
if (byteCount < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteCount), SR.ValueMustBeNonNegative));
if (byteCount > bytes.Length - byteIndex)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteCount), SR.Format(SR.SizeExceedsRemainingBufferSpace, bytes.Length - byteIndex)));
int charCount = GetCharCount(bytes, byteIndex, byteCount);
ArgumentNullException.ThrowIfNull(chars);
if (charIndex < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charIndex), SR.ValueMustBeNonNegative));
if (charIndex > chars.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charIndex), SR.Format(SR.OffsetExceedsBufferSize, chars.Length)));
if (charCount < 0 || charCount > chars.Length - charIndex)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.XmlArrayTooSmall, nameof(chars)));
// We've computed exactly how many chars there are and verified that
// there's enough space in the char buffer, so we can proceed without
// checking the charCount.
if (byteCount > 0)
{
fixed (byte* _val2byte = &Val2byte[0])
{
fixed (byte* _bytes = &bytes[byteIndex])
{
fixed (byte* _chars = &chars[charIndex])
{
byte* pb = _bytes;
byte* pbMax = pb + byteCount - 3;
byte* pch = _chars;
// Convert chunks of 3 bytes to 4 chars
while (pb <= pbMax)
{
// 76543210 76543210 76543210
// xx765432 xx107654 xx321076 xx543210
// Inspect the code carefully before you change this
pch[0] = _val2byte[(pb[0] >> 2)];
pch[1] = _val2byte[((pb[0] & 0x03) << 4) | (pb[1] >> 4)];
pch[2] = _val2byte[((pb[1] & 0x0F) << 2) | (pb[2] >> 6)];
pch[3] = _val2byte[pb[2] & 0x3F];
pb += 3;
pch += 4;
}
// Handle 1 or 2 trailing bytes
if (pb - pbMax == 2)
{
// 1 trailing byte
// 76543210 xxxxxxxx xxxxxxxx
// xx765432 xx10xxxx xxxxxxxx xxxxxxxx
pch[0] = _val2byte[(pb[0] >> 2)];
pch[1] = _val2byte[((pb[0] & 0x03) << 4)];
pch[2] = (byte)'=';
pch[3] = (byte)'=';
}
else if (pb - pbMax == 1)
{
// 2 trailing bytes
// 76543210 76543210 xxxxxxxx
// xx765432 xx107654 xx3210xx xxxxxxxx
pch[0] = _val2byte[(pb[0] >> 2)];
pch[1] = _val2byte[((pb[0] & 0x03) << 4) | (pb[1] >> 4)];
pch[2] = _val2byte[((pb[1] & 0x0F) << 2)];
pch[3] = (byte)'=';
}
else
{
// 0 trailing bytes
DiagnosticUtility.DebugAssert(pb - pbMax == 3, "");
}
}
}
}
}
return charCount;
}
}
}
| -1 |
dotnet/runtime | 66,046 | Fix handling of atomic nodes in RegexCompiler / source generator | We weren't properly resetting the stack position, so if we had an atomic group that contained something that backtracked, any backtracking positions left on the stack by that nested construct would then be consumed by a previous backtracking construct and lead to it reading the wrong state. | stephentoub | 2022-03-02T01:17:05Z | 2022-03-03T16:24:40Z | fdbdb9a81d2974b38c4c6c3dea9c3d2bf1d4b7d8 | b410984a6287b722b7bd215441504fe78ecb2ca0 | Fix handling of atomic nodes in RegexCompiler / source generator. We weren't properly resetting the stack position, so if we had an atomic group that contained something that backtracked, any backtracking positions left on the stack by that nested construct would then be consumed by a previous backtracking construct and lead to it reading the wrong state. | ./src/libraries/System.Speech/src/Internal/SrgsCompiler/PropertyTag.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Runtime.InteropServices;
using System.Speech.Internal.SrgsParser;
namespace System.Speech.Internal.SrgsCompiler
{
internal sealed class PropertyTag : ParseElement, IPropertyTag
{
#region Constructors
internal PropertyTag(ParseElement parent, Backend backend)
: base(parent._rule)
{
}
#endregion
#region Internal Methods
// The probability that this item will be repeated.
void IPropertyTag.NameValue(IElement parent, string name, object value)
{
//Return if the Tag content is empty
string sValue = value as string;
if (string.IsNullOrEmpty(name) && (value == null || (sValue != null && string.IsNullOrEmpty((sValue).Trim()))))
{
return;
}
// Build semantic properties to attach to epsilon transition.
// <tag>Name=</tag> pszValue = null vValue = VT_EMPTY
// <tag>Name="string"</tag> pszValue = "string" vValue = VT_EMPTY
// <tag>Name=true</tag> pszValue = null vValue = VT_BOOL
// <tag>Name=123</tag> pszValue = null vValue = VT_I4
// <tag>Name=3.14</tag> pszValue = null vValue = VT_R8
if (!string.IsNullOrEmpty(name))
{
// Set property name
_propInfo._pszName = name;
}
else
{
// If no property, set the name to the anonymous property name
_propInfo._pszName = "=";
}
// Set property value
_propInfo._comValue = value;
#pragma warning disable 0618 // VarEnum is obsolete
if (value == null)
{
_propInfo._comType = VarEnum.VT_EMPTY;
}
else if (sValue != null)
{
_propInfo._comType = VarEnum.VT_EMPTY;
}
else if (value is int)
{
_propInfo._comType = VarEnum.VT_I4;
}
else if (value is double)
{
_propInfo._comType = VarEnum.VT_R8;
}
else if (value is bool)
{
_propInfo._comType = VarEnum.VT_BOOL;
}
else
{
// should never get here
System.Diagnostics.Debug.Assert(false);
}
#pragma warning restore 0618
}
void IElement.PostParse(IElement parentElement)
{
ParseElementCollection parent = (ParseElementCollection)parentElement;
_propInfo._ulId = (uint)parent._rule._iSerialize2;
// Attach the semantic properties on the parent element.
parent.AddSementicPropertyTag(_propInfo);
}
#endregion
#region Private Fields
private CfgGrammar.CfgProperty _propInfo = new();
#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.Runtime.InteropServices;
using System.Speech.Internal.SrgsParser;
namespace System.Speech.Internal.SrgsCompiler
{
internal sealed class PropertyTag : ParseElement, IPropertyTag
{
#region Constructors
internal PropertyTag(ParseElement parent, Backend backend)
: base(parent._rule)
{
}
#endregion
#region Internal Methods
// The probability that this item will be repeated.
void IPropertyTag.NameValue(IElement parent, string name, object value)
{
//Return if the Tag content is empty
string sValue = value as string;
if (string.IsNullOrEmpty(name) && (value == null || (sValue != null && string.IsNullOrEmpty((sValue).Trim()))))
{
return;
}
// Build semantic properties to attach to epsilon transition.
// <tag>Name=</tag> pszValue = null vValue = VT_EMPTY
// <tag>Name="string"</tag> pszValue = "string" vValue = VT_EMPTY
// <tag>Name=true</tag> pszValue = null vValue = VT_BOOL
// <tag>Name=123</tag> pszValue = null vValue = VT_I4
// <tag>Name=3.14</tag> pszValue = null vValue = VT_R8
if (!string.IsNullOrEmpty(name))
{
// Set property name
_propInfo._pszName = name;
}
else
{
// If no property, set the name to the anonymous property name
_propInfo._pszName = "=";
}
// Set property value
_propInfo._comValue = value;
#pragma warning disable 0618 // VarEnum is obsolete
if (value == null)
{
_propInfo._comType = VarEnum.VT_EMPTY;
}
else if (sValue != null)
{
_propInfo._comType = VarEnum.VT_EMPTY;
}
else if (value is int)
{
_propInfo._comType = VarEnum.VT_I4;
}
else if (value is double)
{
_propInfo._comType = VarEnum.VT_R8;
}
else if (value is bool)
{
_propInfo._comType = VarEnum.VT_BOOL;
}
else
{
// should never get here
System.Diagnostics.Debug.Assert(false);
}
#pragma warning restore 0618
}
void IElement.PostParse(IElement parentElement)
{
ParseElementCollection parent = (ParseElementCollection)parentElement;
_propInfo._ulId = (uint)parent._rule._iSerialize2;
// Attach the semantic properties on the parent element.
parent.AddSementicPropertyTag(_propInfo);
}
#endregion
#region Private Fields
private CfgGrammar.CfgProperty _propInfo = new();
#endregion
}
}
| -1 |
dotnet/runtime | 66,046 | Fix handling of atomic nodes in RegexCompiler / source generator | We weren't properly resetting the stack position, so if we had an atomic group that contained something that backtracked, any backtracking positions left on the stack by that nested construct would then be consumed by a previous backtracking construct and lead to it reading the wrong state. | stephentoub | 2022-03-02T01:17:05Z | 2022-03-03T16:24:40Z | fdbdb9a81d2974b38c4c6c3dea9c3d2bf1d4b7d8 | b410984a6287b722b7bd215441504fe78ecb2ca0 | Fix handling of atomic nodes in RegexCompiler / source generator. We weren't properly resetting the stack position, so if we had an atomic group that contained something that backtracked, any backtracking positions left on the stack by that nested construct would then be consumed by a previous backtracking construct and lead to it reading the wrong state. | ./src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/ProfileDataNode.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.Reflection.Metadata.Ecma335;
using ILCompiler.DependencyAnalysisFramework;
using Internal.Text;
using Internal.TypeSystem;
using Internal.TypeSystem.Ecma;
namespace ILCompiler.DependencyAnalysis.ReadyToRun
{
public class ProfileDataNode : EmbeddedObjectNode, ISymbolDefinitionNode
{
MethodWithGCInfo _methodNode;
private byte[] _profileData;
private int _ilSize;
private int _blockCount;
private TargetDetails _targetDetails;
public ProfileDataNode(MethodWithGCInfo methodNode, TargetDetails targetDetails)
{
_methodNode = methodNode;
_targetDetails = targetDetails;
}
public void SetProfileData(int ilSize, int blockCount, byte[] data)
{
Debug.Assert(_profileData == null); // This function should not be called twice on the same object
_profileData = data;
_ilSize = ilSize;
_blockCount = blockCount;
}
public override bool StaticDependenciesAreComputed => _profileData != null;
public override int ClassCode => 274394286;
private int OffsetFromStartOfObjectToSymbol
{
get
{
int offset = 0
// sizeof(CORCOMPILE_METHOD_PROFILE_LIST)
+ _targetDetails.PointerSize // (CORCOMPILE_METHOD_PROFILE_LIST::next)
// sizeof(CORBBTPROF_METHOD_HEADER)
+ sizeof(int) // (CORBBTPROF_METHOD_HEADER::size)
+ sizeof(int) // (CORBBTPROF_METHOD_HEADER::cDetail)
// Next field is a CORBBT_METHOD_INFO struct (CORBBTPROF_METHOD_HEADER::method)
+ sizeof(int) // (CORBBT_METHOD_INFO::token)
+ sizeof(int) // (CORBBT_METHOD_INFO::ILSize)
+ sizeof(int); // (CORBBT_METHOD_INFO::cBlock)
// At this offset lies the block counts
return offset;
}
}
int ISymbolDefinitionNode.Offset
{
get
{
// At this offset lies the block counts
return OffsetFromStartOfObjectToSymbol + OffsetFromBeginningOfArray;
}
}
int ISymbolNode.Offset => 0;
public void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb)
{
sb.Append("ProfileDataNode->");
_methodNode.AppendMangledName(nameMangler, sb);
}
protected override void OnMarked(NodeFactory factory)
{
factory.ProfileDataSection.AddEmbeddedObject(this);
}
public override void EncodeData(ref ObjectDataBuilder dataBuilder, NodeFactory factory, bool relocsOnly)
{
ProfileDataNode nextElementInList = ((ProfileDataSectionNode)ContainingNode).NextElementToEncode;
if (nextElementInList != null)
dataBuilder.EmitPointerReloc(nextElementInList, -OffsetFromStartOfObjectToSymbol);
else
dataBuilder.EmitZeroPointer();
if (relocsOnly)
{
return;
}
EcmaMethod ecmaMethod = (EcmaMethod)_methodNode.Method.GetTypicalMethodDefinition();
int startOffset = dataBuilder.CountBytes;
var reservation = dataBuilder.ReserveInt();
dataBuilder.EmitInt(0); // CORBBTPROF_METHOD_HEADER::cDetail
dataBuilder.EmitInt(ecmaMethod.MetadataReader.GetToken(ecmaMethod.Handle)); // CORBBT_METHOD_INFO::token
dataBuilder.EmitInt(_ilSize); // CORBBT_METHOD_INFO::ILSize
dataBuilder.EmitInt(_blockCount); // CORBBT_METHOD_INFO::cBlock
int sizeOfCORBBTPROF_METHOD_HEADER = dataBuilder.CountBytes - startOffset;
Debug.Assert(sizeOfCORBBTPROF_METHOD_HEADER == (OffsetFromStartOfObjectToSymbol - _targetDetails.PointerSize));
dataBuilder.EmitInt(reservation, sizeOfCORBBTPROF_METHOD_HEADER + _profileData.Length);
dataBuilder.EmitBytes(_profileData);
while ((dataBuilder.CountBytes & (dataBuilder.TargetPointerSize - 1)) != 0)
dataBuilder.EmitByte(0);
}
protected override string GetName(NodeFactory context)
{
Utf8StringBuilder sb = new Utf8StringBuilder();
sb.Append("ProfileDataNode->");
_methodNode.AppendMangledName(context.NameMangler, sb);
return sb.ToString();
}
public override IEnumerable<DependencyListEntry> GetStaticDependencies(NodeFactory context)
{
return Array.Empty<DependencyListEntry>();
}
public override int CompareToImpl(ISortableNode other, CompilerComparer comparer)
{
return comparer.Compare(_methodNode, ((ProfileDataNode)other)._methodNode);
}
}
}
| // 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.Reflection.Metadata.Ecma335;
using ILCompiler.DependencyAnalysisFramework;
using Internal.Text;
using Internal.TypeSystem;
using Internal.TypeSystem.Ecma;
namespace ILCompiler.DependencyAnalysis.ReadyToRun
{
public class ProfileDataNode : EmbeddedObjectNode, ISymbolDefinitionNode
{
MethodWithGCInfo _methodNode;
private byte[] _profileData;
private int _ilSize;
private int _blockCount;
private TargetDetails _targetDetails;
public ProfileDataNode(MethodWithGCInfo methodNode, TargetDetails targetDetails)
{
_methodNode = methodNode;
_targetDetails = targetDetails;
}
public void SetProfileData(int ilSize, int blockCount, byte[] data)
{
Debug.Assert(_profileData == null); // This function should not be called twice on the same object
_profileData = data;
_ilSize = ilSize;
_blockCount = blockCount;
}
public override bool StaticDependenciesAreComputed => _profileData != null;
public override int ClassCode => 274394286;
private int OffsetFromStartOfObjectToSymbol
{
get
{
int offset = 0
// sizeof(CORCOMPILE_METHOD_PROFILE_LIST)
+ _targetDetails.PointerSize // (CORCOMPILE_METHOD_PROFILE_LIST::next)
// sizeof(CORBBTPROF_METHOD_HEADER)
+ sizeof(int) // (CORBBTPROF_METHOD_HEADER::size)
+ sizeof(int) // (CORBBTPROF_METHOD_HEADER::cDetail)
// Next field is a CORBBT_METHOD_INFO struct (CORBBTPROF_METHOD_HEADER::method)
+ sizeof(int) // (CORBBT_METHOD_INFO::token)
+ sizeof(int) // (CORBBT_METHOD_INFO::ILSize)
+ sizeof(int); // (CORBBT_METHOD_INFO::cBlock)
// At this offset lies the block counts
return offset;
}
}
int ISymbolDefinitionNode.Offset
{
get
{
// At this offset lies the block counts
return OffsetFromStartOfObjectToSymbol + OffsetFromBeginningOfArray;
}
}
int ISymbolNode.Offset => 0;
public void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb)
{
sb.Append("ProfileDataNode->");
_methodNode.AppendMangledName(nameMangler, sb);
}
protected override void OnMarked(NodeFactory factory)
{
factory.ProfileDataSection.AddEmbeddedObject(this);
}
public override void EncodeData(ref ObjectDataBuilder dataBuilder, NodeFactory factory, bool relocsOnly)
{
ProfileDataNode nextElementInList = ((ProfileDataSectionNode)ContainingNode).NextElementToEncode;
if (nextElementInList != null)
dataBuilder.EmitPointerReloc(nextElementInList, -OffsetFromStartOfObjectToSymbol);
else
dataBuilder.EmitZeroPointer();
if (relocsOnly)
{
return;
}
EcmaMethod ecmaMethod = (EcmaMethod)_methodNode.Method.GetTypicalMethodDefinition();
int startOffset = dataBuilder.CountBytes;
var reservation = dataBuilder.ReserveInt();
dataBuilder.EmitInt(0); // CORBBTPROF_METHOD_HEADER::cDetail
dataBuilder.EmitInt(ecmaMethod.MetadataReader.GetToken(ecmaMethod.Handle)); // CORBBT_METHOD_INFO::token
dataBuilder.EmitInt(_ilSize); // CORBBT_METHOD_INFO::ILSize
dataBuilder.EmitInt(_blockCount); // CORBBT_METHOD_INFO::cBlock
int sizeOfCORBBTPROF_METHOD_HEADER = dataBuilder.CountBytes - startOffset;
Debug.Assert(sizeOfCORBBTPROF_METHOD_HEADER == (OffsetFromStartOfObjectToSymbol - _targetDetails.PointerSize));
dataBuilder.EmitInt(reservation, sizeOfCORBBTPROF_METHOD_HEADER + _profileData.Length);
dataBuilder.EmitBytes(_profileData);
while ((dataBuilder.CountBytes & (dataBuilder.TargetPointerSize - 1)) != 0)
dataBuilder.EmitByte(0);
}
protected override string GetName(NodeFactory context)
{
Utf8StringBuilder sb = new Utf8StringBuilder();
sb.Append("ProfileDataNode->");
_methodNode.AppendMangledName(context.NameMangler, sb);
return sb.ToString();
}
public override IEnumerable<DependencyListEntry> GetStaticDependencies(NodeFactory context)
{
return Array.Empty<DependencyListEntry>();
}
public override int CompareToImpl(ISortableNode other, CompilerComparer comparer)
{
return comparer.Compare(_methodNode, ((ProfileDataNode)other)._methodNode);
}
}
}
| -1 |
dotnet/runtime | 66,046 | Fix handling of atomic nodes in RegexCompiler / source generator | We weren't properly resetting the stack position, so if we had an atomic group that contained something that backtracked, any backtracking positions left on the stack by that nested construct would then be consumed by a previous backtracking construct and lead to it reading the wrong state. | stephentoub | 2022-03-02T01:17:05Z | 2022-03-03T16:24:40Z | fdbdb9a81d2974b38c4c6c3dea9c3d2bf1d4b7d8 | b410984a6287b722b7bd215441504fe78ecb2ca0 | Fix handling of atomic nodes in RegexCompiler / source generator. We weren't properly resetting the stack position, so if we had an atomic group that contained something that backtracked, any backtracking positions left on the stack by that nested construct would then be consumed by a previous backtracking construct and lead to it reading the wrong state. | ./src/tests/JIT/HardwareIntrinsics/X86/Avx2/Multiply.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics.X86;
using System.Runtime.Intrinsics;
namespace IntelHardwareIntrinsicTest
{
class Program
{
const int Pass = 100;
const int Fail = 0;
static unsafe int Main(string[] args)
{
int testResult = Pass;
if (Avx2.IsSupported)
{
using (TestTable<int, int, long> intTable = new TestTable<int, int, long>(new int[8] { 1, -5, 100, 0, 1, -5, 100, 0 }, new int[8] { 22, -1, -50, 0, 22, -1, -50, 0 }, new long[4]))
using (TestTable<uint, uint, ulong> uintTable = new TestTable<uint, uint, ulong>(new uint[8] { 1, 5, 100, 0, 1, 5, 100, 0 }, new uint[8] { 22, 1, 50, 0, 22, 1, 50, 0 }, new ulong[4]))
{
var vi1 = Unsafe.Read<Vector256<int>>(intTable.inArray1Ptr);
var vi2 = Unsafe.Read<Vector256<int>>(intTable.inArray2Ptr);
var vi3 = Avx2.Multiply(vi1, vi2);
Unsafe.Write(intTable.outArrayPtr, vi3);
var vui1 = Unsafe.Read<Vector256<uint>>(uintTable.inArray1Ptr);
var vui2 = Unsafe.Read<Vector256<uint>>(uintTable.inArray2Ptr);
var vui3 = Avx2.Multiply(vui1, vui2);
Unsafe.Write(uintTable.outArrayPtr, vui3);
for (int i = 0; i < intTable.outArray.Length; i++)
{
if (intTable.inArray1[i * 2] * intTable.inArray2[i * 2] != intTable.outArray[i])
{
Console.WriteLine("AVX2 Multiply failed on int:");
foreach (var item in intTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
return Fail;
}
}
for (int i = 0; i < uintTable.outArray.Length; i++)
{
if (uintTable.inArray1[i * 2] * uintTable.inArray2[i * 2] != uintTable.outArray[i])
{
Console.WriteLine("AVX2 Multiply failed on uint:");
foreach (var item in uintTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
return Fail;
}
}
}
}
return testResult;
}
public unsafe struct TestTable<T1, T2, T3> : IDisposable where T1 : struct where T2 : struct where T3 : struct
{
public T1[] inArray1;
public T2[] inArray2;
public T3[] outArray;
public void* inArray1Ptr => inHandle1.AddrOfPinnedObject().ToPointer();
public void* inArray2Ptr => inHandle2.AddrOfPinnedObject().ToPointer();
public void* outArrayPtr => outHandle.AddrOfPinnedObject().ToPointer();
GCHandle inHandle1;
GCHandle inHandle2;
GCHandle outHandle;
public TestTable(T1[] a, T2[] b, T3[] c)
{
this.inArray1 = a;
this.inArray2 = b;
this.outArray = c;
inHandle1 = GCHandle.Alloc(inArray1, GCHandleType.Pinned);
inHandle2 = GCHandle.Alloc(inArray2, GCHandleType.Pinned);
outHandle = GCHandle.Alloc(outArray, GCHandleType.Pinned);
}
public bool CheckResult(Func<T1, T2, T3, bool> check)
{
for (int i = 0; i < inArray1.Length; i++)
{
if (!check(inArray1[i], inArray2[i], outArray[i]))
{
return false;
}
}
return true;
}
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics.X86;
using System.Runtime.Intrinsics;
namespace IntelHardwareIntrinsicTest
{
class Program
{
const int Pass = 100;
const int Fail = 0;
static unsafe int Main(string[] args)
{
int testResult = Pass;
if (Avx2.IsSupported)
{
using (TestTable<int, int, long> intTable = new TestTable<int, int, long>(new int[8] { 1, -5, 100, 0, 1, -5, 100, 0 }, new int[8] { 22, -1, -50, 0, 22, -1, -50, 0 }, new long[4]))
using (TestTable<uint, uint, ulong> uintTable = new TestTable<uint, uint, ulong>(new uint[8] { 1, 5, 100, 0, 1, 5, 100, 0 }, new uint[8] { 22, 1, 50, 0, 22, 1, 50, 0 }, new ulong[4]))
{
var vi1 = Unsafe.Read<Vector256<int>>(intTable.inArray1Ptr);
var vi2 = Unsafe.Read<Vector256<int>>(intTable.inArray2Ptr);
var vi3 = Avx2.Multiply(vi1, vi2);
Unsafe.Write(intTable.outArrayPtr, vi3);
var vui1 = Unsafe.Read<Vector256<uint>>(uintTable.inArray1Ptr);
var vui2 = Unsafe.Read<Vector256<uint>>(uintTable.inArray2Ptr);
var vui3 = Avx2.Multiply(vui1, vui2);
Unsafe.Write(uintTable.outArrayPtr, vui3);
for (int i = 0; i < intTable.outArray.Length; i++)
{
if (intTable.inArray1[i * 2] * intTable.inArray2[i * 2] != intTable.outArray[i])
{
Console.WriteLine("AVX2 Multiply failed on int:");
foreach (var item in intTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
return Fail;
}
}
for (int i = 0; i < uintTable.outArray.Length; i++)
{
if (uintTable.inArray1[i * 2] * uintTable.inArray2[i * 2] != uintTable.outArray[i])
{
Console.WriteLine("AVX2 Multiply failed on uint:");
foreach (var item in uintTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
return Fail;
}
}
}
}
return testResult;
}
public unsafe struct TestTable<T1, T2, T3> : IDisposable where T1 : struct where T2 : struct where T3 : struct
{
public T1[] inArray1;
public T2[] inArray2;
public T3[] outArray;
public void* inArray1Ptr => inHandle1.AddrOfPinnedObject().ToPointer();
public void* inArray2Ptr => inHandle2.AddrOfPinnedObject().ToPointer();
public void* outArrayPtr => outHandle.AddrOfPinnedObject().ToPointer();
GCHandle inHandle1;
GCHandle inHandle2;
GCHandle outHandle;
public TestTable(T1[] a, T2[] b, T3[] c)
{
this.inArray1 = a;
this.inArray2 = b;
this.outArray = c;
inHandle1 = GCHandle.Alloc(inArray1, GCHandleType.Pinned);
inHandle2 = GCHandle.Alloc(inArray2, GCHandleType.Pinned);
outHandle = GCHandle.Alloc(outArray, GCHandleType.Pinned);
}
public bool CheckResult(Func<T1, T2, T3, bool> check)
{
for (int i = 0; i < inArray1.Length; i++)
{
if (!check(inArray1[i], inArray2[i], outArray[i]))
{
return false;
}
}
return true;
}
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
}
}
}
| -1 |
dotnet/runtime | 66,046 | Fix handling of atomic nodes in RegexCompiler / source generator | We weren't properly resetting the stack position, so if we had an atomic group that contained something that backtracked, any backtracking positions left on the stack by that nested construct would then be consumed by a previous backtracking construct and lead to it reading the wrong state. | stephentoub | 2022-03-02T01:17:05Z | 2022-03-03T16:24:40Z | fdbdb9a81d2974b38c4c6c3dea9c3d2bf1d4b7d8 | b410984a6287b722b7bd215441504fe78ecb2ca0 | Fix handling of atomic nodes in RegexCompiler / source generator. We weren't properly resetting the stack position, so if we had an atomic group that contained something that backtracked, any backtracking positions left on the stack by that nested construct would then be consumed by a previous backtracking construct and lead to it reading the wrong state. | ./src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/FileChangeMonitor.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.ObjectModel;
namespace System.Runtime.Caching
{
public abstract class FileChangeMonitor : ChangeMonitor
{
public abstract ReadOnlyCollection<string> FilePaths { get; }
public abstract DateTimeOffset LastModified { get; }
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.ObjectModel;
namespace System.Runtime.Caching
{
public abstract class FileChangeMonitor : ChangeMonitor
{
public abstract ReadOnlyCollection<string> FilePaths { get; }
public abstract DateTimeOffset LastModified { get; }
}
}
| -1 |
dotnet/runtime | 66,046 | Fix handling of atomic nodes in RegexCompiler / source generator | We weren't properly resetting the stack position, so if we had an atomic group that contained something that backtracked, any backtracking positions left on the stack by that nested construct would then be consumed by a previous backtracking construct and lead to it reading the wrong state. | stephentoub | 2022-03-02T01:17:05Z | 2022-03-03T16:24:40Z | fdbdb9a81d2974b38c4c6c3dea9c3d2bf1d4b7d8 | b410984a6287b722b7bd215441504fe78ecb2ca0 | Fix handling of atomic nodes in RegexCompiler / source generator. We weren't properly resetting the stack position, so if we had an atomic group that contained something that backtracked, any backtracking positions left on the stack by that nested construct would then be consumed by a previous backtracking construct and lead to it reading the wrong state. | ./src/tests/JIT/HardwareIntrinsics/General/Vector256/EqualsAny.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 EqualsAnyUInt16()
{
var test = new VectorBooleanBinaryOpTest__EqualsAnyUInt16();
// 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__EqualsAnyUInt16
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private GCHandle inHandle1;
private GCHandle inHandle2;
private ulong alignment;
public DataTable(UInt16[] inArray1, UInt16[] inArray2, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt16>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt16>();
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<UInt16, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt16, 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<UInt16> _fld1;
public Vector256<UInt16> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
return testStruct;
}
public void RunStructFldScenario(VectorBooleanBinaryOpTest__EqualsAnyUInt16 testClass)
{
var result = Vector256.EqualsAny(_fld1, _fld2);
testClass.ValidateResult(_fld1, _fld2, result);
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16);
private static UInt16[] _data1 = new UInt16[Op1ElementCount];
private static UInt16[] _data2 = new UInt16[Op2ElementCount];
private static Vector256<UInt16> _clsVar1;
private static Vector256<UInt16> _clsVar2;
private Vector256<UInt16> _fld1;
private Vector256<UInt16> _fld2;
private DataTable _dataTable;
static VectorBooleanBinaryOpTest__EqualsAnyUInt16()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
}
public VectorBooleanBinaryOpTest__EqualsAnyUInt16()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
_dataTable = new DataTable(_data1, _data2, LargestVectorSize);
}
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Vector256.EqualsAny(
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr)
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var method = typeof(Vector256).GetMethod(nameof(Vector256.EqualsAny), new Type[] {
typeof(Vector256<UInt16>),
typeof(Vector256<UInt16>)
});
if (method is null)
{
method = typeof(Vector256).GetMethod(nameof(Vector256.EqualsAny), 1, new Type[] {
typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)),
typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0))
});
}
if (method.IsGenericMethodDefinition)
{
method = method.MakeGenericMethod(typeof(UInt16));
}
var result = method.Invoke(null, new object[] {
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr)
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Vector256.EqualsAny(
_clsVar1,
_clsVar2
);
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr);
var result = Vector256.EqualsAny(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new VectorBooleanBinaryOpTest__EqualsAnyUInt16();
var result = Vector256.EqualsAny(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Vector256.EqualsAny(_fld1, _fld2);
ValidateResult(_fld1, _fld2, result);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Vector256.EqualsAny(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<UInt16> op1, Vector256<UInt16> op2, bool result, [CallerMemberName] string method = "")
{
UInt16[] inArray1 = new UInt16[Op1ElementCount];
UInt16[] inArray2 = new UInt16[Op2ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), op2);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "")
{
UInt16[] inArray1 = new UInt16[Op1ElementCount];
UInt16[] inArray2 = new UInt16[Op2ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(UInt16[] left, UInt16[] right, bool result, [CallerMemberName] string method = "")
{
bool succeeded = true;
var expectedResult = false;
for (var i = 0; i < Op1ElementCount; i++)
{
expectedResult |= (left[i] == right[i]);
}
succeeded = (expectedResult == result);
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.{nameof(Vector256.EqualsAny)}<UInt16>(Vector256<UInt16>, Vector256<UInt16>): {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 EqualsAnyUInt16()
{
var test = new VectorBooleanBinaryOpTest__EqualsAnyUInt16();
// 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__EqualsAnyUInt16
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private GCHandle inHandle1;
private GCHandle inHandle2;
private ulong alignment;
public DataTable(UInt16[] inArray1, UInt16[] inArray2, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt16>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt16>();
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<UInt16, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt16, 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<UInt16> _fld1;
public Vector256<UInt16> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
return testStruct;
}
public void RunStructFldScenario(VectorBooleanBinaryOpTest__EqualsAnyUInt16 testClass)
{
var result = Vector256.EqualsAny(_fld1, _fld2);
testClass.ValidateResult(_fld1, _fld2, result);
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16);
private static UInt16[] _data1 = new UInt16[Op1ElementCount];
private static UInt16[] _data2 = new UInt16[Op2ElementCount];
private static Vector256<UInt16> _clsVar1;
private static Vector256<UInt16> _clsVar2;
private Vector256<UInt16> _fld1;
private Vector256<UInt16> _fld2;
private DataTable _dataTable;
static VectorBooleanBinaryOpTest__EqualsAnyUInt16()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
}
public VectorBooleanBinaryOpTest__EqualsAnyUInt16()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
_dataTable = new DataTable(_data1, _data2, LargestVectorSize);
}
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Vector256.EqualsAny(
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr)
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var method = typeof(Vector256).GetMethod(nameof(Vector256.EqualsAny), new Type[] {
typeof(Vector256<UInt16>),
typeof(Vector256<UInt16>)
});
if (method is null)
{
method = typeof(Vector256).GetMethod(nameof(Vector256.EqualsAny), 1, new Type[] {
typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0)),
typeof(Vector256<>).MakeGenericType(Type.MakeGenericMethodParameter(0))
});
}
if (method.IsGenericMethodDefinition)
{
method = method.MakeGenericMethod(typeof(UInt16));
}
var result = method.Invoke(null, new object[] {
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr)
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Vector256.EqualsAny(
_clsVar1,
_clsVar2
);
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr);
var result = Vector256.EqualsAny(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new VectorBooleanBinaryOpTest__EqualsAnyUInt16();
var result = Vector256.EqualsAny(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Vector256.EqualsAny(_fld1, _fld2);
ValidateResult(_fld1, _fld2, result);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Vector256.EqualsAny(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<UInt16> op1, Vector256<UInt16> op2, bool result, [CallerMemberName] string method = "")
{
UInt16[] inArray1 = new UInt16[Op1ElementCount];
UInt16[] inArray2 = new UInt16[Op2ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), op2);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "")
{
UInt16[] inArray1 = new UInt16[Op1ElementCount];
UInt16[] inArray2 = new UInt16[Op2ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(UInt16[] left, UInt16[] right, bool result, [CallerMemberName] string method = "")
{
bool succeeded = true;
var expectedResult = false;
for (var i = 0; i < Op1ElementCount; i++)
{
expectedResult |= (left[i] == right[i]);
}
succeeded = (expectedResult == result);
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Vector256)}.{nameof(Vector256.EqualsAny)}<UInt16>(Vector256<UInt16>, Vector256<UInt16>): {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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.