From c70a4502d2a8b6a6ed60c00b0fe27ef9f31e92ed Mon Sep 17 00:00:00 2001 From: ringabout <43030857+ringabout@users.noreply.github.com> Date: Mon, 6 Jul 2026 20:26:14 +0800 Subject: [PATCH] fix #25608; improve implicit range conversion checks (#25838) fix #25608 This pull request improves how the compiler handles warnings for implicit range conversions, ensuring that only non-constant values trigger downsizing warnings. It also adds new test cases to verify that assignments and function calls involving compile-time constants do not produce unnecessary warnings. Improvements to range conversion warnings: * Updated the logic in `compiler/sempass2.nim` to skip implicit range conversion warnings for compile-time constants by checking if an expression is constant with `getConstExpr`. Now, only non-constant values will trigger the warning. Testing enhancements: * Added new test cases in `tests/range/timplicitrangedownsizing.nim` to confirm that assignments and function calls with constant enum and integer values do not trigger downsizing warnings. --- compiler/sempass2.nim | 7 +++--- tests/range/timplicitrangedownsizing.nim | 29 +++++++++++++++++++++++- 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/compiler/sempass2.nim b/compiler/sempass2.nim index 05e24894a6..876802ed7a 100644 --- a/compiler/sempass2.nim +++ b/compiler/sempass2.nim @@ -1649,10 +1649,11 @@ proc track(tracked: PEffects, n: PNode) = message(tracked.config, n.info, warnPtrToCstringConv, $n[1].typ) - # Check for implicit range conversions + # Check for implicit range conversions. Compile-time constants are already + # fully known here, so only non-constant values need the downsizing warning. if n.kind == nkHiddenStdConv and (not tracked.isArrayIndexing) and - n[1].kind notin {nkCharLit..nkUInt64Lit, nkFloatLit..nkFloat128Lit} and - shouldWarnRangeConversion(tracked.config, n.info, n.typ, n[1].typ): + shouldWarnRangeConversion(tracked.config, n.info, n.typ, n[1].typ) and + getConstExpr(tracked.ownerModule, n[1], tracked.c.idgen, tracked.graph) == nil: message(tracked.config, n.info, warnImplicitRangeConversion, typeToString(n[1].typ) & " -> " & typeToString(n.typ)) diff --git a/tests/range/timplicitrangedownsizing.nim b/tests/range/timplicitrangedownsizing.nim index 930d91bb11..d1409ed33e 100644 --- a/tests/range/timplicitrangedownsizing.nim +++ b/tests/range/timplicitrangedownsizing.nim @@ -75,4 +75,31 @@ wf = smallFloatRange # OK - SmallFloat range fits in WideFloatRange proc foo(x: Natural) = discard -foo(12) \ No newline at end of file +foo(12) + +block: + type + E = enum + ea, eb + + R = range[eb..eb] + I = range[0..3] + + proc accept(r: R) = discard + proc accept(i: I) = discard + + var r: R + var i: I + const enumOk = eb + const enumAlias = enumOk + const intOk = 1 + 2 + + r = eb + r = enumOk + r = enumAlias + accept(eb) + accept(enumOk) + accept(enumAlias) + + i = intOk + accept(intOk)