Skip to content

Commit

Permalink
fix nim-lang#12334 const cstring conversion from string cause cgen error
Browse files Browse the repository at this point in the history
  • Loading branch information
bung87 committed Oct 29, 2022
1 parent e68a6ea commit 58408ba
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 1 deletion.
17 changes: 17 additions & 0 deletions compiler/sem.nim
Original file line number Diff line number Diff line change
Expand Up @@ -368,6 +368,21 @@ proc tryConstExpr(c: PContext, n: PNode; expectedType: PType = nil): PNode =
const
errConstExprExpected = "constant expression expected"

proc transformConstBuiltins(n: PNode; expectedType: PType): PNode =
result = n
let srcKind = n.typ.kind
let destKind = expectedType.kind
if srcKind == tyString and destKind == tyCstring:
result = newNodeIT(nkStringToCString, n.info, n.typ)
newSeq(result.sons, 1)
result[0] = n
result.typ = expectedType
elif srcKind == tyCstring and destKind == tyString:
result = newNodeIT(nkCStringToString, n.info, n.typ)
newSeq(result.sons, 1)
result[0] = n
result.typ = expectedType

proc semConstExpr(c: PContext, n: PNode; expectedType: PType = nil): PNode =
var e = semExprWithType(c, n, expectedType = expectedType)
if e == nil:
Expand All @@ -390,6 +405,8 @@ proc semConstExpr(c: PContext, n: PNode; expectedType: PType = nil): PNode =
result = e
else:
result = fixupTypeAfterEval(c, result, e)
elif expectedType != nil:
result = transformConstBuiltins(result, expectedType)

proc semExprFlagDispatched(c: PContext, n: PNode, flags: TExprFlags; expectedType: PType = nil): PNode =
if efNeedStatic in flags:
Expand Down
2 changes: 1 addition & 1 deletion compiler/semstmts.nim
Original file line number Diff line number Diff line change
Expand Up @@ -785,7 +785,7 @@ proc semConst(c: PContext, n: PNode): PNode =
typ = def.typ

# evaluate the node
def = semConstExpr(c, def)
def = semConstExpr(c, def, typ)
if def == nil:
localError(c.config, a[^1].info, errConstExprExpected)
continue
Expand Down
6 changes: 6 additions & 0 deletions tests/statictypes/t12334.nim
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
const a = "foo"
const b: cstring = a

# const b: cstring = "foo" # would work
var c = b
doAssert c == "foo"

0 comments on commit 58408ba

Please sign in to comment.