From 58408ba018101fb01a351b02b87ae03fc20794bb Mon Sep 17 00:00:00 2001 From: unknown Date: Sun, 30 Oct 2022 00:54:28 +0800 Subject: [PATCH] fix #12334 const cstring conversion from string cause cgen error --- compiler/sem.nim | 17 +++++++++++++++++ compiler/semstmts.nim | 2 +- tests/statictypes/t12334.nim | 6 ++++++ 3 files changed, 24 insertions(+), 1 deletion(-) create mode 100644 tests/statictypes/t12334.nim diff --git a/compiler/sem.nim b/compiler/sem.nim index 8f766f126c8e7..8266f84de2eed 100644 --- a/compiler/sem.nim +++ b/compiler/sem.nim @@ -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: @@ -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: diff --git a/compiler/semstmts.nim b/compiler/semstmts.nim index 81be6772526f7..a90eb17a12b2d 100644 --- a/compiler/semstmts.nim +++ b/compiler/semstmts.nim @@ -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 diff --git a/tests/statictypes/t12334.nim b/tests/statictypes/t12334.nim new file mode 100644 index 0000000000000..4532c0a0047dd --- /dev/null +++ b/tests/statictypes/t12334.nim @@ -0,0 +1,6 @@ +const a = "foo" +const b: cstring = a + +# const b: cstring = "foo" # would work +var c = b +doAssert c == "foo"