diff --git a/src/coreclr/debug/ee/amd64/gen_amd64InstrDecode/Amd64InstructionTableGenerator.cs b/src/coreclr/debug/ee/amd64/gen_amd64InstrDecode/Amd64InstructionTableGenerator.cs index 0e55c4c2d4fac3..498b2cfb718e2c 100644 --- a/src/coreclr/debug/ee/amd64/gen_amd64InstrDecode/Amd64InstructionTableGenerator.cs +++ b/src/coreclr/debug/ee/amd64/gen_amd64InstrDecode/Amd64InstructionTableGenerator.cs @@ -125,16 +125,16 @@ internal sealed partial class Amd64InstructionSample @"(?(\S[^#]*?)?)\s*" + @"(?#.*)?$", RegexOptions.ExplicitCapture)] - private static partial Regex EncDisassemblySplit(); + private static partial Regex EncDisassemblySplit { get; } [GeneratedRegex(@"^\s*,?\s*(?[^\(,]*(\([^\)]*\))?)?(?.+$)?", RegexOptions.ExplicitCapture)] - private static partial Regex EncOperandSplit(); + private static partial Regex EncOperandSplit { get; } [GeneratedRegex(@"\[.*\]({1to[0-9]+})?$")] - private static partial Regex EncOperandIsMemOp(); + private static partial Regex EncOperandIsMemOp { get; } [GeneratedRegex(@"\[rip.*\]({1to[0-9]+})?$")] - private static partial Regex EncOperandIsMOp(); + private static partial Regex EncOperandIsMOp { get; } private static readonly HashSet allOperands = new HashSet(); @@ -255,7 +255,7 @@ public Amd64InstructionSample(string disassembly_) if (Debug.debug) Console.WriteLine($"new sample: {disassembly}"); - var match = EncDisassemblySplit().Match(disassembly); + var match = EncDisassemblySplit.Match(disassembly); if (Debug.debug) { @@ -299,7 +299,7 @@ private static List parseOperands(string operandDisassembly) while (rest?.Length != 0) { - var opMatch = EncOperandSplit().Match(rest); + var opMatch = EncOperandSplit.Match(rest); string op = opMatch.Groups["op"].ToString(); operands.Add(op); @@ -593,7 +593,7 @@ public SuffixFlags parseSuffix() for (int i = 0; i < operands.Count; i++) { string operand = operands[i]; - bool memop = EncOperandIsMemOp().IsMatch(operand); + bool memop = EncOperandIsMemOp.IsMatch(operand); if (memop) { @@ -603,7 +603,7 @@ public SuffixFlags parseSuffix() accounted += hasSIB ? 6 : 5; - if (EncOperandIsMOp().IsMatch(operand)) + if (EncOperandIsMOp.IsMatch(operand)) { if (i == 0) { @@ -661,11 +661,11 @@ internal sealed partial class Amd64InstructionTableGenerator private List samples = new List(); [GeneratedRegex(@"^\s+0x00000000")] - private static partial Regex AssemblyPrefix(); + private static partial Regex AssemblyPrefix { get; } // The '0x' prefix is not included in the regex match. [GeneratedRegex(@"^\s*0x(?
[0-9a-fA-F]+)", RegexOptions.ExplicitCapture)] - private static partial Regex AssemblyAddress(); + private static partial Regex AssemblyAddress { get; } // NOTE: APX instructions push2/push2p/pop2/pop2p are not causing gdb to report an illegal instruction, // which is causing problems. So manually disallow them. @@ -673,7 +673,7 @@ internal sealed partial class Amd64InstructionTableGenerator // can be encoded with either an EVEX or VEX encoding, and the disassembler will annotate the instruction with // `{evex}` to indicate it is not the canonical encoding. [GeneratedRegex(@"((push2)|(pop2)|(\{vex\})|(\{bad\})|(\(bad\))|(\srex(\.[WRXB]*)?\s*(#.*)?$))")] - private static partial Regex BadDisassembly(); + private static partial Regex BadDisassembly { get; } private List<(Map, int)> regExpandOpcodes; @@ -737,7 +737,7 @@ private void ParseSamples() { //if (Debug.debug) Console.WriteLine($"line: {line}"); - var match = AssemblyAddress().Match(line); + var match = AssemblyAddress.Match(line); if (!match.Success) { continue; @@ -759,7 +759,7 @@ private void ParseSamples() continue; } - if (!BadDisassembly().IsMatch(sample)) + if (!BadDisassembly.IsMatch(sample)) { try { diff --git a/src/coreclr/ilasm/GrammarExtractor/Program.cs b/src/coreclr/ilasm/GrammarExtractor/Program.cs index a993e32fcda00a..2184e40e4d4e09 100644 --- a/src/coreclr/ilasm/GrammarExtractor/Program.cs +++ b/src/coreclr/ilasm/GrammarExtractor/Program.cs @@ -16,7 +16,7 @@ string fileContent = File.ReadAllText(filePath); -var match = GetRegexExtractMarkers().Match(fileContent); +var match = GetRegexExtractMarkers.Match(fileContent); if (!match.Success) { Console.Error.WriteLine("Could not find %% markers"); @@ -27,7 +27,7 @@ string grammar = match.Groups[2].Value; // Remove any text in {} -var regexRemoveTextInBraces = GetRegexRemoveTextInBraces(); +var regexRemoveTextInBraces = GetRegexRemoveTextInBraces; string previousGrammar; do @@ -37,14 +37,14 @@ } while (grammar != previousGrammar); // Change keyword identifiers into the string they represent (lowercase) -grammar = GetRegexKeywordIdentifiers().Replace(grammar, m => $"'{m.Groups[1].Value.ToLowerInvariant()}'"); +grammar = GetRegexKeywordIdentifiers.Replace(grammar, m => $"'{m.Groups[1].Value.ToLowerInvariant()}'"); // Change assembler directives into their string (lowercase with a period) -grammar = GetRegexAssemblerDirectives().Replace(grammar, m => $"'.{m.Groups[1].Value.ToLowerInvariant()}'"); +grammar = GetRegexAssemblerDirectives.Replace(grammar, m => $"'.{m.Groups[1].Value.ToLowerInvariant()}'"); // Handle special punctuation -grammar = GetRegexEllipsis().Replace(grammar, "'...'"); -grammar = GetRegexDcolon().Replace(grammar, "'::'"); +grammar = GetRegexEllipsis.Replace(grammar, "'...'"); +grammar = GetRegexDcolon.Replace(grammar, "'::'"); // Print the output header Console.Write(@"// Licensed to the .NET Foundation under one or more agreements. @@ -79,20 +79,20 @@ Auxiliary lexical tokens internal static partial class Patterns { [GeneratedRegex(@"^(.*)%%(.*)%%", RegexOptions.Singleline)] - internal static partial Regex GetRegexExtractMarkers(); + internal static partial Regex GetRegexExtractMarkers { get; } [GeneratedRegex(@"\s*([^'])\{[^{}]*\}", RegexOptions.Singleline)] - internal static partial Regex GetRegexRemoveTextInBraces(); + internal static partial Regex GetRegexRemoveTextInBraces { get; } [GeneratedRegex(@"\b([A-Z0-9_]+)_\b", RegexOptions.Singleline)] - internal static partial Regex GetRegexKeywordIdentifiers(); + internal static partial Regex GetRegexKeywordIdentifiers { get; } [GeneratedRegex(@"\b_([A-Z0-9]+)\b", RegexOptions.Singleline)] - internal static partial Regex GetRegexAssemblerDirectives(); + internal static partial Regex GetRegexAssemblerDirectives { get; } [GeneratedRegex(@"\bELLIPSIS\b", RegexOptions.Singleline)] - internal static partial Regex GetRegexEllipsis(); + internal static partial Regex GetRegexEllipsis { get; } [GeneratedRegex(@"\bDCOLON\b", RegexOptions.Singleline)] - internal static partial Regex GetRegexDcolon(); + internal static partial Regex GetRegexDcolon { get; } } diff --git a/src/coreclr/inc/CrstTypeTool/CrstTypeTool.cs b/src/coreclr/inc/CrstTypeTool/CrstTypeTool.cs index 5db0a5527dae2d..32e76ef0485b7b 100644 --- a/src/coreclr/inc/CrstTypeTool/CrstTypeTool.cs +++ b/src/coreclr/inc/CrstTypeTool/CrstTypeTool.cs @@ -472,10 +472,10 @@ internal sealed partial class TypeFileParser // Compile regular expressions for detecting comments and tokens in the parser input. [GeneratedRegex(@"//.*")] - private static partial Regex CommentRegex(); + private static partial Regex CommentRegex { get; } [GeneratedRegex(@"^(\s*(\S+)\s*)*")] - private static partial Regex TokenRegex(); + private static partial Regex TokenRegex { get; } // Input is lexed into an array of tokens. We record the index of the token being currently parsed. private Token[] m_tokens; @@ -630,10 +630,10 @@ private void InitTokenStream() while ((line = file.ReadLine()) != null) { // Remove comments from the current line. - line = CommentRegex().Replace(line, ""); + line = CommentRegex.Replace(line, ""); // Match all contiguous non-whitespace characters as individual tokens. - Match match = TokenRegex().Match(line); + Match match = TokenRegex.Match(line); if (match.Success) { // For each token captured build a token instance and record the token text and the file, line diff --git a/src/coreclr/tools/cdac-build-tool/ContractDescriptorSourceFileEmitter.cs b/src/coreclr/tools/cdac-build-tool/ContractDescriptorSourceFileEmitter.cs index 02927cb1ff84ef..735a8cc7e6b09b 100644 --- a/src/coreclr/tools/cdac-build-tool/ContractDescriptorSourceFileEmitter.cs +++ b/src/coreclr/tools/cdac-build-tool/ContractDescriptorSourceFileEmitter.cs @@ -23,7 +23,7 @@ public ContractDescriptorSourceFileEmitter(string templateFilePath) } [GeneratedRegex("%%([a-zA-Z0-9_]+)%%", RegexOptions.CultureInvariant)] - private static partial Regex FindTemplatePlaceholderRegex(); + private static partial Regex FindTemplatePlaceholderRegex { get; } private string GetTemplateString() { @@ -44,20 +44,20 @@ public void SetPlatformFlags(uint platformFlags) public void SetJsonDescriptor(string jsonDescriptor) { var count = jsonDescriptor.Length; // return the length before escaping - var escaped = CStringEscape().Replace(jsonDescriptor, "\\$1"); + var escaped = CStringEscape.Replace(jsonDescriptor, "\\$1"); Elements[JsonDescriptorKey] = escaped; Elements[JsonDescriptorSizeKey] = count.ToString(); } [GeneratedRegex("(\")", RegexOptions.CultureInvariant)] - private static partial Regex CStringEscape(); + private static partial Regex CStringEscape { get; } public Dictionary Elements { get; } = new(); public void Emit(TextWriter dest) { var template = GetTemplateString(); - var matches = FindTemplatePlaceholderRegex().Matches(template); + var matches = FindTemplatePlaceholderRegex.Matches(template); var prevPos = 0; foreach (Match match in matches) { diff --git a/src/libraries/Common/src/System/Data/Common/DbConnectionOptions.Common.cs b/src/libraries/Common/src/System/Data/Common/DbConnectionOptions.Common.cs index da3b254f99eb25..7852f3f2b7029f 100644 --- a/src/libraries/Common/src/System/Data/Common/DbConnectionOptions.Common.cs +++ b/src/libraries/Common/src/System/Data/Common/DbConnectionOptions.Common.cs @@ -47,37 +47,30 @@ internal partial class DbConnectionOptions + "[\\s;]*[\u0000\\s]*" // trailing whitespace/semicolons (DataSourceLocator), embedded nulls are allowed only in the end ; - private static readonly Regex s_connectionStringRegex = CreateConnectionStringRegex(); - private static readonly Regex s_connectionStringRegexOdbc = CreateConnectionStringRegexOdbc(); - #if NET [GeneratedRegex(ConnectionStringPattern, RegexOptions.ExplicitCapture)] - private static partial Regex CreateConnectionStringRegex(); + private static partial Regex ConnectionStringRegex { get; } [GeneratedRegex(ConnectionStringPatternOdbc, RegexOptions.ExplicitCapture)] - private static partial Regex CreateConnectionStringRegexOdbc(); + private static partial Regex ConnectionStringRegexOdbc { get; } #else - private static Regex CreateConnectionStringRegex() => new Regex(ConnectionStringPattern, RegexOptions.ExplicitCapture | RegexOptions.Compiled); - private static Regex CreateConnectionStringRegexOdbc() => new Regex(ConnectionStringPatternOdbc, RegexOptions.ExplicitCapture | RegexOptions.Compiled); + private static Regex ConnectionStringRegex { get; } = new Regex(ConnectionStringPattern, RegexOptions.ExplicitCapture | RegexOptions.Compiled); + private static Regex ConnectionStringRegexOdbc { get; } = new Regex(ConnectionStringPatternOdbc, RegexOptions.ExplicitCapture | RegexOptions.Compiled); #endif #endif internal const string DataDirectory = "|datadirectory|"; - 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_connectionStringQuoteValueRegex = CreateConnectionStringQuoteValueRegex(); // 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 - #if NET [GeneratedRegex("^(?![;\\s])[^\\p{Cc}]+(? new Regex("^(?![;\\s])[^\\p{Cc}]+(? new Regex("^[^\"'=;\\s\\p{Cc}]*$", RegexOptions.Compiled); - private static Regex CreateConnectionStringQuoteOdbcValueRegex() => new Regex("^\\{([^\\}\u0000]|\\}\\})*\\}$", RegexOptions.ExplicitCapture | RegexOptions.Compiled); + private static Regex ConnectionStringValidKeyRegex { get; } = new Regex("^(?![;\\s])[^\\p{Cc}]+(? SplitConnectionString(string connectionString, Dictionary? synonyms, bool firstKey) { var parsetable = new Dictionary(); - Regex parser = (firstKey ? s_connectionStringRegexOdbc : s_connectionStringRegex); + Regex parser = (firstKey ? ConnectionStringRegexOdbc : ConnectionStringRegex); const int KeyIndex = 1, ValueIndex = 2; Debug.Assert(KeyIndex == parser.GroupNumberFromName("key"), "wrong key index"); diff --git a/src/libraries/Common/tests/TestUtilities.Unicode/System/Text/Unicode/PropsFileEntry.cs b/src/libraries/Common/tests/TestUtilities.Unicode/System/Text/Unicode/PropsFileEntry.cs index c664fa8c9de7ad..c56672f6950c0f 100644 --- a/src/libraries/Common/tests/TestUtilities.Unicode/System/Text/Unicode/PropsFileEntry.cs +++ b/src/libraries/Common/tests/TestUtilities.Unicode/System/Text/Unicode/PropsFileEntry.cs @@ -32,7 +32,7 @@ private PropsFileEntry(uint firstCodePoint, uint lastCodePoint, string propName) public static bool TryParseLine(string line, [NotNullWhen(true)] out PropsFileEntry? value) { - Match match = GetRegex().Match(line); + Match match = GetRegex.Match(line); if (!match.Success) { @@ -53,6 +53,6 @@ public static bool TryParseLine(string line, [NotNullWhen(true)] out PropsFileEn } [GeneratedRegex(@"^\s*(?[0-9a-f]{4,})(\.\.(?[0-9a-f]{4,}))?\s*;\s*(?.+?)\s*(#\s*(?.*))?$", RegexOptions.IgnoreCase)] - private static partial Regex GetRegex(); + private static partial Regex GetRegex { get; } } } diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DbConnectionOptions.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DbConnectionOptions.cs index 26870bfdb23f11..e8d47b42e975c0 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DbConnectionOptions.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DbConnectionOptions.cs @@ -57,7 +57,7 @@ internal static void AppendKeyValuePairBuilder(StringBuilder builder, string key ADP.CheckArgumentNull(builder, nameof(builder)); ADP.CheckArgumentLength(keyName, nameof(keyName)); - if ((null == keyName) || !s_connectionStringValidKeyRegex.IsMatch(keyName)) + if ((null == keyName) || !ConnectionStringValidKeyRegex.IsMatch(keyName)) { throw ADP.InvalidKeyname(keyName); } @@ -89,7 +89,7 @@ internal static void AppendKeyValuePairBuilder(StringBuilder builder, string key if ((0 < keyValue.Length) && // string.Contains(char) is .NetCore2.1+ specific (('{' == keyValue[0]) || (0 <= keyValue.IndexOf(';')) || string.Equals(DbConnectionStringKeywords.Driver, keyName, StringComparison.OrdinalIgnoreCase)) && - !s_connectionStringQuoteOdbcValueRegex.IsMatch(keyValue)) + !ConnectionStringQuoteOdbcValueRegex.IsMatch(keyValue)) { // always quote Driver value (required for ODBC Version 2.65 and earlier) // always quote values that contain a ';' @@ -100,7 +100,7 @@ internal static void AppendKeyValuePairBuilder(StringBuilder builder, string key builder.Append(keyValue); } } - else if (s_connectionStringQuoteValueRegex.IsMatch(keyValue)) + else if (ConnectionStringQuoteValueRegex.IsMatch(keyValue)) { // -> builder.Append(keyValue); @@ -184,7 +184,7 @@ static partial void DebugTraceKeyValuePair(string keyname, string? keyvalue, Dic internal static void ValidateKeyValuePair(string keyword, string value) { - if ((null == keyword) || !s_connectionStringValidKeyRegex.IsMatch(keyword)) + if ((null == keyword) || !ConnectionStringValidKeyRegex.IsMatch(keyword)) { throw ADP.InvalidKeyname(keyword); } diff --git a/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/DbConnectionOptions.cs b/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/DbConnectionOptions.cs index 331969fa50a21f..ee5b8d409a9783 100644 --- a/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/DbConnectionOptions.cs +++ b/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/DbConnectionOptions.cs @@ -119,7 +119,7 @@ internal static void AppendKeyValuePairBuilder(StringBuilder builder, string key ADP.CheckArgumentNull(builder, nameof(builder)); ADP.CheckArgumentLength(keyName, nameof(keyName)); - if ((null == keyName) || !s_connectionStringValidKeyRegex.IsMatch(keyName)) + if ((null == keyName) || !ConnectionStringValidKeyRegex.IsMatch(keyName)) { throw ADP.InvalidKeyname(keyName); } @@ -150,7 +150,7 @@ internal static void AppendKeyValuePairBuilder(StringBuilder builder, string key if ((0 < keyValue.Length) && // string.Contains(char) is .NetCore2.1+ specific (('{' == keyValue[0]) || (0 <= keyValue.IndexOf(';')) || (string.Equals(DbConnectionStringKeywords.Driver, keyName, StringComparison.OrdinalIgnoreCase))) && - !s_connectionStringQuoteOdbcValueRegex.IsMatch(keyValue)) + !ConnectionStringQuoteOdbcValueRegex.IsMatch(keyValue)) { // always quote Driver value (required for ODBC Version 2.65 and earlier) // always quote values that contain a ';' @@ -161,7 +161,7 @@ internal static void AppendKeyValuePairBuilder(StringBuilder builder, string key builder.Append(keyValue); } } - else if (s_connectionStringQuoteValueRegex.IsMatch(keyValue)) + else if (ConnectionStringQuoteValueRegex.IsMatch(keyValue)) { // -> builder.Append(keyValue); @@ -446,7 +446,7 @@ internal string ExpandKeyword(string keyword, string replacementValue) internal static void ValidateKeyValuePair(string keyword, string value) { - if ((null == keyword) || !s_connectionStringValidKeyRegex.IsMatch(keyword)) + if ((null == keyword) || !ConnectionStringValidKeyRegex.IsMatch(keyword)) { throw ADP.InvalidKeyname(keyword); } diff --git a/src/libraries/System.Data.OleDb/src/DbConnectionOptions.cs b/src/libraries/System.Data.OleDb/src/DbConnectionOptions.cs index 16e41fb89f9f97..d49016a91be60c 100644 --- a/src/libraries/System.Data.OleDb/src/DbConnectionOptions.cs +++ b/src/libraries/System.Data.OleDb/src/DbConnectionOptions.cs @@ -56,37 +56,30 @@ internal partial class DbConnectionOptions ; - private static readonly Regex ConnectionStringRegex = CreateConnectionStringRegex(); - private static readonly Regex ConnectionStringRegexOdbc = CreateConnectionStringRegexOdbc(); - #if NET [GeneratedRegex(ConnectionStringPattern, RegexOptions.ExplicitCapture)] - private static partial Regex CreateConnectionStringRegex(); + private static partial Regex ConnectionStringRegex { get; } [GeneratedRegex(ConnectionStringPatternOdbc, RegexOptions.ExplicitCapture)] - private static partial Regex CreateConnectionStringRegexOdbc(); + private static partial Regex ConnectionStringRegexOdbc { get; } #else - private static Regex CreateConnectionStringRegex() => new Regex(ConnectionStringPattern, RegexOptions.ExplicitCapture | RegexOptions.Compiled); - private static Regex CreateConnectionStringRegexOdbc() => new Regex(ConnectionStringPatternOdbc, RegexOptions.ExplicitCapture | RegexOptions.Compiled); + private static Regex ConnectionStringRegex { get; } = new Regex(ConnectionStringPattern, RegexOptions.ExplicitCapture | RegexOptions.Compiled); + private static Regex ConnectionStringRegexOdbc { get; } = new Regex(ConnectionStringPatternOdbc, RegexOptions.ExplicitCapture | RegexOptions.Compiled); #endif #endif internal const string DataDirectory = "|datadirectory|"; - 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 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 NET [GeneratedRegex("^(?![;\\s])[^\\p{Cc}]+(? new Regex("^(?![;\\s])[^\\p{Cc}]+(? new Regex("^[^\"'=;\\s\\p{Cc}]*$", RegexOptions.Compiled); - private static Regex CreateConnectionStringQuoteOdbcValueRegex() => new Regex("^\\{([^\\}\u0000]|\\}\\})*\\}$", RegexOptions.ExplicitCapture | RegexOptions.Compiled); + private static Regex ConnectionStringValidKeyRegex { get; } = new Regex("^(?![;\\s])[^\\p{Cc}]+(? /// Gets a Regex instance for recognizing integer representations of enums. /// - public static readonly Regex IntegerRegex = CreateIntegerRegex(); private const string IntegerRegexPattern = @"^\s*(?:\+|\-)?[0-9]+\s*$"; private const int IntegerRegexTimeoutMs = 200; #if NET [GeneratedRegex(IntegerRegexPattern, RegexOptions.None, matchTimeoutMilliseconds: IntegerRegexTimeoutMs)] - private static partial Regex CreateIntegerRegex(); + public static partial Regex IntegerRegex { get; } #else - private static Regex CreateIntegerRegex() => new(IntegerRegexPattern, RegexOptions.Compiled, TimeSpan.FromMilliseconds(IntegerRegexTimeoutMs)); + public static Regex IntegerRegex { get; } = new(IntegerRegexPattern, RegexOptions.Compiled, TimeSpan.FromMilliseconds(IntegerRegexTimeoutMs)); #endif /// diff --git a/src/libraries/System.Text.RegularExpressions/tests/FunctionalTests/Regex.Match.Tests.cs b/src/libraries/System.Text.RegularExpressions/tests/FunctionalTests/Regex.Match.Tests.cs index 33ffbc6a1bf7a1..d45ba0b93addb3 100644 --- a/src/libraries/System.Text.RegularExpressions/tests/FunctionalTests/Regex.Match.Tests.cs +++ b/src/libraries/System.Text.RegularExpressions/tests/FunctionalTests/Regex.Match.Tests.cs @@ -1502,7 +1502,7 @@ public void Match_InstanceMethods_DefaultTimeout_SourceGenerated_Throws() { AppDomain.CurrentDomain.SetData(RegexHelpers.DefaultMatchTimeout_ConfigKeyName, TimeSpan.FromMilliseconds(100)); - Regex r = Match_InstanceMethods_DefaultTimeout_SourceGenerated_ThrowsImpl(); + Regex r = Match_InstanceMethods_DefaultTimeout_SourceGenerated_ThrowsImpl; string input = new string('a', 50) + "@a.a"; Assert.Throws(() => r.Match(input)); @@ -1512,7 +1512,7 @@ public void Match_InstanceMethods_DefaultTimeout_SourceGenerated_Throws() } [GeneratedRegex(@"^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@(([0-9a-zA-Z])+([-\w]*[0-9a-zA-Z])*\.)+[a-zA-Z]{2,9})$")] - private static partial Regex Match_InstanceMethods_DefaultTimeout_SourceGenerated_ThrowsImpl(); + private static partial Regex Match_InstanceMethods_DefaultTimeout_SourceGenerated_ThrowsImpl { get; } #endif [ConditionalTheory(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] diff --git a/src/mono/browser/debugger/BrowserDebugProxy/DebugStore.cs b/src/mono/browser/debugger/BrowserDebugProxy/DebugStore.cs index 78e4d614c0d657..1408f21cfed8c0 100644 --- a/src/mono/browser/debugger/BrowserDebugProxy/DebugStore.cs +++ b/src/mono/browser/debugger/BrowserDebugProxy/DebugStore.cs @@ -1374,7 +1374,7 @@ internal async Task LoadPDBFromSymbolServer(MonoProxy proxy, MonoSDBHelper sdbHe internal sealed partial class SourceFile { [GeneratedRegex(@"([:/])")] - private static partial Regex RegexForEscapeFileName(); + private static partial Regex RegexForEscapeFileName { get; } private readonly Dictionary methods; private readonly AssemblyInfo assembly; @@ -1476,7 +1476,7 @@ private static string GetHashOfString(string str) private static string EscapePathForUri(string path) { var builder = new StringBuilder(); - foreach (var part in RegexForEscapeFileName().Split(path)) + foreach (var part in RegexForEscapeFileName.Split(path)) { if (part == ":" || part == "/") builder.Append(part); diff --git a/src/mono/browser/debugger/BrowserDebugProxy/EvaluateExpression.cs b/src/mono/browser/debugger/BrowserDebugProxy/EvaluateExpression.cs index 1f00048cf2548a..bbbd5759f70cb2 100644 --- a/src/mono/browser/debugger/BrowserDebugProxy/EvaluateExpression.cs +++ b/src/mono/browser/debugger/BrowserDebugProxy/EvaluateExpression.cs @@ -41,7 +41,7 @@ internal static partial class ExpressionEvaluator private sealed partial class ExpressionSyntaxReplacer : CSharpSyntaxWalker { [GeneratedRegex(@"[^A-Za-z0-9_]", RegexOptions.Singleline)] - private static partial Regex RegexForReplaceVarName(); + private static partial Regex RegexForReplaceVarName { get; } public List identifiers = new List(); public List methodCalls = new List(); @@ -126,7 +126,7 @@ public SyntaxTree ReplaceVars(SyntaxTree syntaxTree, IEnumerable ma_val { // Generate a random suffix string suffix = Guid.NewGuid().ToString().Substring(0, 5); - string prefix = RegexForReplaceVarName().Replace(ma_str, "_"); + string prefix = RegexForReplaceVarName.Replace(ma_str, "_"); id_name = $"{prefix}_{suffix}"; memberAccessToParamName[ma_str] = id_name; @@ -143,7 +143,7 @@ public SyntaxTree ReplaceVars(SyntaxTree syntaxTree, IEnumerable ma_val { // Generate a random suffix string suffix = Guid.NewGuid().ToString().Substring(0, 5); - string prefix = RegexForReplaceVarName().Replace(iesStr, "_"); + string prefix = RegexForReplaceVarName.Replace(iesStr, "_"); id_name = $"{prefix}_{suffix}"; methodCallToParamName[iesStr] = id_name; } @@ -159,7 +159,7 @@ public SyntaxTree ReplaceVars(SyntaxTree syntaxTree, IEnumerable ma_val { // Generate a random suffix string suffix = Guid.NewGuid().ToString().Substring(0, 5); - string prefix = RegexForReplaceVarName().Replace(eaStr, "_"); + string prefix = RegexForReplaceVarName.Replace(eaStr, "_"); id_name = $"{prefix}_{suffix}"; elementAccessToParamName[eaStr] = id_name; } diff --git a/src/mono/browser/debugger/BrowserDebugProxy/MonoSDBHelper.cs b/src/mono/browser/debugger/BrowserDebugProxy/MonoSDBHelper.cs index 8d710dee9a1968..bd38a0d0286e2f 100644 --- a/src/mono/browser/debugger/BrowserDebugProxy/MonoSDBHelper.cs +++ b/src/mono/browser/debugger/BrowserDebugProxy/MonoSDBHelper.cs @@ -922,22 +922,22 @@ internal sealed partial class MonoSDBHelper internal readonly ILogger logger; [GeneratedRegex(@"\<(?[^)]*)\>(?[^)]*)(__)(?\d+)", RegexOptions.Singleline)] - private static partial Regex RegexForAsyncLocals(); //5__1 // works + private static partial Regex RegexForAsyncLocals { get; } //5__1 // works [GeneratedRegex(@"\$VB\$ResumableLocal_(?[^\$]*)\$(?\d+)", RegexOptions.Singleline)] - private static partial Regex RegexForVBAsyncLocals(); //$VB$ResumableLocal_testVbScope$2 + private static partial Regex RegexForVBAsyncLocals { get; } //$VB$ResumableLocal_testVbScope$2 [GeneratedRegex(@"VB\$StateMachine_(\d+)_(?.*)", RegexOptions.Singleline)] - private static partial Regex RegexForVBAsyncMethodName(); //VB$StateMachine_2_RunVBScope + private static partial Regex RegexForVBAsyncMethodName { get; } //VB$StateMachine_2_RunVBScope [GeneratedRegex(@"\<([^>]*)\>([d][_][_])([0-9]*)")] - private static partial Regex RegexForAsyncMethodName(); + private static partial Regex RegexForAsyncMethodName { get; } [GeneratedRegex(@"[`][0-9]+")] - private static partial Regex RegexForGenericArgs(); + private static partial Regex RegexForGenericArgs { get; } [GeneratedRegex("^(((?'Open'<)[^<>]*)+((?'Close-Open'>)[^<>]*)+)*(?(Open)(?!))[^<>]*")] - private static partial Regex RegexForNestedLeftRightAngleBrackets(); // b__3_0 + private static partial Regex RegexForNestedLeftRightAngleBrackets { get; } // b__3_0 public JObjectValueCreator ValueCreator { get; init; } @@ -1013,7 +1013,7 @@ public static string GetPrettierMethodName(string methodName) { methodName = methodName.Replace(':', '.'); methodName = methodName.Replace('/', '.'); - methodName = RegexForGenericArgs().Replace(methodName, ""); + methodName = RegexForGenericArgs.Replace(methodName, ""); return methodName; } @@ -1395,7 +1395,7 @@ public async Task GetPrettyMethodName(int methodId, bool isAnonymous, Ca var ret = retDebuggerCmdReader.ReadString(); if (ret.IndexOf(':') is int index && index > 0) ret = ret.Substring(0, index); - ret = RegexForAsyncMethodName().Replace(ret, "$1"); + ret = RegexForAsyncMethodName.Replace(ret, "$1"); var numGenericTypeArgs = retDebuggerCmdReader.ReadInt32(); var numGenericMethodArgs = retDebuggerCmdReader.ReadInt32(); int numTotalGenericArgs = numGenericTypeArgs + numGenericMethodArgs; @@ -1403,17 +1403,17 @@ public async Task GetPrettyMethodName(int methodId, bool isAnonymous, Ca for (int i = 0; i < numTotalGenericArgs; i++) { var typeArgC = retDebuggerCmdReader.ReadString(); - typeArgC = RegexForGenericArgs().Replace(typeArgC, ""); + typeArgC = RegexForGenericArgs.Replace(typeArgC, ""); genericArgs.Add(typeArgC); } - var match = RegexForGenericArgs().Match(ret); + var match = RegexForGenericArgs.Match(ret); while (match.Success) { var countArgs = Convert.ToInt32(match.Value.Remove(0, 1)); ret = ret.Remove(match.Index, match.Value.Length); ret = ret.Insert(match.Index, $"<{string.Join(", ", genericArgs.Take(countArgs))}>"); genericArgs.RemoveRange(0, countArgs); - match = RegexForGenericArgs().Match(ret); + match = RegexForGenericArgs.Match(ret); } ret = ret.Replace('/', '.'); return ret; @@ -1433,7 +1433,7 @@ public async Task GetPrettyMethodName(int methodId, bool isAnonymous, Ca } else if (klassName.StartsWith("VB$")) { - var match = RegexForVBAsyncMethodName().Match(klassName); + var match = RegexForVBAsyncMethodName.Match(klassName); if (match.Success) ret = ret.Insert(0, match.Groups["methodName"].Value); else @@ -1441,7 +1441,7 @@ public async Task GetPrettyMethodName(int methodId, bool isAnonymous, Ca } else { - var matchOnClassName = RegexForNestedLeftRightAngleBrackets().Match(klassName); + var matchOnClassName = RegexForNestedLeftRightAngleBrackets.Match(klassName); if (matchOnClassName.Success && matchOnClassName.Groups["Close"].Captures.Count > 0) klassName = matchOnClassName.Groups["Close"].Captures[0].Value; if (ret.Length > 0) @@ -1450,7 +1450,7 @@ public async Task GetPrettyMethodName(int methodId, bool isAnonymous, Ca } } var methodName = retDebuggerCmdReader.ReadString(); - var matchOnMethodName = RegexForNestedLeftRightAngleBrackets().Match(methodName); + var matchOnMethodName = RegexForNestedLeftRightAngleBrackets.Match(methodName); if (matchOnMethodName.Success && matchOnMethodName.Groups["Close"].Captures.Count > 0) { if (isAnonymous && anonymousMethodId.Length == 0 && methodName.Contains("__")) @@ -1805,17 +1805,17 @@ public async Task GetValueFromDebuggerDisplayAttribute(DotnetObjectId do } [GeneratedRegex(@"`\d+")] - private static partial Regex RegexForGenericArity(); + private static partial Regex RegexForGenericArity { get; } [GeneratedRegex(@"[[, ]+]")] - private static partial Regex RegexForSquareBrackets(); + private static partial Regex RegexForSquareBrackets { get; } public async Task GetTypeName(int typeId, CancellationToken token) { string className = await GetTypeNameOriginal(typeId, token); className = className.Replace("+", "."); - className = RegexForGenericArity().Replace(className, ""); - className = RegexForSquareBrackets().Replace(className, "__SQUARED_BRACKETS__"); + className = RegexForGenericArity.Replace(className, ""); + className = RegexForSquareBrackets.Replace(className, "__SQUARED_BRACKETS__"); //className = className.Replace("[]", "__SQUARED_BRACKETS__"); className = className.Replace("[", "<"); className = className.Replace("]", ">"); @@ -2158,7 +2158,7 @@ public async Task GetHoistedLocalVariables(MethodInfoWithDebugInformatio } else if (fieldName.StartsWith('<')) //examples: 5__2 { - var match = RegexForAsyncLocals().Match(fieldName); + var match = RegexForAsyncLocals.Match(fieldName); if (match.Success) { if (!method.Info.ContainsAsyncScope(Convert.ToInt32(match.Groups["scopeId"].Value), offset)) @@ -2173,7 +2173,7 @@ public async Task GetHoistedLocalVariables(MethodInfoWithDebugInformatio } else if (fieldName.StartsWith("$VB$ResumableLocal_", StringComparison.Ordinal)) { - var match = RegexForVBAsyncLocals().Match(fieldName); + var match = RegexForVBAsyncLocals.Match(fieldName); if (match.Success) { if (!method.Info.ContainsAsyncScope(Convert.ToInt32(match.Groups["scopeId"].Value) + 1, offset)) diff --git a/src/mono/wasm/Wasm.Build.Tests/LibraryInitializerTests.cs b/src/mono/wasm/Wasm.Build.Tests/LibraryInitializerTests.cs index e281f86d48d8f4..f6cfb18468a370 100644 --- a/src/mono/wasm/Wasm.Build.Tests/LibraryInitializerTests.cs +++ b/src/mono/wasm/Wasm.Build.Tests/LibraryInitializerTests.cs @@ -38,7 +38,7 @@ public async Task LoadLibraryInitializer() } [GeneratedRegex("MONO_WASM: Failed to invoke 'onRuntimeConfigLoaded' on library initializer '../WasmBasicTestApp.[a-z0-9]+.lib.module.js': Error: Error thrown from library initializer")] - private static partial Regex AbortStartupOnErrorRegex(); + private static partial Regex AbortStartupOnErrorRegex { get; } [Fact, TestCategory("bundler-friendly")] public async Task AbortStartupOnError() @@ -53,6 +53,6 @@ public async Task AbortStartupOnError() BrowserQueryString: new NameValueCollection { {"throwError", "true" } }, ExpectedExitCode: 1); RunResult result = await RunForPublishWithWebServer(options); - Assert.True(result.ConsoleOutput.Any(m => AbortStartupOnErrorRegex().IsMatch(m)), "The library initializer test didn't emit expected error message"); + Assert.True(result.ConsoleOutput.Any(m => AbortStartupOnErrorRegex.IsMatch(m)), "The library initializer test didn't emit expected error message"); } } diff --git a/src/mono/wasm/host/Options.cs b/src/mono/wasm/host/Options.cs index b29cb7caf11ad7..634f7c7e33fa37 100644 --- a/src/mono/wasm/host/Options.cs +++ b/src/mono/wasm/host/Options.cs @@ -1149,14 +1149,14 @@ private static bool Unprocessed(List extra, Option def, OptionContext c, } [GeneratedRegex(@"^(?--|-|/)(?[^:=]+)((?[:=])(?.*))?$")] - private static partial Regex ValueOption(); + private static partial Regex ValueOption { get; } protected bool GetOptionParts(string argument, out string flag, out string name, out string sep, out string value) { ArgumentNullException.ThrowIfNull(argument); flag = name = sep = value = null; - Match m = ValueOption().Match(argument); + Match m = ValueOption.Match(argument); if (!m.Success) { return false; @@ -1462,11 +1462,11 @@ private static void Write(TextWriter o, ref int n, string s) } [GeneratedRegex(@"(?<=(? FindV8VersionFromChromeVersion(string chromeVersion) Log.LogMessage(MessageImportance.Low, $"Checking {lkgUrl} ..."); string v8VersionHContents = await s_httpClient.GetStringAsync(lkgUrl).ConfigureAwait(false); - var m = V8BuildNumberRegex().Match(v8VersionHContents); + var m = V8BuildNumberRegex.Match(v8VersionHContents); if (!m.Success) throw new LogAsErrorException($"Failed to find v8 build number at {lkgUrl}: {v8VersionHContents}"); diff --git a/src/tools/illink/src/linker/Linker.Steps/MarkStep.cs b/src/tools/illink/src/linker/Linker.Steps/MarkStep.cs index 8c4bcd08ff4e63..ddbb70b8d13810 100644 --- a/src/tools/illink/src/linker/Linker.Steps/MarkStep.cs +++ b/src/tools/illink/src/linker/Linker.Steps/MarkStep.cs @@ -2362,10 +2362,10 @@ void MarkXmlSchemaProvider(TypeDefinition type, CustomAttribute attribute, Messa } [GeneratedRegex("{[^{}]+}")] - private static partial Regex DebuggerDisplayAttributeValueRegex(); + private static partial Regex DebuggerDisplayAttributeValueRegex { get; } [GeneratedRegex(@".+,\s*nq")] - private static partial Regex ContainsNqSuffixRegex(); + private static partial Regex ContainsNqSuffixRegex { get; } void MarkTypeWithDebuggerDisplayAttribute(TypeDefinition type, CustomAttribute attribute, MessageOrigin origin) { @@ -2394,14 +2394,14 @@ void MarkTypeWithDebuggerDisplayAttributeValue(TypeDefinition type, CustomAttrib if (string.IsNullOrEmpty(displayString)) return; - foreach (Match match in DebuggerDisplayAttributeValueRegex().Matches(displayString)) + foreach (Match match in DebuggerDisplayAttributeValueRegex.Matches(displayString)) { // Remove '{' and '}' string realMatch = match.Value.Substring(1, match.Value.Length - 2); // Remove ",nq" suffix if present // (it asks the expression evaluator to remove the quotes when displaying the final value) - if (ContainsNqSuffixRegex().IsMatch(realMatch)) + if (ContainsNqSuffixRegex.IsMatch(realMatch)) { realMatch = realMatch.Substring(0, realMatch.LastIndexOf(',')); }