File: QuoteStr.hs

package info (click to toggle)
haskell-toml-parser 2.0.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 320 kB
  • sloc: haskell: 3,364; yacc: 131; makefile: 3
file content (36 lines) | stat: -rw-r--r-- 1,127 bytes parent folder | download
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
{-|
Module      : QuoteStr
Description : Quasiquoter for multi-line string literals
Copyright   : (c) Eric Mertens, 2023
License     : ISC
Maintainer  : emertens@gmail.com

This module makes it easy to write inline TOML for
test cases without worrying about escaping newlines
or quotation marks.

-}
module QuoteStr (quoteStr) where

import Language.Haskell.TH (Exp(LitE), ExpQ, Lit(StringL))
import Language.Haskell.TH.Quote ( QuasiQuoter(..) )
import Data.List ( stripPrefix )

quoteStr :: QuasiQuoter
quoteStr = QuasiQuoter {
    quoteDec = \_ -> fail "quoteStr doesn't support declarations",
    quotePat = \_ -> fail "quoteStr doesn't support patterns",
    quoteType = \_ -> fail "quoteStr doesn't support types",
    quoteExp = processString
  }

processString :: String -> ExpQ
processString ('\n':xs) =
    let ws = takeWhile (' '==) xs

        cleanup "" = pure ""
        cleanup x = case stripPrefix ws x of
                      Nothing -> fail "bad prefix"
                      Just x' -> pure x'
    in LitE . StringL . unlines <$> traverse cleanup (lines xs)
processString _ = fail "malformed string literal"