Skip to content

A conditional whose branches have different numeric types (c ? 1 : 2.5, c ? intVar : longVar) fails to compile in Rust and Go #375

Open

Description

@matt-edmondson

What's wrong

Neither generator widens a conditional's branches to their common type, or to the type that receives the value.

Rust writes both branches raw:

protected override void GenerateConditionalExpression(ConditionalExpression conditional, CodeBlocker code)
{
Ensure.NotNull(conditional);
Ensure.NotNull(code);
code.Write("(if ");
GenerateInternal(conditional.Condition, code);
code.Write(" { ");
GenerateInternal(conditional.WhenTrue, code);
code.Write(" } else { ");
GenerateInternal(conditional.WhenFalse, code);
code.Write(" })");

Go lowers a conditional into if/return or if/assign:

  • the return path is GoGenerator.cs:1754-1773 (GenerateReturnStatement)
  • the assignment path is GoGenerator.cs:1801-1812 (GenerateAssignmentStatement)

Both paths write each branch with GenerateInternal. That skips the return- and assignment-type widening that the plain return b path already applies through GenerateWidenedTo.

Reproduction

AST Target Output Result
double cond(bool c) => c ? 1 : 2.5 Rust return (if c { 1 } else { 2.5 }); E0308 expected integer, found floating-point number
long cond2(bool c, int a, long b) => c ? a : b Rust (if c { a } else { b }) E0308
same Go if c { return a }; return b cannot use a (variable of type int) as int64 value in return statement

Expected: if c { 1.0 } else { 2.5 } (or (1 as f64)), if c { (a as i64) } else { b }, and if c { return int64(a) }; return b.

Why it matters

A conditional mixing an integer literal with a floating one, or an int with a long, is a very common shape, and it breaks both compiled targets that don't widen implicitly. #152 (closed) fixed Go's typing of ready ? 1 : 2.5 in an inferred local, but not what Go emits in return or assignment position, and not Rust.

Suggested fix

  • Rust: in GenerateConditionalExpression, write each branch through GenerateWidenedTo(branch, Promoted(StaticType(WhenTrue), StaticType(WhenFalse)), code).
  • Go: in the return and assignment lowerings, write each branch through GenerateWidenedTo with the function's return type or the assignment target's static type.

Acceptance: both functions above compile and return the right values with rustc and go, and are covered by the existing compile tests.

Activity

  1. added
    bug
    on Oct 30, 2026
  2. matt-edmondson commented on Oct 30, 2026

    @matt-edmondson
    ContributorAuthor

    Triage


    Generated by Claude Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions