DEV Community

Zero Heartbeat
Zero Heartbeat

Posted on Originally published at delta1labs.com

How a decompiler recognizes a custom collection builder

Collection expressions were sold as syntax sugar, but the interesting part is that the sugar is extensible. Put [CollectionBuilder] on a type and [1, 2, 3] will build an instance of it. The catch, for anyone reading compiled code, is that nothing in the emitted IL contains a bracket, a list, or any hint that the author wrote a collection expression at all. What you get is a ReadOnlySpan<T> conjured out of nowhere and handed to a static factory method. Recovering the original [...] from that is a small, self-contained decompilation problem — and a good illustration of how a decompiler reasons from an attribute rather than from an opcode.

The real question

There is no "collection expression" instruction. For a type carrying [CollectionBuilder], the compiler's entire contribution is: materialize a span of the elements, then call the designated builder. So the question Glass has to answer is not what did this opcode mean but does this particular call, with this particular span source, reconstitute a collection expression — and if so, for which target type. That reasoning runs backwards through metadata, not forwards through instructions.

A custom collection, start to finish

Here is a minimal collection type that opts in. The attribute names the builder type and the method; the method must be static and take a ReadOnlySpan<T>.

using System.Runtime.CompilerServices;

[CollectionBuilder(typeof(RingBuffer), nameof(RingBuffer.Create))]
public sealed class RingBuffer<T>
{
    private readonly T[] _items;
    internal RingBuffer(ReadOnlySpan<T> items) => _items = items.ToArray();
    public int Count => _items.Length;
    public ReadOnlySpan<T>.Enumerator GetEnumerator() => _items.AsSpan().GetEnumerator();
}

public static class RingBuffer
{
    public static RingBuffer<T> Create<T>(ReadOnlySpan<T> items) => new(items);
}
Enter fullscreen mode Exit fullscreen mode

Now a site that uses it with constant elements:

public static RingBuffer<int> Build() => [10, 20, 30];
Enter fullscreen mode Exit fullscreen mode

The compiler does not allocate an int[], and it does not call a RingBuffer constructor. For an all-constant primitive payload it parks the three integers in a read-only data field and builds the span with RuntimeHelpers.CreateSpan, which hands back a span pointing straight at that field — zero heap allocation:

.method public static class RingBuffer`1<int32> Build() cil managed
{
  ldtoken    field valuetype '<PrivateImplementationDetails>'/'__StaticArrayInitTypeSize=12_Align=4'
             '<PrivateImplementationDetails>'::'3C8CE...A1'
  call       valuetype [System.Runtime]System.ReadOnlySpan`1<!!0>
             [System.Runtime]System.Runtime.CompilerServices.RuntimeHelpers::CreateSpan<int32>(
               valuetype [System.Runtime]System.RuntimeFieldHandle)
  call       class RingBuffer`1<!!0> RingBuffer::Create<int32>(
               valuetype [System.Runtime]System.ReadOnlySpan`1<!!0>)
  ret
}
Enter fullscreen mode Exit fullscreen mode

Three instructions. The brackets are gone, the element count survives only as the TypeSize=12 of a synthetic struct (12 bytes / sizeof(int) = 3), and the only word that ties any of this to the source is the Create in the final call.

When the elements are not constants

Swap the literals for parameters and the span can no longer come from a data field — there is nothing constant to park. The compiler synthesizes an [InlineArray(3)] buffer type, stack-allocates one, fills it through a generated InlineArrayElementRef helper, and takes a span over it with InlineArrayAsReadOnlySpan:

.locals init (valuetype '<>y__InlineArray3`1'<int32> V_0)
ldloca.s   V_0
initobj    valuetype '<>y__InlineArray3`1'<int32>
ldloca.s   V_0
ldc.i4.0
call       !!1& '<PrivateImplementationDetails>'::InlineArrayElementRef<valuetype '<>y__InlineArray3`1'<int32>, int32>(!!0&, int32)
ldarg.0
stind.i4
// … index 1 from ldarg.1, index 2 from ldarg.2 …
ldloca.s   V_0
ldc.i4.3
call       valuetype [System.Runtime]System.ReadOnlySpan`1<!!1> '<PrivateImplementationDetails>'::InlineArrayAsReadOnlySpan<valuetype '<>y__InlineArray3`1'<int32>, int32>(!!0&, int32)
call       class RingBuffer`1<!!0> RingBuffer::Create<int32>(valuetype [System.Runtime]System.ReadOnlySpan`1<!!0>)
Enter fullscreen mode Exit fullscreen mode

