fixes #14511 [backport:1.4] (#18732)

* fixes #14511 [backport:1.4]

Signed-off-by: Dankr4d <dude569@freenet.de>

* Replaced fix with code from alaviss, for better readability, with small
changes.

Signed-off-by: Dankr4d <dude569@freenet.de>

* - Specified output in test.

Signed-off-by: Dankr4d <dude569@freenet.de>

* Replaced case in nnkRecCase with a simpler version, which just adds the
last son.

Signed-off-by: Dankr4d <dude569@freenet.de>

* Update tests/macros/t14511.nim

* Update tests/macros/t14511.nim

Co-authored-by: Andreas Rumpf <rumpf_a@web.de>
This commit is contained in:
Dankr4d
2021-08-25 19:27:00 +02:00
committed by GitHub
parent 3aa16c1de0
commit c70e4040bd
2 changed files with 64 additions and 11 deletions

View File

@@ -1541,18 +1541,17 @@ proc customPragmaNode(n: NimNode): NimNode =
for i in 0..<identDefsStack.len: identDefsStack[i] = obj[2][i]
while identDefsStack.len > 0:
var identDefs = identDefsStack.pop()
if identDefs.kind == nnkRecCase:
identDefsStack.add(identDefs[0])
for i in 1..<identDefs.len:
let varNode = identDefs[i]
# if it is and empty branch, skip
if varNode[0].kind == nnkNilLit: continue
if varNode[1].kind == nnkIdentDefs:
identDefsStack.add(varNode[1])
else: # nnkRecList
for j in 0 ..< varNode[1].len:
identDefsStack.add(varNode[1][j])
case identDefs.kind
of nnkRecList:
for child in identDefs.children:
identDefsStack.add(child)
of nnkRecCase:
# Add condition definition
identDefsStack.add(identDefs[0])
# Add branches
for i in 1 ..< identDefs.len:
identDefsStack.add(identDefs[i].last)
else:
for i in 0 .. identDefs.len - 3:
let varNode = identDefs[i]

54
tests/macros/t14511.nim Normal file
View File

@@ -0,0 +1,54 @@
discard """
output: "true\n(y: XInt, a: 5)\n(y: XString, b: \"abc\")"
"""
import macros
block TEST_1:
# https://github.com/nim-lang/Nim/issues/14511
template myPragma() {.pragma.}
type
XType = enum
XInt,
XString,
XUnused
X = object
case y {.myPragma.}: XType
of XInt, XUnused:
a: int
else: # <-- Else case caused the "Error: index 1 not in 0 .. 0" error
b: string
var x: X = X(y: XInt, a: 5)
echo x.y.hasCustomPragma(myPragma)
echo x
echo X(y: XString, b: "abc")
block TEST_2:
template myDevice(val: string) {.pragma.}
template myKey(val: string) {.pragma.}
template myMouse(val: string) {.pragma.}
type
Device {.pure.} = enum Keyboard, Mouse
Key = enum Key1, Key2
Mouse = enum Mouse1, Mouse2
type
Obj = object of RootObj
case device {.myDevice: "MyDevicePragmaStr".}: Device
of Device.Keyboard:
key {.myKey: "MyKeyPragmaStr".}: Key
else: # <-- Else case caused the "Error: index 1 not in 0 .. 0" error
mouse {.myMouse: "MyMousePragmaStr".}: Mouse
var obj: Obj
assert obj.device.hasCustomPragma(myDevice) == true
assert obj.key.hasCustomPragma(myKey) == true
assert obj.mouse.hasCustomPragma(myMouse) == true
assert obj.device.getCustomPragmaVal(myDevice) == "MyDevicePragmaStr"
assert obj.key.getCustomPragmaVal(myKey) == "MyKeyPragmaStr"
assert obj.mouse.getCustomPragmaVal(myMouse) == "MyMousePragmaStr"