Registry Mirror
Skip to content

Conversation

@siegfriedpammer

@siegfriedpammer siegfriedpammer commented Aug 27, 2026 •

Copy link
Copy Markdown
Member

ExpressionTransforms.HandleConditionalOperator collapses if (c) a = x; else a = y; into a
conditional operator, innermost first, and keeps going for as long as the chain does. A source
else if ladder therefore comes back as one expression, however long it was. The sample attached
to #2027 decompiles to a single 2095-character statement; one NLog method reaches 2230
characters nested 29 brackets deep
.

ExpandNestedConditionals undoes that past one level, so a statement keeps at most a single ?:.

// before
text2 = ((!text.StartsWith("aspnet", ...) && !text.StartsWith("iis", ...)) ? (text.StartsWith("HostAppName", ...) ? ... /* 20 more levels */ ));

// after
if (text.StartsWith("aspnet", StringComparison.OrdinalIgnoreCase) || text.StartsWith("iis", StringComparison.OrdinalIgnoreCase))
{
    text2 += " - Extension NLog.Web.AspNetCore not included?";
}
else if (text.StartsWith("HostAppName", StringComparison.OrdinalIgnoreCase))
{
    ...

Note the compound assignment comes back too: the conditional form forced text2 = ... (text2 + "...").

Where it runs, and why that is the whole design

At the end of the pipeline, immediately before AssignVariableNames - not inside
ExpressionTransforms.

Every transform that needs its input to be a single expression has to see the collapsed form first:
object and collection initializers, with, switch expressions, interpolated string handlers, and
the query lambdas the C# stage later rewrites into clauses. Cutting the chain earlier leaves an
if/else between the statements they pattern-match on, and they silently stop matching - an
object initializer assigning an init-only member then does not even compile.

This is the same reasoning ReduceNestingTransform already gives for walking back
ConditionDetection's aggressive else-inlining once the structure is settled: an earlier transform
is deliberately aggressive because later stages depend on it, and a late pass chooses the final
shape.

Two consequences of running late:

  • No type question. Only a store to a declared local is expanded. Such a local carries its own
    type from metadata, so splitting the branches cannot widen the result to a stack type and lose a
    cast - the defect filed as Cast lost when ternary with mismatched branch types is hoisted to object local #3736. No type inference is involved.
  • No polarity question. The pass builds the if/else itself instead of inheriting
    ConditionDetection's IL ordering, so the ladder reads else if (cond) rather than
    else if (!(cond)). Negated else if occurrences across the corpus are unchanged from master.

Tests

TestCases/Pretty/ConditionalOperatorNesting.cs covers what must not change - each member
is a construct that has to stay a single expression, and each was a compile error or a silent
degradation in the earlier version of this PR:

member guards guard
ArrayInitializer array initializer block
Query query lambda
RefLocal ref local, CS8174 #if CS70
SwitchExpression switch expression arm #if CS80
ObjectInitializer init-only member, CS8852 #if CS90
WithExpression with / record clone, CS1061 #if CS90
FilterKeepsExpression + the two ctor classes catch-when filter, : base(...), : this(...)
ShallowChainStaysInline, MismatchedBranchTypesStayInline, LogicOperatorsAreNotCounted the one-level boundary, and && / || sharing the IfInstruction representation

TestCases/ILPretty/ConditionalChain.il holds the positive case. It is an ILPretty test rather
than a Pretty one because a Pretty fixture is its own input and expected output, and a chain that
round-trips through collapse and expansion has no fixed point there - whichever polarity is written
comes back inverted.

Measurements

decompdiff over 20 popular NuGet packages, all 20 decompilable on both sides, against
origin/master:

old new
types compared 5927
types changed 35
new errors 0
lines 667345 +451
gotos / //IL_ warnings / <> name leaks 0 delta

Across the changed types, deepest line 2230 -> 618 characters, maximum bracket depth 29 -> 7,
lines at depth >= 5 down from 22 to 12.

Every declaration the diff introduces carries a name from metadata - XPathNavigator, DbType,
Expression, Type, string, byte[], NamingStrategy - except four (int num, long num)
that are pre-existing locals whose declaration split off its assignment. No temporary is typed
from a stack type.

ICSharpCode.Decompiler.Tests: 3587 total, 0 failed.

Scope

The transform handles a nested conditional in two situations.

Stored to a variable that already exists - the expansion reuses that variable, so nothing has
to be decided: the variable carries its own type from metadata.

Anywhere else - an argument, a return value, a field store - there is nothing to expand into,
so ILExtraction provides one, with PrepareExtract vetting the move so the order of evaluation
is preserved. The temporary it creates is typed from the stack type though, and I4 is int,
bool, char and every enum at once; extracting on that basis turned a bool into int num with
if (num == 0), and an enum into dbType = (IsFixedLength ? 22 : 0).

InferExpectedType (new, next to InferType in ILTypeExtensions) is what makes that position
usable. Where InferType asks what a value is, it asks what the position the value flows into
says it should be - a parameter, a return type, a field - all of which carry their type in
metadata, and it answers UnknownType where nothing does. Extraction happens only where that
question has an answer, and the temporary is typed from it:

XPathNavigator xPathNavigator;                  // the receiver's declaring type, no cast back
if (root) { xPathNavigator = node.GetRootElement(); } else if (IsElement) { … }
xPathNavigator.CreateAttribute("xmlns", prefix, …);

DbType dbType;                                  // the field's type, real member names
dbType = (IsFixedLength ? DbType.AnsiStringFixedLength : DbType.AnsiString);

Chains whose position names nothing are left alone - JToken.ReadFrom's, for instance, sits inside
a !(…), so the rule declines rather than guessing.

Two widenings were also built and rejected as unmeasurable: admitting stack slots whose type is not
object, and retyping a stack slot from the types its branches agree on. Both produced output
byte-identical to this PR over 5006 types.

Refs #2027 (implements the "only for long conditions" half of that request; there is no global
switch to disable ?:).

