Follow Cabal changes
[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 Distribution.Compiler
37 import Distribution.Package
38 import Distribution.Version
39
40 import Control.Exception
41 import Control.Monad
42 import System.Exit
43 import System.IO
44 import Data.List
45
46 #if __GLASGOW_HASKELL__ >= 601
47 import System.IO                ( openBinaryFile )
48 #else
49 import IOExts                   ( openFileEx, IOModeEx(..) )
50 #endif
51
52 #if __GLASGOW_HASKELL__ < 601
53 openBinaryFile fp mode = openFileEx fp (BinaryMode mode)
54 #endif
55
56 -- getImportsFromFile is careful to close the file afterwards, otherwise
57 -- we can end up with a large number of open handles before the garbage
58 -- collector gets around to closing them.
59 getImportsFromFile :: DynFlags -> FilePath
60    -> IO ([Located ModuleName], [Located ModuleName], Located ModuleName)
61 getImportsFromFile dflags filename = do
62   buf <- hGetStringBuffer filename
63   getImports dflags buf filename
64
65 getImports :: DynFlags -> StringBuffer -> FilePath
66     -> IO ([Located ModuleName], [Located ModuleName], Located ModuleName)
67 getImports dflags buf filename = do
68   let loc  = mkSrcLoc (mkFastString filename) 1 0
69   case unP parseHeader (mkPState buf loc dflags) of
70         PFailed span err -> parseError span err
71         POk pst rdr_module -> do
72           let ms = getMessages pst
73           printErrorsAndWarnings dflags ms
74           when (errorsFound dflags ms) $ exitWith (ExitFailure 1)
75           case rdr_module of
76             L _ (HsModule mb_mod _ imps _ _ _ _ _) ->
77               let
78                 mod = mb_mod `orElse` L (srcLocSpan loc) mAIN_NAME
79                 (src_idecls, ord_idecls) = partition isSourceIdecl (map unLoc imps)
80                 source_imps   = map getImpMod src_idecls        
81                 ordinary_imps = filter ((/= moduleName gHC_PRIM) . unLoc) 
82                                         (map getImpMod ord_idecls)
83                      -- GHC.Prim doesn't exist physically, so don't go looking for it.
84               in
85               return (source_imps, ordinary_imps, mod)
86   
87 parseError span err = throwDyn $ mkPlainErrMsg span err
88
89 isSourceIdecl (ImportDecl _ s _ _ _) = s
90
91 getImpMod (ImportDecl located_mod _ _ _ _) = located_mod
92
93 --------------------------------------------------------------
94 -- Get options
95 --------------------------------------------------------------
96
97
98 getOptionsFromFile :: FilePath            -- input file
99                    -> IO [Located String] -- options, if any
100 getOptionsFromFile filename
101     = Control.Exception.bracket
102               (openBinaryFile filename ReadMode)
103               (hClose)
104               (\handle ->
105                    do buf <- hGetStringBufferBlock handle blockSize
106                       loop handle buf)
107     where blockSize = 1024
108           loop handle buf
109               | len buf == 0 = return []
110               | otherwise
111               = case getOptions' buf filename of
112                   (Nothing, opts) -> return opts
113                   (Just buf', opts) -> do nextBlock <- hGetStringBufferBlock handle blockSize
114                                           newBuf <- appendStringBuffers buf' nextBlock
115                                           if len newBuf == len buf
116                                              then return opts
117                                              else do opts' <- loop handle newBuf
118                                                      return (opts++opts')
119
120 getOptions :: StringBuffer -> FilePath -> [Located String]
121 getOptions buf filename
122     = case getOptions' buf filename of
123         (_,opts) -> opts
124
125 -- The token parser is written manually because Happy can't
126 -- return a partial result when it encounters a lexer error.
127 -- We want to extract options before the buffer is passed through
128 -- CPP, so we can't use the same trick as 'getImports'.
129 getOptions' :: StringBuffer         -- Input buffer
130             -> FilePath             -- Source file. Used for msgs only.
131             -> ( Maybe StringBuffer -- Just => we can use more input
132                , [Located String]   -- Options.
133                )
134 getOptions' buf filename
135     = parseToks (lexAll (pragState buf loc))
136     where loc  = mkSrcLoc (mkFastString filename) 1 0
137
138           getToken (buf,L _loc tok) = tok
139           getLoc (buf,L loc _tok) = loc
140           getBuf (buf,_tok) = buf
141           combine opts (flag, opts') = (flag, opts++opts')
142           add opt (flag, opts) = (flag, opt:opts)
143
144           parseToks (open:close:xs)
145               | IToptions_prag str <- getToken open
146               , ITclose_prag       <- getToken close
147               = map (L (getLoc open)) (words str) `combine`
148                 parseToks xs
149           parseToks (open:close:xs)
150               | ITinclude_prag str <- getToken open
151               , ITclose_prag       <- getToken close
152               = map (L (getLoc open)) ["-#include",removeSpaces str] `combine`
153                 parseToks xs
154           parseToks (open:xs)
155               | ITlanguage_prag <- getToken open
156               = parseLanguage xs
157           -- The last token before EOF could have been truncated.
158           -- We ignore it to be on the safe side.
159           parseToks [tok,eof]
160               | ITeof <- getToken eof
161               = (Just (getBuf tok),[])
162           parseToks (eof:_)
163               | ITeof <- getToken eof
164               = (Just (getBuf eof),[])
165           parseToks _ = (Nothing,[])
166           parseLanguage ((_buf,L loc (ITconid fs)):rest)
167               = checkExtension (L loc fs) `add`
168                 case rest of
169                   (_,L loc ITcomma):more -> parseLanguage more
170                   (_,L loc ITclose_prag):more -> parseToks more
171                   (_,L loc _):_ -> languagePragParseError loc
172           parseLanguage (tok:_)
173               = languagePragParseError (getLoc tok)
174           lexToken t = return t
175           lexAll state = case unP (lexer lexToken) state of
176                            POk state' t@(L _ ITeof) -> [(buffer state,t)]
177                            POk state' t -> (buffer state,t):lexAll state'
178                            _ -> [(buffer state,L (last_loc state) ITeof)]
179
180 thisCompiler :: Compiler
181 thisCompiler = Compiler {
182                    compilerFlavor = GHC,
183                    compilerId = PackageIdentifier {
184                                     pkgName = "ghc",
185                                     pkgVersion = v
186                                 },
187                    compilerProg = panic "No compiler program yet",
188                    compilerPkgTool = panic "No package program yet",
189                    compilerLanguagesKnown = True,
190                    compilerLanguages = supportedLanguages
191                }
192     where v = case readVersion cProjectVersion of
193                   Just version -> version
194                   Nothing ->
195                       panic ("Can't parse version: " ++ show cProjectVersion)
196
197 checkExtension :: Located FastString -> Located String
198 checkExtension (L l ext)
199  = case reads (unpackFS ext) of
200        [] -> languagePragParseError l
201        (okExt,""):_ ->
202            case extensionsToFlags thisCompiler [okExt] of
203                ([],[opt]) -> L l opt
204                _ -> unsupportedExtnError l okExt
205
206 languagePragParseError loc =
207   pgmError (showSDoc (mkLocMessage loc (
208                 text "cannot parse LANGUAGE pragma")))
209
210 unsupportedExtnError loc unsup =
211   pgmError (showSDoc (mkLocMessage loc (
212                 text "unsupported extension: " <>
213                 (text.show) unsup)))
214
215
216 optionsErrorMsgs :: [String] -> [Located String] -> FilePath -> Messages
217 optionsErrorMsgs unhandled_flags flags_lines filename
218   = (emptyBag, listToBag (map mkMsg unhandled_flags_lines))
219   where unhandled_flags_lines = [ L l f | f <- unhandled_flags, 
220                                           L l f' <- flags_lines, f == f' ]
221         mkMsg (L flagSpan flag) = 
222             ErrUtils.mkPlainErrMsg flagSpan $
223                     text "unknown flag in  {-# OPTIONS #-} pragma:" <+> text flag
224