Search code examples
haskelltypesmetaprogrammingtype-systems

Typechecking inside quasi-quotes in Template Haskell


I'm trying to become familiar with Template Haskell, and to my surprise the code below compiles under ghc (version 6.10.4).


    main = do
       let
           y = [| "hello" + 1 |]
       putStr ""

This suggest to me that there's no typechecking inside quasi-quotes. This is not what I'd have expected after reading the original paper on Template Haskell. Moreover the following program does not compile.


    main = do
       let
          y = [| "hello" && True |]
       putStr ""

What's going on here?


Solution

  • It looks like GHC does type check all quotations but assumes that all generated instance constraints can be satisfied.

    In this code:

    main = do
       let
           y = [| "hello" + 1 |]
       putStr ""
    

    The y bracket is typeable under the assumption that we have a Num String instance. Since GHC can't say for sure that you won't introduce such an instance before y is spliced in, it doesn't give a type error.

    In this code:

     main = do
       let
          y = [| "hello" && True |]
       putStr ""
    

    There is no way that y can ever be spliced in successfully, no matter what instance environment you set up.

    This is just one example of how Template Haskell's typechecking mechanism is too lenient -- further examples are discussed in Simon PJ's blog post at http://hackage.haskell.org/trac/ghc/blog/Template%20Haskell%20Proposal, where he proposes a change to not type check any quotations at all.