1 {-# OPTIONS -fno-warn-incomplete-patterns #-}
2 -- The above warning supression flag is a temporary kludge.
3 -- While working on this module you are encouraged to remove it and fix
4 -- any warnings in the module. See
5 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
8 -----------------------------------------------------------------------------
10 -- Parsing the top of a Haskell source file to get its module name,
11 -- imports and options.
13 -- (c) Simon Marlow 2005
16 -----------------------------------------------------------------------------
18 module HeaderInfo ( getImports
19 , getOptionsFromFile, getOptions
21 checkProcessArgsResult ) where
23 #include "HsVersions.h"
26 import Parser ( parseHeader )
29 import HsSyn ( ImportDecl(..), HsModule(..) )
30 import Module ( ModuleName, moduleName )
31 import PrelNames ( gHC_PRIM, mAIN_NAME )
32 import StringBuffer ( StringBuffer(..), hGetStringBufferBlock
33 , appendStringBuffers )
42 import Bag ( emptyBag, listToBag )
50 getImports :: DynFlags -> StringBuffer -> FilePath -> FilePath
51 -> IO ([Located ModuleName], [Located ModuleName], Located ModuleName)
52 getImports dflags buf filename source_filename = do
53 let loc = mkSrcLoc (mkFastString filename) 1 0
54 case unP parseHeader (mkPState buf loc dflags) of
55 PFailed span err -> parseError span err
56 POk pst rdr_module -> do
57 let ms = getMessages pst
58 printErrorsAndWarnings dflags ms
59 when (errorsFound dflags ms) $ exitWith (ExitFailure 1)
61 L _ (HsModule mb_mod _ imps _ _ _ _) ->
63 main_loc = mkSrcLoc (mkFastString source_filename) 1 0
64 mod = mb_mod `orElse` L (srcLocSpan main_loc) mAIN_NAME
65 imps' = filter isHomeImp (map unLoc imps)
66 (src_idecls, ord_idecls) = partition isSourceIdecl imps'
67 source_imps = map getImpMod src_idecls
68 ordinary_imps = filter ((/= moduleName gHC_PRIM) . unLoc)
69 (map getImpMod ord_idecls)
70 -- GHC.Prim doesn't exist physically, so don't go looking for it.
72 return (source_imps, ordinary_imps, mod)
74 parseError :: SrcSpan -> Message -> IO a
75 parseError span err = throwOneError $ mkPlainErrMsg span err
77 -- we aren't interested in package imports here, filter them out
78 isHomeImp :: ImportDecl name -> Bool
79 isHomeImp (ImportDecl _ (Just p) _ _ _ _) = p == fsLit "this"
80 isHomeImp (ImportDecl _ Nothing _ _ _ _) = True
82 isSourceIdecl :: ImportDecl name -> Bool
83 isSourceIdecl (ImportDecl _ _ s _ _ _) = s
85 getImpMod :: ImportDecl name -> Located ModuleName
86 getImpMod (ImportDecl located_mod _ _ _ _ _) = located_mod
88 --------------------------------------------------------------
90 --------------------------------------------------------------
93 getOptionsFromFile :: DynFlags
94 -> FilePath -- input file
95 -> IO [Located String] -- options, if any
96 getOptionsFromFile dflags filename
98 (openBinaryFile filename ReadMode)
101 do buf <- hGetStringBufferBlock handle blockSize
103 where blockSize = 1024
105 | len buf == 0 = return []
107 = case getOptions' dflags 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 :: DynFlags -> StringBuffer -> FilePath -> [Located String]
117 getOptions dflags buf filename
118 = case getOptions' dflags 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' :: DynFlags
126 -> StringBuffer -- Input buffer
127 -> FilePath -- Source file. Used for msgs only.
128 -> ( Maybe StringBuffer -- Just => we can use more input
129 , [Located String] -- Options.
131 getOptions' dflags buf filename
132 = parseToks (lexAll (pragState dflags buf loc))
133 where loc = mkSrcLoc (mkFastString filename) 1 0
135 getToken (_buf,L _loc tok) = tok
136 getLoc (_buf,L loc _tok) = loc
137 getBuf (buf,_tok) = buf
138 combine opts (flag, opts') = (flag, opts++opts')
139 add opt (flag, opts) = (flag, opt:opts)
141 parseToks (open:close:xs)
142 | IToptions_prag str <- getToken open
143 , ITclose_prag <- getToken close
144 = map (L (getLoc open)) (words str) `combine`
146 parseToks (open:close:xs)
147 | ITinclude_prag str <- getToken open
148 , ITclose_prag <- getToken close
149 = map (L (getLoc open)) ["-#include",removeSpaces str] `combine`
151 parseToks (open:close:xs)
152 | ITdocOptions str <- getToken open
153 , ITclose_prag <- getToken close
154 = map (L (getLoc open)) ["-haddock-opts", removeSpaces str]
155 `combine` parseToks xs
157 | ITdocOptionsOld str <- getToken open
158 = map (L (getLoc open)) ["-haddock-opts", removeSpaces str]
159 `combine` parseToks xs
161 | ITlanguage_prag <- getToken open
163 -- The last token before EOF could have been truncated.
164 -- We ignore it to be on the safe side.
166 | ITeof <- getToken eof
167 = (Just (getBuf tok),[])
169 | ITeof <- getToken eof
170 = (Just (getBuf eof),[])
171 parseToks _ = (Nothing,[])
172 parseLanguage ((_buf,L loc (ITconid fs)):rest)
173 = checkExtension (L loc fs) `add`
175 (_,L _loc ITcomma):more -> parseLanguage more
176 (_,L _loc ITclose_prag):more -> parseToks more
177 (_,L loc _):_ -> languagePragParseError loc
178 parseLanguage (tok:_)
179 = languagePragParseError (getLoc tok)
180 lexToken t = return t
181 lexAll state = case unP (lexer lexToken) state of
182 POk _ t@(L _ ITeof) -> [(buffer state,t)]
183 POk state' t -> (buffer state,t):lexAll state'
184 _ -> [(buffer state,L (last_loc state) ITeof)]
186 -----------------------------------------------------------------------------
187 -- Complain about non-dynamic flags in OPTIONS pragmas
189 checkProcessArgsResult :: [Located String] -> IO ()
190 checkProcessArgsResult flags
191 = when (notNull flags) $
192 ghcError $ ProgramError $ showSDoc $ vcat $ map f flags
194 = hang (ppr loc <> char ':') 4
195 (text "unknown flag in {-# OPTIONS #-} pragma:" <+>
198 -----------------------------------------------------------------------------
200 checkExtension :: Located FastString -> Located String
201 checkExtension (L l ext)
202 -- Checks if a given extension is valid, and if so returns
203 -- its corresponding flag. Otherwise it throws an exception.
204 = let ext' = unpackFS ext in
205 if ext' `elem` supportedLanguages
206 || ext' `elem` (map ("No"++) supportedLanguages)
207 then L l ("-X"++ext')
208 else unsupportedExtnError l ext'
210 languagePragParseError :: SrcSpan -> a
211 languagePragParseError loc =
213 (showSDoc (mkLocMessage loc (
214 text "cannot parse LANGUAGE pragma: comma-separated list expected")))
216 unsupportedExtnError :: SrcSpan -> String -> a
217 unsupportedExtnError loc unsup =
218 pgmError (showSDoc (mkLocMessage loc (
219 text "unsupported extension: " <>
223 optionsErrorMsgs :: [String] -> [Located String] -> FilePath -> Messages
224 optionsErrorMsgs unhandled_flags flags_lines _filename
225 = (emptyBag, listToBag (map mkMsg unhandled_flags_lines))
226 where unhandled_flags_lines = [ L l f | f <- unhandled_flags,
227 L l f' <- flags_lines, f == f' ]
228 mkMsg (L flagSpan flag) =
229 ErrUtils.mkPlainErrMsg flagSpan $
230 text "unknown flag in {-# OPTIONS #-} pragma:" <+> text flag