DEV Community

Zero Heartbeat
Zero Heartbeat

Posted on Edited on Originally published at delta1labs.com

How a decompiler recovers list patterns

A list pattern reads like one tidy idea — data is [10, 20, .. var rest] — but there is no "match a list" instruction in the CLR. By the time the compiler is done, that single line has become a null test, a length comparison, a run of element comparisons, and a call that carves out the slice. Reading compiled code, you do not see a pattern; you see a small forest of conditional branches that happens to spell one out. Folding that forest back into brackets is a precise exercise in pattern-matching the decompiler's own input.

The real question

Pattern matching in C# is syntactic sugar over ordinary comparisons, and list patterns are the sugariest of all. So the question Glass answers is not what does this opcode mean — every opcode here is a plain ldlen, ldelem, or beq. The question is does this particular cluster of branches, in this particular order, reconstitute a list pattern — and if so, what were the element subpatterns and where did the slice bind. That is a shape-matching problem over a region of IL, not a one-instruction decode.

A list pattern, lowered

Here is a method that classifies an int[] by its leading elements and binds the tail:

public static bool LooksLikeHeader(int[] data)
    => data is [10, 20, .. var rest] && rest.Length == 0;
Enter fullscreen mode Exit fullscreen mode

Three things have to be true before rest even exists: data is non-null, its Length is at least 2 (two element subpatterns precede the slice, none follow), and the first two elements are 10 and 20. Only then is rest bound to data[2..]. The compiler emits exactly those tests, short-circuiting to failure the moment one breaks:

.method public hidebysig static bool LooksLikeHeader(int32[] data) cil managed
{
  ldarg.0
  brfalse.s  FAIL           // data is not null
  ldarg.0
  ldlen
  conv.i4
  ldc.i4.2
  blt.s      FAIL           // data.Length >= 2
  ldarg.0
  ldc.i4.0
  ldelem.i4
  ldc.i4.s   10
  bne.un.s   FAIL           // data[0] == 10
  ldarg.0
  ldc.i4.1
  ldelem.i4
  ldc.i4.s   20
  bne.un.s   FAIL           // data[1] == 20
  ldarg.0
  ldc.i4.2
  call       !!0[] [System.Runtime]System.Runtime.CompilerServices.RuntimeHelpers::GetSubArray<int32>(
               !!0[], valuetype [System.Runtime]System.Range)   // rest = data[2..]
  // … rest.Length == 0 …
}
Enter fullscreen mode Exit fullscreen mode

(The GetSubArray call is preceded by the construction of a System.Range from Index 2 to Index ^0, elided here for width.) Notice what is not present: no attribute, no synthetic type, no marker of any kind that says "pattern." The brackets have dissolved into a null check, a length check, two element checks, and a slice call. Every one of those instructions is something a programmer could have written by hand — and that is the crux of the recovery problem.

The slice subpattern

The .. var rest is the only part that needs special support, and it is where the countable/indexable rules bite. A list pattern requires the matched type to be countable (a Length or Count property) and indexable (an indexer taking int or System.Index). A slice subpattern needs one more thing: a way to take a range. Arrays have no Range indexer, so the compiler routes an array slice through RuntimeHelpers.GetSubArray, as above. A Span<T> or ReadOnlySpan<T> has a Slice(int, int) method, so the same pattern over a span lowers to:

