haskellcommentstemplate-haskellgenerated-code

Is it possible to generate comments to functions in Template Haskell?


In our project we have a lot of TH-generated functions. It'd make sense to add generic comments to them so that they are visible in Haddock/Hoogle. At the very least, something like "This has been generated by TH." Is something like that possible?


Solution

  • Yes it is.

    Here is a basic example that declares a copy of some function, adds hello_ in front of its name, and adds Hello ! in front of its documentation.

    {-# LANGUAGE TemplateHaskell #-}
    
    module MyTH where
    
    import Language.Haskell.TH
    import Language.Haskell.TH.Syntax
    
    helloCopy :: Name -> Q [Dec]
    helloCopy name = do
      doc  <- getDoc (DeclDoc name)
      let helloName = mkName ("hello_" ++ nameBase name)
      let helloDoc = case doc of
            Nothing -> "Hello !"
            Just old -> "Hello !" ++ old
      addModFinalizer $ putDoc (DeclDoc helloName) helloDoc
      [d| $(varP helloName)= $(varE name) |]
    
    module MyModule where
    
    import MyTH
    
    -- | Interesting stuff about blub
    blub :: Int
    blub = 4
    
    $(helloCopy 'blub)
    

    Now if you run haddock you will get a documentation for hello_blub that says "Hello ! Interesting stuff about blub"