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 ( getImports
12 , getOptionsFromFile, getOptions
14 checkProcessArgsResult ) where
16 #include "HsVersions.h"
20 import Parser ( parseHeader )
23 import HsSyn ( ImportDecl(..), HsModule(..) )
24 import Module ( ModuleName, moduleName )
25 import PrelNames ( gHC_PRIM, mAIN_NAME )
26 import StringBuffer ( StringBuffer(..), hGetStringBufferBlock
27 , appendStringBuffers )
35 import Bag ( emptyBag, listToBag, unitBag )
37 import MonadUtils ( MonadIO )
43 ------------------------------------------------------------------------------
45 -- | Parse the imports of a source file.
47 -- Throws a 'SourceError' if parsing fails.
48 getImports :: GhcMonad m =>
50 -> StringBuffer -- ^ Parse this.
51 -> FilePath -- ^ Filename the buffer came from. Used for
52 -- reporting parse error locations.
53 -> FilePath -- ^ The original source filename (used for locations
54 -- in the function result)
55 -> m ([Located (ImportDecl RdrName)], [Located (ImportDecl RdrName)], Located ModuleName)
56 -- ^ The source imports, normal imports, and the module name.
57 getImports dflags buf filename source_filename = do
58 let loc = mkSrcLoc (mkFastString filename) 1 0
59 case unP parseHeader (mkPState buf loc dflags) of
60 PFailed span err -> parseError span err
61 POk pst rdr_module -> do
62 let ms@(warns, errs) = getMessages pst
64 if errorsFound dflags ms
65 then liftIO $ throwIO $ mkSrcErr errs
68 L _ (HsModule mb_mod _ imps _ _ _ _) ->
70 main_loc = mkSrcLoc (mkFastString source_filename) 1 0
71 mod = mb_mod `orElse` L (srcLocSpan main_loc) mAIN_NAME
72 (src_idecls, ord_idecls) = partition (ideclSource.unLoc) imps
73 ordinary_imps = filter ((/= moduleName gHC_PRIM) . unLoc . ideclName . unLoc)
75 -- GHC.Prim doesn't exist physically, so don't go looking for it.
77 return (src_idecls, ordinary_imps, mod)
79 parseError :: GhcMonad m => SrcSpan -> Message -> m a
80 parseError span err = throwOneError $ mkPlainErrMsg span err
82 --------------------------------------------------------------
84 --------------------------------------------------------------
86 -- | Parse OPTIONS and LANGUAGE pragmas of the source file.
88 -- Throws a 'SourceError' if flag parsing fails (including unsupported flags.)
89 getOptionsFromFile :: DynFlags
90 -> FilePath -- ^ Input file
91 -> IO [Located String] -- ^ Parsed options, if any.
92 getOptionsFromFile dflags filename
94 (openBinaryFile filename ReadMode)
97 do buf <- hGetStringBufferBlock handle blockSize
99 where blockSize = 1024
101 | len buf == 0 = return []
103 = case getOptions' dflags buf filename of
104 (Nothing, opts) -> return opts
105 (Just buf', opts) -> do nextBlock <- hGetStringBufferBlock handle blockSize
106 newBuf <- appendStringBuffers buf' nextBlock
107 if len newBuf == len buf
109 else do opts' <- loop handle newBuf
112 -- | Parse OPTIONS and LANGUAGE pragmas of the source file.
114 -- Throws a 'SourceError' if flag parsing fails (including unsupported flags.)
115 getOptions :: DynFlags
116 -> StringBuffer -- ^ Input Buffer
117 -> FilePath -- ^ Source filename. Used for location info.
118 -> [Located String] -- ^ Parsed options.
119 getOptions dflags buf filename
120 = case getOptions' dflags buf filename of
123 -- The token parser is written manually because Happy can't
124 -- return a partial result when it encounters a lexer error.
125 -- We want to extract options before the buffer is passed through
126 -- CPP, so we can't use the same trick as 'getImports'.
127 getOptions' :: DynFlags
128 -> StringBuffer -- Input buffer
129 -> FilePath -- Source file. Used for msgs only.
130 -> ( Maybe StringBuffer -- Just => we can use more input
131 , [Located String] -- Options.
133 getOptions' dflags buf filename
134 = parseToks (lexAll (pragState dflags buf loc))
135 where loc = mkSrcLoc (mkFastString filename) 1 0
137 getToken (_buf,L _loc tok) = tok
138 getLoc (_buf,L loc _tok) = loc
139 getBuf (buf,_tok) = buf
140 combine opts (flag, opts') = (flag, opts++opts')
141 add opt (flag, opts) = (flag, opt:opts)
143 parseToks (open:close:xs)
144 | IToptions_prag str <- getToken open
145 , ITclose_prag <- getToken close
146 = map (L (getLoc open)) (words str) `combine`
148 parseToks (open:close:xs)
149 | ITinclude_prag str <- getToken open
150 , ITclose_prag <- getToken close
151 = map (L (getLoc open)) ["-#include",removeSpaces str] `combine`
153 parseToks (open:close:xs)
154 | ITdocOptions str <- getToken open
155 , ITclose_prag <- getToken close
156 = map (L (getLoc open)) ["-haddock-opts", removeSpaces str]
157 `combine` parseToks xs
159 | ITdocOptionsOld str <- getToken open
160 = map (L (getLoc open)) ["-haddock-opts", removeSpaces str]
161 `combine` parseToks xs
163 | ITlanguage_prag <- getToken open
165 -- The last token before EOF could have been truncated.
166 -- We ignore it to be on the safe side.
168 | ITeof <- getToken eof
169 = (Just (getBuf tok),[])
171 | ITeof <- getToken eof
172 = (Just (getBuf eof),[])
173 parseToks _ = (Nothing,[])
174 parseLanguage ((_buf,L loc (ITconid fs)):rest)
175 = checkExtension (L loc fs) `add`
177 (_,L _loc ITcomma):more -> parseLanguage more
178 (_,L _loc ITclose_prag):more -> parseToks more
179 (_,L loc _):_ -> languagePragParseError loc
180 [] -> panic "getOptions'.parseLanguage(1) went past eof token"
181 parseLanguage (tok:_)
182 = languagePragParseError (getLoc tok)
184 = panic "getOptions'.parseLanguage(2) went past eof token"
185 lexToken t = return t
186 lexAll state = case unP (lexer lexToken) state of
187 POk _ t@(L _ ITeof) -> [(buffer state,t)]
188 POk state' t -> (buffer state,t):lexAll state'
189 _ -> [(buffer state,L (last_loc state) ITeof)]
191 -----------------------------------------------------------------------------
193 -- | Complain about non-dynamic flags in OPTIONS pragmas.
195 -- Throws a 'SourceError' if the input list is non-empty claiming that the
196 -- input flags are unknown.
197 checkProcessArgsResult :: MonadIO m => [Located String] -> m ()
198 checkProcessArgsResult flags
199 = when (notNull flags) $
200 liftIO $ throwIO $ mkSrcErr $ listToBag $ map mkMsg flags
201 where mkMsg (L loc flag)
202 = mkPlainErrMsg loc $
203 (text "unknown flag in {-# OPTIONS #-} pragma:" <+>
206 -----------------------------------------------------------------------------
208 checkExtension :: Located FastString -> Located String
209 checkExtension (L l ext)
210 -- Checks if a given extension is valid, and if so returns
211 -- its corresponding flag. Otherwise it throws an exception.
212 = let ext' = unpackFS ext in
213 if ext' `elem` supportedLanguages
214 || ext' `elem` (map ("No"++) supportedLanguages)
215 then L l ("-X"++ext')
216 else unsupportedExtnError l ext'
218 languagePragParseError :: SrcSpan -> a
219 languagePragParseError loc =
220 throw $ mkSrcErr $ unitBag $
222 text "cannot parse LANGUAGE pragma: comma-separated list expected")
224 unsupportedExtnError :: SrcSpan -> String -> a
225 unsupportedExtnError loc unsup =
226 throw $ mkSrcErr $ unitBag $
228 text "unsupported extension: " <> text unsup
231 optionsErrorMsgs :: [String] -> [Located String] -> FilePath -> Messages
232 optionsErrorMsgs unhandled_flags flags_lines _filename
233 = (emptyBag, listToBag (map mkMsg unhandled_flags_lines))
234 where unhandled_flags_lines = [ L l f | f <- unhandled_flags,
235 L l f' <- flags_lines, f == f' ]
236 mkMsg (L flagSpan flag) =
237 ErrUtils.mkPlainErrMsg flagSpan $
238 text "unknown flag in {-# OPTIONS #-} pragma:" <+> text flag