15

Quasiquotation as described in haskellwiki is shown mostly as useful tool for embedding other languages inside Haskell without messing around with string quotation.

Question is: For Haskell itself, how easy it would be to put existing Haskell code through a quasiquoter for the purpose of just replacing tokens and passing the result over to ghc? Perhaps Template Haskell is key here?

I have looked for code examples and didn't find any. Some EDSLs can benefit from this ability by reducing the size of their combinating operators (e.g. turn 'a .|. b .>>. c' to '[myedsl|a | b >> c]').

Chris Kuklewicz
  • 8,123
  • 22
  • 33
Dan Aloni
  • 3,968
  • 22
  • 30
  • 1
    You might want to look at `haskell-src-exts` which will parse Haskell and give you the AST, which you can then mess with. – luqui Aug 22 '12 at 16:58
  • Template Haskell essentially is nothing more than a quasiquoter for Haskell. – John L Mar 02 '13 at 07:15

1 Answers1

18

You can build quasi-quoters that manipulate Haskell code by, for example, using the haskell-src-meta package. It parses valid Haskell code into an AST, which you can then modify.

In this case, the easiest way to modify the AST is by using Data.Generics to apply a generic transformation to the whole AST that replaces operators with other operators.

We'll begin by building the transformation function for generic Haskell expressions. The data type that represents an expression is Exp in the template-haskell package.

For example, to convert the operator >> to .>>. we'd use a function like

import Language.Haskell.TH (Exp(..), mkName)

replaceOp :: Exp -> Exp
replaceOp (VarE n) | n == mkName ">>" = VarE (mkName ".>>.")
replaceOp e = e

This changes a variable expression (VarE), but cannot do anything to any other kind of expressions.

Now, to walk the whole AST and to replace all occurrences of >> we'll use the functions everywhere and mkT from Data.Generic.

import Data.Generics (everywhere, mkT)

replaceEveryOp :: Exp -> Exp
replaceEveryOp = everywhere (mkT replaceOp) 

In order to make several replacements, we can alter the function so that it takes an association list of any operator to replace.

type Replacements = [(String, String)]

replaceOps :: Replacements -> Exp -> Exp
replaceOps reps = everywhere (mkT f) where
    f e@(VarE n) = case rep of
        Just n' -> VarE (mkName n')
        _ -> e
        where rep = lookup (show n) reps
    f e = e

And by the way, this is a good example of a function that is much nicer to write by using the view patterns language extension.

{-# LANGUAGE ViewPatterns #-}

replaceOps :: Replacements -> Exp -> Exp
replaceOps reps = everywhere (mkT f) where
    f (VarE (replace -> Just n')) = VarE (mkName n')
    f e = e

    replace n = lookup (show n) reps

Now all that's left for us to do is to build the "myedsl" quasi-quoter.

{-# LANGUAGE ViewPatterns #-}

import Data.Generics (everywhere, mkT)
import Language.Haskell.Meta.Parse (parseExp)
import Language.Haskell.TH (Exp(..), mkName, ExpQ)
import Language.Haskell.TH.Quote (QuasiQuoter(..))

type Replacements = [(String, String)]

replacements :: Replacements
replacements =
    [ ("||", ".|.")
    , (">>", ".>>.")
    ]

myedls = QuasiQuoter
    { quoteExp  = replaceOpsQ
    , quotePat  = undefined
    , quoteType = undefined
    , quoteDec  = undefined
    }

replaceOpsQ :: String -> ExpQ
replaceOpsQ s = case parseExp s of
    Right e -> return $ replaceOps replacements e
    Left err -> fail err

replaceOps :: Replacements -> Exp -> Exp
replaceOps reps = everywhere (mkT f) where
    f (VarE (replace -> Just n')) = VarE (mkName n')
    f e = e

    replace n = lookup (show n) reps

If you save the above to its own module (e.g. MyEDSL.hs), then you can import it and use the quasi-quoter.

{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE QuasiQuotes #-}

import MyEDSL

foo = [myedsl| a || b >> c |]

Note that I've used || instead of | because the latter is not a valid operator in Haskell (since it's the syntactic element used for pattern guards).

dflemstr
  • 25,947
  • 5
  • 70
  • 105
shang
  • 24,642
  • 3
  • 58
  • 86
  • Really clever use of `everywhere` there, I deleted my answer because I didn't use that function. – dflemstr Aug 22 '12 at 17:30
  • Your code would fail, however, if the transformed functions are qualified (e.g. `foo = [myedsl| a MyEDSL.|| b MyEDSL.>> c |]`), and even if you replace operator names by suffixing, things can get ambiguous if there's an operator `MyEDSL.|.|.||` which would be replaced with `MyEDSL.|.|..||.`. For an universal solution, `nameBase` and `nameModule` should be used instead of `show`. See [my attempt](http://hpaste.org/73537) for an example. – dflemstr Aug 22 '12 at 17:41
  • Nice! BTW, what if the infix values of the replacement operators are different than of the original operators? Does the result of parseExp already takes infix into account? – Dan Aloni Aug 22 '12 at 20:37