Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

GeneratedRegex attribute #95

Open
gregsdennis opened this issue Jan 30, 2024 · 2 comments
Open

GeneratedRegex attribute #95

gregsdennis opened this issue Jan 30, 2024 · 2 comments

Comments

@gregsdennis
Copy link

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.

@cremor
Copy link

cremor commented May 14, 2024

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.

@gregsdennis
Copy link
Author

Sounds like a long shot. No worries.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants