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.58k stars 1.47k forks source link

Const block in function cannot evaluate vars at compile time #21610

Closed tsoj closed 1 year ago

tsoj commented 1 year ago

Description

A compile time block in a function body doesn't allow the creation of vars. The following example fails to compile:

func stuff(): int =
  const r = block:
    var r = 0 # Error: cannot evaluate at compile time: r
    for i in 0..10:
      r *= i
    r
  r

echo stuff()

When the const block is outside the function, it works however:

const r = block:
  var r = 0
  for i in 0..10:
    r *= i
  r

func stuff(): int =
  r

echo stuff()

Nim Version

Nim Compiler Version 1.9.3 [Linux: amd64] Compiled at 2023-04-01 Copyright (c) 2006-2023 by Andreas Rumpf

git hash: 1c7fd717206c79be400f81a05eee771823b880ca active boot switches: -d:release

Current Output

Hint: used config file '/home/tsoj/.choosenim/toolchains/nim-#devel/config/nim.cfg' [Conf]
Hint: used config file '/home/tsoj/.choosenim/toolchains/nim-#devel/config/config.nims' [Conf]
......................................................................
/tmp/main.nim(3, 9) Error: cannot evaluate at compile time: r

Expected Output

0

or if it's supposed to not compile, a better error message.

Possible Solution

No response

Additional Information

No response

metagn commented 1 year ago

Similar/same #8758 #10828 #12172