{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Text.Pandoc.Lua.Marshaling.PandocError
( peekPandocError
, pushPandocError
)
where
import Foreign.Lua (Lua, Peekable, Pushable, StackIndex)
import Text.Pandoc.Error (PandocError (PandocLuaError))
import qualified Foreign.Lua as Lua
import qualified Foreign.Lua.Userdata as Lua
import qualified Text.Pandoc.Lua.Util as LuaUtil
import qualified Text.Pandoc.UTF8 as UTF8
pandocErrorName :: String
pandocErrorName = "pandoc error"
pushPandocError :: PandocError -> Lua ()
pushPandocError = Lua.pushAnyWithMetatable pushPandocErrorMT
where
pushPandocErrorMT = Lua.ensureUserdataMetatable pandocErrorName $
LuaUtil.addFunction "__tostring" __tostring
peekPandocError :: StackIndex -> Lua PandocError
peekPandocError idx = Lua.ltype idx >>= \case
Lua.TypeUserdata -> do
errMb <- Lua.toAnyWithName idx pandocErrorName
return $ case errMb of
Just err -> err
Nothing -> PandocLuaError "could not retrieve original error"
_ -> do
Lua.pushvalue idx
msg <- Lua.state >>= \l -> Lua.liftIO (Lua.errorMessage l)
return $ PandocLuaError (UTF8.toText msg)
__tostring :: PandocError -> Lua String
__tostring = return . show
instance Pushable PandocError where
push = pushPandocError
instance Peekable PandocError where
peek = peekPandocError