Nim icon indicating copy to clipboard operation
Nim copied to clipboard

Unsigned subrange type will not panic when overflow/underflow

Open derekdai opened this issue 3 years ago • 4 comments

What happened?

type
  X = range[0'u8..64'u8]
  Y = range[0'i8..64'i8]

var x: X = X.high
x.inc               # nothing happened
echo x              # 65
var y: Y = Y.high
y.inc               # over- or underflow [OverflowDefect]

According to manual, both x.inc and y.inc should panic.

Nim Version

all nim versions.

Current Standard Output Logs

/home/derekdai/test.nim(8) test
/home/derekdai/.choosenim/toolchains/nim-#devel/lib/system/fatal.nim(53) sysFatal
Error: unhandled exception: over- or underflow [OverflowDefect]


### Expected Standard Output Logs

```shell
Should panic at line 6

/home/derekdai/test.nim(6) test
/home/derekdai/.choosenim/toolchains/nim-#devel/lib/system/fatal.nim(53) sysFatal
Error: unhandled exception: over- or underflow [OverflowDefect]


### Possible Solution

_No response_

### Additional Information

_No response_

derekdai avatar Aug 12 '22 17:08 derekdai

Unsigned numbers don't produce overflows. I'm not sure if range of unsigned should.

Araq avatar Aug 24 '22 18:08 Araq

As an alternative, you could make uint subranges behave the same way as modular types in Ada, so that the lower bound is always 0 and arithmetic is done modulo the upper bound + 1. This would ensure the uint never overflows while still respecting the bounds of the subrange. I don't think there is much reason to use a uint subrange as they are now, but this change would give them some utility.

jcprpr avatar Jun 25 '23 03:06 jcprpr

Makes sense.

Araq avatar Jun 26 '23 14:06 Araq

I know this issue is super old but I agree that there should be some form of modular type like Ada. Using a range of unsigned ints seems valid to me.

VoidAlone avatar Dec 03 '25 13:12 VoidAlone