Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ranges don't work in generics, and subtypes of array don't get bounds-checked, with dramatic consequences #17423

Open
ShadowElf37 opened this issue Mar 20, 2021 · 0 comments

Comments

@ShadowElf37
Copy link

ShadowElf37 commented Mar 20, 2021

Expands on #16969 and #16492.

There are (at least) two related issues at play here. First, subtypes of array won't have their bounds checked. Second, range doesn't get checked in generics. As it stands, this behavior is both unintuitive and extremely unsafe, as impossible code gets through without erroring, or with unhelpful messages.

Example (both issues)

Somewhat incredibly, this both compiles and runs.

type NaturalArray[N: static[Natural]] = array[N, int]

var a: NaturalArray[-1000]
echo a  # output: []

However, this will fail to compile, as expected:

var b: array[-1000, int]  # Error: Array length can't be negative, but was -1000

Expected Output

Error: cannot instantiate NaturalArray: invalid value -1000 for N

Some Amusing Very Serious Examples and Related Issues

Some more things that compile and run but shouldn't:

type IntArray[N: static[int]] = array[N, int]
var c: IntArray[-1000]
echo c  # []

type RangedArray[N: static[3..high(int)]] = array[N, int]
var d: RangedArray[1]
echo d  # [0]

While we're here, these both makes the compiler hang forever, but only if you echo the variables afterwards:

type FunnyArray[N] = array[N, int]
var e: FunnyArray[0.5]
echo e

type HilariousArray[N] = array[N, int]
var f: HilariousArray["not even a number lmao"]
echo f

If you DON'T echo, you get this very helpful message:

Error: internal error: invalid kind for lastOrd(tyFloat)
No stack traceback available
To create a stacktrace, rerun compilation with './koch temp c <file>', see https://nim-lang.github.io/Nim/intern.html#debugging-the-compiler for details

Below will also give you that message, with or without echoing, as long as you leave out the static in the generic (related to #17362 ?):

type BadRangedArray[N: range[3..high(int)]] = array[N, int]  # Error: internal error: invalid kind for lastOrd(tyAnything)
let g = BadRangedArray([1, 1, 1])

Ok I'll stop 😅.

Version

Nim Compiler Version 1.4.4 [Windows: amd64]
Compiled at 2021-02-23
Copyright (c) 2006-2020 by Andreas Rumpf
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

No branches or pull requests

1 participant