Suggested severity: Info
Suggested category: Performance
For new Regex(...) and Regex.StaticMethod(...) involving patterns, options, and timeouts known at compile time, we should provide an analyzer and fixer that will transform the regex into its corresponding RegexGenerator form, including fixing up the call sites.
Flag
- Use of Regex constructor or static method with inline literals like:
// Flag object creation invocations
Regex myRegex = new Regex("ab|cd", RegexOptions.None, TimeSpan.FromSeconds(2));
// Flag static method invocations
var match = Regex.Match(input, "ab|cd", RegexOptions.None, TimeSpan.FromSeconds(2));
- Use of Regex constructor or static method when using constant values like:
const string pattern = "ab|cd";
const RegexOptions options = RegexOptions.None;
Regex myRegex = new Regex(pattern, options, TimeSpan.FromSeconds(2));
var match = Regex.Match(input, pattern, options, TimeSpan.FromSeconds(2));
Don't Flag
- Use of non-constant variables as parameters like:
public void Foo(RegexOptions parameterOptions)
{
string nonConstantPattern = "ab|cd";
Regex myRegex = new Regex(nonConstantPattern , parameterOptions, TimeSpan.FromSeconds(2));
var match = Regex.Match(input, nonConstantPattern , parameterOptions, TimeSpan.FromSeconds(2));
}
- Options contain NonBacktracking (since this option is not supported by source generator yet) like:
Regex myRegex = new Regex("ab|cd", RegexOptions.NonBacktracking);
Fixer
The fixer will mainly do three things:
- Add
partial keyword (if it's not there already) to the type (or types for nested types) which contains the invocation that generated the diagnostic
- Declare a new private static partial method with the
RegexGenerator attribute and parameters so the source generator generates the Regex type.
- Change the invocation that produced the diagnostic to use the new static partial method instead.
Suggested severity: Info
Suggested category: Performance
For
new Regex(...)andRegex.StaticMethod(...)involving patterns, options, and timeouts known at compile time, we should provide an analyzer and fixer that will transform the regex into its corresponding RegexGenerator form, including fixing up the call sites.Flag
Don't Flag
Fixer
The fixer will mainly do three things:
partialkeyword (if it's not there already) to the type (or types for nested types) which contains the invocation that generated the diagnosticRegexGeneratorattribute and parameters so the source generator generates the Regex type.