Removed a dependency on Cabal that caused a build failure when Cabal changed
[ghc-hetmet.git] / compiler / main / HeaderInfo.hs
1 -----------------------------------------------------------------------------
2 --
3 -- Parsing the top of a Haskell source file to get its module name,
4 -- imports and options.
5 --
6 -- (c) Simon Marlow 2005
7 -- (c) Lemmih 2006
8 --
9 -----------------------------------------------------------------------------
10
11 module HeaderInfo ( getImportsFromFile, getImports
12                   , getOptionsFromFile, getOptions
13                   , optionsErrorMsgs ) where
14
15 #include "HsVersions.h"
16
17 import Parser           ( parseHeader )
18 import Lexer
19 import FastString
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 )
25 import Config
26 import SrcLoc
27 import DynFlags
28 import ErrUtils
29 import Util
30 import Outputable
31 import Pretty           ()
32 import Panic
33 import Maybes
34 import Bag              ( emptyBag, listToBag )
35
36 import Control.Exception
37 import Control.Monad
38 import System.Exit
39 import System.IO
40 import Data.List
41
42 #if __GLASGOW_HASKELL__ >= 601
43 import System.IO                ( openBinaryFile )
44 #else
45 import IOExts                   ( openFileEx, IOModeEx(..) )
46 #endif
47
48 #if __GLASGOW_HASKELL__ < 601
49 openBinaryFile fp mode = openFileEx fp (BinaryMode mode)
50 #endif
51
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
60
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
67         POk pst rdr_module -> do
68           let ms = getMessages pst
69           printErrorsAndWarnings dflags ms
70           when (errorsFound dflags ms) $ exitWith (ExitFailure 1)
71           case rdr_module of
72             L _ (HsModule mb_mod _ imps _ _ _ _ _) ->
73               let
74                 mod = mb_mod `orElse` L (srcLocSpan loc) mAIN_NAME
75                 (src_idecls, ord_idecls) = partition isSourceIdecl (map unLoc imps)
76                 source_imps   = map getImpMod src_idecls        
77                 ordinary_imps = filter ((/= moduleName gHC_PRIM) . unLoc) 
78                                         (map getImpMod ord_idecls)
79                      -- GHC.Prim doesn't exist physically, so don't go looking for it.
80               in
81               return (source_imps, ordinary_imps, mod)
82   
83 parseError span err = throwDyn $ mkPlainErrMsg span err
84
85 isSourceIdecl (ImportDecl _ s _ _ _) = s
86
87 getImpMod (ImportDecl located_mod _ _ _ _) = located_mod
88
89 --------------------------------------------------------------
90 -- Get options
91 --------------------------------------------------------------
92
93
94 getOptionsFromFile :: FilePath            -- input file
95                    -> IO [Located String] -- options, if any
96 getOptionsFromFile filename
97     = Control.Exception.bracket
98               (openBinaryFile filename ReadMode)
99               (hClose)
100               (\handle ->
101                    do buf <- hGetStringBufferBlock handle blockSize
102                       loop handle buf)
103     where blockSize = 1024
104           loop handle buf
105               | len buf == 0 = return []
106               | otherwise
107               = case getOptions' buf filename of
108                   (Nothing, opts) -> return opts
109                   (Just buf', opts) -> do nextBlock <- hGetStringBufferBlock handle blockSize
110                                           newBuf <- appendStringBuffers buf' nextBlock
111                                           if len newBuf == len buf
112                                              then return opts
113                                              else do opts' <- loop handle newBuf
114                                                      return (opts++opts')
115
116 getOptions :: StringBuffer -> FilePath -> [Located String]
117 getOptions buf filename
118     = case getOptions' buf filename of
119         (_,opts) -> opts
120
121 -- The token parser is written manually because Happy can't
122 -- return a partial result when it encounters a lexer error.
123 -- We want to extract options before the buffer is passed through
124 -- CPP, so we can't use the same trick as 'getImports'.
125 getOptions' :: StringBuffer         -- Input buffer
126             -> FilePath             -- Source file. Used for msgs only.
127             -> ( Maybe StringBuffer -- Just => we can use more input
128                , [Located String]   -- Options.
129                )
130 getOptions' buf filename
131     = parseToks (lexAll (pragState buf loc))
132     where loc  = mkSrcLoc (mkFastString filename) 1 0
133
134           getToken (buf,L _loc tok) = tok
135           getLoc (buf,L loc _tok) = loc
136           getBuf (buf,_tok) = buf
137           combine opts (flag, opts') = (flag, opts++opts')
138           add opt (flag, opts) = (flag, opt:opts)
139
140           parseToks (open:close:xs)
141               | IToptions_prag str <- getToken open
142               , ITclose_prag       <- getToken close
143               = map (L (getLoc open)) (words str) `combine`
144                 parseToks xs
145           parseToks (open:close:xs)
146               | ITinclude_prag str <- getToken open
147               , ITclose_prag       <- getToken close
148               = map (L (getLoc open)) ["-#include",removeSpaces str] `combine`
149                 parseToks xs
150           parseToks (open:xs)
151               | ITlanguage_prag <- getToken open
152               = parseLanguage xs
153           -- The last token before EOF could have been truncated.
154           -- We ignore it to be on the safe side.
155           parseToks [tok,eof]
156               | ITeof <- getToken eof
157               = (Just (getBuf tok),[])
158           parseToks (eof:_)
159               | ITeof <- getToken eof
160               = (Just (getBuf eof),[])
161           parseToks _ = (Nothing,[])
162           parseLanguage ((_buf,L loc (ITconid fs)):rest)
163               = checkExtension (L loc fs) `add`
164                 case rest of
165                   (_,L loc ITcomma):more -> parseLanguage more
166                   (_,L loc ITclose_prag):more -> parseToks more
167                   (_,L loc _):_ -> languagePragParseError loc
168           parseLanguage (tok:_)
169               = languagePragParseError (getLoc tok)
170           lexToken t = return t
171           lexAll state = case unP (lexer lexToken) state of
172                            POk state' t@(L _ ITeof) -> [(buffer state,t)]
173                            POk state' t -> (buffer state,t):lexAll state'
174                            _ -> [(buffer state,L (last_loc state) ITeof)]
175
176 checkExtension :: Located FastString -> Located String
177 checkExtension (L l ext)
178 -- Checks if a given extension is valid, and if so returns
179 -- its corresponding flag. Otherwise it throws an exception.
180  =  let ext' = unpackFS ext in
181     if ext' `elem` supportedLanguages
182        || ext' `elem` (map ("No"++) supportedLanguages)
183     then L l ("-X"++ext')
184     else unsupportedExtnError l ext'
185
186 languagePragParseError loc =
187   pgmError (showSDoc (mkLocMessage loc (
188                 text "cannot parse LANGUAGE pragma")))
189
190 unsupportedExtnError loc unsup =
191   pgmError (showSDoc (mkLocMessage loc (
192                 text "unsupported extension: " <>
193                 (text.show) unsup)))
194
195
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
204