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"
25 import Parser ( parseHeader )
28 import HsSyn ( ImportDecl(..), HsModule(..) )
29 import Module ( ModuleName, moduleName )
30 import PrelNames ( gHC_PRIM, mAIN_NAME )
31 import StringBuffer ( StringBuffer(..), hGetStringBufferBlock
32 , appendStringBuffers )
41 import Bag ( emptyBag, listToBag )
49 getImports :: DynFlags -> StringBuffer -> FilePath -> FilePath
50 -> IO ([Located ModuleName], [Located ModuleName], Located ModuleName)
51 getImports dflags buf filename source_filename = do
52 let loc = mkSrcLoc (mkFastString filename) 1 0
53 case unP parseHeader (mkPState buf loc dflags) of
54 PFailed span err -> parseError span err
55 POk pst rdr_module -> do
56 let ms = getMessages pst
57 printErrorsAndWarnings dflags ms
58 when (errorsFound dflags ms) $ exitWith (ExitFailure 1)
60 L _ (HsModule mb_mod _ imps _ _ _ _) ->
62 main_loc = mkSrcLoc (mkFastString source_filename) 1 0
63 mod = mb_mod `orElse` L (srcLocSpan main_loc) mAIN_NAME
64 imps' = filter isHomeImp (map unLoc imps)
65 (src_idecls, ord_idecls) = partition isSourceIdecl imps'
66 source_imps = map getImpMod src_idecls
67 ordinary_imps = filter ((/= moduleName gHC_PRIM) . unLoc)
68 (map getImpMod ord_idecls)
69 -- GHC.Prim doesn't exist physically, so don't go looking for it.
71 return (source_imps, ordinary_imps, mod)
73 parseError :: SrcSpan -> Message -> a
74 parseError span err = throwErrMsg $ mkPlainErrMsg span err
76 -- we aren't interested in package imports here, filter them out
77 isHomeImp :: ImportDecl name -> Bool
78 isHomeImp (ImportDecl _ (Just p) _ _ _ _) = p == fsLit "this"
79 isHomeImp (ImportDecl _ Nothing _ _ _ _) = True
81 isSourceIdecl :: ImportDecl name -> Bool
82 isSourceIdecl (ImportDecl _ _ s _ _ _) = s
84 getImpMod :: ImportDecl name -> Located ModuleName
85 getImpMod (ImportDecl located_mod _ _ _ _ _) = located_mod
87 --------------------------------------------------------------
89 --------------------------------------------------------------
92 getOptionsFromFile :: DynFlags
93 -> FilePath -- input file
94 -> IO [Located String] -- options, if any
95 getOptionsFromFile dflags filename
97 (openBinaryFile filename ReadMode)
100 do buf <- hGetStringBufferBlock handle blockSize
102 where blockSize = 1024
104 | len buf == 0 = return []
106 = case getOptions' dflags buf filename of
107 (Nothing, opts) -> return opts
108 (Just buf', opts) -> do nextBlock <- hGetStringBufferBlock handle blockSize
109 newBuf <- appendStringBuffers buf' nextBlock
110 if len newBuf == len buf
112 else do opts' <- loop handle newBuf
115 getOptions :: DynFlags -> StringBuffer -> FilePath -> [Located String]
116 getOptions dflags buf filename
117 = case getOptions' dflags buf filename of
120 -- The token parser is written manually because Happy can't
121 -- return a partial result when it encounters a lexer error.
122 -- We want to extract options before the buffer is passed through
123 -- CPP, so we can't use the same trick as 'getImports'.
124 getOptions' :: DynFlags
125 -> 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' dflags buf filename
131 = parseToks (lexAll (pragState dflags 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`
150 parseToks (open:close:xs)
151 | ITdocOptions str <- getToken open
152 , ITclose_prag <- getToken close
153 = map (L (getLoc open)) ["-haddock-opts", removeSpaces str]
154 `combine` parseToks xs
156 | ITdocOptionsOld str <- getToken open
157 = map (L (getLoc open)) ["-haddock-opts", removeSpaces str]
158 `combine` parseToks xs
160 | ITlanguage_prag <- getToken open
162 -- The last token before EOF could have been truncated.
163 -- We ignore it to be on the safe side.
165 | ITeof <- getToken eof
166 = (Just (getBuf tok),[])
168 | ITeof <- getToken eof
169 = (Just (getBuf eof),[])
170 parseToks _ = (Nothing,[])
171 parseLanguage ((_buf,L loc (ITconid fs)):rest)
172 = checkExtension (L loc fs) `add`
174 (_,L _loc ITcomma):more -> parseLanguage more
175 (_,L _loc ITclose_prag):more -> parseToks more
176 (_,L loc _):_ -> languagePragParseError loc
177 parseLanguage (tok:_)
178 = languagePragParseError (getLoc tok)
179 lexToken t = return t
180 lexAll state = case unP (lexer lexToken) state of
181 POk _ t@(L _ ITeof) -> [(buffer state,t)]
182 POk state' t -> (buffer state,t):lexAll state'
183 _ -> [(buffer state,L (last_loc state) ITeof)]
185 -----------------------------------------------------------------------------
186 -- Complain about non-dynamic flags in OPTIONS pragmas
188 checkProcessArgsResult :: [Located String] -> IO ()
189 checkProcessArgsResult flags
190 = when (notNull flags) $
191 ghcError $ ProgramError $ showSDoc $ vcat $ map f flags
193 = hang (ppr loc <> char ':') 4
194 (text "unknown flag in {-# OPTIONS #-} pragma:" <+>
197 -----------------------------------------------------------------------------
199 checkExtension :: Located FastString -> Located String
200 checkExtension (L l ext)
201 -- Checks if a given extension is valid, and if so returns
202 -- its corresponding flag. Otherwise it throws an exception.
203 = let ext' = unpackFS ext in
204 if ext' `elem` supportedLanguages
205 || ext' `elem` (map ("No"++) supportedLanguages)
206 then L l ("-X"++ext')
207 else unsupportedExtnError l ext'
209 languagePragParseError :: SrcSpan -> a
210 languagePragParseError loc =
212 (showSDoc (mkLocMessage loc (
213 text "cannot parse LANGUAGE pragma: comma-separated list expected")))
215 unsupportedExtnError :: SrcSpan -> String -> a
216 unsupportedExtnError loc unsup =
217 pgmError (showSDoc (mkLocMessage loc (
218 text "unsupported extension: " <>
222 optionsErrorMsgs :: [String] -> [Located String] -> FilePath -> Messages
223 optionsErrorMsgs unhandled_flags flags_lines _filename
224 = (emptyBag, listToBag (map mkMsg unhandled_flags_lines))
225 where unhandled_flags_lines = [ L l f | f <- unhandled_flags,
226 L l f' <- flags_lines, f == f' ]
227 mkMsg (L flagSpan flag) =
228 ErrUtils.mkPlainErrMsg flagSpan $
229 text "unknown flag in {-# OPTIONS #-} pragma:" <+> text flag