DEV Community

Zero Heartbeat
Zero Heartbeat

Posted on Originally published at delta1labs.com

Reading source-generated regex in Glass.NET

Most .NET engineers picture a regular expression as a pattern string that some engine walks character by character at runtime. That is what new Regex("…") gives you: an interpreter driving over your pattern. The regex source generator is a different animal. Mark a partial method with [GeneratedRegex] and the C# compiler writes you a purpose-built Regex subclass whose matching logic is plain, compiled C# — no pattern to interpret, no reflection, nothing built at runtime. When you decompile such an assembly, you do not get an opaque engine; you get the scan code itself. Here is exactly what the generator emits and how to read it in Glass.NET.

The real question

A classic new Regex(@"\d{3}-\d{4}") leaves almost nothing in the assembly: a string literal and a constructor call. The actual matching is done later, at runtime, by the shared regex engine interpreting that string. So where does all the logic go when you use the source generator instead — and why does it come back as readable code? The answer is that the generator moves the entire matching algorithm to compile time, emitting it as a method you could have written by hand.

What you write

The input is small. A partial method, no body, carrying the attribute:

internal static partial class Patterns
{
    [GeneratedRegex(@"\d{3}-\d{4}")]
    public static partial Regex PhoneNumber();
}
Enter fullscreen mode Exit fullscreen mode

That is all the engineer sees. Everything below is produced by System.Text.RegularExpressions.Generator during the build and compiled into the assembly alongside your code.

What the generator emits

First, the partial method you declared gets its other half — a one-line accessor that hands back a cached singleton:

partial class Patterns
{
    [GeneratedCode("System.Text.RegularExpressions.Generator", "8.0.10.36612")]
    public static partial Regex PhoneNumber()
        => global::System.Text.RegularExpressions.Generated.PhoneNumber_0.Instance;
}
Enter fullscreen mode Exit fullscreen mode

The real work lives in that PhoneNumber_0 type. It is a file-local class deriving from Regex, and its constructor just wires up the familiar Regex fields — the pattern (kept only as metadata, never interpreted), the options, the timeout, the capture count, and a factory that produces the runner:

