Skip to content

"GHC.Integer can't throw exceptions" is wrong

The various integer packages, and anything else that might be loaded before the Prelude, goes through contortions to report errors, or else doesn't report them and crashes, because those packages are compiled before the Exception type is available.

However, there is a way to throw exceptions from code that only has access to ghc-prim. It relies on the fact that the RTS itself throws an exception in a certain circumstance: when atomically is called from within atomically.

This gives us the following:

{-# LANGUAGE MagicHash, UnboxedTuples, NoImplicitPrelude #-}
import GHC.Prim
import GHC.Magic

atomicLoop :: State# RealWorld -> (# State# RealWorld, a #)
atomicLoop s = atomically atomicLoop s

exception :: a
exception = runRW# (\s -> case atomicLoop s of
  (# _, a #) -> a)

I think that integer-simple and integer-gmp, and maybe the very earliest parts of base, are the only packages that would benefit from this circumlocution; however, having the error be a catchable exception rather than a straight-up crash has benefits.

Priority is low because I don't think there have been any bugs regarding GHC.Integer crashing; I just think it might make the code a bit more elegant.

Trac metadata
Trac field Value
Version 8.2.2
Type FeatureRequest
TypeOfFailure OtherFailure
Priority low
Resolution Unresolved
Component Compiler
Test case
Differential revisions
BlockedBy
Related
Blocking
CC
Operating system
Architecture
To upload designs, you'll need to enable LFS and have an admin enable hashed storage. More information