diff --git a/changelog.md b/changelog.md index 2a9c8aabf2..8e1b05f430 100644 --- a/changelog.md +++ b/changelog.md @@ -33,7 +33,7 @@ errors. - Bitshift operators (`shl`, `shr`, `ashr`) now apply bitmasking to the right operand in the C/C++/VM/JS backends. -- Adds a new warning enabled by `--warning:ImplicitRangeConversion` that detects downsizing implicit conversions to range types (e.g., `int -> range[0..255]` or `range[1..256] -> range[0..255]`) that could cause runtime panics. Safe conversions like `range[0..255] -> range[0..65535]` and explicit casts are not warned on. +- Adds a new warning `--warning:ImplicitRangeConversion` that detects downsizing implicit conversions to range types (e.g., `int -> range[0..255]` or `range[1..256] -> range[0..255]`) that could cause runtime panics. Safe conversions like `range[0..255] -> range[0..65535]` and explicit casts are not warned on. `int` to `Natural` and `Positive` conversions are not warned. ## Standard library additions and changes diff --git a/compiler/nim.cfg b/compiler/nim.cfg index 9dab29eeed..425f0df324 100644 --- a/compiler/nim.cfg +++ b/compiler/nim.cfg @@ -65,3 +65,7 @@ define:useStdoutAsStdmsg @if nimHasVtables: experimental:vtables @end + +@if nimHasImplicitRangeConversion: + warning[ImplicitRangeConversion]:off +@end diff --git a/compiler/sempass2.nim b/compiler/sempass2.nim index 02ec23fc3e..d3b9349257 100644 --- a/compiler/sempass2.nim +++ b/compiler/sempass2.nim @@ -176,7 +176,12 @@ proc shouldWarnRangeConversion(conf: ConfigRef; formalType, argType: PType): boo if f.kind == tyRange: # Only warn if formal range doesn't fully contain argument range # Check if the ranges don't perfectly overlap - result = not isRangeSupertype(conf, f, a) + if f.sym != nil and (f.sym.name.s == "Positive" or + f.sym.name.s == "Natural"): + # Positive and Natural are special cases that we never warn on + result = false + else: + result = not isRangeSupertype(conf, f, a) else: result = false diff --git a/doc/manual.md b/doc/manual.md index f52e0ba38c..2f89d6dddf 100644 --- a/doc/manual.md +++ b/doc/manual.md @@ -1144,6 +1144,8 @@ semantic analysis). Assignments from the base type to one of its subrange types A subrange type has the same size as its base type (`int` in the Subrange example). +Implicit "downsizing" conversions to range types (for example, `int -> range[0..255]` or `range[1..256] -> range[0..255]`) emit the `ImplicitRangeConversion` warning. Conversions that are clearly safe (for example, `range[0..255] -> range[0..65535]`) and any explicit casts do not trigger this warning. Conversions from `int` to common subranges such as `Natural` or `Positive` are also exempt. + Pre-defined floating-point types --------------------------------