argotorg / argotorg/solidity

Ternary operator does not correctly deduce common type for `-1` and `0` to be `int8`

Open
#13,078 7 comments 1 reaction 0 assignees View on GitHub
bug :bug: language design :rage4: low impact should compile without error
Dominant language
C++
Stars
25.7k
Forks
6.2k
Avg merge
2d 19h
Merged PRs (30d)
29

Description

## Description

Using trinary comparison operators causes type inference to fail.

## Environment

- Compiler version: 0.8.14
- Target EVM version (as per compiler settings): unknown
- Framework/IDE (e.g. Truffle or Remix): Hardhat
- EVM execution environment / backend / blockchain client:
- Operating system: Linux

## Steps to Reproduce

```solidity
function ab(int a, int b) public returns (int) {
return a < b ? -1 : 0;
}
```

Yields

```
TypeError: True expression's type int8 does not match false expression's type uint8.
|
16 | return a < b ? -1
| ^ (Relevant source part starts here and spans across multiple lines).
```

So there are really two problems:

1. The trinary operator's true and false operands are not appropriately unified to `int8` (which works for both operands)
2. The trinary operator's true and false operands are not correctly widened from `int8` to the return type `int`.

The solution is a bit ugly:

```solidity
function ab(int a, int b) public returns (int) {
return a < b ? int(-1) : int(0);
}
```

Contributor guide

Open the contributing guide

Research direction

Reproduce the issue with the shown Solidity function using compiler version 0.8.14. Trace the ternary operator's common-type inference for -1 and 0, then check how that result is widened to the function's int return type; the issue is done when this expression compiles without explicit casts and the existing type rules remain correct.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp, solidity
Domain
blockchain, compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.