1
0
Fork 0
mirror of https://github.com/VSadov/Satori.git synced 2025-06-09 17:44:48 +09:00

Add SYSLIB* analyzers to global configs (#80930)

* Add SYSLIB* analyzers to global configs

* Address PR feedback
This commit is contained in:
Stephen Toub 2023-01-26 08:25:39 -05:00 committed by GitHub
parent 26b58b99ae
commit fb7d8b186b
Signed by: github
GPG key ID: 4AEE18F83AFDEB23
28 changed files with 222 additions and 118 deletions

View file

@ -21,6 +21,30 @@ dotnet_diagnostic.BCL0015.severity = none
# BCL0020: Invalid SR.Format call # BCL0020: Invalid SR.Format call
dotnet_diagnostic.BCL0020.severity = warning dotnet_diagnostic.BCL0020.severity = warning
# SYSLIB1045: Convert to 'GeneratedRegexAttribute'.
dotnet_diagnostic.SYSLIB1045.severity = warning
# SYSLIB1054: Use 'LibraryImportAttribute' instead of 'DllImportAttribute' to generate P/Invoke marshalling code at compile time
dotnet_diagnostic.SYSLIB1054.severity = warning
# SYSLIB1055: Invalid 'CustomMarshallerAttribute' usage
dotnet_diagnostic.SYSLIB1055.severity = error
# SYSLIB1056:Specified marshaller type is invalid
dotnet_diagnostic.SYSLIB1056.severity = error
# SYSLIB1057: Marshaller type does not have the required shape
dotnet_diagnostic.SYSLIB1057.severity = error
# SYSLIB1058: Invalid 'NativeMarshallingAttribute' usage
dotnet_diagnostic.SYSLIB1058.severity = error
# SYSLIB1060: Specified marshaller type is invalid
dotnet_diagnostic.SYSLIB1060.severity = error
# SYSLIB1061: Marshaller type has incompatible method signatures
dotnet_diagnostic.SYSLIB1061.severity = error
# CA1000: Do not declare static members on generic types # CA1000: Do not declare static members on generic types
dotnet_diagnostic.CA1000.severity = none dotnet_diagnostic.CA1000.severity = none

View file

@ -21,6 +21,30 @@ dotnet_diagnostic.BCL0015.severity = none
# BCL0020: Invalid SR.Format call # BCL0020: Invalid SR.Format call
dotnet_diagnostic.BCL0020.severity = none dotnet_diagnostic.BCL0020.severity = none
# SYSLIB1045: Convert to 'GeneratedRegexAttribute'.
dotnet_diagnostic.SYSLIB1045.severity = none
# SYSLIB1054: Use 'LibraryImportAttribute' instead of 'DllImportAttribute' to generate P/Invoke marshalling code at compile time
dotnet_diagnostic.SYSLIB1054.severity = none
# SYSLIB1055: Invalid 'CustomMarshallerAttribute' usage
dotnet_diagnostic.SYSLIB1055.severity = error
# SYSLIB1056:Specified marshaller type is invalid
dotnet_diagnostic.SYSLIB1056.severity = error
# SYSLIB1057: Marshaller type does not have the required shape
dotnet_diagnostic.SYSLIB1057.severity = error
# SYSLIB1058: Invalid 'NativeMarshallingAttribute' usage
dotnet_diagnostic.SYSLIB1058.severity = error
# SYSLIB1060: Specified marshaller type is invalid
dotnet_diagnostic.SYSLIB1060.severity = error
# SYSLIB1061: Marshaller type has incompatible method signatures
dotnet_diagnostic.SYSLIB1061.severity = error
# CA1000: Do not declare static members on generic types # CA1000: Do not declare static members on generic types
dotnet_diagnostic.CA1000.severity = none dotnet_diagnostic.CA1000.severity = none

View file

@ -10,6 +10,8 @@ using System.Runtime.CompilerServices;
using Internal.Runtime; using Internal.Runtime;
#pragma warning disable SYSLIB1054 // Use DllImport here instead of LibraryImport because this file is used by Test.CoreLib
namespace System.Runtime namespace System.Runtime
{ {
internal enum DispatchCellType internal enum DispatchCellType

View file

@ -285,10 +285,11 @@ namespace System.Runtime
return RhpGetCurrentThreadStackTrace(pOutputBuffer, (uint)((outputBuffer != null) ? outputBuffer.Length : 0), new UIntPtr(&pOutputBuffer)); return RhpGetCurrentThreadStackTrace(pOutputBuffer, (uint)((outputBuffer != null) ? outputBuffer.Length : 0), new UIntPtr(&pOutputBuffer));
} }
// Use DllImport here instead of LibraryImport because this file is used by Test.CoreLib. #pragma warning disable SYSLIB1054 // Use DllImport here instead of LibraryImport because this file is used by Test.CoreLib.
[DllImport(Redhawk.BaseName)] [DllImport(Redhawk.BaseName)]
[UnmanagedCallConv(CallConvs = new Type[] { typeof(CallConvCdecl) })] [UnmanagedCallConv(CallConvs = new Type[] { typeof(CallConvCdecl) })]
private static extern unsafe int RhpGetCurrentThreadStackTrace(IntPtr* pOutputBuffer, uint outputBufferLength, UIntPtr addressInCurrentFrame); private static extern unsafe int RhpGetCurrentThreadStackTrace(IntPtr* pOutputBuffer, uint outputBufferLength, UIntPtr addressInCurrentFrame);
#pragma warning restore SYSLIB1054
// Worker for RhGetCurrentThreadStackTrace. RhGetCurrentThreadStackTrace just allocates a transition // Worker for RhGetCurrentThreadStackTrace. RhGetCurrentThreadStackTrace just allocates a transition
// frame that will be used to seed the stack trace and this method does all the real work. // frame that will be used to seed the stack trace and this method does all the real work.

View file

@ -0,0 +1,6 @@
### Code Style Analyzers
[*.cs]
# TODO: Update tools to use LibraryImport instead of DllImport
dotnet_diagnostic.SYSLIB1054.severity = suggestion

View file

@ -3,6 +3,7 @@
<PropertyGroup> <PropertyGroup>
<TargetFramework>$(NetCoreAppToolCurrent)</TargetFramework> <TargetFramework>$(NetCoreAppToolCurrent)</TargetFramework>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<NoWarn>$(NoWarn);SYSLIB1045</NoWarn>
<IsPackable>false</IsPackable> <IsPackable>false</IsPackable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks> <AllowUnsafeBlocks>true</AllowUnsafeBlocks>

View file

@ -4,7 +4,6 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.Diagnostics.CodeAnalysis; using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text; using System.Text;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
@ -13,19 +12,6 @@ namespace System.Data.Common
internal partial class DbConnectionOptions internal partial class DbConnectionOptions
{ {
#if DEBUG #if DEBUG
/*private const string ConnectionStringPatternV1 =
"[\\s;]*"
+"(?<key>([^=\\s]|\\s+[^=\\s]|\\s+==|==)+)"
+ "\\s*=(?!=)\\s*"
+"(?<value>("
+ "(" + "\"" + "([^\"]|\"\")*" + "\"" + ")"
+ "|"
+ "(" + "'" + "([^']|'')*" + "'" + ")"
+ "|"
+ "(" + "(?![\"'])" + "([^\\s;]|\\s+[^\\s;])*" + "(?<![\"'])" + ")"
+ "))"
+ "[\\s;]*"
;*/
private const string ConnectionStringPattern = // may not contain embedded null except trailing last value private const string ConnectionStringPattern = // may not contain embedded null except trailing last value
"([\\s;]*" // leading whitespace and extra semicolons "([\\s;]*" // leading whitespace and extra semicolons
+ "(?![\\s;])" // key does not start with space or semicolon + "(?![\\s;])" // key does not start with space or semicolon
@ -61,16 +47,38 @@ namespace System.Data.Common
+ "[\\s;]*[\u0000\\s]*" // trailing whitespace/semicolons (DataSourceLocator), embedded nulls are allowed only in the end + "[\\s;]*[\u0000\\s]*" // trailing whitespace/semicolons (DataSourceLocator), embedded nulls are allowed only in the end
; ;
private static readonly Regex s_connectionStringRegex = new Regex(ConnectionStringPattern, RegexOptions.ExplicitCapture | RegexOptions.Compiled); private static readonly Regex s_connectionStringRegex = CreateConnectionStringRegex();
private static readonly Regex s_connectionStringRegexOdbc = new Regex(ConnectionStringPatternOdbc, RegexOptions.ExplicitCapture | RegexOptions.Compiled); private static readonly Regex s_connectionStringRegexOdbc = CreateConnectionStringRegexOdbc();
#if NET7_0_OR_GREATER
[GeneratedRegex(ConnectionStringPattern, RegexOptions.ExplicitCapture)]
private static partial Regex CreateConnectionStringRegex();
[GeneratedRegex(ConnectionStringPatternOdbc, RegexOptions.ExplicitCapture)]
private static partial Regex CreateConnectionStringRegexOdbc();
#else
private static Regex CreateConnectionStringRegex() => new Regex(ConnectionStringPattern, RegexOptions.ExplicitCapture | RegexOptions.Compiled);
private static Regex CreateConnectionStringRegexOdbc() => new Regex(ConnectionStringPatternOdbc, RegexOptions.ExplicitCapture | RegexOptions.Compiled);
#endif
#endif #endif
internal const string DataDirectory = "|datadirectory|"; internal const string DataDirectory = "|datadirectory|";
#pragma warning disable CA1823 // used in some compilations and not others private static readonly Regex s_connectionStringValidKeyRegex = CreateConnectionStringValidKeyRegex(); // key not allowed to start with semi-colon or space or contain non-visible characters or end with space
private static readonly Regex s_connectionStringValidKeyRegex = new Regex("^(?![;\\s])[^\\p{Cc}]+(?<!\\s)$", RegexOptions.Compiled); // key not allowed to start with semi-colon or space or contain non-visible characters or end with space private static readonly Regex s_connectionStringQuoteValueRegex = CreateConnectionStringQuoteValueRegex(); // generally do not quote the value if it matches the pattern
private static readonly Regex s_connectionStringQuoteValueRegex = new Regex("^[^\"'=;\\s\\p{Cc}]*$", RegexOptions.Compiled); // generally do not quote the value if it matches the pattern private static readonly Regex s_connectionStringQuoteOdbcValueRegex = CreateConnectionStringQuoteOdbcValueRegex(); // do not quote odbc value if it matches this pattern
private static readonly Regex s_connectionStringQuoteOdbcValueRegex = new Regex("^\\{([^\\}\u0000]|\\}\\})*\\}$", RegexOptions.ExplicitCapture | RegexOptions.Compiled); // do not quote odbc value if it matches this pattern
#pragma warning restore CA1823 #if NET7_0_OR_GREATER
[GeneratedRegex("^(?![;\\s])[^\\p{Cc}]+(?<!\\s)$")]
private static partial Regex CreateConnectionStringValidKeyRegex();
[GeneratedRegex("^[^\"'=;\\s\\p{Cc}]*$")]
private static partial Regex CreateConnectionStringQuoteValueRegex();
[GeneratedRegex("^\\{([^\\}\u0000]|\\}\\})*\\}$", RegexOptions.ExplicitCapture)]
private static partial Regex CreateConnectionStringQuoteOdbcValueRegex();
#else
private static Regex CreateConnectionStringValidKeyRegex() => new Regex("^(?![;\\s])[^\\p{Cc}]+(?<!\\s)$", RegexOptions.Compiled);
private static Regex CreateConnectionStringQuoteValueRegex() => new Regex("^[^\"'=;\\s\\p{Cc}]*$", RegexOptions.Compiled);
private static Regex CreateConnectionStringQuoteOdbcValueRegex() => new Regex("^\\{([^\\}\u0000]|\\}\\})*\\}$", RegexOptions.ExplicitCapture | RegexOptions.Compiled);
#endif
// connection string common keywords // connection string common keywords
private static class KEY private static class KEY

View file

@ -37,7 +37,7 @@
<!-- Ignore analyzers that recommend APIs introduced in .NET Core when targeting frameworks that lack those APIs <!-- Ignore analyzers that recommend APIs introduced in .NET Core when targeting frameworks that lack those APIs
to avoid issues with multitargeting. to avoid issues with multitargeting.
--> -->
<NoWarn Condition="$(TargetFrameworks.Contains('net4')) or $(TargetFrameworks.Contains('netstandard'))">$(NoWarn);CA1510;CA1511;CA1512;CA1513</NoWarn> <NoWarn Condition="$(TargetFrameworks.Contains('net4')) or $(TargetFrameworks.Contains('netstandard'))">$(NoWarn);CA1510;CA1511;CA1512;CA1513;CA1845;CA1846;CA1847</NoWarn>
<!-- Microsoft.NET.Sdk enables some warnings as errors out of the box. <!-- Microsoft.NET.Sdk enables some warnings as errors out of the box.
We want to remove some items from this list so they don't fail the build. We want to remove some items from this list so they don't fail the build.

View file

@ -5,7 +5,6 @@
<NoWarn>$(NoWarn);nullable</NoWarn> <NoWarn>$(NoWarn);nullable</NoWarn>
<!-- opt-out of trimming until it works https://github.com/dotnet/runtime/issues/49062 --> <!-- opt-out of trimming until it works https://github.com/dotnet/runtime/issues/49062 -->
<IsTrimmable>false</IsTrimmable> <IsTrimmable>false</IsTrimmable>
<NoWarn>$(NoWarn);CA1847</NoWarn>
<IsPackable>true</IsPackable> <IsPackable>true</IsPackable>
<PackageDescription>Provides types that support using XML configuration files (app.config). This package exists only to support migrating existing .NET Framework code that already uses System.Configuration. When writing new code, use another configuration system instead, such as Microsoft.Extensions.Configuration.</PackageDescription> <PackageDescription>Provides types that support using XML configuration files (app.config). This package exists only to support migrating existing .NET Framework code that already uses System.Configuration. When writing new code, use another configuration system instead, such as Microsoft.Extensions.Configuration.</PackageDescription>
</PropertyGroup> </PropertyGroup>

View file

@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks> <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<TargetFramework>$(NetCoreAppCurrent)</TargetFramework> <TargetFramework>$(NetCoreAppCurrent)</TargetFramework>
@ -327,5 +327,9 @@
<Reference Include="System.Transactions.Local" /> <Reference Include="System.Transactions.Local" />
<Reference Include="System.Xml.ReaderWriter" /> <Reference Include="System.Xml.ReaderWriter" />
<Reference Include="System.Xml.XmlSerializer" /> <Reference Include="System.Xml.XmlSerializer" />
<ProjectReference Include="..\..\System.Text.RegularExpressions\gen\System.Text.RegularExpressions.Generator.csproj"
SetTargetFramework="TargetFramework=netstandard2.0"
OutputItemType="Analyzer"
ReferenceOutputAssembly="false" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View file

@ -2,9 +2,7 @@
<PropertyGroup> <PropertyGroup>
<TargetFrameworks>$(NetCoreAppCurrent)-windows;$(NetCoreAppCurrent)-freebsd;$(NetCoreAppCurrent)-illumos;$(NetCoreAppCurrent)-solaris;$(NetCoreAppCurrent)-linux;$(NetCoreAppCurrent)-osx;$(NetCoreAppCurrent)-ios;$(NetCoreAppCurrent)-tvos;$(NetCoreAppCurrent);$(NetCoreAppPrevious)-windows;$(NetCoreAppPrevious)-freebsd;$(NetCoreAppPrevious)-illumos;$(NetCoreAppPrevious)-solaris;$(NetCoreAppPrevious)-linux;$(NetCoreAppPrevious)-osx;$(NetCoreAppPrevious)-ios;$(NetCoreAppPrevious)-tvos;$(NetCoreAppPrevious);$(NetCoreAppMinimum)-windows;$(NetCoreAppMinimum)-freebsd;$(NetCoreAppMinimum)-linux;$(NetCoreAppMinimum)-osx;$(NetCoreAppMinimum);netstandard2.0;$(NetFrameworkMinimum)</TargetFrameworks> <TargetFrameworks>$(NetCoreAppCurrent)-windows;$(NetCoreAppCurrent)-freebsd;$(NetCoreAppCurrent)-illumos;$(NetCoreAppCurrent)-solaris;$(NetCoreAppCurrent)-linux;$(NetCoreAppCurrent)-osx;$(NetCoreAppCurrent)-ios;$(NetCoreAppCurrent)-tvos;$(NetCoreAppCurrent);$(NetCoreAppPrevious)-windows;$(NetCoreAppPrevious)-freebsd;$(NetCoreAppPrevious)-illumos;$(NetCoreAppPrevious)-solaris;$(NetCoreAppPrevious)-linux;$(NetCoreAppPrevious)-osx;$(NetCoreAppPrevious)-ios;$(NetCoreAppPrevious)-tvos;$(NetCoreAppPrevious);$(NetCoreAppMinimum)-windows;$(NetCoreAppMinimum)-freebsd;$(NetCoreAppMinimum)-linux;$(NetCoreAppMinimum)-osx;$(NetCoreAppMinimum);netstandard2.0;$(NetFrameworkMinimum)</TargetFrameworks>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks> <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<NoWarn>$(NoWarn);CA2249;CA1838;CA1846</NoWarn> <NoWarn>$(NoWarn);CA2249;CA1838</NoWarn>
<!-- Suppress CA1845: Use span-based 'string.Concat' and 'AsSpan' instead of 'Substring' to avoid ifdefs. -->
<NoWarn>$(NoWarn);CA1845</NoWarn>
<IsPackable>true</IsPackable> <IsPackable>true</IsPackable>
<PackageDescription>Provides a collection of classes used to access an ODBC data source in the managed space <PackageDescription>Provides a collection of classes used to access an ODBC data source in the managed space
@ -135,6 +133,10 @@ System.Data.Odbc.OdbcTransaction</PackageDescription>
Link="Common\DisableRuntimeMarshalling.cs" /> Link="Common\DisableRuntimeMarshalling.cs" />
<Compile Include="$(CommonPath)System\Runtime\InteropServices\HandleRefMarshaller.cs" <Compile Include="$(CommonPath)System\Runtime\InteropServices\HandleRefMarshaller.cs"
Link="Common\System\Runtime\InteropServices\HandleRefMarshaller.cs" /> Link="Common\System\Runtime\InteropServices\HandleRefMarshaller.cs" />
<ProjectReference Include="..\..\System.Text.RegularExpressions\gen\System.Text.RegularExpressions.Generator.csproj"
SetTargetFramework="TargetFramework=netstandard2.0"
OutputItemType="Analyzer"
ReferenceOutputAssembly="false" />
</ItemGroup> </ItemGroup>
<ItemGroup Condition="'$(TargetPlatformIdentifier)' == 'linux' or '$(TargetPlatformIdentifier)' == 'freebsd' or '$(TargetPlatformIdentifier)' == 'illumos' or '$(TargetPlatformIdentifier)' == 'solaris'"> <ItemGroup Condition="'$(TargetPlatformIdentifier)' == 'linux' or '$(TargetPlatformIdentifier)' == 'freebsd' or '$(TargetPlatformIdentifier)' == 'illumos' or '$(TargetPlatformIdentifier)' == 'solaris'">

View file

@ -5,32 +5,18 @@ using System.Collections;
using System.Diagnostics; using System.Diagnostics;
using System.Diagnostics.CodeAnalysis; using System.Diagnostics.CodeAnalysis;
using System.Globalization; using System.Globalization;
using System.Runtime.Versioning;
using System.Text; using System.Text;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
namespace System.Data.Common namespace System.Data.Common
{ {
internal class DbConnectionOptions internal partial class DbConnectionOptions
{ {
// instances of this class are intended to be immutable, i.e readonly // instances of this class are intended to be immutable, i.e readonly
// used by pooling classes so it is much easier to verify correctness // used by pooling classes so it is much easier to verify correctness
// when not worried about the class being modified during execution // when not worried about the class being modified during execution
#if DEBUG #if DEBUG
/*private const string ConnectionStringPatternV1 =
"[\\s;]*"
+"(?<key>([^=\\s]|\\s+[^=\\s]|\\s+==|==)+)"
+ "\\s*=(?!=)\\s*"
+"(?<value>("
+ "(" + "\"" + "([^\"]|\"\")*" + "\"" + ")"
+ "|"
+ "(" + "'" + "([^']|'')*" + "'" + ")"
+ "|"
+ "(" + "(?![\"'])" + "([^\\s;]|\\s+[^\\s;])*" + "(?<![\"'])" + ")"
+ "))"
+ "[\\s;]*"
;*/
private const string ConnectionStringPattern = // may not contain embedded null except trailing last value private const string ConnectionStringPattern = // may not contain embedded null except trailing last value
"([\\s;]*" // leading whitespace and extra semicolons "([\\s;]*" // leading whitespace and extra semicolons
+ "(?![\\s;])" // key does not start with space or semicolon + "(?![\\s;])" // key does not start with space or semicolon
@ -69,15 +55,39 @@ namespace System.Data.Common
+ "[\\s;]*[\u0000\\s]*" // trailing whitespace/semicolons (DataSourceLocator), embedded nulls are allowed only in the end + "[\\s;]*[\u0000\\s]*" // trailing whitespace/semicolons (DataSourceLocator), embedded nulls are allowed only in the end
; ;
private static readonly Regex ConnectionStringRegex = new Regex(ConnectionStringPattern, RegexOptions.ExplicitCapture | RegexOptions.Compiled);
private static readonly Regex ConnectionStringRegexOdbc = new Regex(ConnectionStringPatternOdbc, RegexOptions.ExplicitCapture | RegexOptions.Compiled);
#endif
private static readonly Regex ConnectionStringValidKeyRegex = new Regex("^(?![;\\s])[^\\p{Cc}]+(?<!\\s)$", RegexOptions.Compiled); // key not allowed to start with semi-colon or space or contain non-visible characters or end with space
private static readonly Regex ConnectionStringRegex = CreateConnectionStringRegex();
private static readonly Regex ConnectionStringRegexOdbc = CreateConnectionStringRegexOdbc();
#if NET7_0_OR_GREATER
[GeneratedRegex(ConnectionStringPattern, RegexOptions.ExplicitCapture)]
private static partial Regex CreateConnectionStringRegex();
[GeneratedRegex(ConnectionStringPatternOdbc, RegexOptions.ExplicitCapture)]
private static partial Regex CreateConnectionStringRegexOdbc();
#else
private static Regex CreateConnectionStringRegex() => new Regex(ConnectionStringPattern, RegexOptions.ExplicitCapture | RegexOptions.Compiled);
private static Regex CreateConnectionStringRegexOdbc() => new Regex(ConnectionStringPatternOdbc, RegexOptions.ExplicitCapture | RegexOptions.Compiled);
#endif
#endif
internal const string DataDirectory = "|datadirectory|"; internal const string DataDirectory = "|datadirectory|";
private static readonly Regex ConnectionStringQuoteValueRegex = new Regex("^[^\"'=;\\s\\p{Cc}]*$", RegexOptions.Compiled); // generally do not quote the value if it matches the pattern private static readonly Regex ConnectionStringValidKeyRegex = CreateConnectionStringValidKeyRegex(); // key not allowed to start with semi-colon or space or contain non-visible characters or end with space
private static readonly Regex ConnectionStringQuoteOdbcValueRegex = new Regex("^\\{([^\\}\u0000]|\\}\\})*\\}$", RegexOptions.ExplicitCapture | RegexOptions.Compiled); // do not quote odbc value if it matches this pattern private static readonly Regex ConnectionStringQuoteValueRegex = CreateConnectionStringQuoteValueRegex(); // generally do not quote the value if it matches the pattern
private static readonly Regex ConnectionStringQuoteOdbcValueRegex = CreateConnectionStringQuoteOdbcValueRegex(); // do not quote odbc value if it matches this pattern
#if NET7_0_OR_GREATER
[GeneratedRegex("^(?![;\\s])[^\\p{Cc}]+(?<!\\s)$")]
private static partial Regex CreateConnectionStringValidKeyRegex();
[GeneratedRegex("^[^\"'=;\\s\\p{Cc}]*$")]
private static partial Regex CreateConnectionStringQuoteValueRegex();
[GeneratedRegex("^\\{([^\\}\u0000]|\\}\\})*\\}$", RegexOptions.ExplicitCapture)]
private static partial Regex CreateConnectionStringQuoteOdbcValueRegex();
#else
private static Regex CreateConnectionStringValidKeyRegex() => new Regex("^(?![;\\s])[^\\p{Cc}]+(?<!\\s)$", RegexOptions.Compiled);
private static Regex CreateConnectionStringQuoteValueRegex() => new Regex("^[^\"'=;\\s\\p{Cc}]*$", RegexOptions.Compiled);
private static Regex CreateConnectionStringQuoteOdbcValueRegex() => new Regex("^\\{([^\\}\u0000]|\\}\\})*\\}$", RegexOptions.ExplicitCapture | RegexOptions.Compiled);
#endif
// connection string common keywords // connection string common keywords
private static class KEY private static class KEY

View file

@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFrameworks>$(NetCoreAppCurrent)-windows;$(NetCoreAppCurrent);$(NetCoreAppPrevious)-windows;$(NetCoreAppPrevious);$(NetCoreAppMinimum)-windows;$(NetCoreAppMinimum);netstandard2.0;$(NetFrameworkMinimum)</TargetFrameworks> <TargetFrameworks>$(NetCoreAppCurrent)-windows;$(NetCoreAppCurrent);$(NetCoreAppPrevious)-windows;$(NetCoreAppPrevious);$(NetCoreAppMinimum)-windows;$(NetCoreAppMinimum);netstandard2.0;$(NetFrameworkMinimum)</TargetFrameworks>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks> <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
@ -6,8 +6,6 @@
<NoWarn>$(NoWarn);CA2249</NoWarn> <NoWarn>$(NoWarn);CA2249</NoWarn>
<!-- Suppress SYSLIB0004: 'RuntimeHelpers.PrepareConstrainedRegions()' is obsolete to avoid ifdefs. --> <!-- Suppress SYSLIB0004: 'RuntimeHelpers.PrepareConstrainedRegions()' is obsolete to avoid ifdefs. -->
<NoWarn>$(NoWarn);SYSLIB0004</NoWarn> <NoWarn>$(NoWarn);SYSLIB0004</NoWarn>
<!-- Suppress CA1845: Use span-based 'string.Concat' and 'AsSpan' instead of 'Substring' to avoid ifdefs. -->
<NoWarn>$(NoWarn);CA1845</NoWarn>
<IsPackable>true</IsPackable> <IsPackable>true</IsPackable>
<PackageDescription>Provides a collection of classes for OLEDB. <PackageDescription>Provides a collection of classes for OLEDB.
@ -149,4 +147,11 @@ System.Data.OleDb.OleDbTransaction</PackageDescription>
<ProjectReference Include="$(LibrariesProjectRoot)System.Configuration.ConfigurationManager\src\System.Configuration.ConfigurationManager.csproj" /> <ProjectReference Include="$(LibrariesProjectRoot)System.Configuration.ConfigurationManager\src\System.Configuration.ConfigurationManager.csproj" />
<ProjectReference Include="$(LibrariesProjectRoot)System.Diagnostics.PerformanceCounter\src\System.Diagnostics.PerformanceCounter.csproj" /> <ProjectReference Include="$(LibrariesProjectRoot)System.Diagnostics.PerformanceCounter\src\System.Diagnostics.PerformanceCounter.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup Condition="$([MSBuild]::IsTargetFrameworkCompatible('$(TargetFramework)', 'net7.0'))">
<ProjectReference Include="..\..\System.Text.RegularExpressions\gen\System.Text.RegularExpressions.Generator.csproj"
SetTargetFramework="TargetFramework=netstandard2.0"
OutputItemType="Analyzer"
ReferenceOutputAssembly="false" />
</ItemGroup>
</Project> </Project>

View file

@ -3,7 +3,7 @@
<TargetFrameworks>$(NetCoreAppCurrent);$(NetCoreAppPrevious);$(NetCoreAppMinimum);netstandard2.0;$(NetFrameworkMinimum)</TargetFrameworks> <TargetFrameworks>$(NetCoreAppCurrent);$(NetCoreAppPrevious);$(NetCoreAppMinimum);netstandard2.0;$(NetFrameworkMinimum)</TargetFrameworks>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks> <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<CLSCompliant>false</CLSCompliant> <CLSCompliant>false</CLSCompliant>
<NoWarn>$(NoWarn);SA1205;CA1845</NoWarn> <NoWarn>$(NoWarn);SA1205</NoWarn>
<EnableTrimAnalyzer Condition="$([MSBuild]::GetTargetFrameworkIdentifier('$(TargetFramework)')) == '.NETFramework'">false</EnableTrimAnalyzer> <EnableTrimAnalyzer Condition="$([MSBuild]::GetTargetFrameworkIdentifier('$(TargetFramework)')) == '.NETFramework'">false</EnableTrimAnalyzer>
<IsPackable>true</IsPackable> <IsPackable>true</IsPackable>
<EnableAOTAnalyzer>true</EnableAOTAnalyzer> <EnableAOTAnalyzer>true</EnableAOTAnalyzer>

View file

@ -2,11 +2,6 @@
<PropertyGroup> <PropertyGroup>
<TargetFrameworks>$(NetCoreAppCurrent)-windows;$(NetCoreAppCurrent);$(NetCoreAppPrevious)-windows;$(NetCoreAppPrevious);$(NetCoreAppMinimum)-windows;$(NetCoreAppMinimum);netstandard2.0;$(NetFrameworkMinimum)</TargetFrameworks> <TargetFrameworks>$(NetCoreAppCurrent)-windows;$(NetCoreAppCurrent);$(NetCoreAppPrevious)-windows;$(NetCoreAppPrevious);$(NetCoreAppMinimum)-windows;$(NetCoreAppMinimum);netstandard2.0;$(NetFrameworkMinimum)</TargetFrameworks>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks> <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<NoWarn>$(NoWarn);CA1847</NoWarn>
<!-- Suppressions to avoid ifdefs:
CA1845: Use span-based 'string.Concat' and 'AsSpan' instead of 'Substring'
CA1846: Prefer 'AsSpan' over 'Substring' when span-based overloads are available -->
<NoWarn>$(NoWarn);CA1845;CA1846</NoWarn>
<Nullable>annotations</Nullable> <Nullable>annotations</Nullable>
<IsPackable>true</IsPackable> <IsPackable>true</IsPackable>
<PackageDescription>Provides the System.Diagnostics.EventLog class, which allows the applications to use the Windows event log service. <PackageDescription>Provides the System.Diagnostics.EventLog class, which allows the applications to use the Windows event log service.

View file

@ -2,7 +2,6 @@
<PropertyGroup> <PropertyGroup>
<TargetFrameworks>$(NetCoreAppCurrent)-windows;$(NetCoreAppCurrent);$(NetCoreAppPrevious)-windows;$(NetCoreAppPrevious);$(NetCoreAppMinimum)-windows;$(NetCoreAppMinimum);netstandard2.0;$(NetFrameworkMinimum)</TargetFrameworks> <TargetFrameworks>$(NetCoreAppCurrent)-windows;$(NetCoreAppCurrent);$(NetCoreAppPrevious)-windows;$(NetCoreAppPrevious);$(NetCoreAppMinimum)-windows;$(NetCoreAppMinimum);netstandard2.0;$(NetFrameworkMinimum)</TargetFrameworks>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks> <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<NoWarn>$(NoWarn);CA1847</NoWarn>
<Nullable>annotations</Nullable> <Nullable>annotations</Nullable>
<IsPackable>true</IsPackable> <IsPackable>true</IsPackable>
<PackageDescription>Provides the System.Diagnostics.PerformanceCounter class, which allows access to Windows performance counters. <PackageDescription>Provides the System.Diagnostics.PerformanceCounter class, which allows access to Windows performance counters.

View file

@ -1,13 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFrameworks>$(NetCoreAppCurrent)-windows;$(NetCoreAppCurrent);$(NetCoreAppPrevious)-windows;$(NetCoreAppPrevious);$(NetCoreAppMinimum)-windows;$(NetCoreAppMinimum);netstandard2.0</TargetFrameworks> <TargetFrameworks>$(NetCoreAppCurrent)-windows;$(NetCoreAppCurrent);$(NetCoreAppPrevious)-windows;$(NetCoreAppPrevious);$(NetCoreAppMinimum)-windows;$(NetCoreAppMinimum);netstandard2.0</TargetFrameworks>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks> <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<IncludeDllSafeSearchPathAttribute>true</IncludeDllSafeSearchPathAttribute> <IncludeDllSafeSearchPathAttribute>true</IncludeDllSafeSearchPathAttribute>
<NoWarn>$(NoWarn);CA2249</NoWarn> <NoWarn>$(NoWarn);CA2249</NoWarn>
<!-- Suppressions to avoid ifdefs: <NoWarn>$(NoWarn);IDE0059;IDE0060;CA1822</NoWarn>
CA1845: Use span-based 'string.Concat' and 'AsSpan' instead of 'Substring'
CA1846: Prefer 'AsSpan' over 'Substring' when span-based overloads are available -->
<NoWarn>$(NoWarn);CA1845;CA1846;IDE0059;IDE0060;CA1822</NoWarn>
<Nullable>annotations</Nullable> <Nullable>annotations</Nullable>
<IsPackable>true</IsPackable> <IsPackable>true</IsPackable>
<AddNETFrameworkPlaceholderFileToPackage>true</AddNETFrameworkPlaceholderFileToPackage> <AddNETFrameworkPlaceholderFileToPackage>true</AddNETFrameworkPlaceholderFileToPackage>

View file

@ -1,12 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFrameworks>$(NetCoreAppCurrent)-windows;$(NetCoreAppCurrent);$(NetCoreAppPrevious)-windows;$(NetCoreAppPrevious);$(NetCoreAppMinimum)-windows;$(NetCoreAppMinimum);netstandard2.0</TargetFrameworks> <TargetFrameworks>$(NetCoreAppCurrent)-windows;$(NetCoreAppCurrent);$(NetCoreAppPrevious)-windows;$(NetCoreAppPrevious);$(NetCoreAppMinimum)-windows;$(NetCoreAppMinimum);netstandard2.0</TargetFrameworks>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks> <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<IncludeInternalObsoleteAttribute>true</IncludeInternalObsoleteAttribute> <IncludeInternalObsoleteAttribute>true</IncludeInternalObsoleteAttribute>
<!-- Suppressions to avoid ifdefs: <NoWarn>$(NoWarn);IDE0059;IDE0060;CA1822</NoWarn>
CA1845: Use span-based 'string.Concat' and 'AsSpan' instead of 'Substring'
CA1846: Prefer 'AsSpan' over 'Substring' when span-based overloads are available -->
<NoWarn>$(NoWarn);CA1845;CA1846;IDE0059;IDE0060;CA1822</NoWarn>
<IsPackable>true</IsPackable> <IsPackable>true</IsPackable>
<AddNETFrameworkPlaceholderFileToPackage>true</AddNETFrameworkPlaceholderFileToPackage> <AddNETFrameworkPlaceholderFileToPackage>true</AddNETFrameworkPlaceholderFileToPackage>
<AddNETFrameworkAssemblyReferenceToPackage>true</AddNETFrameworkAssemblyReferenceToPackage> <AddNETFrameworkAssemblyReferenceToPackage>true</AddNETFrameworkAssemblyReferenceToPackage>

View file

@ -2,8 +2,6 @@
<PropertyGroup> <PropertyGroup>
<TargetFrameworks>$(NetCoreAppCurrent);$(NetCoreAppPrevious);$(NetCoreAppMinimum);netstandard2.0;$(NetFrameworkMinimum)</TargetFrameworks> <TargetFrameworks>$(NetCoreAppCurrent);$(NetCoreAppPrevious);$(NetCoreAppMinimum);netstandard2.0;$(NetFrameworkMinimum)</TargetFrameworks>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks> <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<!-- Suppress `string.Contains(char)` offers better performance than `string.Contains(string)` to avoid ifdefs.-->
<NoWarn>$(NoWarn);CA1847</NoWarn>
<IsPackable>true</IsPackable> <IsPackable>true</IsPackable>
<PackageDescription>Provides classes that support storage of multiple data objects in a single container.</PackageDescription> <PackageDescription>Provides classes that support storage of multiple data objects in a single container.</PackageDescription>
</PropertyGroup> </PropertyGroup>
@ -51,4 +49,4 @@
<ItemGroup Condition="'$(TargetFrameworkIdentifier)' == '.NETFramework'"> <ItemGroup Condition="'$(TargetFrameworkIdentifier)' == '.NETFramework'">
<Reference Include="WindowsBase" /> <Reference Include="WindowsBase" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View file

@ -1,11 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFrameworks>$(NetCoreAppCurrent)-windows;$(NetCoreAppCurrent);$(NetCoreAppPrevious)-windows;$(NetCoreAppPrevious);$(NetCoreAppMinimum)-windows;$(NetCoreAppMinimum);netstandard2.0</TargetFrameworks> <TargetFrameworks>$(NetCoreAppCurrent)-windows;$(NetCoreAppCurrent);$(NetCoreAppPrevious)-windows;$(NetCoreAppPrevious);$(NetCoreAppMinimum)-windows;$(NetCoreAppMinimum);netstandard2.0</TargetFrameworks>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks> <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<NoWarn>$(NoWarn);0618</NoWarn> <NoWarn>$(NoWarn);0618</NoWarn>
<!-- Suppressins to avoid ifdefs: <NoWarn>$(NoWarn);IDE0059;IDE0060;CA1822</NoWarn>
CA1845: Use span-based 'string.Concat' and 'AsSpan' instead of 'Substring'. -->
<NoWarn>$(NoWarn);CA1845;IDE0059;IDE0060;CA1822</NoWarn>
<Nullable>annotations</Nullable> <Nullable>annotations</Nullable>
<IncludeDllSafeSearchPathAttribute>true</IncludeDllSafeSearchPathAttribute> <IncludeDllSafeSearchPathAttribute>true</IncludeDllSafeSearchPathAttribute>
<IsPackable>true</IsPackable> <IsPackable>true</IsPackable>

View file

@ -1,8 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks> <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<TargetFrameworks>$(NetCoreAppCurrent)-windows;$(NetCoreAppCurrent)-linux;$(NetCoreAppCurrent)-osx;$(NetCoreAppCurrent)-freebsd;$(NetCoreAppCurrent)</TargetFrameworks> <TargetFrameworks>$(NetCoreAppCurrent)-windows;$(NetCoreAppCurrent)-linux;$(NetCoreAppCurrent)-osx;$(NetCoreAppCurrent)-freebsd;$(NetCoreAppCurrent)</TargetFrameworks>
<EnableAOTAnalyzer>true</EnableAOTAnalyzer> <EnableAOTAnalyzer>true</EnableAOTAnalyzer>
<!-- DllImports are in shared msquic interop file -->
<NoWarn>$(NoWarn);SYSLIB1054</NoWarn>
</PropertyGroup> </PropertyGroup>
<!-- DesignTimeBuild requires all the TargetFramework Derived Properties to not be present in the first property group. --> <!-- DesignTimeBuild requires all the TargetFramework Derived Properties to not be present in the first property group. -->
<PropertyGroup> <PropertyGroup>

View file

@ -4,8 +4,7 @@
<AllowUnsafeBlocks>true</AllowUnsafeBlocks> <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<!-- CS0649: uninitialized interop type fields --> <!-- CS0649: uninitialized interop type fields -->
<!-- SA1129: https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/3277 --> <!-- SA1129: https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/3277 -->
<!-- CA1846: Prefer 'AsSpan' over 'Substring' when span-based overloads are available --> <NoWarn>$(NoWarn);CS0649;SA1129;IDE0059;IDE0060;CA1822;CA1852</NoWarn>
<NoWarn>$(NoWarn);CS0649;SA1129;CA1846;CA1847;IDE0059;IDE0060;CA1822;CA1852</NoWarn>
<Nullable>annotations</Nullable> <Nullable>annotations</Nullable>
<IsTrimmable>false</IsTrimmable> <IsTrimmable>false</IsTrimmable>
<IsPackable>true</IsPackable> <IsPackable>true</IsPackable>

View file

@ -1221,11 +1221,13 @@ namespace Microsoft.WebAssembly.Diagnostics
logger.LogError($"Failed to load symbols from symbol server. ({ex.Message})"); logger.LogError($"Failed to load symbols from symbol server. ({ex.Message})");
} }
} }
}
} internal sealed partial class SourceFile
internal sealed class SourceFile
{ {
private static readonly Regex regexForEscapeFileName = new(@"([:/])", RegexOptions.Compiled); [GeneratedRegex(@"([:/])")]
private static partial Regex RegexForEscapeFileName();
private Dictionary<int, MethodInfo> methods; private Dictionary<int, MethodInfo> methods;
private AssemblyInfo assembly; private AssemblyInfo assembly;
private Document doc; private Document doc;
@ -1326,7 +1328,7 @@ namespace Microsoft.WebAssembly.Diagnostics
private static string EscapePathForUri(string path) private static string EscapePathForUri(string path)
{ {
var builder = new StringBuilder(); var builder = new StringBuilder();
foreach (var part in regexForEscapeFileName.Split(path)) foreach (var part in RegexForEscapeFileName().Split(path))
{ {
if (part == ":" || part == "/") if (part == ":" || part == "/")
builder.Append(part); builder.Append(part);

View file

@ -24,7 +24,7 @@ using Microsoft.Extensions.Logging;
namespace Microsoft.WebAssembly.Diagnostics namespace Microsoft.WebAssembly.Diagnostics
{ {
internal static class ExpressionEvaluator internal static partial class ExpressionEvaluator
{ {
internal static Script<object> script = CSharpScript.Create( internal static Script<object> script = CSharpScript.Create(
"", "",
@ -33,9 +33,11 @@ namespace Microsoft.WebAssembly.Diagnostics
typeof(Enumerable).Assembly, typeof(Enumerable).Assembly,
typeof(JObject).Assembly typeof(JObject).Assembly
)); ));
private sealed class ExpressionSyntaxReplacer : CSharpSyntaxWalker private sealed partial class ExpressionSyntaxReplacer : CSharpSyntaxWalker
{ {
private static Regex regexForReplaceVarName = new Regex(@"[^A-Za-z0-9_]", RegexOptions.Singleline); [GeneratedRegex(@"[^A-Za-z0-9_]", RegexOptions.Singleline)]
private static partial Regex RegexForReplaceVarName();
public List<IdentifierNameSyntax> identifiers = new List<IdentifierNameSyntax>(); public List<IdentifierNameSyntax> identifiers = new List<IdentifierNameSyntax>();
public List<InvocationExpressionSyntax> methodCalls = new List<InvocationExpressionSyntax>(); public List<InvocationExpressionSyntax> methodCalls = new List<InvocationExpressionSyntax>();
public List<MemberAccessExpressionSyntax> memberAccesses = new List<MemberAccessExpressionSyntax>(); public List<MemberAccessExpressionSyntax> memberAccesses = new List<MemberAccessExpressionSyntax>();
@ -111,7 +113,7 @@ namespace Microsoft.WebAssembly.Diagnostics
{ {
// Generate a random suffix // Generate a random suffix
string suffix = Guid.NewGuid().ToString().Substring(0, 5); string suffix = Guid.NewGuid().ToString().Substring(0, 5);
string prefix = regexForReplaceVarName.Replace(ma_str, "_"); string prefix = RegexForReplaceVarName().Replace(ma_str, "_");
id_name = $"{prefix}_{suffix}"; id_name = $"{prefix}_{suffix}";
memberAccessToParamName[ma_str] = id_name; memberAccessToParamName[ma_str] = id_name;
@ -128,7 +130,7 @@ namespace Microsoft.WebAssembly.Diagnostics
{ {
// Generate a random suffix // Generate a random suffix
string suffix = Guid.NewGuid().ToString().Substring(0, 5); string suffix = Guid.NewGuid().ToString().Substring(0, 5);
string prefix = regexForReplaceVarName.Replace(iesStr, "_"); string prefix = RegexForReplaceVarName().Replace(iesStr, "_");
id_name = $"{prefix}_{suffix}"; id_name = $"{prefix}_{suffix}";
methodCallToParamName[iesStr] = id_name; methodCallToParamName[iesStr] = id_name;
} }
@ -144,7 +146,7 @@ namespace Microsoft.WebAssembly.Diagnostics
{ {
// Generate a random suffix // Generate a random suffix
string suffix = Guid.NewGuid().ToString().Substring(0, 5); string suffix = Guid.NewGuid().ToString().Substring(0, 5);
string prefix = regexForReplaceVarName.Replace(eaStr, "_"); string prefix = RegexForReplaceVarName().Replace(eaStr, "_");
id_name = $"{prefix}_{suffix}"; id_name = $"{prefix}_{suffix}";
elementAccessToParamName[eaStr] = id_name; elementAccessToParamName[eaStr] = id_name;
} }

View file

@ -785,7 +785,7 @@ namespace Microsoft.WebAssembly.Diagnostics
return _value; return _value;
} }
} }
internal sealed class MonoSDBHelper internal sealed partial class MonoSDBHelper
{ {
private static int debuggerObjectId; private static int debuggerObjectId;
private static int cmdId = 1; //cmdId == 0 is used by events which come from runtime private static int cmdId = 1; //cmdId == 0 is used by events which come from runtime
@ -804,12 +804,25 @@ namespace Microsoft.WebAssembly.Diagnostics
private SessionId sessionId; private SessionId sessionId;
internal readonly ILogger logger; internal readonly ILogger logger;
private static readonly Regex regexForAsyncLocals = new(@"\<(?<varName>[^)]*)\>(?<varId>[^)]*)(__)(?<scopeId>\d+)", RegexOptions.Singleline); //<testCSharpScope>5__1 // works
private static readonly Regex regexForVBAsyncLocals = new(@"\$VB\$ResumableLocal_(?<varName>[^\$]*)\$(?<scopeId>\d+)", RegexOptions.Singleline); //$VB$ResumableLocal_testVbScope$2 [GeneratedRegex(@"\<(?<varName>[^)]*)\>(?<varId>[^)]*)(__)(?<scopeId>\d+)", RegexOptions.Singleline)]
private static readonly Regex regexForVBAsyncMethodName = new(@"VB\$StateMachine_(\d+)_(?<methodName>.*)", RegexOptions.Singleline); //VB$StateMachine_2_RunVBScope private static partial Regex RegexForAsyncLocals(); //<testCSharpScope>5__1 // works
private static readonly Regex regexForAsyncMethodName = new (@"\<([^>]*)\>([d][_][_])([0-9]*)", RegexOptions.Compiled);
private static readonly Regex regexForGenericArgs = new (@"[`][0-9]+", RegexOptions.Compiled); [GeneratedRegex(@"\$VB\$ResumableLocal_(?<varName>[^\$]*)\$(?<scopeId>\d+)", RegexOptions.Singleline)]
private static readonly Regex regexForNestedLeftRightAngleBrackets = new ("^(((?'Open'<)[^<>]*)+((?'Close-Open'>)[^<>]*)+)*(?(Open)(?!))[^<>]*", RegexOptions.Compiled); // <ContinueWithStaticAsync>b__3_0 private static partial Regex RegexForVBAsyncLocals(); //$VB$ResumableLocal_testVbScope$2
[GeneratedRegex(@"VB\$StateMachine_(\d+)_(?<methodName>.*)", RegexOptions.Singleline)]
private static partial Regex RegexForVBAsyncMethodName(); //VB$StateMachine_2_RunVBScope
[GeneratedRegex(@"\<([^>]*)\>([d][_][_])([0-9]*)")]
private static partial Regex RegexForAsyncMethodName();
[GeneratedRegex(@"[`][0-9]+")]
private static partial Regex RegexForGenericArgs();
[GeneratedRegex("^(((?'Open'<)[^<>]*)+((?'Close-Open'>)[^<>]*)+)*(?(Open)(?!))[^<>]*")]
private static partial Regex RegexForNestedLeftRightAngleBrackets(); // <ContinueWithStaticAsync>b__3_0
public JObjectValueCreator ValueCreator { get; init; } public JObjectValueCreator ValueCreator { get; init; }
public static int GetNewId() { return cmdId++; } public static int GetNewId() { return cmdId++; }
@ -867,7 +880,7 @@ namespace Microsoft.WebAssembly.Diagnostics
{ {
methodName = methodName.Replace(':', '.'); methodName = methodName.Replace(':', '.');
methodName = methodName.Replace('/', '.'); methodName = methodName.Replace('/', '.');
methodName = regexForGenericArgs.Replace(methodName, ""); methodName = RegexForGenericArgs().Replace(methodName, "");
return methodName; return methodName;
} }
@ -1244,7 +1257,7 @@ namespace Microsoft.WebAssembly.Diagnostics
var ret = retDebuggerCmdReader.ReadString(); var ret = retDebuggerCmdReader.ReadString();
if (ret.IndexOf(':') is int index && index > 0) if (ret.IndexOf(':') is int index && index > 0)
ret = ret.Substring(0, index); ret = ret.Substring(0, index);
ret = regexForAsyncMethodName.Replace(ret, "$1"); ret = RegexForAsyncMethodName().Replace(ret, "$1");
var numGenericTypeArgs = retDebuggerCmdReader.ReadInt32(); var numGenericTypeArgs = retDebuggerCmdReader.ReadInt32();
var numGenericMethodArgs = retDebuggerCmdReader.ReadInt32(); var numGenericMethodArgs = retDebuggerCmdReader.ReadInt32();
int numTotalGenericArgs = numGenericTypeArgs + numGenericMethodArgs; int numTotalGenericArgs = numGenericTypeArgs + numGenericMethodArgs;
@ -1252,17 +1265,17 @@ namespace Microsoft.WebAssembly.Diagnostics
for (int i = 0; i < numTotalGenericArgs; i++) for (int i = 0; i < numTotalGenericArgs; i++)
{ {
var typeArgC = retDebuggerCmdReader.ReadString(); var typeArgC = retDebuggerCmdReader.ReadString();
typeArgC = regexForGenericArgs.Replace(typeArgC, ""); typeArgC = RegexForGenericArgs().Replace(typeArgC, "");
genericArgs.Add(typeArgC); genericArgs.Add(typeArgC);
} }
var match = regexForGenericArgs.Match(ret); var match = RegexForGenericArgs().Match(ret);
while (match.Success) while (match.Success)
{ {
var countArgs = Convert.ToInt32(match.Value.Remove(0, 1)); var countArgs = Convert.ToInt32(match.Value.Remove(0, 1));
ret = ret.Remove(match.Index, match.Value.Length); ret = ret.Remove(match.Index, match.Value.Length);
ret = ret.Insert(match.Index, $"<{string.Join(", ", genericArgs.Take(countArgs))}>"); ret = ret.Insert(match.Index, $"<{string.Join(", ", genericArgs.Take(countArgs))}>");
genericArgs.RemoveRange(0, countArgs); genericArgs.RemoveRange(0, countArgs);
match = regexForGenericArgs.Match(ret); match = RegexForGenericArgs().Match(ret);
} }
ret = ret.Replace('/', '.'); ret = ret.Replace('/', '.');
return ret; return ret;
@ -1282,7 +1295,7 @@ namespace Microsoft.WebAssembly.Diagnostics
} }
else if (klassName.StartsWith("VB$")) else if (klassName.StartsWith("VB$"))
{ {
var match = regexForVBAsyncMethodName.Match(klassName); var match = RegexForVBAsyncMethodName().Match(klassName);
if (match.Success) if (match.Success)
ret = ret.Insert(0, match.Groups["methodName"].Value); ret = ret.Insert(0, match.Groups["methodName"].Value);
else else
@ -1290,7 +1303,7 @@ namespace Microsoft.WebAssembly.Diagnostics
} }
else else
{ {
var matchOnClassName = regexForNestedLeftRightAngleBrackets.Match(klassName); var matchOnClassName = RegexForNestedLeftRightAngleBrackets().Match(klassName);
if (matchOnClassName.Success && matchOnClassName.Groups["Close"].Captures.Count > 0) if (matchOnClassName.Success && matchOnClassName.Groups["Close"].Captures.Count > 0)
klassName = matchOnClassName.Groups["Close"].Captures[0].Value; klassName = matchOnClassName.Groups["Close"].Captures[0].Value;
if (ret.Length > 0) if (ret.Length > 0)
@ -1299,7 +1312,7 @@ namespace Microsoft.WebAssembly.Diagnostics
} }
} }
var methodName = retDebuggerCmdReader.ReadString(); var methodName = retDebuggerCmdReader.ReadString();
var matchOnMethodName = regexForNestedLeftRightAngleBrackets.Match(methodName); var matchOnMethodName = RegexForNestedLeftRightAngleBrackets().Match(methodName);
if (matchOnMethodName.Success && matchOnMethodName.Groups["Close"].Captures.Count > 0) if (matchOnMethodName.Success && matchOnMethodName.Groups["Close"].Captures.Count > 0)
{ {
if (isAnonymous && anonymousMethodId.Length == 0 && methodName.Contains("__")) if (isAnonymous && anonymousMethodId.Length == 0 && methodName.Contains("__"))
@ -1653,12 +1666,18 @@ namespace Microsoft.WebAssembly.Diagnostics
return null; return null;
} }
[GeneratedRegex(@"`\d+")]
private static partial Regex RegexForGenericArity();
[GeneratedRegex(@"[[, ]+]")]
private static partial Regex RegexForSquareBrackets();
public async Task<string> GetTypeName(int typeId, CancellationToken token) public async Task<string> GetTypeName(int typeId, CancellationToken token)
{ {
string className = await GetTypeNameOriginal(typeId, token); string className = await GetTypeNameOriginal(typeId, token);
className = className.Replace("+", "."); className = className.Replace("+", ".");
className = Regex.Replace(className, @"`\d+", ""); className = RegexForGenericArity().Replace(className, "");
className = Regex.Replace(className, @"[[, ]+]", "__SQUARED_BRACKETS__"); className = RegexForSquareBrackets().Replace(className, "__SQUARED_BRACKETS__");
//className = className.Replace("[]", "__SQUARED_BRACKETS__"); //className = className.Replace("[]", "__SQUARED_BRACKETS__");
className = className.Replace("[", "<"); className = className.Replace("[", "<");
className = className.Replace("]", ">"); className = className.Replace("]", ">");
@ -2001,7 +2020,7 @@ namespace Microsoft.WebAssembly.Diagnostics
} }
else if (fieldName.StartsWith('<')) //examples: <code>5__2 else if (fieldName.StartsWith('<')) //examples: <code>5__2
{ {
var match = regexForAsyncLocals.Match(fieldName); var match = RegexForAsyncLocals().Match(fieldName);
if (match.Success) if (match.Success)
{ {
if (!method.Info.ContainsAsyncScope(Convert.ToInt32(match.Groups["scopeId"].Value), offset)) if (!method.Info.ContainsAsyncScope(Convert.ToInt32(match.Groups["scopeId"].Value), offset))
@ -2016,7 +2035,7 @@ namespace Microsoft.WebAssembly.Diagnostics
} }
else if (fieldName.StartsWith("$VB$ResumableLocal_", StringComparison.Ordinal)) else if (fieldName.StartsWith("$VB$ResumableLocal_", StringComparison.Ordinal))
{ {
var match = regexForVBAsyncLocals.Match(fieldName); var match = RegexForVBAsyncLocals().Match(fieldName);
if (match.Success) if (match.Success)
{ {
if (!method.Info.ContainsAsyncScope(Convert.ToInt32(match.Groups["scopeId"].Value) + 1, offset)) if (!method.Info.ContainsAsyncScope(Convert.ToInt32(match.Groups["scopeId"].Value) + 1, offset))

View file

@ -785,7 +785,7 @@ namespace Mono.Options
public delegate void OptionAction<TKey, TValue>(TKey key, TValue value); public delegate void OptionAction<TKey, TValue>(TKey key, TValue value);
public class OptionSet : KeyedCollection<string, Option> public partial class OptionSet : KeyedCollection<string, Option>
{ {
public OptionSet() public OptionSet()
: this(null, null) : this(null, null)
@ -1148,15 +1148,15 @@ namespace Mono.Options
return false; return false;
} }
private readonly Regex ValueOption = new Regex( [GeneratedRegex(@"^(?<flag>--|-|/)(?<name>[^:=]+)((?<sep>[:=])(?<value>.*))?$")]
@"^(?<flag>--|-|/)(?<name>[^:=]+)((?<sep>[:=])(?<value>.*))?$"); private static partial Regex ValueOption();
protected bool GetOptionParts(string argument, out string flag, out string name, out string sep, out string value) protected bool GetOptionParts(string argument, out string flag, out string name, out string sep, out string value)
{ {
ArgumentNullException.ThrowIfNull(argument); ArgumentNullException.ThrowIfNull(argument);
flag = name = sep = value = null; flag = name = sep = value = null;
Match m = ValueOption.Match(argument); Match m = ValueOption().Match(argument);
if (!m.Success) if (!m.Success)
{ {
return false; return false;
@ -1461,9 +1461,12 @@ namespace Mono.Options
o.Write(s); o.Write(s);
} }
[GeneratedRegex(@"(?<=(?<!\{)\{)[^{}]*(?=\}(?!\}))")]
private static partial Regex IgnoreDoubleBracesRegex();
private static string GetArgumentName(int index, int maxIndex, string description) private static string GetArgumentName(int index, int maxIndex, string description)
{ {
var matches = Regex.Matches(description ?? "", @"(?<=(?<!\{)\{)[^{}]*(?=\}(?!\}))"); // ignore double braces var matches = IgnoreDoubleBracesRegex().Matches(description ?? "");
string argName = ""; string argName = "";
foreach (Match match in matches) foreach (Match match in matches)
{ {

View file

@ -10,7 +10,7 @@ using System.Text.RegularExpressions;
using Microsoft.Build.Framework; using Microsoft.Build.Framework;
using Microsoft.Build.Utilities; using Microsoft.Build.Utilities;
public class ApkBuilder public partial class ApkBuilder
{ {
private const string DefaultMinApiLevel = "21"; private const string DefaultMinApiLevel = "21";
private const string DefaultTargetApiLevel = "31"; private const string DefaultTargetApiLevel = "31";
@ -380,7 +380,7 @@ public class ApkBuilder
string javaActivityPath = Path.Combine(javaSrcFolder, "MainActivity.java"); string javaActivityPath = Path.Combine(javaSrcFolder, "MainActivity.java");
string monoRunnerPath = Path.Combine(javaSrcFolder, "MonoRunner.java"); string monoRunnerPath = Path.Combine(javaSrcFolder, "MonoRunner.java");
Regex checkNumerics = new Regex(@"\.(\d)"); Regex checkNumerics = DotNumberRegex();
if (!string.IsNullOrEmpty(ProjectName) && checkNumerics.IsMatch(ProjectName)) if (!string.IsNullOrEmpty(ProjectName) && checkNumerics.IsMatch(ProjectName))
ProjectName = checkNumerics.Replace(ProjectName, @"_$1"); ProjectName = checkNumerics.Replace(ProjectName, @"_$1");
@ -633,4 +633,7 @@ public class ApkBuilder
.FirstOrDefault() .FirstOrDefault()
.ToString(); .ToString();
} }
[GeneratedRegex(@"\.(\d)")]
private static partial Regex DotNumberRegex();
} }

View file

@ -2172,7 +2172,11 @@ namespace Mono.Linker.Steps
} }
} }
static readonly Regex DebuggerDisplayAttributeValueRegex = new Regex ("{[^{}]+}", RegexOptions.Compiled); [GeneratedRegex ("{[^{}]+}")]
private static partial Regex DebuggerDisplayAttributeValueRegex ();
[GeneratedRegex (@".+,\s*nq")]
private static partial Regex ContainsNqSuffixRegex ();
void MarkTypeWithDebuggerDisplayAttribute (TypeDefinition type, CustomAttribute attribute) void MarkTypeWithDebuggerDisplayAttribute (TypeDefinition type, CustomAttribute attribute)
{ {
@ -2186,13 +2190,13 @@ namespace Mono.Linker.Steps
if (string.IsNullOrEmpty (displayString)) if (string.IsNullOrEmpty (displayString))
return; return;
foreach (Match match in DebuggerDisplayAttributeValueRegex.Matches (displayString)) { foreach (Match match in DebuggerDisplayAttributeValueRegex ().Matches (displayString)) {
// Remove '{' and '}' // Remove '{' and '}'
string realMatch = match.Value.Substring (1, match.Value.Length - 2); string realMatch = match.Value.Substring (1, match.Value.Length - 2);
// Remove ",nq" suffix if present // Remove ",nq" suffix if present
// (it asks the expression evaluator to remove the quotes when displaying the final value) // (it asks the expression evaluator to remove the quotes when displaying the final value)
if (Regex.IsMatch (realMatch, @".+,\s*nq")) { if (ContainsNqSuffixRegex ().IsMatch(realMatch)) {
realMatch = realMatch.Substring (0, realMatch.LastIndexOf (',')); realMatch = realMatch.Substring (0, realMatch.LastIndexOf (','));
} }