Parsing a Haskell source file without an explicit 'module M where' header with GHC 7
The guys at the Budapest Functional Programming meetup group finally convinced me to port Tandoori to GHC 7. Things are turning 开发者_StackOverflow中文版out OK, but I'm having a problem parsing .hs
source files with no module M where
header.
Here's a standalone version of the code that calls GHC's internal parser to parse source files:
module Main where
import SrcLoc
import FastString
import Outputable (showSDoc)
import Parser (parseModule)
import Lexer (unP, mkPState, ParseResult(..))
import StringBuffer (hGetStringBuffer)
import DynFlags (defaultDynFlags)
import System.Environment (getArgs)
parseMod src_filename = do
buf <- hGetStringBuffer src_filename
let loc = mkSrcLoc (mkFastString src_filename) 1 0
dflags = defaultDynFlags
case unP Parser.parseModule (mkPState dflags buf loc) of
POk pst rdr_module -> return rdr_module
PFailed srcspan message -> error $ showSDoc message
main = do
args <- getArgs
case args of
[src_filename] -> parseMod src_filename
_ -> error "Usage: parse-test filename.hs"
here's an input file that works:
foo = 1
here's another one that works:
module M where
foo = 1
bar = 2
and here's one that doesn't:
foo = 1
bar = 2
For this one, the output of the program above is:
*** Exception: parse error on input `='
Note that I'm using GHC's parser instead of something like haskell-src
because the real code also uses the renamer from GHC.
We simply prepend a module header line to the source we want to get parsed by the parser of GHC. Would this help you?
精彩评论