No more exceptions: debugging Haskell code with GHCi

One of the true gems of the new GHC 6.8.1 release (besides the ubiquitous 20% speedup in your compiled code) is that we finally have a robust solution to tracking down unknown exceptions in Haskell code! Using the shiny new GHCi debugger, courtesy of Simon Marlow, José Iborra, Bernie Pope and Andy Gill it is possible to obtain a perfect backtrace to source location, and display the source, of your failing code — the kind you might find if you’re a bit sloppy when reasoning about totality:

    $ ./a.out
    *** Exception: Prelude.head: empty list

Pretty useless error message. Tracking this down has been a hard problem using GHC in the past. You had to either:

  • Convince the profiler to give you a stack trace (i.e. the little known +RTS -xc option) (buried in the “interested souls” section of the GHC manual
  • Replace calls to head with calls that will fail with a better error message (maybe using a library such as loch)
  • Get your code into Haskell 98 shape, and use Catch totality checker to statically analyse your code for partial functions, or maybe use Hat to trace the code.

All three solutions are quite obscure, the first one works but is tedious, the second is used by no one, and the third only works in theory. Yet the problem of partial functions and unknown exceptions persists.

Until now.

Imagine you develop a lovely Haskell program called HsColour, and deep down inside is a call to ‘head’:

    head       :: [a] -> a
    head (x:_) = x
    head []    = error "Prelude.head: empty list"

that relies on some invariant in your code you forgot to write a QuickCheck property for. As long as the invariant holds, the call to head is safe. When run, your program happily marks up Haskell code as html:

    $ runhaskell HsColour.hs -css < source.hs
    -- The stream data type
    data Stream a = forall s. Unlifted s =>
                              Stream !(s -> Step a s)  -- ^ a stepper function
                                     !s                -- ^ an initial state

    map :: (a -> b) -> Stream a -> Stream b
    map f (Stream next0 s0) = Stream next s0
        next !s = case next0 s of
            Done       -> Done
            Skip    s' -> Skip        s'
            Yield x s' -> Yield (f x) s'

Lovely stuff. Years go by, and someone joins your project, and starts refactoring. In the process, they break this crucial invariant. Now your programs says:

    $ runhaskell HsColour.hs -css < source.hs
    HsColour.hs: Prelude.head: empty list

Where do you begin to debug this? Not much information. Now, some people, at this point would mumble something about monads being too hard, and rewrite the project in Python, but there’s no need. Fire up ghci 6.8.1, and set a breakpoint on exceptions, and set up some command line args for your program:

    $ ghci HsColour.hs
    *Main> :set -fbreak-on-exception
    *Main> :set args "source.hs"

Now run your program with tracing on, and GHCi will stop your program at the call to error:

    *Main> :trace main
    Stopped at (exception thrown)

Ok, good. We had an exception… Let’s just back up a bit and see where we are. Watch now as we travel backwards in time through our program, using the (bizarre, I know) “:back” command:

    [(exception thrown)] *Main> :back
    Logged breakpoint at Language/Haskell/HsColour/Classify.hs:(19,0)-(31,46)
    _result :: [String]

This tells us that immediately before hitting error, we were in the file Language/Haskell/HsColour/Classify.hs, at line 19. We’re in pretty good shape now. Let’s see where exactly:

    [-1: Language/Haskell/HsColour/Classify.hs:(19,0)-(31,46)] *Main> :list
    18  chunk :: String -> [String]
    19  chunk []    = head []
    20  chunk ('\r':s) = chunk s -- get rid of DOS newline stuff
    21  chunk ('\n':s) = "\n": chunk s

Ok, that’s awesome! Our bogus call to head, deep down in the program is somewhere on those two lines: can you spot it? :) Fixing that line, and we’re back in business. The days of head scratching at head [] failures are over. Now go and write some QuickCheck properties to ensure this never happens again.

The GHCi debugger can do a lot more than just travel back in time and find your bugs for you, and it is just one point in the world of declarative debugging. For more reading have a look at:

Haskell has a debugger, it’s there if you need it.

One thought on “No more exceptions: debugging Haskell code with GHCi

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s