{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
module Text.Microstache.Type
( Template (..)
, Node (..)
, Key (..)
, showKey
, PName (..)
, MustacheException (..)
, displayMustacheException
, MustacheWarning (..)
, displayMustacheWarning
)
where
import Data.Word (Word)
import Control.DeepSeq
import Control.Exception (Exception(..))
import Data.Data (Data)
import Data.Map (Map)
import Data.Semigroup
import Data.String (IsString (..))
import Data.Text (Text)
import Data.Typeable (Typeable)
import GHC.Generics
import Text.Parsec
import qualified Data.Map as M
import qualified Data.Text as T
data Template = Template
{ templateActual :: PName
, templateCache :: Map PName [Node]
} deriving (Eq, Ord, Show, Data, Typeable, Generic)
instance Semigroup Template where
(Template pname x) <> (Template _ y) = Template pname (M.union x y)
data Node
= TextBlock Text
| EscapedVar Key
| UnescapedVar Key
| Section Key [Node]
| InvertedSection Key [Node]
| Partial PName (Maybe Word)
deriving (Eq, Ord, Show, Data, Typeable, Generic)
newtype Key = Key { unKey :: [Text] }
deriving (Eq, Ord, Show, Semigroup, Monoid, Data, Typeable, Generic)
instance NFData Key
showKey :: Key -> Text
showKey (Key []) = "<implicit>"
showKey (Key xs) = T.intercalate "." xs
newtype PName = PName { unPName :: Text }
deriving (Eq, Ord, Show, Data, Typeable, Generic)
instance IsString PName where
fromString = PName . T.pack
instance NFData PName
data MustacheException
= MustacheParserException ParseError
| MustacheRenderException PName Key
deriving (Eq, Show, Typeable, Generic)
{-# DEPRECATED MustacheRenderException "Not thrown anymore, will be removed in the next major version of microstache" #-}
displayMustacheException :: MustacheException -> String
displayMustacheException (MustacheParserException e) = show e
displayMustacheException (MustacheRenderException pname key) =
"Referenced value was not provided in partial \"" ++ T.unpack (unPName pname) ++
"\", key: " ++ T.unpack (showKey key)
instance Exception MustacheException where
#if MIN_VERSION_base(4,8,0)
displayException = displayMustacheException
#endif
data MustacheWarning
= MustacheVariableNotFound Key
| MustacheDirectlyRenderedValue Key
deriving (Eq, Show, Typeable, Generic)
displayMustacheWarning :: MustacheWarning -> String
displayMustacheWarning (MustacheVariableNotFound key) =
"Referenced value was not provided, key: " ++ T.unpack (showKey key)
displayMustacheWarning (MustacheDirectlyRenderedValue key) =
"Complex value rendered as such, key: " ++ T.unpack (showKey key)
instance Exception MustacheWarning where
#if MIN_VERSION_base(4,8,0)
displayException = displayMustacheWarning
#endif