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 Distribution.Compiler
37 import Distribution.Version
39 import Control.Exception
45 #if __GLASGOW_HASKELL__ >= 601
46 import System.IO ( openBinaryFile )
48 import IOExts ( openFileEx, IOModeEx(..) )
51 #if __GLASGOW_HASKELL__ < 601
52 openBinaryFile fp mode = openFileEx fp (BinaryMode mode)
55 -- getImportsFromFile is careful to close the file afterwards, otherwise
56 -- we can end up with a large number of open handles before the garbage
57 -- collector gets around to closing them.
58 getImportsFromFile :: DynFlags -> FilePath
59 -> IO ([Located ModuleName], [Located ModuleName], Located ModuleName)
60 getImportsFromFile dflags filename = do
61 buf <- hGetStringBuffer filename
62 getImports dflags buf filename
64 getImports :: DynFlags -> StringBuffer -> FilePath
65 -> IO ([Located ModuleName], [Located ModuleName], Located ModuleName)
66 getImports dflags buf filename = do
67 let loc = mkSrcLoc (mkFastString filename) 1 0
68 case unP parseHeader (mkPState buf loc dflags) of
69 PFailed span err -> parseError span err
70 POk pst rdr_module -> do
71 let ms = getMessages pst
72 printErrorsAndWarnings dflags ms
73 when (errorsFound dflags ms) $ exitWith (ExitFailure 1)
75 L _ (HsModule mb_mod _ imps _ _ _ _ _) ->
77 mod = mb_mod `orElse` L (srcLocSpan loc) mAIN_NAME
78 (src_idecls, ord_idecls) = partition isSourceIdecl (map unLoc imps)
79 source_imps = map getImpMod src_idecls
80 ordinary_imps = filter ((/= moduleName gHC_PRIM) . unLoc)
81 (map getImpMod ord_idecls)
82 -- GHC.Prim doesn't exist physically, so don't go looking for it.
84 return (source_imps, ordinary_imps, mod)
86 parseError span err = throwDyn $ mkPlainErrMsg span err
88 isSourceIdecl (ImportDecl _ s _ _ _) = s
90 getImpMod (ImportDecl located_mod _ _ _ _) = located_mod
92 --------------------------------------------------------------
94 --------------------------------------------------------------
97 getOptionsFromFile :: FilePath -- input file
98 -> IO [Located String] -- options, if any
99 getOptionsFromFile filename
100 = Control.Exception.bracket
101 (openBinaryFile filename ReadMode)
104 do buf <- hGetStringBufferBlock handle blockSize
106 where blockSize = 1024
108 | len buf == 0 = return []
110 = case getOptions' buf filename of
111 (Nothing, opts) -> return opts
112 (Just buf', opts) -> do nextBlock <- hGetStringBufferBlock handle blockSize
113 newBuf <- appendStringBuffers buf' nextBlock
114 if len newBuf == len buf
116 else do opts' <- loop handle newBuf
119 getOptions :: StringBuffer -> FilePath -> [Located String]
120 getOptions buf filename
121 = case getOptions' buf filename of
124 -- The token parser is written manually because Happy can't
125 -- return a partial result when it encounters a lexer error.
126 -- We want to extract options before the buffer is passed through
127 -- CPP, so we can't use the same trick as 'getImports'.
128 getOptions' :: 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' buf filename
134 = parseToks (lexAll (pragState 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`
154 | ITlanguage_prag <- getToken open
156 -- The last token before EOF could have been truncated.
157 -- We ignore it to be on the safe side.
159 | ITeof <- getToken eof
160 = (Just (getBuf tok),[])
162 | ITeof <- getToken eof
163 = (Just (getBuf eof),[])
164 parseToks _ = (Nothing,[])
165 parseLanguage ((_buf,L loc (ITconid fs)):rest)
166 = checkExtension (L loc fs) `add`
168 (_,L loc ITcomma):more -> parseLanguage more
169 (_,L loc ITclose_prag):more -> parseToks more
170 (_,L loc _):_ -> languagePragParseError loc
171 parseLanguage (tok:_)
172 = languagePragParseError (getLoc tok)
173 lexToken t = return t
174 lexAll state = case unP (lexer lexToken) state of
175 POk state' t@(L _ ITeof) -> [(buffer state,t)]
176 POk state' t -> (buffer state,t):lexAll state'
177 _ -> [(buffer state,L (last_loc state) ITeof)]
179 checkExtension :: Located FastString -> Located String
180 checkExtension (L l ext)
181 = case reads (unpackFS ext) of
182 [] -> languagePragParseError l
184 case readVersion cProjectVersion of
186 case extensionsToGHCFlag version [okExt] of
187 ([],[opt]) -> L l opt
188 _ -> unsupportedExtnError l okExt
190 panic ("Can't parse version: " ++ show cProjectVersion)
192 languagePragParseError loc =
193 pgmError (showSDoc (mkLocMessage loc (
194 text "cannot parse LANGUAGE pragma")))
196 unsupportedExtnError loc unsup =
197 pgmError (showSDoc (mkLocMessage loc (
198 text "unsupported extension: " <>
202 optionsErrorMsgs :: [String] -> [Located String] -> FilePath -> Messages
203 optionsErrorMsgs unhandled_flags flags_lines filename
204 = (emptyBag, listToBag (map mkMsg unhandled_flags_lines))
205 where unhandled_flags_lines = [ L l f | f <- unhandled_flags,
206 L l f' <- flags_lines, f == f' ]
207 mkMsg (L flagSpan flag) =
208 ErrUtils.mkPlainErrMsg flagSpan $
209 text "unknown flag in {-# OPTIONS #-} pragma:" <+> text flag