aboutsummaryrefslogtreecommitdiff
path: root/mustache/src/Text/Mustache/Parser.hs
blob: 2dc5d9336ce5d073937d3d2389750b8a6b995b96 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
{-|
Module      : $Header$
Description : Basic functions for dealing with mustache templates.
Copyright   : (c) Justus Adam, 2015
License     : BSD3
Maintainer  : dev@justus.science
Stability   : experimental
Portability : POSIX
-}
{-# LANGUAGE FlexibleContexts      #-}
{-# LANGUAGE LambdaCase            #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NamedFieldPuns        #-}
{-# LANGUAGE OverloadedStrings     #-}
{-# LANGUAGE TupleSections         #-}
module Text.Mustache.Parser
  (
  -- * Generic parsing functions

    parse, parseWithConf

  -- * Configurations

  , MustacheConf(..), defaultConf

  -- * Parser

  , Parser, MustacheState

  -- * Mustache Constants

  , sectionBegin, sectionEnd, invertedSectionBegin, unescape2, unescape1
  , delimiterChange, nestingSeparator

  ) where


import           Control.Monad
import           Data.Char           (isAlphaNum, isSpace)
import           Data.List           (nub)
import           Data.Text           as T (Text, null, pack)
import           Prelude             as Prel
import           Text.Mustache.Types
import           Text.Parsec         as P hiding (endOfLine, parse)


-- | Initial configuration for the parser
data MustacheConf = MustacheConf
  { delimiters :: (String, String)
  }


-- | User state for the parser
data MustacheState = MustacheState
  { sDelimiters        :: (String, String)
  , textStack          :: Text
  , isBeginngingOfLine :: Bool
  , currentSectionName :: Maybe DataIdentifier
  }


data SectionStart = Normal | Existing | Inverted

data ParseTagRes
  = SectionBegin SectionStart DataIdentifier
  | SectionEnd DataIdentifier
  | Tag (Node Text)
  | HandledTag


-- | @#@
sectionBegin :: Char
sectionBegin = '#'
-- | @/@
sectionEnd :: Char
sectionEnd = '/'
-- | @>@
partialBegin :: Char
partialBegin = '>'
-- | @^@
invertedSectionBegin :: Char
invertedSectionBegin = '^'
-- | @^@
existingSectionBegin :: Char
existingSectionBegin = '?'
-- | @{@ and @}@
unescape2 :: (Char, Char)
unescape2 = ('{', '}')
-- | @&@
unescape1 :: Char
unescape1 = '&'
-- | @=@
delimiterChange :: Char
delimiterChange = '='
-- | @.@
nestingSeparator :: Char
nestingSeparator = '.'
-- | @!@
comment :: Char
comment = '!'
-- | @.@
implicitIterator :: Char
implicitIterator = '.'
-- | Cannot be a letter, number or the nesting separation Character @.@
isAllowedDelimiterCharacter :: Char -> Bool
isAllowedDelimiterCharacter =
  not . Prel.or . sequence
    [ isSpace, isAlphaNum, (== nestingSeparator) ]
allowedDelimiterCharacter :: Parser Char
allowedDelimiterCharacter =
  satisfy isAllowedDelimiterCharacter


-- | Empty configuration
emptyState :: MustacheState
emptyState = MustacheState ("", "") mempty True Nothing


-- | Default configuration (delimiters = ("{{", "}}"))
defaultConf :: MustacheConf
defaultConf = MustacheConf ("{{", "}}")


initState :: MustacheConf -> MustacheState
initState (MustacheConf { delimiters }) = emptyState { sDelimiters = delimiters }


setIsBeginning :: Bool -> Parser ()
setIsBeginning b = modifyState (\s -> s { isBeginngingOfLine = b })


-- | The parser monad in use
type Parser = Parsec Text MustacheState


(<<) :: Monad m => m b -> m a -> m b
(<<) = flip (>>)


endOfLine :: Parser String
endOfLine = do
  r <- optionMaybe $ char '\r'
  n <- char '\n'
  return $ maybe id (:) r [n]


{-|
  Runs the parser for a mustache template, returning the syntax tree.
-}
parse :: FilePath -> Text -> Either ParseError STree
parse = parseWithConf defaultConf


-- | Parse using a custom initial configuration
parseWithConf :: MustacheConf -> FilePath -> Text -> Either ParseError STree
parseWithConf = P.runParser parseText . initState


parseText :: Parser STree
parseText = do
  (MustacheState { isBeginngingOfLine }) <- getState
  if isBeginngingOfLine
    then parseLine
    else continueLine


appendStringStack :: String -> Parser ()
appendStringStack t = modifyState (\s -> s { textStack = textStack s <> pack t})


continueLine :: Parser STree
continueLine = do
  (MustacheState { sDelimiters = ( start@(x:_), _ )}) <- getState
  let forbidden = x : "\n\r"

  many (noneOf forbidden) >>= appendStringStack

  (try endOfLine >>= appendStringStack >> setIsBeginning True >> parseLine)
    <|> (try (string start) >> switchOnTag >>= continueFromTag)
    <|> (try eof >> finishFile)
    <|> (anyChar >>= appendStringStack . (:[]) >> continueLine)


flushText :: Parser STree
flushText = do
  s@(MustacheState { textStack = text }) <- getState
  putState $ s { textStack = mempty }
  return $ if T.null text
              then []
              else [TextBlock text]


finishFile :: Parser STree
finishFile =
  getState >>= \case
    (MustacheState {currentSectionName = Nothing}) -> flushText
    (MustacheState {currentSectionName = Just name}) ->
      parserFail $ "Unclosed section " <> show name


parseLine :: Parser STree
parseLine = do
  (MustacheState { sDelimiters = ( start, _ ) }) <- getState
  initialWhitespace <- many (oneOf " \t")
  let handleStandalone = do
        tag <- switchOnTag
        let continueNoStandalone = do
              appendStringStack initialWhitespace
              setIsBeginning False
              continueFromTag tag
            standaloneEnding = do
              try (skipMany (oneOf " \t") >> (eof <|> void endOfLine))
              setIsBeginning True
        case tag of
          Tag (Partial _ name) ->
            ( standaloneEnding >>
              continueFromTag (Tag (Partial (Just (pack initialWhitespace)) name))
            ) <|> continueNoStandalone
          Tag _ -> continueNoStandalone
          _     ->
            ( standaloneEnding >>
              continueFromTag tag
            ) <|> continueNoStandalone
  (try (string start) >> handleStandalone)
    <|> (try eof >> appendStringStack initialWhitespace >> finishFile)
    <|> (appendStringStack initialWhitespace >> setIsBeginning False >> continueLine)


continueFromTag :: ParseTagRes -> Parser STree
continueFromTag (SectionBegin start name) = do
  textNodes <- flushText
  state@(MustacheState
    { currentSectionName = previousSection }) <- getState
  putState $ state { currentSectionName = return name }
  innerSectionContent <- parseText
  let sectionTag = case start of
                     Normal -> Section
                     Inverted -> InvertedSection
                     Existing -> ExistingSection
  modifyState $ \s -> s { currentSectionName = previousSection }
  outerSectionContent <- parseText
  return (textNodes <> [sectionTag name innerSectionContent] <> outerSectionContent)
continueFromTag (SectionEnd name) = do
  (MustacheState
    { currentSectionName }) <- getState
  case currentSectionName of
    Just name' | name' == name -> flushText
    Just name' -> parserFail $ "Expected closing sequence for \"" <> show name <> "\" got \"" <> show name' <> "\"."
    Nothing -> parserFail $ "Encountered closing sequence for \"" <> show name <> "\" which has never been opened."
continueFromTag (Tag tag) = do
  textNodes    <- flushText
  furtherNodes <- parseText
  return $ textNodes <> return tag <> furtherNodes
continueFromTag HandledTag = parseText


switchOnTag :: Parser ParseTagRes
switchOnTag = do
  (MustacheState { sDelimiters = ( _, end )}) <- getState

  choice
    [ SectionBegin Normal <$> (try (char sectionBegin) >> genParseTagEnd mempty)
    , SectionEnd
        <$> (try (char sectionEnd) >> genParseTagEnd mempty)
    , Tag . Variable False
        <$> (try (char unescape1) >> genParseTagEnd mempty)
    , Tag . Variable False
        <$> (try (char (fst unescape2)) >> genParseTagEnd (return $ snd unescape2))
    , Tag . Partial Nothing
        <$> (try (char partialBegin) >> spaces >> (noneOf (nub end) `manyTill` try (spaces >> string end)))
    , return HandledTag
        << (try (char delimiterChange) >> parseDelimChange)
    , SectionBegin Existing
        <$> (try (char existingSectionBegin) >> genParseTagEnd mempty >>= \case
              n@(NamedData _) -> return n
              _ -> parserFail "Existing Sections can not be implicit."
            )
    , SectionBegin Inverted
        <$> (try (char invertedSectionBegin) >> genParseTagEnd mempty >>= \case
              n@(NamedData _) -> return n
              _ -> parserFail "Inverted Sections can not be implicit."
            )
    , return HandledTag << (try (char comment) >> manyTill anyChar (try $ string end))
    , Tag . Variable True
        <$> genParseTagEnd mempty
    ]
  where
    parseDelimChange = do
      (MustacheState { sDelimiters = ( _, end )}) <- getState
      spaces
      delim1 <- allowedDelimiterCharacter `manyTill` space
      spaces
      delim2 <- allowedDelimiterCharacter `manyTill` try (spaces >> string (delimiterChange : end))
      when (delim1 == mempty || delim2 == mempty)
        $ parserFail "Tags must contain more than 0 characters"
      oldState <- getState
      putState $ oldState { sDelimiters = (delim1, delim2) }


genParseTagEnd :: String -> Parser DataIdentifier
genParseTagEnd emod = do
  (MustacheState { sDelimiters = ( start, end ) }) <- getState

  let nEnd = emod <> end
      disallowed = nub $ nestingSeparator : start <> end

      parseOne :: Parser [Text]
      parseOne = do

        one <- noneOf disallowed
          `manyTill` lookAhead
            (try (spaces >> void (string nEnd))
            <|> try (void $ char nestingSeparator))

        others <- (char nestingSeparator >> parseOne)
                  <|> (const mempty <$> (spaces >> string nEnd))
        return $ pack one : others
  spaces
  (try (char implicitIterator) >> spaces >> string nEnd >> return Implicit)
    <|> (NamedData <$> parseOne)