Suppose this piece of code for a very simple menu system I'm developing in Nim.
type
MenuId = enum
MainMenu, FileMenu, EditMenu, ViewMenu
ActionId = enum
Action1, Action2, Action3
ActionKind = enum
GoToMenu, ExecuteAction
MenuChoice = object
text: string
case actionKind: ActionKind:
of GoToMenu:
target: MenuId
of ExecuteAction:
actionId: ActionId
Menu = object
id: MenuId
name: string
choices: seq[MenuChoice]
let mainMenu = Menu(id: MainMenu, name: "MAIN MENU", choices: @[
MenuChoice(text: "&File", actionKind: GoToMenu, target: FileMenu),
MenuChoice(text: "&Edit", actionKind: GoToMenu, target: EditMenu),
MenuChoice(text: "&View", actionKind: GoToMenu, target: ViewMenu)
])
As the documentation states, MenuChoice can be initialized with different members depending on the actionKind value, making variant-types possible in Nim. Doing echo $(mainMenu) gives the expected output:
(id: MainMenu, name: "MAIN MENU", choices: @[(text: "&File", actionKind: GoToMenu, target: FileMenu), (text: "&Edit", actionKind: GoToMenu, target: EditMenu), (text: "&View", actionKind: GoToMenu, target: ViewMenu)])
But Using const instead of let to force the static mainMenu object to reside a readonly section breaks this behavior. It will compile successfully, but seems the target member is locked at zero:
(id: MainMenu, name: "MAIN MENU", choices: @[(text: "&File", actionKind: GoToMenu, target: MainMenu), (text: "&Edit", actionKind: GoToMenu, target: MainMenu), (text: "&View", actionKind: GoToMenu, target: MainMenu)])
What is going on? I'm compiling with MSC compiler in C mode.
Thanks!
Looks like this is a Nim bug. Normally you are not allowed to put an object variant into a const. The compiler will error out if you do so. Apparantly using an array somehow bypassed this check.
I think you should open an issue on nim-lang/Nim for this.
This is a already reported in this bug: https://github.com/nim-lang/Nim/issues/8015 "Const arrays losing object variants data at runtime" though in my case it was a proc field that was locked.
Seems like enum fields are also affected (and probably others).