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 ( Module, mkModule )
23 import PrelNames ( gHC_PRIM )
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 ( unitBag, emptyBag, listToBag )
36 import Distribution.Compiler
40 import EXCEPTION ( throwDyn )
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 Module], [Located Module], Located Module)
59 getImportsFromFile dflags filename = do
60 buf <- hGetStringBuffer filename
61 getImports dflags buf filename
63 getImports :: DynFlags -> StringBuffer -> FilePath
64 -> IO ([Located Module], [Located Module], Located Module)
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
71 L _ (HsModule mod _ imps _ _) ->
73 mod_name | Just located_mod <- mod = located_mod
74 | otherwise = L noSrcSpan (mkModule "Main")
75 (src_idecls, ord_idecls) = partition isSourceIdecl (map unLoc imps)
76 source_imps = map getImpMod src_idecls
77 ordinary_imps = filter ((/= gHC_PRIM) . unLoc)
78 (map getImpMod ord_idecls)
79 -- GHC.Prim doesn't exist physically, so don't go looking for it.
81 return (source_imps, ordinary_imps, mod_name)
83 parseError span err = throwDyn $ mkPlainErrMsg span err
85 isSourceIdecl (ImportDecl _ s _ _ _) = s
87 getImpMod (ImportDecl located_mod _ _ _ _) = located_mod
89 --------------------------------------------------------------
91 --------------------------------------------------------------
94 getOptionsFromFile :: FilePath -- input file
95 -> IO [Located String] -- options, if any
96 getOptionsFromFile filename
97 = bracket (openBinaryFile filename ReadMode)
100 do buf <- hGetStringBufferBlock handle blockSize
102 where blockSize = 1024
104 | len buf == 0 = return []
106 = case getOptions' buf filename of
107 (Nothing, opts) -> return opts
108 (Just buf', opts) -> do nextBlock <- hGetStringBufferBlock handle blockSize
109 newBuf <- appendStringBuffers buf' nextBlock
110 if len newBuf == len buf
112 else do opts' <- loop handle newBuf
115 getOptions :: StringBuffer -> FilePath -> [Located String]
116 getOptions buf filename
117 = case getOptions' buf filename of
120 -- The token parser is written manually because Happy can't
121 -- return a partial result when it encounters a lexer error.
122 -- We want to extract options before the buffer is passed through
123 -- CPP, so we can't use the same trick as 'getImports'.
124 getOptions' :: StringBuffer -- Input buffer
125 -> FilePath -- Source file. Used for msgs only.
126 -> ( Maybe StringBuffer -- Just => we can use more input
127 , [Located String] -- Options.
129 getOptions' buf filename
130 = parseToks (lexAll (pragState buf loc))
131 where loc = mkSrcLoc (mkFastString filename) 1 0
133 getToken (buf,L _loc tok) = tok
134 getLoc (buf,L loc _tok) = loc
135 getBuf (buf,_tok) = buf
136 combine opts (flag, opts') = (flag, opts++opts')
137 add opt (flag, opts) = (flag, opt:opts)
139 parseToks (open:close:xs)
140 | IToptions_prag str <- getToken open
141 , ITclose_prag <- getToken close
142 = map (L (getLoc open)) (words str) `combine`
144 parseToks (open:close:xs)
145 | ITinclude_prag str <- getToken open
146 , ITclose_prag <- getToken close
147 = map (L (getLoc open)) ["-#include",removeSpaces str] `combine`
150 | ITlanguage_prag <- getToken open
152 -- The last token before EOF could have been truncated.
153 -- We ignore it to be on the safe side.
155 | ITeof <- getToken eof
156 = (Just (getBuf tok),[])
158 | ITeof <- getToken eof
159 = (Just (getBuf eof),[])
160 parseToks _ = (Nothing,[])
161 parseLanguage ((_buf,L loc (ITconid fs)):rest)
162 = checkExtension (L loc fs) `add`
164 (_,L loc ITcomma):more -> parseLanguage more
165 (_,L loc ITclose_prag):more -> parseToks more
166 (_,L loc _):_ -> languagePragParseError loc
167 parseLanguage (tok:_)
168 = languagePragParseError (getLoc tok)
169 lexToken t = return t
170 lexAll state = case unP (lexer lexToken) state of
171 POk state' t@(L _ ITeof) -> [(buffer state,t)]
172 POk state' t -> (buffer state,t):lexAll state'
173 _ -> [(buffer state,L (last_loc state) ITeof)]
175 checkExtension :: Located FastString -> Located String
176 checkExtension (L l ext)
177 = case reads (unpackFS ext) of
178 [] -> languagePragParseError l
179 (okExt,""):_ -> case extensionsToGHCFlag [okExt] of
180 ([],[opt]) -> L l opt
181 _ -> unsupportedExtnError l okExt
183 languagePragParseError loc =
184 pgmError (showSDoc (mkLocMessage loc (
185 text "cannot parse LANGUAGE pragma")))
187 unsupportedExtnError loc unsup =
188 pgmError (showSDoc (mkLocMessage loc (
189 text "unsupported extension: " <>
193 optionsErrorMsgs :: [String] -> [Located String] -> FilePath -> Messages
194 optionsErrorMsgs unhandled_flags flags_lines filename
195 = (emptyBag, listToBag (map mkMsg unhandled_flags_lines))
196 where unhandled_flags_lines = [ L l f | f <- unhandled_flags,
197 L l f' <- flags_lines, f == f' ]
198 mkMsg (L flagSpan flag) =
199 ErrUtils.mkPlainErrMsg flagSpan $
200 text "unknown flag in {-# OPTIONS #-} pragma:" <+> text flag