Two different span sources, same destination: a call to RingBuffer::Create over a ReadOnlySpan<int>. That destination is the invariant Glass anchors on.

The recovery heuristic

Glass treats the fold-back as a four-point confirmation. It will only rewrite a call into bracket syntax when every point holds.

  1. The call is a static method returning a constructed type. RingBuffer::Create<int32> returns RingBuffer<int>. Record the return type C and the method M.
  2. C's definition carries [CollectionBuilder], and it names this method. Glass reads the custom-attribute blob on RingBuffer<T>: a System.Type argument (typeof(RingBuffer)) and a string ("Create"). The called method must be that method on that type. A factory with the right shape but no attribute pointing at it is not a builder.
  3. The single argument is a ReadOnlySpan<E> whose element type E matches the builder's instantiation.
  4. The span was produced by a recognized shape — either RuntimeHelpers.CreateSpan<E> over a <PrivateImplementationDetails> field, or InlineArrayAsReadOnlySpan over a freshly initobj-d <>y__InlineArrayN local. Glass walks the span back to its elements: the RVA blob decoded as E, or the values stored into each inline-array slot.

Only then does it emit [e0, e1, …], typed to C. The attribute in step 2 is the whole game — it is the only metadata that distinguishes "a factory someone happened to call with a span" from "the builder the language wired to brackets."

Both span sources converge on one builder call; recovery is gated on the attribute and the span shape, not on any opcode.

The case it cannot decide

Here is the honest limit, and it is a genuine one rather than a bug. Consider two sources:

RingBuffer<int> a = [1, 2, 3];
RingBuffer<int> b = RingBuffer.Create([1, 2, 3]);
Enter fullscreen mode Exit fullscreen mode

The first is a collection expression targeting RingBuffer<int>. The second is an explicit call to Create, whose argument [1, 2, 3] is a collection expression targeting the ReadOnlySpan<int> parameter. These compile to byte-identical IL: the same CreateSpan and the same call RingBuffer::Create. No metadata separates them, because at the IL level there is nothing to separate — the language defines the first as shorthand for the second.

Glass resolves the tie with a rule, not a guess: when the builder call's result is itself the direct value of a slot target-typed to the collection type — a local initializer, a return, an argument expecting RingBuffer<int> — it prefers the bracket form and prints [1, 2, 3]. When the result flows somewhere that is not target-typed to the collection (it is immediately indexed, passed where ReadOnlySpan is wanted via an implicit conversion, or the builder is a method you clearly meant to see), it leaves RingBuffer.Create([1, 2, 3]) intact. Both renderings recompile to the original assembly; the choice is about which one a human would rather read, and the tie-break is documented so the output is never silently misleading.

A second limit worth stating: if the builder method is non-generic, or lives on a type unrelated to the collection, or the span comes from a source Glass does not recognize (say, a ReadOnlySpan<T> returned from your own helper), the four-point check fails safely and you get the literal call. That is the right answer — anything else would be invention.

Using this when you read code

When you open an assembly in Glass and see a bare [...] on a type you do not recognize as a built-in collection, that is your cue: the type carries [CollectionBuilder], and there is a static factory one hop away that defines how it is built. Jump to the attribute (the IL view shows the blob; the decompiled view shows the reconstructed [CollectionBuilder(typeof(...), "...")] on the type) and you have found the real constructor the brackets were hiding. Conversely, when you see an explicit Xyz.Create([...]), Glass is telling you it could not prove the outer call was sugar — read it as a deliberate factory invocation.

Takeaway

A [CollectionBuilder] collection expression leaves no syntactic trace in IL: just a span and a static call. Glass folds it back by reasoning from the attribute on the target type and the shape of the span, not from any instruction — and where two legal sources collapse to the same bytes, it applies a stated, round-tripping tie-break instead of pretending to know which you typed. Reading the recovered brackets, and knowing when they are a decision rather than a fact, is the difference between trusting a decompiler and being surprised by one.

Top comments (0)