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 )
27 import FastString ( mkFastString )
28 import DynFlags ( DynFlags )
35 import Bag ( emptyBag, listToBag )
37 import Distribution.Compiler
39 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
70 L _ (HsModule mb_mod _ imps _ _ _ _ _) ->
72 mod = mb_mod `orElse` L (srcLocSpan loc) 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)
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 = Control.Exception.bracket
96 (openBinaryFile filename ReadMode)
99 do buf <- hGetStringBufferBlock handle blockSize
101 where blockSize = 1024
103 | len buf == 0 = return []
105 = case getOptions' buf filename of
106 (Nothing, opts) -> return opts
107 (Just buf', opts) -> do nextBlock <- hGetStringBufferBlock handle blockSize
108 newBuf <- appendStringBuffers buf' nextBlock
109 if len newBuf == len buf
111 else do opts' <- loop handle newBuf
114 getOptions :: StringBuffer -> FilePath -> [Located String]
115 getOptions buf filename
116 = case getOptions' buf filename of
119 -- The token parser is written manually because Happy can't
120 -- return a partial result when it encounters a lexer error.
121 -- We want to extract options before the buffer is passed through
122 -- CPP, so we can't use the same trick as 'getImports'.
123 getOptions' :: StringBuffer -- Input buffer
124 -> FilePath -- Source file. Used for msgs only.
125 -> ( Maybe StringBuffer -- Just => we can use more input
126 , [Located String] -- Options.
128 getOptions' buf filename
129 = parseToks (lexAll (pragState buf loc))
130 where loc = mkSrcLoc (mkFastString filename) 1 0
132 getToken (buf,L _loc tok) = tok
133 getLoc (buf,L loc _tok) = loc
134 getBuf (buf,_tok) = buf
135 combine opts (flag, opts') = (flag, opts++opts')
136 add opt (flag, opts) = (flag, opt:opts)
138 parseToks (open:close:xs)
139 | IToptions_prag str <- getToken open
140 , ITclose_prag <- getToken close
141 = map (L (getLoc open)) (words str) `combine`
143 parseToks (open:close:xs)
144 | ITinclude_prag str <- getToken open
145 , ITclose_prag <- getToken close
146 = map (L (getLoc open)) ["-#include",removeSpaces str] `combine`
149 | ITlanguage_prag <- getToken open
151 -- The last token before EOF could have been truncated.
152 -- We ignore it to be on the safe side.
154 | ITeof <- getToken eof
155 = (Just (getBuf tok),[])
157 | ITeof <- getToken eof
158 = (Just (getBuf eof),[])
159 parseToks _ = (Nothing,[])
160 parseLanguage ((_buf,L loc (ITconid fs)):rest)
161 = checkExtension (L loc fs) `add`
163 (_,L loc ITcomma):more -> parseLanguage more
164 (_,L loc ITclose_prag):more -> parseToks more
165 (_,L loc _):_ -> languagePragParseError loc
166 parseLanguage (tok:_)
167 = languagePragParseError (getLoc tok)
168 lexToken t = return t
169 lexAll state = case unP (lexer lexToken) state of
170 POk state' t@(L _ ITeof) -> [(buffer state,t)]
171 POk state' t -> (buffer state,t):lexAll state'
172 _ -> [(buffer state,L (last_loc state) ITeof)]
174 checkExtension :: Located FastString -> Located String
175 checkExtension (L l ext)
176 = case reads (unpackFS ext) of
177 [] -> languagePragParseError l
178 (okExt,""):_ -> case extensionsToGHCFlag [okExt] of
179 ([],[opt]) -> L l opt
180 _ -> unsupportedExtnError l okExt
182 languagePragParseError loc =
183 pgmError (showSDoc (mkLocMessage loc (
184 text "cannot parse LANGUAGE pragma")))
186 unsupportedExtnError loc unsup =
187 pgmError (showSDoc (mkLocMessage loc (
188 text "unsupported extension: " <>
192 optionsErrorMsgs :: [String] -> [Located String] -> FilePath -> Messages
193 optionsErrorMsgs unhandled_flags flags_lines filename
194 = (emptyBag, listToBag (map mkMsg unhandled_flags_lines))
195 where unhandled_flags_lines = [ L l f | f <- unhandled_flags,
196 L l f' <- flags_lines, f == f' ]
197 mkMsg (L flagSpan flag) =
198 ErrUtils.mkPlainErrMsg flagSpan $
199 text "unknown flag in {-# OPTIONS #-} pragma:" <+> text flag