Pretty-print haskell source code with comments

不羁岁月 提交于 2019-12-21 10:15:05

问题


I'm trying to reformat/reprint haskell source code (remove/add whitespace, linebreaks, change indention style...). I've found the package haskell-src-exts which can parse and pretty-print haskell source code.

Using the function parseFileWithComments :: ParseMode -> FilePath -> IO (ParseResult (Module, [Comment])) I also get the comments included in the source code. Now I want to print the Module/AST with the comments at the original positions, but I cannot find a function which will do that. I can only pretty-print the AST. Do I have to implement printing of the AST plus the comments myself or does such a library already exist?

To clarify consider following example:

file A.hs:

module A (fn1) where

-- | Haddock-comment
fn1 ::
    String ->
    String
fn1 _ = "" -- another comment

In ghci, typing

Prelude Control.Monad.Reader Language.Haskell.Exts> (liftM prettyPrint) $ (liftM fst) $ (liftM fromParseResult) $ parseFileWithComments defaultParseMode "A.hs"`

prints the module source code (without the comments, of course). I can use any prettyPrint-function to modify the source code formatting.

Now I want to be able to do something like this:

do
    (ast, comments) <- fromParseResult $ parseFileWithComments defaultParseMode "A.hs"
    prettyPrintWithComments ast comments

to get a pretty-printed version of the original file including the comments.


回答1:


Use the Annotated versions of the modules, e.g. Language.Haskell.Exts.Annotated vs Language.Haskell.Exts.




回答2:


Depending on what kind of pretty printing do you want to do, you might want to take a look at the hscolour package, which is used to colorize Haskell source code into various output formats.

In particular, the module Language.Haskell.HsColour.Classify contains a Haskell tokenizer which preserves whitespace and comments, which might serve as a good starting point.



来源:https://stackoverflow.com/questions/9392546/pretty-print-haskell-source-code-with-comments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!