Skip to content

Non-terminating typeclass method (that never actually gets called) with UndecidableInstances, UndecidableSuperClasses, KnownNat

Summary

Trying to call a certain typeclass method, the actual call never seems to happen, instead the program runs out of stack (in ghci) or memory (compiled).

Steps to reproduce

Minimal example:

{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE UndecidableSuperClasses #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE DataKinds #-}

module Derp where

import GHC.TypeLits (KnownNat, Nat)
import Data.Kind (Type)

class (PConstantDecl (PLifted p)) => PUnsafeLiftDecl (p :: Type) where
  type PLifted p :: Type

class (PUnsafeLiftDecl (PConstanted h)) => PConstantDecl (h :: Type) where
  type PConstanted h :: Type
  pconstantToRepr :: h -> h

data FixedDecimal (unit :: Nat) = FixedDecimal deriving stock Show

data PFixedDecimal (unit :: Nat) = PFixedDecimal

instance (KnownNat unit) => PUnsafeLiftDecl (PFixedDecimal unit) where
  type PLifted (PFixedDecimal unit) = FixedDecimal unit

instance (KnownNat unit) => PConstantDecl (FixedDecimal unit) where
  type PConstanted (FixedDecimal unit) = PFixedDecimal unit
  -- this never gets actually executed, can replace it with undefined
  pconstantToRepr = id

-- in ghci: *** Exception: stack overflow
endless :: FixedDecimal 1
endless = pconstantToRepr FixedDecimal

Compiled code runs until out of memory. Reproduced with 9.2.3 (ghci and compiled) and 9.2.4 (only tested in ghci). Terminates on 9.4.2 (only tested in ghci). Removing the KnownNat constraints makes it terminate on 9.2.3. Possibly this is the same issue as #21973 (closed), but there is stated that it's not fixed in 9.4.2, while this issue here seems to not affect 9.4.2.

Expected behavior

Terminate instantly.

Environment

  • GHC version used: 9.2.3 and 9.2.4

Optional:

  • Operating System: NixOS 22.05
  • System Architecture: Linux
To upload designs, you'll need to enable LFS and have an admin enable hashed storage. More information