1 -----------------------------------------------------------------------------
3 -- Parsing the top of a Haskell source file to get its module name,
4 -- imports and options.
6 -- (c) Simon Marlow 2005
9 -----------------------------------------------------------------------------
11 module HeaderInfo ( getImportsFromFile, getImports
12 , getOptionsFromFile, getOptions
13 , optionsErrorMsgs ) where
15 #include "HsVersions.h"
17 import Parser ( parseHeader )
20 import HsSyn ( ImportDecl(..), HsModule(..) )
21 import Module ( ModuleName, moduleName )
22 import PrelNames ( gHC_PRIM, mAIN_NAME )
23 import StringBuffer ( StringBuffer(..), hGetStringBuffer, hGetStringBufferBlock
24 , appendStringBuffers )
34 import Bag ( emptyBag, listToBag )
36 import Control.Exception
42 #if __GLASGOW_HASKELL__ >= 601
43 import System.IO ( openBinaryFile )
45 import IOExts ( openFileEx, IOModeEx(..) )
48 #if __GLASGOW_HASKELL__ < 601
49 openBinaryFile fp mode = openFileEx fp (BinaryMode mode)
52 -- getImportsFromFile is careful to close the file afterwards, otherwise
53 -- we can end up with a large number of open handles before the garbage
54 -- collector gets around to closing them.
55 getImportsFromFile :: DynFlags -> FilePath
56 -> IO ([Located ModuleName], [Located ModuleName], Located ModuleName)
57 getImportsFromFile dflags filename = do
58 buf <- hGetStringBuffer filename
59 getImports dflags buf filename
61 getImports :: DynFlags -> StringBuffer -> FilePath
62 -> IO ([Located ModuleName], [Located ModuleName], Located ModuleName)
63 getImports dflags buf filename = do
64 let loc = mkSrcLoc (mkFastString filename) 1 0
65 case unP parseHeader (mkPState buf loc dflags) of
66 PFailed span err -> parseError span err
67 POk pst rdr_module -> do
68 let ms = getMessages pst
69 printErrorsAndWarnings dflags ms
70 when (errorsFound dflags ms) $ exitWith (ExitFailure 1)
72 L _ (HsModule mb_mod _ imps _ _ _ _ _) ->
74 mod = mb_mod `orElse` L (srcLocSpan loc) mAIN_NAME
75 (src_idecls, ord_idecls) = partition isSourceIdecl (map unLoc imps)
76 source_imps = map getImpMod src_idecls
77 ordinary_imps = filter ((/= moduleName gHC_PRIM) . unLoc)
78 (map getImpMod ord_idecls)
79 -- GHC.Prim doesn't exist physically, so don't go looking for it.
81 return (source_imps, ordinary_imps, mod)
83 parseError span err = throwDyn $ mkPlainErrMsg span err
85 isSourceIdecl (ImportDecl _ s _ _ _) = s
87 getImpMod (ImportDecl located_mod _ _ _ _) = located_mod
89 --------------------------------------------------------------
91 --------------------------------------------------------------
94 getOptionsFromFile :: FilePath -- input file
95 -> IO [Located String] -- options, if any
96 getOptionsFromFile filename
97 = Control.Exception.bracket
98 (openBinaryFile filename ReadMode)
101 do buf <- hGetStringBufferBlock handle blockSize
103 where blockSize = 1024
105 | len buf == 0 = return []
107 = case getOptions' buf filename of
108 (Nothing, opts) -> return opts
109 (Just buf', opts) -> do nextBlock <- hGetStringBufferBlock handle blockSize
110 newBuf <- appendStringBuffers buf' nextBlock
111 if len newBuf == len buf
113 else do opts' <- loop handle newBuf
116 getOptions :: StringBuffer -> FilePath -> [Located String]
117 getOptions buf filename
118 = case getOptions' buf filename of
121 -- The token parser is written manually because Happy can't
122 -- return a partial result when it encounters a lexer error.
123 -- We want to extract options before the buffer is passed through
124 -- CPP, so we can't use the same trick as 'getImports'.
125 getOptions' :: StringBuffer -- Input buffer
126 -> FilePath -- Source file. Used for msgs only.
127 -> ( Maybe StringBuffer -- Just => we can use more input
128 , [Located String] -- Options.
130 getOptions' buf filename
131 = parseToks (lexAll (pragState buf loc))
132 where loc = mkSrcLoc (mkFastString filename) 1 0
134 getToken (buf,L _loc tok) = tok
135 getLoc (buf,L loc _tok) = loc
136 getBuf (buf,_tok) = buf
137 combine opts (flag, opts') = (flag, opts++opts')
138 add opt (flag, opts) = (flag, opt:opts)
140 parseToks (open:close:xs)
141 | IToptions_prag str <- getToken open
142 , ITclose_prag <- getToken close
143 = map (L (getLoc open)) (words str) `combine`
145 parseToks (open:close:xs)
146 | ITinclude_prag str <- getToken open
147 , ITclose_prag <- getToken close
148 = map (L (getLoc open)) ["-#include",removeSpaces str] `combine`
151 | ITlanguage_prag <- getToken open
153 -- The last token before EOF could have been truncated.
154 -- We ignore it to be on the safe side.
156 | ITeof <- getToken eof
157 = (Just (getBuf tok),[])
159 | ITeof <- getToken eof
160 = (Just (getBuf eof),[])
161 parseToks _ = (Nothing,[])
162 parseLanguage ((_buf,L loc (ITconid fs)):rest)
163 = checkExtension (L loc fs) `add`
165 (_,L loc ITcomma):more -> parseLanguage more
166 (_,L loc ITclose_prag):more -> parseToks more
167 (_,L loc _):_ -> languagePragParseError loc
168 parseLanguage (tok:_)
169 = languagePragParseError (getLoc tok)
170 lexToken t = return t
171 lexAll state = case unP (lexer lexToken) state of
172 POk state' t@(L _ ITeof) -> [(buffer state,t)]
173 POk state' t -> (buffer state,t):lexAll state'
174 _ -> [(buffer state,L (last_loc state) ITeof)]
176 checkExtension :: Located FastString -> Located String
177 checkExtension (L l ext)
178 -- Checks if a given extension is valid, and if so returns
179 -- its corresponding flag. Otherwise it throws an exception.
180 = let ext' = unpackFS ext in
181 if ext' `elem` supportedLanguages
182 || ext' `elem` (map ("No"++) supportedLanguages)
183 then L l ("-X"++ext')
184 else unsupportedExtnError l ext'
186 languagePragParseError loc =
187 pgmError (showSDoc (mkLocMessage loc (
188 text "cannot parse LANGUAGE pragma")))
190 unsupportedExtnError loc unsup =
191 pgmError (showSDoc (mkLocMessage loc (
192 text "unsupported extension: " <>
196 optionsErrorMsgs :: [String] -> [Located String] -> FilePath -> Messages
197 optionsErrorMsgs unhandled_flags flags_lines filename
198 = (emptyBag, listToBag (map mkMsg unhandled_flags_lines))
199 where unhandled_flags_lines = [ L l f | f <- unhandled_flags,
200 L l f' <- flags_lines, f == f' ]
201 mkMsg (L flagSpan flag) =
202 ErrUtils.mkPlainErrMsg flagSpan $
203 text "unknown flag in {-# OPTIONS #-} pragma:" <+> text flag