Sergio0694 / PolySharp

PolySharp provides generated, source-only polyfills for C# language features, to easily use all runtime-agnostic features downlevel. Add a reference, set your C# version to latest and have fun! 🚀
MIT License
1.77k stars 46 forks source link

GeneratedRegex attribute #95

Open gregsdennis opened 8 months ago

gregsdennis commented 8 months ago

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 commented 4 months ago

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:

gregsdennis commented 4 months ago

Sounds like a long shot. No worries.