ldarg.0
ldc.i4.2
ldarg.0
call       instance int32 valuetype [System.Runtime]System.ReadOnlySpan`1<uint8>::get_Length()
ldc.i4.2
sub
call       instance valuetype [System.Runtime]System.ReadOnlySpan`1<!0>
             [System.Runtime]System.ReadOnlySpan`1<uint8>::Slice(int32, int32)   // rest = frame[2..]
Enter fullscreen mode Exit fullscreen mode

Same meaning, different instruction: Slice(start, length) where length = Length - 2. Glass treats GetSubArray over a Range and Slice(int, int) as two spellings of the same slice source, binds the variable to whichever the subpattern named, and moves on.

How Glass folds it back

Glass walks the branch cluster and tries to match the lowering template. It commits to a list pattern only when the whole shape lines up:

  1. A guarded Length/Count comparison against a constant N, immediately dominating a run of element accesses. For a pattern with no slice the comparison is == N; with a slice it is >= N, where N is the count of non-slice subpatterns. The null test, where the type is a reference type, precedes it.
  2. A contiguous run of indexer reads at ascending constant positions — data[0], data[1], … for the head, and for patterns with elements after the slice, data[^k] (lowered as Length - k) for the tail. Each read feeds a subpattern: a constant comparison (== 10), a type test, or a capture.
  3. At most one slice, materialized by GetSubArray over a Range or by Slice(int, int) with length = Length - (head + tail). Its result either binds a variable (.. var rest) or is discarded (..).
  4. All failure branches target one join — the single "no match" continuation. A list pattern is an atomic test; if the branches scatter to different destinations, it was never one pattern.

When every point holds, Glass emits [sub0, sub1, .. bind, …] with the subpatterns it recovered. When any point fails, it leaves the ordinary if/&& chain exactly as written — because that is what the code is.

A list pattern is a shape, not an opcode: ordered length and index checks plus one slice, all failing to a single join. Glass folds that shape back to brackets and otherwise prints the real branches.

The case it cannot decide

Here is the honest limit. These two methods compile to byte-identical IL:

bool A(int[] d) => d is [10, 20];
bool B(int[] d) => d is not null && d.Length == 2 && d[0] == 10 && d[1] == 20;
Enter fullscreen mode Exit fullscreen mode

There is no metadata that distinguishes a list pattern from the hand-written chain it desugars to, because at the IL level there is nothing to distinguish — the language defines the first as shorthand for the second. Glass resolves this the only defensible way: it prints the bracket form when the cluster matches the lowering template exactly, including the compiler's precise comparison order and its single-join structure. The moment a hand-written check deviates — a reordered test, an extra condition folded in, a Length > 1 instead of == 2 — the shape no longer matches and Glass prints the literal && chain. It never guesses that an ordinary condition "was probably" a pattern. The result always recompiles to the same assembly; the choice is which reading a human would rather see, and the fallback is the truthful one.

A second limit is worth stating plainly: a slice subpattern over a custom type works only if that type is both countable/indexable and exposes a Slice(int, int) method or a Range indexer. List<T>, for instance, supports a list pattern without a slice (it has Count and an int indexer) but not [.. var rest], because it has no Slice. When you see element checks over a List<T> with no GetSubArray/Slice call, that is a sliceless pattern — Glass will not invent a tail that the type could never have produced.

Using this when you read code

When Glass shows you a bare x is [ … ], you are reading a recovered shape, not a transcription of keystrokes — but a faithful one: it round-trips. When instead you see an expanded x is not null && x.Length == … && x[0] == …, Glass is telling you it could not prove that chain was a single pattern, and you should read it as the sequence of conditions it literally is. Either way, jump to the slice call if there is one: GetSubArray or Slice is where the .. bound its variable, and it marks the exact split between head, tail, and the captured middle.

Takeaway

A list pattern leaves no trace in IL beyond a length check, a run of indexer reads, and at most one slice call — the same instructions a careful programmer writes by hand. Glass recovers the brackets by matching that whole ordered shape, not any single opcode, and it falls back to the plain branch chain the instant the shape is not exact. Knowing that the brackets are a recognized template rather than a recorded fact is what lets you trust the recovered pattern — and know when the expanded form in front of you is the real code.

Glass.NET is a free .NET decompiler with a VS-native Avalonia UI, a headless CLI, and an MCP server. It reads metadata and IL statically and never executes the assembly you open — point it at your own binaries or at third-party dependencies you are auditing or debugging. Grab it at /products/glass.

Top comments (0)