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

`offsetOf` compilation error in a static context inside a procedure #17693

Open exelotl opened 3 years ago

exelotl commented 3 years ago

Attempting to use offsetOf on a type fails when used within a procedure inside a static block or assigned to a const.

Example

type
  GoodboySave = object
    checksum: uint32
    header: array[8, char]
    version: uint8
    saveCount: uint8
    savePoint: uint16
    shards: uint32
    friendCount: uint8

proc getSaveSize: int =
  ## Get size in bytes without checksum
  const ofs = GoodboySave.offsetof(header)  # Error here
  const len = GoodboySave.sizeof - ofs
  len

echo getSaveSize()

Current Output

system.nim(607, 13) Error: cannot evaluate at compile time: tmp`gensym0

Expected Output

20

Additional Information

It works fine when calling offsetOf at the top level:

const ofs = GoodboySave.offsetof(header)  # Ok
proc getSaveSize: int =
  ## Get size in bytes without checksum
  const len = GoodboySave.sizeof - ofs
  len

Tested from Nim 1.4.2 to 1.4.6 RC1

$ nim -v
Nim Compiler Version 1.4.4 [Linux: amd64]
Compiled at 2021-02-23
Copyright (c) 2006-2020 by Andreas Rumpf
metagn commented 2 weeks ago

This seems to be a consequence of #10828 etc, moving it to a proc or even doing (proc (): auto = GoodboySave.offsetof(header))() is a workaround