Search code examples
haskellpreprocessorcaballiterate-programming

Conditional Compilation inside Literate Haskell


I have a literate haskell file and want to use conditional compilation. I use the bird style of literate programming. The following code does not work.

> #if MIN_VERSION_base(4,6,0)
> import Control.Exception
> #endif

I need a solution for cabal 1.14.0

EDIT:

cpphs has an option --unlit which unlits literate sourcecode, but I don't know how to pass this option to cpphs in cabal.


Solution

  • As @kosmikus points out, you can simply put the C preprocessor directives outside any > or \begin{code} and they will work as expected – if they do not interfere with your processing of the non-code parts of your literal code.

    You simply cannot use C preprocessor directives with bird-style literate programming, as the unlitting step replaces the > with a space, so you have no chance to get the # into the first column. You can verify this by passing -keep-tmp-files to GHC and checkout the generated .lpp file.

    You can resort to \begin{code}...\end{code} blocks to get both, but if you mix them them with >-style lines of code, keep the extra space in mind and add it to your lines wrapped in \begin{code}...\end{code}:

    > {-# LANGUAGE CPP #-}
    
    A literal comment
    
    \begin{code}
    #if MIN_VERSION_base(4,6,0)
      import Control.Exception
    #endif
    \end{code}
    
    > main = return ()