fixes #22389; fixes #19840; don't fold paths containing addr (#23807)

fixes #22389;
fixes #19840

(cherry picked from commit 5c5e7a9b6e)
(cherry picked from commit 00e39185f1d59597d17b69bbccf8879e3427f928)
This commit is contained in:
ringabout
2024-07-09 18:59:21 +08:00
committed by narimiran
parent fe72db98c1
commit eedfcbeb30
3 changed files with 21 additions and 5 deletions

View File

@@ -688,10 +688,7 @@ proc getConstExpr(m: PSym, n: PNode; idgen: IdGenerator; g: ModuleGraph): PNode
except DivByZeroDefect:
localError(g.config, n.info, "division by zero")
of nkAddr:
var a = getConstExpr(m, n[0], idgen, g)
if a != nil:
result = n
n[0] = a
result = nil # don't fold paths containing nkAddr
of nkBracket, nkCurly:
result = copyNode(n)
for son in n.items:

View File

@@ -53,6 +53,7 @@ type
isIntroducingNewLocalVars: bool # true if we are in `introducingNewLocalVars` (don't transform yields)
contSyms, breakSyms: seq[PSym] # to transform 'continue' and 'break'
deferDetected, tooEarly: bool
inAddr: bool
graph: ModuleGraph
idgen: IdGenerator
@@ -1038,7 +1039,10 @@ proc transform(c: PTransf, n: PNode): PNode =
of nkHiddenAddr:
result = transformAddrDeref(c, n, {nkHiddenDeref})
of nkAddr:
let oldInAddr = c.inAddr
c.inAddr = true
result = transformAddrDeref(c, n, {nkDerefExpr, nkHiddenDeref})
c.inAddr = oldInAddr
of nkDerefExpr:
result = transformAddrDeref(c, n, {nkAddr, nkHiddenAddr})
of nkHiddenDeref:
@@ -1118,7 +1122,7 @@ proc transform(c: PTransf, n: PNode): PNode =
let exprIsPointerCast = n.kind in {nkCast, nkConv, nkHiddenStdConv} and
n.typ != nil and
n.typ.kind == tyPointer
if not exprIsPointerCast:
if not exprIsPointerCast and not c.inAddr:
var cnst = getConstExpr(c.module, result, c.idgen, c.graph)
# we inline constants if they are not complex constants:
if cnst != nil and not dontInlineConstant(n, cnst):

View File

@@ -17,3 +17,18 @@ x = "ah"
echo foo[x]
x = "possible."
echo foo[x]
block: # bug #19840
const testBytes = [byte 0xD8, 0x08, 0xDF, 0x45, 0x00, 0x3D, 0x00, 0x52, 0x00, 0x61]
var tempStr = "__________________"
tempStr.prepareMutation
copyMem(addr tempStr[0], addr testBytes[0], testBytes.len)
block: # bug #22389
func foo(): ptr UncheckedArray[byte] =
const bar = [77.byte]
cast[ptr UncheckedArray[byte]](addr bar[0])
doAssert foo()[0] == 77