packages feed

marvin-interpolate (empty) → 0.0.1

raw patch · 11 files changed

+446/−0 lines, 11 filesdep +basedep +haskell-src-metadep +hspecsetup-changed

Dependencies added: base, haskell-src-meta, hspec, marvin-interpolate, mtl, parsec, template-haskell, text

Files

+ LICENSE view
@@ -0,0 +1,30 @@+Copyright JustusAdam (c) 2016++All rights reserved.++Redistribution and use in source and binary forms, with or without+modification, are permitted provided that the following conditions are met:++    * Redistributions of source code must retain the above copyright+      notice, this list of conditions and the following disclaimer.++    * Redistributions in binary form must reproduce the above+      copyright notice, this list of conditions and the following+      disclaimer in the documentation and/or other materials provided+      with the distribution.++    * Neither the name of JustusAdam nor the names of other+      contributors may be used to endorse or promote products derived+      from this software without specific prior written permission.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ README.md view
@@ -0,0 +1,83 @@+# Simple string interpolation++[![Travis](https://travis-ci.org/JustusAdam/marvin-interpolate.svg?branch=master)](https://travis-ci.org/JustusAdam/marvin-interpolate)+[![Hackage](https://img.shields.io/hackage/v/marvin-interpolate.svg)](http://hackage.haskell.org/package/marvin-interpolate)++This string interpolation library originates from the [Marvin project](https://github.com/JustusAdam/marvin) where, in an attempt to make it easy for the user to write text with some generated data in it, I developed this string interpolation library.+The design is very similar to the string interpolation in Scala and CoffeeScript, in that the hard work happens at compile time (no parsing overhead at runtime) and any valid Haskell expression can be interpolated.++The library uses the builtin Haskell compiler extension in the form of *QuasiQuoters* ([`QuasiQuotes`](https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/glasgow_exts.html#template-haskell-quasi-quotation) language extension).++```haskell+{-# LANGUAGE QuasiQuotes #-}++import Marvin.Interpolate++myStr = [i|some string %{show $ map succ [1,2,3]} and data |]+-- "some string [2,3,4] and data"+```++It basically transforms the interpolated string, which is anything between `[i|` and `|]` into a concatenation of all string bits and the expressions in `%{}`.+Therefore it is not limited to `String` alone, rather it produces a literal at compile time, which can either be interpreted as `String` or, using the [`OverloadedStrings`](https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/glasgow_exts.html#overloaded-string-literals) extension, as `Text` or `ByteString` or any other string type.++`i` is the basic interpolator, which inserts the expressions verbatim. Hence when using `i` all expressions must return the desired string type.++There are specialized interpolators, which also perform automatic conversion of non-string types into the desired string type.+These specialized interpolators each have an associated typeclass, which converts string types (`String`, `Text` and lazy `Text`) to the target type, but leaves the contents unchanged and calls `show` on all other types before converting.+This last instance, which is based on `Show`, can be overlapped by specifying a custom instance for your type, allowing the user to define the conversion.++- `iS` in `Marvin.Interpolate.String` converts to `String` via the `ShowS` typeclass+- `iT` in `Marvin.Interpolate.Text` converts to `Text` via the `ShowT` typeclass+- `iLT` in `Marvin.Interpolate.Text.Lazy` converts to lazy `Text` via the `ShowLT` typeclass++To import all interpolators, import `Marvin.Interpolate.All`.++## Syntax++Interpolation uses the quasi quoter sytax, which starts with `[interpolator_name|` and ends with `|]`.+Anything in between is interpreted by the library.++The format string in between uses the syntax `%{expression}`.+Any valid Haskell expression can be used inside the braces.+And all names which are in scope can be used, like so.++```haskell+let x = 5 in [iS|x equals %{x}|] -- > "x equals 5"+```++There are three escape sequences to allow literal `%{` and `|]`++| Input | Output |+|-------|--------|+| `\]`  | `]`    |+| `\\`  | `\\`   |+| `\%`  | `%` (only outside `%{}`) |+| `\}`  | `}` (only inside `%{}`) | +++As a result the sequence `\%{` will show up as a literal `%{` in the output and `|\]` results in a literal `|]`.+++## Differences to/Advantages over other libraries++There are a few advantages this libary has over other string formatting options.++1. **The hard work happens at compile time**++    Unlike libraries like [text-format](https://hackage.haskell.org/package/text-format) and the [`Text.Printf`](https://www.stackage.org/haddock/lts-7.14/base-4.9.0.0/Text-Printf.html) module parsing the format string, producing the string fragments and interleaving data and strings happens all at compile time.+    At runtime a single fusable string concatenation expression is produced.  +    Furthermore all errors, like missing identifiers happen at compile time, not at runtime.++2. **Type Polymorphism**+    +    The created, interpolated string has no type. +    It can be interpreted as any string type, so long as there is an [`IsString`](https://www.stackage.org/haddock/lts-7.14/base-4.9.0.0/Data-String.html#t:IsString) instance and the expressions inside return the appropriate type.++    This is different format string libraries like [text-format](https://hackage.haskell.org/package/text-format) and the [`Text.Printf`](https://www.stackage.org/haddock/lts-7.14/base-4.9.0.0/Text-Printf.html) module which always produce strings of a particular type, and interpolation libraries like [interpolate](http://hackage.haskell.org/package/interpolate) and [interpol](http://hackage.haskell.org/package/interpol) which require instances of `Show`.++3. **Simple API and full Haskell support**++    The interpolated expressions are just plain Haskell expressions, no extra syntax, beyond the interpolation braces `%{}`.+    Also all Haskell expressions, including infix expressions, are fully supported.++    This is different from [Interpolation](http://hackage.haskell.org/package/Interpolation) which introduces additional syntax and does not fully support infix expressions.
+ Setup.hs view
@@ -0,0 +1,2 @@+import           Distribution.Simple+main = defaultMain
+ marvin-interpolate.cabal view
@@ -0,0 +1,50 @@+name: marvin-interpolate+version: 0.0.1+cabal-version: >=1.10+build-type: Simple+license: BSD3+license-file: LICENSE+copyright: Copyright: (c) 2016 Justus Adam+maintainer: dev@justus.science+homepage: http://marvin.readthedocs.io/en/latest/interpolation.html+synopsis: Compile time string interpolation a la Scala and CoffeeScript+description:+    The official documentation can be found on readthedocs http://marvin.readthedocs.io/en/latest/interpolation.html.+category: Text+author: JustusAdam+extra-source-files:+    README.md++source-repository head+    type: git+    location: https://github.com/JustusAdam/marvin-interpolate++library+    exposed-modules:+        Marvin.Interpolate+        Marvin.Interpolate.String+        Marvin.Interpolate.Text+        Marvin.Interpolate.All+        Marvin.Interpolate.Text.Lazy+    build-depends:+        base >=4.7 && <5,+        parsec >=3.1.11 && <3.2,+        template-haskell >=2.11.0.0 && <2.12,+        haskell-src-meta >=0.6.0.14 && <0.7,+        text >=1.2.2.1 && <1.3,+        mtl >=2.2.1 && <2.3+    default-language: Haskell2010+    hs-source-dirs: src+    other-modules:+        Util++test-suite marvin-interpolate-test+    type: exitcode-stdio-1.0+    main-is: Spec.hs+    build-depends:+        base >=4.9.0.0 && <4.10,+        marvin-interpolate >=0.0.1 && <0.1,+        hspec >=2.2.4 && <2.3+    default-language: Haskell2010+    hs-source-dirs: test+    ghc-options: -threaded -rtsopts -with-rtsopts=-N
+ src/Marvin/Interpolate.hs view
@@ -0,0 +1,91 @@+{-# LANGUAGE MultiWayIf      #-}+{-# LANGUAGE TemplateHaskell #-}+module Marvin.Interpolate+  ( interpolateInto+  , i+  ) where+++import           Control.Monad+import           Control.Monad.State                 as S+import           Data.Either+import           Data.List                           (intercalate)+import           Data.Monoid+import           Language.Haskell.Meta.Parse.Careful+import           Language.Haskell.TH+import           Language.Haskell.TH.Quote+import           Text.Parsec+import           Util+++type Parsed = [Either String String]+++parser :: Parsec String () Parsed+parser = manyTill (parseInterpolation <|> parseString) eof++parseString :: Parsec String () (Either String String)+parseString = Right <$> parseTillEscape '%' True++parseInterpolation :: Parsec String () (Either String String)+parseInterpolation = Left <$> between (string "%{") (char '}') (parseTillEscape '}' False)++parseTillEscape :: Char -> Bool -> Parsec String () String+parseTillEscape endChar allowEOF = do+    chunk <- many $ noneOf ['\\', endChar]+    rest <- eofEND <|> (lookAhead (try anyChar) >>= restEND)+    return $ chunk <> rest+  where+    eofEND+        | allowEOF = eof >> return ""+        | otherwise = fail "EOF not allowed in interpolation"++    restEND c+        | c == '\\' = parseEscaped+        | c == endChar = return ""++    parseEscaped = do+        char '\\'+        next <- anyChar+        let escaped+                | next == '\\' = "\\"+                | next == ']' = "]"+                | next == endChar = [endChar]+                | otherwise = "\\" ++ [next]+        rest <- parseTillEscape endChar allowEOF+        return $ escaped <> rest+++evalExprs :: Parsed -> [Either Exp String]+evalExprs l = evalState (mapM stitch l) decls+  where+    strDecls = lefts l+    decls = case partitionEithers $ map parseExp strDecls of+                ([], d) -> d+                (errs, _) -> error $ intercalate "\n" errs++    stitch :: Either a b -> S.State [c] (Either c b)+    stitch (Right str) = return $ Right str+    stitch (Left _) = do+        (name:rest) <- get+        put rest+        return $ Left name+++interpolateInto :: Exp -> String -> Exp+interpolateInto converter str =+    foldl f (LitE (StringL "")) interleaved++  where+    parsed = either (error . show) id $ parse parser "inline" str+    interleaved = evalExprs parsed++    f expr bit = AppE (VarE 'mappend) expr `AppE` bitExpr+      where+        bitExpr = case bit of+                      Right str -> LitE (StringL str)+                      Left expr2 -> AppE converter expr2+++i :: QuasiQuoter+i = mqq { quoteExp = return . interpolateInto (VarE 'id) }
+ src/Marvin/Interpolate/All.hs view
@@ -0,0 +1,12 @@+module Marvin.Interpolate.All+    ( module Marvin.Interpolate+    , module Marvin.Interpolate.String+    , module Marvin.Interpolate.Text+    , module Marvin.Interpolate.Text.Lazy+    ) where+++import           Marvin.Interpolate+import           Marvin.Interpolate.String+import           Marvin.Interpolate.Text+import           Marvin.Interpolate.Text.Lazy
+ src/Marvin/Interpolate/String.hs view
@@ -0,0 +1,38 @@+{-# LANGUAGE FlexibleInstances    #-}+{-# LANGUAGE OverloadedStrings    #-}+{-# LANGUAGE TemplateHaskell      #-}+{-# LANGUAGE UndecidableInstances #-}+module Marvin.Interpolate.String where+++import           Data.List+import           Data.Monoid+import qualified Data.Text                 as T+import qualified Data.Text.Lazy            as L+import           Language.Haskell.TH+import           Language.Haskell.TH.Quote+import           Marvin.Interpolate+import           Util+++class ShowStr a where+    showStr :: a -> String+    showListStr :: [a] -> String+    showListStr l = "[" <> intercalate ", " (map showStr l) <> "]"++instance ShowStr Char where+    showStr = show+    showListStr = id++instance ShowStr T.Text where+    showStr = T.unpack++instance ShowStr L.Text where+    showStr = L.unpack++instance {-# OVERLAPPABLE #-} Show a => ShowStr a where+    showStr = show+++iS :: QuasiQuoter+iS = mqq { quoteExp = return . interpolateInto (VarE 'show) }
+ src/Marvin/Interpolate/Text.hs view
@@ -0,0 +1,37 @@+{-# LANGUAGE FlexibleInstances    #-}+{-# LANGUAGE OverloadedStrings    #-}+{-# LANGUAGE TemplateHaskell      #-}+{-# LANGUAGE UndecidableInstances #-}+module Marvin.Interpolate.Text where+++import           Data.Monoid+import           Data.Text                 hiding (map)+import qualified Data.Text.Lazy            as L+import           Language.Haskell.TH+import           Language.Haskell.TH.Quote+import           Marvin.Interpolate+import           Util+++class ShowT a where+    showT :: a -> Text+    showListT :: [a] -> Text+    showListT l = "[" <> intercalate ", " (map showT l) <> "]"++instance ShowT Text where+    showT = id++instance ShowT L.Text where+    showT = L.toStrict++instance ShowT Char where+    showT = pack . show+    showListT = pack++instance {-# OVERLAPPABLE #-} Show a => ShowT a where+    showT = pack . show+++iT :: QuasiQuoter+iT = mqq { quoteExp = return . interpolateInto (VarE 'showT) }
+ src/Marvin/Interpolate/Text/Lazy.hs view
@@ -0,0 +1,37 @@+{-# LANGUAGE FlexibleInstances    #-}+{-# LANGUAGE OverloadedStrings    #-}+{-# LANGUAGE TemplateHaskell      #-}+{-# LANGUAGE UndecidableInstances #-}+module Marvin.Interpolate.Text.Lazy where+++import           Data.Monoid+import qualified Data.Text                 as T+import qualified Data.Text.Lazy            as L+import           Language.Haskell.TH+import           Language.Haskell.TH.Quote+import           Marvin.Interpolate+import           Util+++class ShowLT a where+    showLT :: a -> L.Text+    showListLT :: [a] -> L.Text+    showListLT l = "[" <> L.intercalate ", " (map showLT l) <> "]"++instance ShowLT L.Text where+    showLT = id++instance ShowLT T.Text where+    showLT = L.fromStrict++instance ShowLT Char where+    showLT = L.pack . show+    showListLT = L.pack++instance {-# OVERLAPPABLE #-} Show a => ShowLT a where+    showLT = L.pack . show+++iLT :: QuasiQuoter+iLT = mqq { quoteExp = return . interpolateInto (VarE 'showLT) }
+ src/Util.hs view
@@ -0,0 +1,13 @@+module Util where+++import           Language.Haskell.TH.Quote+++mqq :: QuasiQuoter+mqq = QuasiQuoter+    { quotePat = error "Interpolation cannot occur in pattern"+    , quoteType = error "Interpolation cannot occur in type"+    , quoteDec = error "Interpolation cannot occur in declaration"+    , quoteExp = error "Interpolation not defined, please contact library author :D"+    }
+ test/Spec.hs view
@@ -0,0 +1,53 @@+{-# LANGUAGE QuasiQuotes #-}+++import           Data.List              (intercalate)+import           Marvin.Interpolate.All+import           Test.Hspec+++formatSpec :: Spec+formatSpec = do+    describe "escape sequences" $ do+        it "parses \\\\ as \\" $+            [i|\\|] `shouldBe` "\\"+        it "parses \\% as %" $+            [i|\%|] `shouldBe` "%"+        it "parses \\] as ]" $+            [i|\]|] `shouldBe` "]"+        it "parses \\%{} as %{}" $+            [i|\%{}|] `shouldBe` "%{}"+        it "parses |\\] as |]" $+            [i||\]|] `shouldBe` "|]"++    describe "interpolation substitution" $ do+        it "leaves an empty string" $+            [i||] `shouldBe` ""+        it "returns a string unchanged if no variable is in it" $+            [i|this is not changed|] `shouldBe` "this is not changed"+        it "interpolates just an external variable" $+            let y = "str" in+                [i|%{y}|] `shouldBe` y+        it "interpolates an external variable" $+            let y = "str2" in [i| hello you %{y} end|] `shouldBe` " hello you " ++ y ++ " end"+        it "interpolates the variable x (used to be special)" $+            let x = "str" in [i| hello x: %{x}|] `shouldBe` " hello x: " ++ x+        it "interpolates infix with $" $+            [i|str %{show $ 4 + (5 :: Int)} str|] `shouldBe` "str 9 str"+        it "interpolates multiple bindings" $+            let+                x = "multiple"+                y = "can"+                z = "local scope"+            in [i|We %{y} interpolate %{x} bindings from %{z}|]+                `shouldBe` "We can interpolate multiple bindings from local scope"++        it "interpolates complex expressions" $+            let+                x = ["haskell", "expression"]+                y = " can be"+            in [i|Any %{intercalate " " x ++ y} interpolated|]+                 `shouldBe` "Any haskell expression can be interpolated"++main :: IO ()+main = hspec formatSpec