Generalise Package Support
[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 EXCEPTION        ( throwDyn )
39 import IO
40 import 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     = bracket (openBinaryFile filename ReadMode)
96               (hClose)
97               (\handle ->
98                    do buf <- hGetStringBufferBlock handle blockSize
99                       loop handle buf)
100     where blockSize = 1024
101           loop handle buf
102               | len buf == 0 = return []
103               | otherwise
104               = case getOptions' buf filename of
105                   (Nothing, opts) -> return opts
106                   (Just buf', opts) -> do nextBlock <- hGetStringBufferBlock handle blockSize
107                                           newBuf <- appendStringBuffers buf' nextBlock
108                                           if len newBuf == len buf
109                                              then return opts
110                                              else do opts' <- loop handle newBuf
111                                                      return (opts++opts')
112
113 getOptions :: StringBuffer -> FilePath -> [Located String]
114 getOptions buf filename
115     = case getOptions' buf filename of
116         (_,opts) -> opts
117
118 -- The token parser is written manually because Happy can't
119 -- return a partial result when it encounters a lexer error.
120 -- We want to extract options before the buffer is passed through
121 -- CPP, so we can't use the same trick as 'getImports'.
122 getOptions' :: StringBuffer         -- Input buffer
123             -> FilePath             -- Source file. Used for msgs only.
124             -> ( Maybe StringBuffer -- Just => we can use more input
125                , [Located String]   -- Options.
126                )
127 getOptions' buf filename
128     = parseToks (lexAll (pragState buf loc))
129     where loc  = mkSrcLoc (mkFastString filename) 1 0
130
131           getToken (buf,L _loc tok) = tok
132           getLoc (buf,L loc _tok) = loc
133           getBuf (buf,_tok) = buf
134           combine opts (flag, opts') = (flag, opts++opts')
135           add opt (flag, opts) = (flag, opt:opts)
136
137           parseToks (open:close:xs)
138               | IToptions_prag str <- getToken open
139               , ITclose_prag       <- getToken close
140               = map (L (getLoc open)) (words str) `combine`
141                 parseToks xs
142           parseToks (open:close:xs)
143               | ITinclude_prag str <- getToken open
144               , ITclose_prag       <- getToken close
145               = map (L (getLoc open)) ["-#include",removeSpaces str] `combine`
146                 parseToks xs
147           parseToks (open:xs)
148               | ITlanguage_prag <- getToken open
149               = parseLanguage xs
150           -- The last token before EOF could have been truncated.
151           -- We ignore it to be on the safe side.
152           parseToks [tok,eof]
153               | ITeof <- getToken eof
154               = (Just (getBuf tok),[])
155           parseToks (eof:_)
156               | ITeof <- getToken eof
157               = (Just (getBuf eof),[])
158           parseToks _ = (Nothing,[])
159           parseLanguage ((_buf,L loc (ITconid fs)):rest)
160               = checkExtension (L loc fs) `add`
161                 case rest of
162                   (_,L loc ITcomma):more -> parseLanguage more
163                   (_,L loc ITclose_prag):more -> parseToks more
164                   (_,L loc _):_ -> languagePragParseError loc
165           parseLanguage (tok:_)
166               = languagePragParseError (getLoc tok)
167           lexToken t = return t
168           lexAll state = case unP (lexer lexToken) state of
169                            POk state' t@(L _ ITeof) -> [(buffer state,t)]
170                            POk state' t -> (buffer state,t):lexAll state'
171                            _ -> [(buffer state,L (last_loc state) ITeof)]
172
173 checkExtension :: Located FastString -> Located String
174 checkExtension (L l ext)
175     = case reads (unpackFS ext) of
176         [] -> languagePragParseError l
177         (okExt,""):_ -> case extensionsToGHCFlag [okExt] of
178                           ([],[opt]) -> L l opt
179                           _ -> unsupportedExtnError l okExt
180
181 languagePragParseError loc =
182   pgmError (showSDoc (mkLocMessage loc (
183                 text "cannot parse LANGUAGE pragma")))
184
185 unsupportedExtnError loc unsup =
186   pgmError (showSDoc (mkLocMessage loc (
187                 text "unsupported extension: " <>
188                 (text.show) unsup)))
189
190
191 optionsErrorMsgs :: [String] -> [Located String] -> FilePath -> Messages
192 optionsErrorMsgs unhandled_flags flags_lines filename
193   = (emptyBag, listToBag (map mkMsg unhandled_flags_lines))
194   where unhandled_flags_lines = [ L l f | f <- unhandled_flags, 
195                                           L l f' <- flags_lines, f == f' ]
196         mkMsg (L flagSpan flag) = 
197             ErrUtils.mkPlainErrMsg flagSpan $
198                     text "unknown flag in  {-# OPTIONS #-} pragma:" <+> text flag
199