Home > database >  Conditional compilation in Haskell other than using CPP
Conditional compilation in Haskell other than using CPP

Time:12-16

The CPP extensions allows conditional compilation, e.g.

{-# LANGUAGE CPP #-}
#ifdef DEBUG
-- some debug code
#endif

It works fine, of course, but it's quite clumsy and non-idiomatic. Is there really no other mechanism to achieve conditional compilation?

(The specific case where I really would like to use it is the Text.Megaparsec.Debug.dbg function. The parse trail it produces is really useful, but the source code gets littered with #ifdef...#endif noise which makes it all rather unreadable. A wrapper function at the top would remove most of the noise, but I'm wondering nonetheless.)

CodePudding user response:

A lightweight solution is to only use CPP once to define a boolean which can then be used in regular Haskell code:

#ifdef DEBUG
#define debug True
#else
#define debug False
#fi

or a macro if you don't even want the debug code to go through typechecking.


Another way to do conditional compilation without CPP is to change the source of modules at the package level, though I don't know any real example of this.

Create two modules with the same name debug/Debug.hs and nodebug/Debug.hs, both exporting, for example, a boolean debug :: Bool.

In the package configuration, add a flag to select between debug/ and nodebug/.

flag debug
  description: debug mode
  default: False
  manual: True

library
  ...
  if flag(debug)
    hs-source-dirs: debug
  else
    hs-source-dirs: nodebug

Now you can build the library with -f debug to enable debugging.

  • Related