namespace System.Text.RegularExpressions.Generated
{
    [GeneratedCode("System.Text.RegularExpressions.Generator", "8.0.10.36612")]
    file sealed class PhoneNumber_0 : Regex
    {
        internal static readonly PhoneNumber_0 Instance = new();

        private PhoneNumber_0()
        {
            base.pattern = "\\d{3}-\\d{4}";
            base.roptions = RegexOptions.None;
            ValidateMatchTimeout(Utilities.s_defaultTimeout);
            base.internalMatchTimeout = Utilities.s_defaultTimeout;
            base.factory = new RunnerFactory();
            base.capsize = 1;
        }

        private sealed class RunnerFactory : RegexRunnerFactory
        {
            protected override RegexRunner CreateInstance() => new Runner();
            // the Runner is where the scanning actually happens
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

capsize = 1 tells you there are no capture groups beyond the whole-match group 0. The RunnerFactory exists because the base Regex machinery expects a factory that mints a fresh RegexRunner per call site; the generator supplies a trivial one.

The interesting part is the runner. It overrides Scan, which does the familiar "try here, advance, try again" loop, delegating the real decision to TryMatchAtCurrentPosition:

private sealed class Runner : RegexRunner
{
    protected override void Scan(ReadOnlySpan<char> inputSpan)
    {
        while (TryFindNextPossibleStartingPosition(inputSpan) &&
               !TryMatchAtCurrentPosition(inputSpan) &&
               base.runtextpos != inputSpan.Length)
        {
            base.runtextpos++;
            if (Utilities.s_hasTimeout) base.CheckTimeout();
        }
    }

    private bool TryMatchAtCurrentPosition(ReadOnlySpan<char> inputSpan)
    {
        int pos = base.runtextpos;
        int matchStart = pos;
        ReadOnlySpan<char> slice = inputSpan.Slice(pos);

        // The pattern is 8 chars wide and fixed-length, so one bounds check
        // guards all the element reads below.
        if ((uint)slice.Length < 8 ||
            !char.IsDigit(slice[0]) ||          // \d
            !char.IsDigit(slice[1]) ||          // \d
            !char.IsDigit(slice[2]) ||          // \d
            slice[3] != '-' ||                  // literal '-'
            !char.IsDigit(slice[4]) ||          // \d
            !char.IsDigit(slice[5]) ||          // \d
            !char.IsDigit(slice[6]) ||          // \d
            !char.IsDigit(slice[7]))            // \d
        {
            return false;
        }

        pos += 8;
        base.runtextpos = pos;
        base.Capture(0, matchStart, pos);
        return true;
    }
}
Enter fullscreen mode Exit fullscreen mode

Read what happened to the pattern. \d{3}-\d{4} had a known, fixed width of eight characters, so the generator did not emit a loop at all — it unrolled the quantifiers into straight-line checks, hoisted a single length guard to the top (so the JIT can elide the per-element bounds checks), and matched each position with an explicit predicate. \d became char.IsDigit; the literal - became an equality test. On success it advances runtextpos, records the whole match with base.Capture(0, …), and returns. There is no pattern parsing, no state table, no backtracking stack for this shape — just code.

The regex attribute on a partial method becomes a file-local Regex subclass; the real matching lives in the runner's scan method, which Glass reads back as C# and lets you flip to IL.

Reading it in Glass.NET

Open the assembly in Glass.NET and the generated code is right there in the tree — the source generator's output is compiled into the same assembly as your own types. Start at Patterns.PhoneNumber(): its body is the one-line accessor returning PhoneNumber_0.Instance. Click through to PhoneNumber_0 and you land on the Regex-derived class; the decompiler renders the file-local modifier and the GeneratedCode attribute so you can tell at a glance this was machine-written. Drill into the nested RunnerFactory and then Runner, and TryMatchAtCurrentPosition reads as the clean C# above — the actual scan, not a description of one.

This is where the decompiler earns its keep. The generated names are predictable but not friendly, and the logic is spread across three nested types. Glass lets you jump from the partial declaration straight to the runner, and when a check looks surprising — a length guard you did not expect, a char.IsBetween where you assumed char.IsDigit — you flip the same method to the IL view and confirm it. You will see ordinary managed IL: ldarga, call char.IsDigit, brfalse, ldc.i4, stfld runtextpos. No DynamicMethod, no Reflection.Emit, no call into a pattern parser. That is the whole point of the generator, made visible.

Why it matters

Knowing this changes what you can learn from an assembly by reading it. With an interpreted new Regex("…"), decompiling tells you the pattern and nothing about how it will be matched — the behaviour is in the shared engine. With a source-generated regex, the matching algorithm is in front of you: which character classes it tests, whether it unrolled or looped a quantifier, where it anchors, how it handles the start search. For auditing your own code, vetting a dependency you have the right to inspect, or chasing a subtle match bug, that transparency is the difference between guessing and reading.

It is also a reliable fingerprint of a modern, AOT-friendly build. Source-generated regexes need no runtime code generation, so they trim and ahead-of-time compile cleanly — seeing the <Pattern>_0 classes in Glass tells you the author chose that path deliberately.

Caveats

Be honest about the limits. The decompiled code is the generator's C#, not yours — it is correct and readable, but verbose, and the names (PhoneNumber_0, Utilities.s_defaultTimeout) are generated artifacts, not an API. The exact shape varies by .NET and compiler version: a fixed-width pattern unrolls into straight-line checks as shown here, but add a variable quantifier, alternation, or backreferences and the generator emits loops, labels, and sometimes a small backtracking structure that is considerably harder to follow. Very large or pathological patterns can fall back to the interpreter even under the generator. And the pattern string stored in the constructor is metadata for diagnostics only — the engine never interprets it, so do not read it as the thing being executed; read the scan method.

Takeaway

new Regex("…") hides its matching in a runtime interpreter, and RegexOptions.Compiled hides it in IL built in memory and never saved. The regex source generator does neither — it writes the scan as plain C# at compile time, so it lands in your assembly as real, decompilable code. Open it in Glass.NET, navigate from the partial method to the generated runner, read the scan as C#, and flip to IL to confirm. Glass.NET is a free, VS-native .NET decompiler with a CLI and an MCP server; the generated-regex docs live at /docs/glass/.

Top comments (0)