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 )
26 import FastString ( mkFastString )
34 import Bag ( emptyBag, listToBag )
36 import Distribution.Compiler
38 import Control.Exception
44 #if __GLASGOW_HASKELL__ >= 601
45 import System.IO ( openBinaryFile )
47 import IOExts ( openFileEx, IOModeEx(..) )
50 #if __GLASGOW_HASKELL__ < 601
51 openBinaryFile fp mode = openFileEx fp (BinaryMode mode)
54 -- getImportsFromFile is careful to close the file afterwards, otherwise
55 -- we can end up with a large number of open handles before the garbage
56 -- collector gets around to closing them.
57 getImportsFromFile :: DynFlags -> FilePath
58 -> IO ([Located ModuleName], [Located ModuleName], Located ModuleName)
59 getImportsFromFile dflags filename = do
60 buf <- hGetStringBuffer filename
61 getImports dflags buf filename
63 getImports :: DynFlags -> StringBuffer -> FilePath
64 -> IO ([Located ModuleName], [Located ModuleName], Located ModuleName)
65 getImports dflags buf filename = do
66 let loc = mkSrcLoc (mkFastString filename) 1 0
67 case unP parseHeader (mkPState buf loc dflags) of
68 PFailed span err -> parseError span err
69 POk pst rdr_module -> do
70 let ms = getMessages pst
71 printErrorsAndWarnings dflags ms
72 when (errorsFound dflags ms) $ exitWith (ExitFailure 1)
74 L _ (HsModule mb_mod _ imps _ _ _ _ _) ->
76 mod = mb_mod `orElse` L (srcLocSpan loc) mAIN_NAME
77 (src_idecls, ord_idecls) = partition isSourceIdecl (map unLoc imps)
78 source_imps = map getImpMod src_idecls
79 ordinary_imps = filter ((/= moduleName gHC_PRIM) . unLoc)
80 (map getImpMod ord_idecls)
81 -- GHC.Prim doesn't exist physically, so don't go looking for it.
83 return (source_imps, ordinary_imps, mod)
85 parseError span err = throwDyn $ mkPlainErrMsg span err
87 isSourceIdecl (ImportDecl _ s _ _ _) = s
89 getImpMod (ImportDecl located_mod _ _ _ _) = located_mod
91 --------------------------------------------------------------
93 --------------------------------------------------------------
96 getOptionsFromFile :: FilePath -- input file
97 -> IO [Located String] -- options, if any
98 getOptionsFromFile filename
99 = Control.Exception.bracket
100 (openBinaryFile filename ReadMode)
103 do buf <- hGetStringBufferBlock handle blockSize
105 where blockSize = 1024
107 | len buf == 0 = return []
109 = case getOptions' buf filename of
110 (Nothing, opts) -> return opts
111 (Just buf', opts) -> do nextBlock <- hGetStringBufferBlock handle blockSize
112 newBuf <- appendStringBuffers buf' nextBlock
113 if len newBuf == len buf
115 else do opts' <- loop handle newBuf
118 getOptions :: StringBuffer -> FilePath -> [Located String]
119 getOptions buf filename
120 = case getOptions' 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' :: StringBuffer -- Input buffer
128 -> FilePath -- Source file. Used for msgs only.
129 -> ( Maybe StringBuffer -- Just => we can use more input
130 , [Located String] -- Options.
132 getOptions' buf filename
133 = parseToks (lexAll (pragState buf loc))
134 where loc = mkSrcLoc (mkFastString filename) 1 0
136 getToken (buf,L _loc tok) = tok
137 getLoc (buf,L loc _tok) = loc
138 getBuf (buf,_tok) = buf
139 combine opts (flag, opts') = (flag, opts++opts')
140 add opt (flag, opts) = (flag, opt:opts)
142 parseToks (open:close:xs)
143 | IToptions_prag str <- getToken open
144 , ITclose_prag <- getToken close
145 = map (L (getLoc open)) (words str) `combine`
147 parseToks (open:close:xs)
148 | ITinclude_prag str <- getToken open
149 , ITclose_prag <- getToken close
150 = map (L (getLoc open)) ["-#include",removeSpaces str] `combine`
153 | ITlanguage_prag <- getToken open
155 -- The last token before EOF could have been truncated.
156 -- We ignore it to be on the safe side.
158 | ITeof <- getToken eof
159 = (Just (getBuf tok),[])
161 | ITeof <- getToken eof
162 = (Just (getBuf eof),[])
163 parseToks _ = (Nothing,[])
164 parseLanguage ((_buf,L loc (ITconid fs)):rest)
165 = checkExtension (L loc fs) `add`
167 (_,L loc ITcomma):more -> parseLanguage more
168 (_,L loc ITclose_prag):more -> parseToks more
169 (_,L loc _):_ -> languagePragParseError loc
170 parseLanguage (tok:_)
171 = languagePragParseError (getLoc tok)
172 lexToken t = return t
173 lexAll state = case unP (lexer lexToken) state of
174 POk state' t@(L _ ITeof) -> [(buffer state,t)]
175 POk state' t -> (buffer state,t):lexAll state'
176 _ -> [(buffer state,L (last_loc state) ITeof)]
178 checkExtension :: Located FastString -> Located String
179 checkExtension (L l ext)
180 = case reads (unpackFS ext) of
181 [] -> languagePragParseError l
182 (okExt,""):_ -> case extensionsToGHCFlag [okExt] of
183 ([],[opt]) -> L l opt
184 _ -> unsupportedExtnError l okExt
186 languagePragParseError loc =
187 pgmError (showSDoc (mkLocMessage loc (
188 text "cannot parse LANGUAGE pragma")))
190 unsupportedExtnError loc unsup =
191 pgmError (showSDoc (mkLocMessage loc (
192 text "unsupported extension: " <>
196 optionsErrorMsgs :: [String] -> [Located String] -> FilePath -> Messages
197 optionsErrorMsgs unhandled_flags flags_lines filename
198 = (emptyBag, listToBag (map mkMsg unhandled_flags_lines))
199 where unhandled_flags_lines = [ L l f | f <- unhandled_flags,
200 L l f' <- flags_lines, f == f' ]
201 mkMsg (L flagSpan flag) =
202 ErrUtils.mkPlainErrMsg flagSpan $
203 text "unknown flag in {-# OPTIONS #-} pragma:" <+> text flag