{- |
Module      :  $Header$
Description :  A parser for the template language.
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 package contains a simple parser for the templating language.
-}
module Headergen.Template.Parser
( parseTemplate
) where


import Control.Applicative
import Control.Monad

import Headergen.Template


-- | Parse a template definition.
parseTemplate :: String -> Template
parseTemplate xs = parse xs []
  where
    parse []       ys =
      if null ys
         then TemplateEOF
         else TemplateSequence (TemplateText (reverse ys)) TemplateEOF
    parse ('$':xs) ys =
      let (zs, res) = parseVariable xs []
          rest = parse zs []
       in TemplateSequence (TemplateText (reverse ys)) (TemplateSequence (TemplateVariable res) rest)
    parse (x  :xs) ys =
      parse xs (x:ys)

    parseVariable []        ys = ([]     , reverse ys)
    parseVariable (' ' :xs) ys = (' ' :xs, reverse ys)
    parseVariable ('\t':xs) ys = ('\t':xs, reverse ys)
    parseVariable ('\n':xs) ys = ('\n':xs, reverse ys)
    parseVariable ('\r':xs) ys = ('\r':xs, reverse ys)
    parseVariable (x   :xs) ys = parseVariable xs (x:ys)

