Sergio0694/PolySharp

GeneratedRegex attribute

gregsdennis opened this issue · 3 comments

Description (optional)

Support for [GeneratedRegex] attribute. MS Docs

Rationale

This is the new .Net 8 way of having static readonly regexes in code:

[GeneratedRegex(@"^by\(\s*(?<var>[a-zA-Z_][a-zA-Z0-9_]*)\s*\)")]
private static partial Regex MyRegex();
private static readonly Regex _byForm = MyRegex();

Prior to .Net 8, this is required:

private static readonly Regex _byForm = new(@"^by\(\s*(?<var>[a-zA-Z_][a-zA-Z0-9_]*)\s*\)");

which is arguably cleaner, but it means that regex table lookups are performed at runtime instead of at compile time. (I expect my usage isn't an ideal example.)

Proposed API

No proposal

Drawbacks

None

Alternatives

None

Other thoughts

None.

It looks like this is not as easy. Maybe even impossible. Even if you provide GeneratedRegexAttribute as a polyfill, the compiler still won't generate the implementation of the partial method. At least not when targeting .NET Framework 4.8 with C# version 12.

Even if you could get the compiler to generate the source code, it would have may compilation errors. From a quick look there are at least the following additional things missing for the generated code:

  • Missing type SearchValues<T>.
  • Missing type ReadOnlySpan<T>.
    You could reference the NuGet package System.Memory for that. But even then there are missing methods on ReadOnlySpan<T>, e.g. IndexOfAnyExcept. The NuGet package wasn't updated for the last few .NET releases.
  • Other missing methods like char.IsAscii.
  • The generated class Runner class inherits from RegexRunner. It looks like RegexRunner was changed from .NET Framework to .NET Core so the generated class doesn't compile (not implemented abstract methods, changed parameters for virtual methods). And you can't just provide your own class for that because the generated Regex inherits from Regex and assigns the field Regex.factory which needs to be of the framework provided RegexRunnerFactory type.

Sounds like a long shot. No worries.