th-test-utils-1.0.0: Utility functions for testing Template Haskell code

MaintainerBrandon Chinn <brandon@leapyear.io>
Stabilityexperimental
Portabilityportable
Safe HaskellNone
LanguageHaskell2010

Language.Haskell.TH.TestUtils

Contents

Description

This module defines utilites for testing Template Haskell code.

Synopsis

Error recovery

Unfortunately, there is no built-in way to get an error message of a Template Haskell computation, since recover throws away the error message. If recover was defined differently, we could maybe do:

recover' :: (String -> Q a) -> Q a -> Q a

spliceFail :: Q Exp
spliceFail = fail "This splice fails"

spliceInt :: Q Exp
spliceInt = [| 1 |]

test1 :: Either String Int
test1 = $(recover' (pure . Left) $ Right <$> spliceFail) -- generates `Left "This splice fails"`

test2 :: Either String Int
test2 = $(recover' (pure . Left) $ Right <$> spliceInt) -- generates `Right 1`

But for now, we'll have to use tryQ:

test1 :: Either String Int
test1 = $(tryQ spliceFail) -- generates `Left "This splice fails"`

test2 :: Either String Int
test2 = $(tryQ spliceInt) -- generates `Right 1`

ref. https://ghc.haskell.org/trac/ghc/ticket/2340

tryQ' :: Q a -> Q (Either String a) Source #

Run the given Template Haskell computation, returning either an error message or the final result.

tryQ :: Q Exp -> Q Exp Source #

Run the given Template Haskell computation, returning a splicable expression that resolves to Left the error message or Right the final result.

-- Left "This splice fails"
$(tryQ spliceFail) :: Either String Int

-- Right 1
$(tryQ spliceInt) :: Either String Int

tryQErr :: Q a -> Q Exp Source #

tryQ, except returns Just the error message or Nothing if the computation succeeded.

-- Just "This splice fails"
$(tryQErr spliceFail) :: Maybe String

-- Nothing
$(tryQErr spliceInt) :: Maybe String

tryQErr' :: Q a -> Q Exp Source #

tryQ, except returns the error message or fails if the computation succeeded.

-- "This splice fails"
$(tryQErr' spliceFail) :: String

-- compile time error: "Q monad unexpectedly succeeded"
$(tryQErr' spliceInt) :: String