Conversation
27cd649 to
d51b284
Compare
christophwille
left a comment
There was a problem hiding this comment.
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.
d51b284 to
4155a4f
Compare
998ac58 to
f1ea581
Compare
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
f1ea581 to
d22d430
Compare
ExpressionTransforms.HandleConditionalOperatorcollapsesif (c) a = x; else a = y;into aconditional operator, innermost first, and keeps going for as long as the chain does. A source
else ifladder therefore comes back as one expression, however long it was. The sample attachedto #2027 decompiles to a single 2095-character statement; one NLog method reaches 2230
characters nested 29 brackets deep.
ExpandNestedConditionalsundoes that past one level, so a statement keeps at most a single?:.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 insideExpressionTransforms.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, andthe query lambdas the C# stage later rewrites into clauses. Cutting the chain earlier leaves an
if/elsebetween the statements they pattern-match on, and they silently stop matching - anobject initializer assigning an init-only member then does not even compile.
This is the same reasoning
ReduceNestingTransformalready gives for walking backConditionDetection's aggressive else-inlining once the structure is settled: an earlier transformis deliberately aggressive because later stages depend on it, and a late pass chooses the final
shape.
Two consequences of running late:
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
objectlocal #3736. No type inference is involved.if/elseitself instead of inheritingConditionDetection's IL ordering, so the ladder readselse if (cond)rather thanelse if (!(cond)). Negatedelse ifoccurrences across the corpus are unchanged from master.Tests
TestCases/Pretty/ConditionalOperatorNesting.cscovers what must not change - each memberis 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:
ArrayInitializerQueryRefLocal#if CS70SwitchExpression#if CS80ObjectInitializer#if CS90WithExpressionwith/ record clone, CS1061#if CS90FilterKeepsExpression+ the two ctor classes: base(...),: this(...)ShallowChainStaysInline,MismatchedBranchTypesStayInline,LogicOperatorsAreNotCounted&&/||sharing the IfInstruction representationTestCases/ILPretty/ConditionalChain.ilholds the positive case. It is an ILPretty test ratherthan 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://IL_warnings /<>name leaksAcross 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
ILExtractionprovides one, withPrepareExtractvetting the move so the order of evaluationis preserved. The temporary it creates is typed from the stack type though, and
I4isint,bool,charand every enum at once; extracting on that basis turned aboolintoint numwithif (num == 0), and an enum intodbType = (IsFixedLength ? 22 : 0).InferExpectedType(new, next toInferTypeinILTypeExtensions) is what makes that positionusable. Where
InferTypeasks what a value is, it asks what the position the value flows intosays it should be - a parameter, a return type, a field - all of which carry their type in
metadata, and it answers
UnknownTypewhere nothing does. Extraction happens only where thatquestion has an answer, and the temporary is typed from it:
Chains whose position names nothing are left alone -
JToken.ReadFrom's, for instance, sits insidea
!(…), 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 outputbyte-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
?:).