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.Package
38 import Distribution.Version
40 import Control.Exception
46 #if __GLASGOW_HASKELL__ >= 601
47 import System.IO ( openBinaryFile )
49 import IOExts ( openFileEx, IOModeEx(..) )
52 #if __GLASGOW_HASKELL__ < 601
53 openBinaryFile fp mode = openFileEx fp (BinaryMode mode)
56 -- getImportsFromFile is careful to close the file afterwards, otherwise
57 -- we can end up with a large number of open handles before the garbage
58 -- collector gets around to closing them.
59 getImportsFromFile :: DynFlags -> FilePath
60 -> IO ([Located ModuleName], [Located ModuleName], Located ModuleName)
61 getImportsFromFile dflags filename = do
62 buf <- hGetStringBuffer filename
63 getImports dflags buf filename
65 getImports :: DynFlags -> StringBuffer -> FilePath
66 -> IO ([Located ModuleName], [Located ModuleName], Located ModuleName)
67 getImports dflags buf filename = do
68 let loc = mkSrcLoc (mkFastString filename) 1 0
69 case unP parseHeader (mkPState buf loc dflags) of
70 PFailed span err -> parseError span err
71 POk pst rdr_module -> do
72 let ms = getMessages pst
73 printErrorsAndWarnings dflags ms
74 when (errorsFound dflags ms) $ exitWith (ExitFailure 1)
76 L _ (HsModule mb_mod _ imps _ _ _ _ _) ->
78 mod = mb_mod `orElse` L (srcLocSpan loc) mAIN_NAME
79 (src_idecls, ord_idecls) = partition isSourceIdecl (map unLoc imps)
80 source_imps = map getImpMod src_idecls
81 ordinary_imps = filter ((/= moduleName gHC_PRIM) . unLoc)
82 (map getImpMod ord_idecls)
83 -- GHC.Prim doesn't exist physically, so don't go looking for it.
85 return (source_imps, ordinary_imps, mod)
87 parseError span err = throwDyn $ mkPlainErrMsg span err
89 isSourceIdecl (ImportDecl _ s _ _ _) = s
91 getImpMod (ImportDecl located_mod _ _ _ _) = located_mod
93 --------------------------------------------------------------
95 --------------------------------------------------------------
98 getOptionsFromFile :: FilePath -- input file
99 -> IO [Located String] -- options, if any
100 getOptionsFromFile filename
101 = Control.Exception.bracket
102 (openBinaryFile filename ReadMode)
105 do buf <- hGetStringBufferBlock handle blockSize
107 where blockSize = 1024
109 | len buf == 0 = return []
111 = case getOptions' buf filename of
112 (Nothing, opts) -> return opts
113 (Just buf', opts) -> do nextBlock <- hGetStringBufferBlock handle blockSize
114 newBuf <- appendStringBuffers buf' nextBlock
115 if len newBuf == len buf
117 else do opts' <- loop handle newBuf
120 getOptions :: StringBuffer -> FilePath -> [Located String]
121 getOptions buf filename
122 = case getOptions' buf filename of
125 -- The token parser is written manually because Happy can't
126 -- return a partial result when it encounters a lexer error.
127 -- We want to extract options before the buffer is passed through
128 -- CPP, so we can't use the same trick as 'getImports'.
129 getOptions' :: StringBuffer -- Input buffer
130 -> FilePath -- Source file. Used for msgs only.
131 -> ( Maybe StringBuffer -- Just => we can use more input
132 , [Located String] -- Options.
134 getOptions' buf filename
135 = parseToks (lexAll (pragState buf loc))
136 where loc = mkSrcLoc (mkFastString filename) 1 0
138 getToken (buf,L _loc tok) = tok
139 getLoc (buf,L loc _tok) = loc
140 getBuf (buf,_tok) = buf
141 combine opts (flag, opts') = (flag, opts++opts')
142 add opt (flag, opts) = (flag, opt:opts)
144 parseToks (open:close:xs)
145 | IToptions_prag str <- getToken open
146 , ITclose_prag <- getToken close
147 = map (L (getLoc open)) (words str) `combine`
149 parseToks (open:close:xs)
150 | ITinclude_prag str <- getToken open
151 , ITclose_prag <- getToken close
152 = map (L (getLoc open)) ["-#include",removeSpaces str] `combine`
155 | ITlanguage_prag <- getToken open
157 -- The last token before EOF could have been truncated.
158 -- We ignore it to be on the safe side.
160 | ITeof <- getToken eof
161 = (Just (getBuf tok),[])
163 | ITeof <- getToken eof
164 = (Just (getBuf eof),[])
165 parseToks _ = (Nothing,[])
166 parseLanguage ((_buf,L loc (ITconid fs)):rest)
167 = checkExtension (L loc fs) `add`
169 (_,L loc ITcomma):more -> parseLanguage more
170 (_,L loc ITclose_prag):more -> parseToks more
171 (_,L loc _):_ -> languagePragParseError loc
172 parseLanguage (tok:_)
173 = languagePragParseError (getLoc tok)
174 lexToken t = return t
175 lexAll state = case unP (lexer lexToken) state of
176 POk state' t@(L _ ITeof) -> [(buffer state,t)]
177 POk state' t -> (buffer state,t):lexAll state'
178 _ -> [(buffer state,L (last_loc state) ITeof)]
180 thisCompiler :: Compiler
181 thisCompiler = Compiler {
182 compilerFlavor = GHC,
183 compilerId = PackageIdentifier {
187 compilerProg = panic "No compiler program yet",
188 compilerPkgTool = panic "No package program yet",
189 compilerLanguagesKnown = True,
190 compilerLanguages = supportedLanguages
192 where v = case readVersion cProjectVersion of
193 Just version -> version
195 panic ("Can't parse version: " ++ show cProjectVersion)
197 checkExtension :: Located FastString -> Located String
198 checkExtension (L l ext)
199 = case reads (unpackFS ext) of
200 [] -> languagePragParseError l
202 case extensionsToFlags thisCompiler [okExt] of
203 ([],[opt]) -> L l opt
204 _ -> unsupportedExtnError l okExt
206 languagePragParseError loc =
207 pgmError (showSDoc (mkLocMessage loc (
208 text "cannot parse LANGUAGE pragma")))
210 unsupportedExtnError loc unsup =
211 pgmError (showSDoc (mkLocMessage loc (
212 text "unsupported extension: " <>
216 optionsErrorMsgs :: [String] -> [Located String] -> FilePath -> Messages
217 optionsErrorMsgs unhandled_flags flags_lines filename
218 = (emptyBag, listToBag (map mkMsg unhandled_flags_lines))
219 where unhandled_flags_lines = [ L l f | f <- unhandled_flags,
220 L l f' <- flags_lines, f == f' ]
221 mkMsg (L flagSpan flag) =
222 ErrUtils.mkPlainErrMsg flagSpan $
223 text "unknown flag in {-# OPTIONS #-} pragma:" <+> text flag