By default GHC enables the -Woverflowed-literals warning to emit a message if a literal's precision is too great for its type:
OverflowedLiterals.hs:10:12: warning: [GHC-97441] [-Woverflowed-literals]
Literal 258 is out of the Word8 range 0..255
|
10 | print (258 :: Word8)
| ^^^
OverflowedLiterals.hs:15:12: warning: [GHC-97441] [-Woverflowed-literals]
Literal 9223372036854775817 is out of the Int range -9223372036854775808..9223372036854775807
|
15 | print (9223372036854775817 :: Int)
| ^^^^^^^^^^^^^^^^^^^
Is there a way to enable this warning for a custom numeric type?
For example, I'd want this code
data Word4 = Word4 Bool Bool Bool Bool
instance Num Word4 where
...
main = print (17 :: Word4)
To cause the compiler to complain
StackoverflowExample:LINE:COL: warning: [GHC-97441] [-Woverflowed-literals]
Literal 17 is out of the Word4 range 0..15
No, or at least not with
ghcat the time of writing. The code to check this is located here [GitHub]:It thus hardcodes the different (implicit) data constructors to work with
Int,Word,Int16,Word32, etc. and thus checks with the corresponding lower and upperbounds.Strictly speaking, it might perhaps be possible, but currently not implemented. It will likely be a bit complicated to check if we know that the type to which
17for example is converted, is of a type that is an instance ofNumandBounded, since it just translates17tofromInteger 17.