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 )
18 import Lexer ( P(..), ParseResult(..), mkPState, pragState
19 , lexer, Token(..), PState(..) )
21 import HsSyn ( ImportDecl(..), HsModule(..) )
22 import Module ( ModuleName, moduleName )
23 import PrelNames ( gHC_PRIM, mAIN_NAME )
24 import StringBuffer ( StringBuffer(..), hGetStringBuffer, hGetStringBufferBlock
25 , appendStringBuffers )
26 import SrcLoc ( Located(..), mkSrcLoc, unLoc, noSrcSpan )
27 import FastString ( mkFastString )
28 import DynFlags ( DynFlags )
34 import Bag ( emptyBag, listToBag )
36 import Distribution.Compiler
38 import EXCEPTION ( throwDyn )
42 #if __GLASGOW_HASKELL__ >= 601
43 import System.IO ( openBinaryFile )
45 import IOExts ( openFileEx, IOModeEx(..) )
48 #if __GLASGOW_HASKELL__ < 601
49 openBinaryFile fp mode = openFileEx fp (BinaryMode mode)
52 -- getImportsFromFile is careful to close the file afterwards, otherwise
53 -- we can end up with a large number of open handles before the garbage
54 -- collector gets around to closing them.
55 getImportsFromFile :: DynFlags -> FilePath
56 -> IO ([Located ModuleName], [Located ModuleName], Located ModuleName)
57 getImportsFromFile dflags filename = do
58 buf <- hGetStringBuffer filename
59 getImports dflags buf filename
61 getImports :: DynFlags -> StringBuffer -> FilePath
62 -> IO ([Located ModuleName], [Located ModuleName], Located ModuleName)
63 getImports dflags buf filename = do
64 let loc = mkSrcLoc (mkFastString filename) 1 0
65 case unP parseHeader (mkPState buf loc dflags) of
66 PFailed span err -> parseError span err
69 L _ (HsModule mod _ imps _ _) ->
71 mod_name | Just located_mod <- mod = located_mod
72 | otherwise = L noSrcSpan mAIN_NAME
73 (src_idecls, ord_idecls) = partition isSourceIdecl (map unLoc imps)
74 source_imps = map getImpMod src_idecls
75 ordinary_imps = filter ((/= moduleName gHC_PRIM) . unLoc)
76 (map getImpMod ord_idecls)
77 -- GHC.Prim doesn't exist physically, so don't go looking for it.
79 return (source_imps, ordinary_imps, mod_name)
81 parseError span err = throwDyn $ mkPlainErrMsg span err
83 isSourceIdecl (ImportDecl _ s _ _ _) = s
85 getImpMod (ImportDecl located_mod _ _ _ _) = located_mod
87 --------------------------------------------------------------
89 --------------------------------------------------------------
92 getOptionsFromFile :: FilePath -- input file
93 -> IO [Located String] -- options, if any
94 getOptionsFromFile filename
95 = bracket (openBinaryFile filename ReadMode)
98 do buf <- hGetStringBufferBlock handle blockSize
100 where blockSize = 1024
102 | len buf == 0 = return []
104 = case getOptions' buf filename of
105 (Nothing, opts) -> return opts
106 (Just buf', opts) -> do nextBlock <- hGetStringBufferBlock handle blockSize
107 newBuf <- appendStringBuffers buf' nextBlock
108 if len newBuf == len buf
110 else do opts' <- loop handle newBuf
113 getOptions :: StringBuffer -> FilePath -> [Located String]
114 getOptions buf filename
115 = case getOptions' buf filename of
118 -- The token parser is written manually because Happy can't
119 -- return a partial result when it encounters a lexer error.
120 -- We want to extract options before the buffer is passed through
121 -- CPP, so we can't use the same trick as 'getImports'.
122 getOptions' :: StringBuffer -- Input buffer
123 -> FilePath -- Source file. Used for msgs only.
124 -> ( Maybe StringBuffer -- Just => we can use more input
125 , [Located String] -- Options.
127 getOptions' buf filename
128 = parseToks (lexAll (pragState buf loc))
129 where loc = mkSrcLoc (mkFastString filename) 1 0
131 getToken (buf,L _loc tok) = tok
132 getLoc (buf,L loc _tok) = loc
133 getBuf (buf,_tok) = buf
134 combine opts (flag, opts') = (flag, opts++opts')
135 add opt (flag, opts) = (flag, opt:opts)
137 parseToks (open:close:xs)
138 | IToptions_prag str <- getToken open
139 , ITclose_prag <- getToken close
140 = map (L (getLoc open)) (words str) `combine`
142 parseToks (open:close:xs)
143 | ITinclude_prag str <- getToken open
144 , ITclose_prag <- getToken close
145 = map (L (getLoc open)) ["-#include",removeSpaces str] `combine`
148 | ITlanguage_prag <- getToken open
150 -- The last token before EOF could have been truncated.
151 -- We ignore it to be on the safe side.
153 | ITeof <- getToken eof
154 = (Just (getBuf tok),[])
156 | ITeof <- getToken eof
157 = (Just (getBuf eof),[])
158 parseToks _ = (Nothing,[])
159 parseLanguage ((_buf,L loc (ITconid fs)):rest)
160 = checkExtension (L loc fs) `add`
162 (_,L loc ITcomma):more -> parseLanguage more
163 (_,L loc ITclose_prag):more -> parseToks more
164 (_,L loc _):_ -> languagePragParseError loc
165 parseLanguage (tok:_)
166 = languagePragParseError (getLoc tok)
167 lexToken t = return t
168 lexAll state = case unP (lexer lexToken) state of
169 POk state' t@(L _ ITeof) -> [(buffer state,t)]
170 POk state' t -> (buffer state,t):lexAll state'
171 _ -> [(buffer state,L (last_loc state) ITeof)]
173 checkExtension :: Located FastString -> Located String
174 checkExtension (L l ext)
175 = case reads (unpackFS ext) of
176 [] -> languagePragParseError l
177 (okExt,""):_ -> case extensionsToGHCFlag [okExt] of
178 ([],[opt]) -> L l opt
179 _ -> unsupportedExtnError l okExt
181 languagePragParseError loc =
182 pgmError (showSDoc (mkLocMessage loc (
183 text "cannot parse LANGUAGE pragma")))
185 unsupportedExtnError loc unsup =
186 pgmError (showSDoc (mkLocMessage loc (
187 text "unsupported extension: " <>
191 optionsErrorMsgs :: [String] -> [Located String] -> FilePath -> Messages
192 optionsErrorMsgs unhandled_flags flags_lines filename
193 = (emptyBag, listToBag (map mkMsg unhandled_flags_lines))
194 where unhandled_flags_lines = [ L l f | f <- unhandled_flags,
195 L l f' <- flags_lines, f == f' ]
196 mkMsg (L flagSpan flag) =
197 ErrUtils.mkPlainErrMsg flagSpan $
198 text "unknown flag in {-# OPTIONS #-} pragma:" <+> text flag