Skip to content

parser: convert conditional branches to their common type - #17

Merged
rameel merged 2 commits into
mainfrom
parser/conditional-common-type
Nov 17, 2026
Merged

rameel merged 2 commits into
mainfrom
parser/conditional-common-type

Conversation

@rameel

@rameel rameel commented Nov 17, 2026

Copy link
Copy Markdown
Owner

The branches of a conditional expression were passed to Expression.Condition as they were, so expressions such as flag ? 1 : 2.0 and flag ? name : null failed with Argument types do not match.

This PR converts one branch to the type of the other when only one of them converts implicitly, as C# does. The common type is always the type of a branch, so the result is object only when a branch is of that type, as in flag ? 1 : x :> object. The null literal takes the type of the other branch if that type accepts null. Branches without a common type, such as in flag ? 1 : "a", fail with Operator '?:' cannot be applied to operands of type 'System.Int32' and 'System.String'.

To convert numbers as C# does, TypeUtils.CanConvertPrimitive now allows the implicit conversions of integer types and char to decimal and rejects conversions to an enum. The method resolver uses it only for primitive parameter types, so overload resolution does not change.

flag ? null : null now fails because neither branch has a type.

CanConvertPrimitive used the widening rules of the reflection binder,
which do not convert integer types and char to decimal. It also took
an enum target for its underlying type, so it reported that any number
converts to any enum.

Allow the implicit conversions to decimal and reject conversions to an
enum. The method resolver uses the table only for primitive parameter
types, and decimal and enums are not primitive, so overload resolution
does not change.
The branches of a conditional expression were passed to
Expression.Condition as they were, so branches of different types, as
in 'flag ? 1 : 2.0' or 'flag ? name : null', failed with "Argument
types do not match".

Convert one branch to the type of the other when only one of them
converts implicitly, as C# does. The common type is always the type of
a branch, so the result is object only when a branch is of that type.
The null literal takes the type of the other branch if that type
accepts null, and 'flag ? null : null' now fails because neither
branch has a type. Branches without a common type fail with an error
that names both types.
@rameel
rameel merged commit 7178ed3 into main Nov 17, 2026
1 check passed
@rameel
rameel deleted the parser/conditional-common-type branch November 17, 2026 17:33
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.

1 participant