headergen-0.1.1.1: src/Headergen/Template.hs
{- |
Module : $Header$
Description : Template language syntax tree.
Author : Nils 'bash0r' Jonsson
Copyright : (c) 2015 Nils 'bash0r' Jonsson
License : MIT
Maintainer : aka.bash0r@gmail.com
Stability : unstable
Portability : non-portable (Portability is untested.)
This module contains the syntax tree for the templating language.
-}
module Headergen.Template
( KeyValue
, Dictionary
, VariableName
, Template (..)
, fillTemplate
) where
import Control.Applicative
import Control.Monad
-- | A key value pair.
type KeyValue = (String, String)
-- | A list of key value pairs.
type Dictionary = [KeyValue]
-- | The name of a variable in a template.
type VariableName = String
-- | A template is used when
data Template
-- | A simple text element in the template.
= TemplateText String
-- | A variable to substitute in later process in the template.
| TemplateVariable VariableName
-- | A sequence of several elements in the template.
| TemplateSequence Template Template
-- | The end of a template.
| TemplateEOF
deriving (Show, Eq)
fillTemplate :: Dictionary -> Template -> Either String String
fillTemplate dict (TemplateEOF ) = Right ""
fillTemplate dict (TemplateVariable var ) = case dict `find` var of
Just v -> Right v
Nothing -> Left ("Variable " ++ var ++ " is not defined.")
fillTemplate dict (TemplateText text ) = Right text
fillTemplate dict (TemplateSequence left right) = do
l <- fillTemplate dict left
r <- fillTemplate dict right
return (l ++ r)
find ((key, value):xs) var =
if key == var
then Just value
else find xs var
find [] _ =
Nothing