@siegfriedpammer
siegfriedpammer force-pushed the exp/ternary-chain-limit branch from 27cd649 to d51b284 Compare August 27, 2026 16:44
@siegfriedpammer siegfriedpammer changed the title Stop collapsing long if-else-if chains into nested conditionals Limit conditional-operator nesting to one level Aug 27, 2026

@christophwille christophwille left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review summary

I built ilspycmd from this branch and from master, decompiled a small fixture assembly with both, and recompiled the output. Master's output compiles cleanly; this branch's output has 5 compiler errors (CS8852 x2, CS1061, CS9035, CS8174) plus several silent degradations.

Root cause: the guard in HandleConditionalOperator cuts the chain in ExpressionTransforms, i.e. before every later transform that requires its input to be a single expression: object/collection initializers, with, switch expressions, query lambdas, interpolated-string handlers, record primary-constructor detection. AllowsStatements only consults ILInlining.OptionsForBlock, which knows about ctor initializers/filters/expression trees but nothing about those transforms. Any nested conditional feeding one of them now leaves an if chain between the statements they pattern-match on.

The 20-package corpus did not catch this because KeepsResultType only lets the guard fire when every leaf is a plain int/long/float/double load (InferType returns Unknown for ldc.i4, conv, arithmetic; an object stack slot never matches a string leaf). MismatchedBranchTypesStayInline passes for that reason, not for the one it claims.

Suggested fix: do not cut in ExpressionTransforms at all. Add a small late pass (after TransformCollectionAndObjectInitializers / switch-expression / query / interpolation transforms) that expands a statement-level stloc local(if (c) x else y) whose branches still nest a ?: back into if/else, restricted to VariableKind.Local targets whose type is not by-reference. At that point every consumer that needed the expression has already taken it, the else if ladder this PR wants still appears, and the type / aggressive-inlining questions go away (a statement-level store to a plain local can always be split).

Repro samples with expected/actual are in the inline comments (all compiled Release, net10.0, decompiled with default settings). Please also add them as pretty-test negative cases so the guard cannot regress them again.

@siegfriedpammer
siegfriedpammer force-pushed the exp/ternary-chain-limit branch from d51b284 to 4155a4f Compare August 27, 2026 17:48
@siegfriedpammer siegfriedpammer changed the title Limit conditional-operator nesting to one level Expand nested conditional operators back into if-else Aug 27, 2026
@siegfriedpammer
siegfriedpammer force-pushed the exp/ternary-chain-limit branch 2 times, most recently from 998ac58 to f1ea581 Compare August 27, 2026 20:31
HandleConditionalOperator collapses `if (c) a = x; else a = y;` into a
conditional operator, innermost first, and keeps going for as long as the
chain does. A source else-if ladder therefore comes back as one expression,
however long it was: the sample in #2027 decompiles to a single
2095-character statement, and one NLog method to 2230 characters nested 29
brackets deep.

ExpandNestedConditionals undoes that past one level, so a statement keeps at
most a single conditional operator.

It runs at the end of the pipeline rather than inside ExpressionTransforms,
because every transform that needs its input to be a single expression has
to see the collapsed form first: object and collection initializers, `with`,
switch expressions, interpolated string handlers, and the query lambdas the
C# stage later rewrites into clauses. Cutting the chain earlier leaves an
if-else between the statements they pattern-match on and they silently stop
matching - an object initializer assigning an init-only member then does not
even compile. The same reasoning ReduceNestingTransform gives for walking
back ConditionDetection's aggressive else-inlining once the structure is
settled.

A chain already stored to a variable is expanded into that variable, so
nothing has to be decided: the variable carries its own type. A chain in any
other position - an argument, a return value, a field store - has nothing to
expand into, and ILExtraction can give it one. The temporary ILExtraction
creates is typed from the stack type though, where `I4` is `int`, `bool`,
`char` and every enum at once, so extracting on that basis turned a bool
into `int num` with `if (num == 0)` and an enum into
`dbType = (IsFixedLength ? 22 : 0)`.

InferExpectedType is the counterpart to InferType that answers this: where
InferType asks what a value is, it asks what the position the value flows
into says it should be - a parameter, a return type, a field, all of which
carry their type in metadata. Extraction is done only where that question
has an answer, and the temporary is typed from it. The receiver of a call
then reads `XPathNavigator xPathNavigator`, not `object obj` with a cast
back, and a field store keeps its enum's member names.

The Pretty fixture covers what must NOT change: an array initializer, a
query lambda, a ref local, a switch expression, an object initializer with
an init-only member, a `with` expression, a catch-when filter and both
constructor-initializer forms. The positive case is an ILPretty test,
because a Pretty fixture is its own input and expected output, and a chain
that round-trips through collapse and expansion has no fixed point there.
The PdbGen test records the cost in breakpoints: the compiler's single
sequence point for the collapsed statement becomes one per expanded
statement, which is inherent to splitting a statement in two.

#2027

Assisted-by: Claude:claude-opus-5:Claude Code
@siegfriedpammer
siegfriedpammer force-pushed the exp/ternary-chain-limit branch from f1ea581 to d22d430 Compare August 29, 2026 22:39
@siegfriedpammer
siegfriedpammer merged commit 51d3d3c into master Aug 29, 2026
15 checks passed
@siegfriedpammer
siegfriedpammer deleted the exp/ternary-chain-limit branch August 29, 2026 23:11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Enhancement] Optionally disable ternary operator for long statements

3 participants