# 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>`.

```csharp
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);
}
```

Now a site that uses it with constant elements:

```csharp
public static RingBuffer<int> Build() => [10, 20, 30];
```

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:

```il
.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
}
```

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`:

```il
.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>)
```

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."

<figure class="my-8"><svg viewBox="0 0 720 300" role="img" aria-label="A collection expression targeting a custom type lowers through two possible span sources into a single builder call; the decompiler confirms the CollectionBuilder attribute and span shape before folding the call back to bracket syntax, and otherwise leaves the explicit call." style="width:100%;height:auto;font-family:system-ui,sans-serif"><defs><marker id="ar" markerWidth="9" markerHeight="9" refX="7" refY="3" orient="auto"><path d="M0 0l6 3-6 3z" fill="#64748b"/></marker></defs><rect x="14" y="120" width="150" height="54" rx="7" fill="#eef2ff" stroke="#6366f1"/><text x="89" y="143" text-anchor="middle" fill="#6366f1" font-size="13" font-weight="600">[10, 20, 30]</text><text x="89" y="161" text-anchor="middle" fill="#64748b" font-size="11">target: RingBuffer&lt;int&gt;</text><rect x="214" y="40" width="210" height="46" rx="6" fill="#ecfeff" stroke="#0891b2"/><text x="319" y="60" text-anchor="middle" fill="#0891b2" font-size="12" font-weight="600">constant payload</text><text x="319" y="77" text-anchor="middle" fill="#64748b" font-size="11">RuntimeHelpers.CreateSpan</text><rect x="214" y="100" width="210" height="46" rx="6" fill="#ecfeff" stroke="#0891b2"/><text x="319" y="120" text-anchor="middle" fill="#0891b2" font-size="12" font-weight="600">variable payload</text><text x="319" y="137" text-anchor="middle" fill="#64748b" font-size="11">InlineArrayAsReadOnlySpan</text><rect x="214" y="178" width="210" height="46" rx="6" fill="#f0fdf4" stroke="#10b981"/><text x="319" y="198" text-anchor="middle" fill="#10b981" font-size="12" font-weight="600">ReadOnlySpan&lt;int&gt;</text><text x="319" y="215" text-anchor="middle" fill="#64748b" font-size="11">the invariant argument</text><rect x="470" y="100" width="150" height="54" rx="7" fill="#eef2ff" stroke="#6366f1"/><text x="545" y="123" text-anchor="middle" fill="#6366f1" font-size="12" font-weight="600">call Create&lt;int&gt;</text><text x="545" y="141" text-anchor="middle" fill="#64748b" font-size="11">no brackets in IL</text><rect x="470" y="200" width="236" height="76" rx="7" fill="#fff7ed" stroke="#f59e0b"/><text x="588" y="222" text-anchor="middle" fill="#b45309" font-size="12" font-weight="600">Glass checks [CollectionBuilder]</text><text x="588" y="241" text-anchor="middle" fill="#64748b" font-size="11">attribute names Create + span shape</text><text x="588" y="261" text-anchor="middle" fill="#10b981" font-size="11">match → fold to [10, 20, 30]</text><text x="588" y="272" text-anchor="middle" fill="#64748b" font-size="10">no match → keep Create(...) call</text><path d="M164 138 L214 70" fill="none" stroke="#64748b" stroke-width="1.5" marker-end="url(#ar)"/><path d="M164 150 L214 122" fill="none" stroke="#64748b" stroke-width="1.5" marker-end="url(#ar)"/><path d="M319 146 L319 176" fill="none" stroke="#64748b" stroke-width="1.5" marker-end="url(#ar)"/><path d="M424 194 L470 140" fill="none" stroke="#64748b" stroke-width="1.5" marker-end="url(#ar)"/><path d="M545 154 L560 200" fill="none" stroke="#64748b" stroke-width="1.5" marker-end="url(#ar)"/></svg><figcaption class="text-sm text-muted mt-2">Both span sources converge on one builder call; recovery is gated on the attribute and the span shape, not on any opcode.</figcaption></figure>

## The case it cannot decide

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

```csharp
RingBuffer<int> a = [1, 2, 3];
RingBuffer<int> b = RingBuffer.Create([1, 2, 3]);
```

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.

