e124e3755b387ab4b9f6d5cbdf624ecc5eea76ab
[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 SrcLoc
26 import FastString       ( mkFastString )
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
38 import Control.Exception
39 import Control.Monad
40 import System.Exit
41 import System.IO
42 import Data.List
43
44 #if __GLASGOW_HASKELL__ >= 601
45 import System.IO                ( openBinaryFile )
46 #else
47 import IOExts                   ( openFileEx, IOModeEx(..) )
48 #endif
49
50 #if __GLASGOW_HASKELL__ < 601
51 openBinaryFile fp mode = openFileEx fp (BinaryMode mode)
52 #endif
53
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 ModuleName], [Located ModuleName], Located ModuleName)
59 getImportsFromFile dflags filename = do
60   buf <- hGetStringBuffer filename
61   getImports dflags buf filename
62
63 getImports :: DynFlags -> StringBuffer -> FilePath
64     -> IO ([Located ModuleName], [Located ModuleName], Located ModuleName)
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
69         POk pst rdr_module -> do
70           let ms = getMessages pst
71           printErrorsAndWarnings dflags ms
72           when (errorsFound dflags ms) $ exitWith (ExitFailure 1)
73           case rdr_module of
74             L _ (HsModule mb_mod _ imps _ _ _ _ _) ->
75               let
76                 mod = mb_mod `orElse` L (srcLocSpan loc) mAIN_NAME
77                 (src_idecls, ord_idecls) = partition isSourceIdecl (map unLoc imps)
78                 source_imps   = map getImpMod src_idecls        
79                 ordinary_imps = filter ((/= moduleName gHC_PRIM) . unLoc) 
80                                         (map getImpMod ord_idecls)
81                      -- GHC.Prim doesn't exist physically, so don't go looking for it.
82               in
83               return (source_imps, ordinary_imps, mod)
84   
85 parseError span err = throwDyn $ mkPlainErrMsg span err
86
87 isSourceIdecl (ImportDecl _ s _ _ _) = s
88
89 getImpMod (ImportDecl located_mod _ _ _ _) = located_mod
90
91 --------------------------------------------------------------
92 -- Get options
93 --------------------------------------------------------------
94
95
96 getOptionsFromFile :: FilePath            -- input file
97                    -> IO [Located String] -- options, if any
98 getOptionsFromFile filename
99     = Control.Exception.bracket
100               (openBinaryFile filename ReadMode)
101               (hClose)
102               (\handle ->
103                    do buf <- hGetStringBufferBlock handle blockSize
104                       loop handle buf)
105     where blockSize = 1024
106           loop handle buf
107               | len buf == 0 = return []
108               | otherwise
109               = case getOptions' buf filename of
110                   (Nothing, opts) -> return opts
111                   (Just buf', opts) -> do nextBlock <- hGetStringBufferBlock handle blockSize
112                                           newBuf <- appendStringBuffers buf' nextBlock
113                                           if len newBuf == len buf
114                                              then return opts
115                                              else do opts' <- loop handle newBuf
116                                                      return (opts++opts')
117
118 getOptions :: StringBuffer -> FilePath -> [Located String]
119 getOptions buf filename
120     = case getOptions' buf filename of
121         (_,opts) -> opts
122
123 -- The token parser is written manually because Happy can't
124 -- return a partial result when it encounters a lexer error.
125 -- We want to extract options before the buffer is passed through
126 -- CPP, so we can't use the same trick as 'getImports'.
127 getOptions' :: StringBuffer         -- Input buffer
128             -> FilePath             -- Source file. Used for msgs only.
129             -> ( Maybe StringBuffer -- Just => we can use more input
130                , [Located String]   -- Options.
131                )
132 getOptions' buf filename
133     = parseToks (lexAll (pragState buf loc))
134     where loc  = mkSrcLoc (mkFastString filename) 1 0
135
136           getToken (buf,L _loc tok) = tok
137           getLoc (buf,L loc _tok) = loc
138           getBuf (buf,_tok) = buf
139           combine opts (flag, opts') = (flag, opts++opts')
140           add opt (flag, opts) = (flag, opt:opts)
141
142           parseToks (open:close:xs)
143               | IToptions_prag str <- getToken open
144               , ITclose_prag       <- getToken close
145               = map (L (getLoc open)) (words str) `combine`
146                 parseToks xs
147           parseToks (open:close:xs)
148               | ITinclude_prag str <- getToken open
149               , ITclose_prag       <- getToken close
150               = map (L (getLoc open)) ["-#include",removeSpaces str] `combine`
151                 parseToks xs
152           parseToks (open:xs)
153               | ITlanguage_prag <- getToken open
154               = parseLanguage xs
155           -- The last token before EOF could have been truncated.
156           -- We ignore it to be on the safe side.
157           parseToks [tok,eof]
158               | ITeof <- getToken eof
159               = (Just (getBuf tok),[])
160           parseToks (eof:_)
161               | ITeof <- getToken eof
162               = (Just (getBuf eof),[])
163           parseToks _ = (Nothing,[])
164           parseLanguage ((_buf,L loc (ITconid fs)):rest)
165               = checkExtension (L loc fs) `add`
166                 case rest of
167                   (_,L loc ITcomma):more -> parseLanguage more
168                   (_,L loc ITclose_prag):more -> parseToks more
169                   (_,L loc _):_ -> languagePragParseError loc
170           parseLanguage (tok:_)
171               = languagePragParseError (getLoc tok)
172           lexToken t = return t
173           lexAll state = case unP (lexer lexToken) state of
174                            POk state' t@(L _ ITeof) -> [(buffer state,t)]
175                            POk state' t -> (buffer state,t):lexAll state'
176                            _ -> [(buffer state,L (last_loc state) ITeof)]
177
178 checkExtension :: Located FastString -> Located String
179 checkExtension (L l ext)
180     = case reads (unpackFS ext) of
181         [] -> languagePragParseError l
182         (okExt,""):_ -> case extensionsToGHCFlag [okExt] of
183                           ([],[opt]) -> L l opt
184                           _ -> unsupportedExtnError l okExt
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