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