Skip to content

Add a option to sort switch cases #3749

@danbopes

Description

@danbopes

Requesting an opt-in decompiler setting that sorts switch sections by their label value instead of by IL offset.

Today, SortSwitchSections in ICSharpCode.Decompiler/IL/ControlFlow/SwitchDetection.cs orders sections primarily by branch target IL offset, with the label value as a tiebreaker. For non-obfuscated assemblies that matches source order and is the correct default, which is exactly the position taken when #2071 was closed. I'm not asking to change that default.

The friction shows up with obfuscated assemblies. A lot of obfuscators reshuffle basic-block layout on every build, so the IL offsets behind a switch come out in arbitrary order even when the case-to-value mapping is identical. Decompiling the same logical method across two consecutive builds then produces a textual diff that is purely a reordering of the case arms, with no real behavior change. Diffing decompiled output across versions of a closed-source app is a real use case (it's what I'm doing here, and #3494 was filed for the same kind of workflow).

There's already a clean precedent for this. #2716 added the SortCustomAttributes setting because attribute order had the same "non-significant per the spec, but unstable in IL across rebuilds" problem, and #3494 / #3505 plumbed those settings through ilspycmd via -ds Name=Value and --ilspy-settingsfile. The end-to-end plumbing for a new opt-in setting already exists.

Concretely:

  • New SortSwitchSections (or similar) bool on DecompilerSettings, defaulting to false so current output is unchanged.
  • When true, SortSwitchSections(sw) orders by s.Labels.Values.FirstOrDefault() instead of by IL offset.
  • No effect on non-obfuscated assemblies unless the user opts in.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions