6.4 compatiblity
[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            ( P(..), ParseResult(..), mkPState, pragState
19                         , lexer, Token(..), PState(..) )
20 import FastString
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 )
26 import SrcLoc           ( Located(..), mkSrcLoc, unLoc, noSrcSpan )
27 import FastString       ( mkFastString )
28 import DynFlags ( DynFlags )
29 import ErrUtils
30 import Util
31 import Outputable
32 import Pretty           ()
33 import Panic
34 import Bag              ( emptyBag, listToBag )
35
36 import Distribution.Compiler
37
38 import Control.Exception
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 _ rdr_module -> 
68           case rdr_module of
69             L _ (HsModule mod _ imps _ _ _ _ _) ->
70               let
71                 mod_name | Just located_mod <- mod = located_mod
72                          | otherwise               = L noSrcSpan 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.
78               in
79               return (source_imps, ordinary_imps, mod_name)
80   
81 parseError span err = throwDyn $ mkPlainErrMsg span err
82
83 isSourceIdecl (ImportDecl _ s _ _ _) = s
84
85 getImpMod (ImportDecl located_mod _ _ _ _) = located_mod
86
87 --------------------------------------------------------------
88 -- Get options
89 --------------------------------------------------------------
90
91
92 getOptionsFromFile :: FilePath            -- input file
93                    -> IO [Located String] -- options, if any
94 getOptionsFromFile filename
95     = Control.Exception.bracket
96               (openBinaryFile filename ReadMode)
97               (hClose)
98               (\handle ->
99                    do buf <- hGetStringBufferBlock handle blockSize
100                       loop handle buf)
101     where blockSize = 1024
102           loop handle buf
103               | len buf == 0 = return []
104               | otherwise
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
110                                              then return opts
111                                              else do opts' <- loop handle newBuf
112                                                      return (opts++opts')
113
114 getOptions :: StringBuffer -> FilePath -> [Located String]
115 getOptions buf filename
116     = case getOptions' buf filename of
117         (_,opts) -> opts
118
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.
127                )
128 getOptions' buf filename
129     = parseToks (lexAll (pragState buf loc))
130     where loc  = mkSrcLoc (mkFastString filename) 1 0
131
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)
137
138           parseToks (open:close:xs)
139               | IToptions_prag str <- getToken open
140               , ITclose_prag       <- getToken close
141               = map (L (getLoc open)) (words str) `combine`
142                 parseToks xs
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`
147                 parseToks xs
148           parseToks (open:xs)
149               | ITlanguage_prag <- getToken open
150               = parseLanguage xs
151           -- The last token before EOF could have been truncated.
152           -- We ignore it to be on the safe side.
153           parseToks [tok,eof]
154               | ITeof <- getToken eof
155               = (Just (getBuf tok),[])
156           parseToks (eof:_)
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`
162                 case rest of
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)]
173
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
181
182 languagePragParseError loc =
183   pgmError (showSDoc (mkLocMessage loc (
184                 text "cannot parse LANGUAGE pragma")))
185
186 unsupportedExtnError loc unsup =
187   pgmError (showSDoc (mkLocMessage loc (
188                 text "unsupported extension: " <>
189                 (text.show) unsup)))
190
191
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
200