nim-lang / Nim

Nim is a statically typed compiled systems programming language. It combines successful concepts from mature languages like Python, Ada and Modula. Its design focuses on efficiency, expressiveness, and elegance (in that order of priority).
https://nim-lang.org
Other
16.64k stars 1.47k forks source link

Const values don't short circuit. #19773

Open treeform opened 2 years ago

treeform commented 2 years ago

If you have a const string it will not short-circuit and will not compile:

Example

const s1 = ""
if s1.len == 0 or s1[0] == '/':
  echo "root"

Current Output

Error: index out of bounds, the container is empty""[0]

Expected Output

root

I would expect it to work similar to let or var.

let s2 = ""
if s2.len == 0 or s2[0] == '/':
  echo "root"

var s3 = ""
if s3.len == 0 or s3[0] == '/':
  echo "root"

output:

root
root

That works fine.

The const make it work more like some sort of substitution:

if "".len == 0 or ""[0] == '/':
  echo "root"

output:

Error: index out of bounds, the container is emptys1[0]

Same thing happens with static values:

proc foo(s2: static string) =
  if s2.len == 0 or s2[0] == '/':
    echo "root"
foo ""

output:

Error: index out of bounds, the container is emptys1[0]
$ nim -v
Nim Compiler Version 1.7.1 [Linux: amd64]
Compiled at 2022-05-05
Copyright (c) 2006-2022 by Andreas Rumpf

git hash: 278ecad973c6581aeea0a6ff9372109b0dd6df5e
active boot switches: -d:release

Related issue: related https://github.com/nim-lang/Nim/issues/19492

ghost commented 2 years ago

See https://github.com/nim-lang/Nim/issues/14631 and https://github.com/nim-lang/Nim/pull/13541 as well

ringabout commented 2 years ago

It seems very hard to make semcheck short circuir, I have no idea.