{-# LANGUAGE TemplateHaskell #-}
-- | functions that help you with debugging.
-- Most would make sense in the Debug.Trace module
-- There are Template Haskell versions that show you file locaiton information
module Debug.FileLocation
  (debug, debugM, debugMsg, dbg, dbgMsg, trc, ltrace, ltraceM, strace, traceId, __LOC__)
  where

import Control.Applicative ((<$>), (<*>), pure)
import Language.Haskell.TH (recConE, litE, stringL, integerL)
import Language.Haskell.TH.Instances
import Language.Haskell.TH.Syntax
import Debug.Util
import Debug.Trace (trace)
import FileLocation.LocationString (locationToString)

-- | TH  version of Debug.Trace.trace that just prints a value.
dbg :: Q Exp
dbg :: Q Exp
dbg = do
  Loc
loc <- Q Loc
forall (m :: * -> *). Quasi m => m Loc
qLocation
  let pre :: [Char]
pre = [Char]
"DEBUG: " [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ (Loc -> [Char]
locationToString Loc
loc)
  [|(\_x -> ltrace pre _x)|]

-- | TH version  of Debug.Trace.trace that prints a value and a message
-- prefix.
dbgMsg :: String -> Q Exp
dbgMsg :: [Char] -> Q Exp
dbgMsg [Char]
msg = do
  Loc
loc <- Q Loc
forall (m :: * -> *). Quasi m => m Loc
qLocation
  let pre :: [Char]
pre = [Char]
"DEBUG: " [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ (Loc -> [Char]
locationToString Loc
loc) [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ Char
' ' Char -> [Char] -> [Char]
forall a. a -> [a] -> [a]
: [Char]
msg
  [|(\_x -> ltrace pre _x)|]

-- | A TH version of Debug.Trace.trace that prints location information
trc :: String -> Q Exp
trc :: [Char] -> Q Exp
trc [Char]
str = do
  Loc
loc <- Q Loc
forall (m :: * -> *). Quasi m => m Loc
qLocation
  let prefix :: [Char]
prefix = [Char]
"TRACE: " [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ (Loc -> [Char]
locationToString Loc
loc) [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
" "
  [|trace (prefix ++ str)|]

-- | A TH monadic version of debug - print a value with location information as a stand alone expression in a monad
dbgM :: Q Exp
dbgM :: Q Exp
dbgM = do
  Loc
loc <- Q Loc
forall (m :: * -> *). Quasi m => m Loc
qLocation
  let prefix :: [Char]
prefix = [Char]
"DEBUG: " [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ (Loc -> [Char]
locationToString Loc
loc) [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
" "
  [|(\_x -> ltraceM (prefix ++ show _x) _x)|]

-- | Embed an expression of type Loc containing the location
-- information for the place where it appears.  Could be used in
-- custom Exception types and similar:
--
-- > throw $ MyException $__LOC__
__LOC__ :: Q Exp
__LOC__ :: Q Exp
__LOC__ = Loc -> Q Exp
forall t (m :: * -> *). (Lift t, Quote m) => t -> m Exp
lift (Loc -> Q Exp) -> Q Loc -> Q Exp
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< Q Loc
location