913ac33a3326dda2c8479083bf29b65c23a00c9f
[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           ( 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 )
29 import ErrUtils
30 import Util
31 import Outputable
32 import Pretty           ()
33 import Panic
34 import Bag              ( unitBag, emptyBag, listToBag )
35
36 import Distribution.Compiler
37
38 import TRACE
39
40 import EXCEPTION        ( throwDyn )
41 import IO
42 import 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 Module], [Located Module], Located Module)
59 getImportsFromFile dflags filename = do
60   buf <- hGetStringBuffer filename
61   getImports dflags buf filename
62
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
69         POk _ rdr_module -> 
70           case rdr_module of
71             L _ (HsModule mod _ imps _ _) ->
72               let
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.
80               in
81               return (source_imps, ordinary_imps, mod_name)
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     = bracket (openBinaryFile filename ReadMode)
98               (hClose)
99               (\handle ->
100                    do buf <- hGetStringBufferBlock handle blockSize
101                       loop handle buf)
102     where blockSize = 1024
103           loop handle buf
104               | len buf == 0 = return []
105               | otherwise
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
111                                              then return opts
112                                              else do opts' <- loop handle newBuf
113                                                      return (opts++opts')
114
115 getOptions :: StringBuffer -> FilePath -> [Located String]
116 getOptions buf filename
117     = case getOptions' buf filename of
118         (_,opts) -> opts
119
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.
128                )
129 getOptions' buf filename
130     = parseToks (lexAll (pragState buf loc))
131     where loc  = mkSrcLoc (mkFastString filename) 1 0
132
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)
138
139           parseToks (open:close:xs)
140               | IToptions_prag str <- getToken open
141               , ITclose_prag       <- getToken close
142               = map (L (getLoc open)) (words str) `combine`
143                 parseToks xs
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`
148                 parseToks xs
149           parseToks (open:xs)
150               | ITlanguage_prag <- getToken open
151               = parseLanguage xs
152           -- The last token before EOF could have been truncated.
153           -- We ignore it to be on the safe side.
154           parseToks [tok,eof]
155               | ITeof <- getToken eof
156               = (Just (getBuf tok),[])
157           parseToks (eof:_)
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`
163                 case rest of
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)]
174
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
182
183 languagePragParseError loc =
184   pgmError (showSDoc (mkLocMessage loc (
185                 text "cannot parse LANGUAGE pragma")))
186
187 unsupportedExtnError loc unsup =
188   pgmError (showSDoc (mkLocMessage loc (
189                 text "unsupported extension: " <>
190                 (text.show) unsup)))
191
192
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
201