From 00be8f287a41be42b3763f71beecd959dd6b7aa2 Mon Sep 17 00:00:00 2001 From: metagn Date: Mon, 8 Jan 2024 05:44:04 +0300 Subject: [PATCH] trigger range check with new type inference on nkIntLit [backport:1.6] (#23179) fixes #23177 `changeType` doesn't perform range checks to see if the expression fits the new type [if the old type is the same as the new type](https://github.com/nim-lang/Nim/blob/62d8ca43063197272968b4acf8c7a1ef27874c54/compiler/semexprs.nim#L633). For `nkIntLit`, we previously set the type to the concrete base of the expected type first, then call `changeType`, which works for things like range types but not bare types of smaller bit size like `int8`. Now we don't set the type (so the type is nil), and `changeType` performs the range check when the type is unset (nil). --- compiler/semexprs.nim | 3 +-- tests/overflow/twronginference.nim | 10 ++++++++++ 2 files changed, 11 insertions(+), 2 deletions(-) create mode 100644 tests/overflow/twronginference.nim diff --git a/compiler/semexprs.nim b/compiler/semexprs.nim index 67eee3a19a..009458089b 100644 --- a/compiler/semexprs.nim +++ b/compiler/semexprs.nim @@ -630,7 +630,7 @@ proc changeType(c: PContext; n: PNode, newType: PType, check: bool) = a.add m changeType(m, tup[i], check) of nkCharLit..nkUInt64Lit: - if check and n.kind != nkUInt64Lit and not sameType(n.typ, newType): + if check and n.kind != nkUInt64Lit and not sameTypeOrNil(n.typ, newType): let value = n.intVal if value < firstOrd(c.config, newType) or value > lastOrd(c.config, newType): localError(c.config, n.info, "cannot convert " & $value & @@ -3152,7 +3152,6 @@ proc semExpr(c: PContext, n: PNode, flags: TExprFlags = {}, expectedType: PType expected.kind in {tyInt..tyInt64, tyUInt..tyUInt64, tyFloat..tyFloat128}): - result.typ = expected if expected.kind in {tyFloat..tyFloat128}: n.transitionIntToFloatKind(nkFloatLit) changeType(c, result, expectedType, check=true) diff --git a/tests/overflow/twronginference.nim b/tests/overflow/twronginference.nim new file mode 100644 index 0000000000..34a982976b --- /dev/null +++ b/tests/overflow/twronginference.nim @@ -0,0 +1,10 @@ +discard """ + errormsg: "cannot convert 256 to int8" + line: 9 +""" + +# issue #23177 + +var x: int8 +x = 256 +echo x # 0