Another round of External Core fixes
[ghc-hetmet.git] / compiler / main / HeaderInfo.hs
1 {-# OPTIONS -fno-warn-incomplete-patterns #-}
2 -- The above warning supression flag is a temporary kludge.
3 -- While working on this module you are encouraged to remove it and fix
4 -- any warnings in the module. See
5 --     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
6 -- for details
7
8 -----------------------------------------------------------------------------
9 --
10 -- Parsing the top of a Haskell source file to get its module name,
11 -- imports and options.
12 --
13 -- (c) Simon Marlow 2005
14 -- (c) Lemmih 2006
15 --
16 -----------------------------------------------------------------------------
17
18 module HeaderInfo ( getImports
19                   , getOptionsFromFile, getOptions
20                   , optionsErrorMsgs ) where
21
22 #include "HsVersions.h"
23
24 import Parser           ( parseHeader )
25 import Lexer
26 import FastString
27 import HsSyn            ( ImportDecl(..), HsModule(..) )
28 import Module           ( ModuleName, moduleName )
29 import PrelNames        ( gHC_PRIM, mAIN_NAME )
30 import StringBuffer     ( StringBuffer(..), hGetStringBufferBlock
31                         , appendStringBuffers )
32 import SrcLoc
33 import DynFlags
34 import ErrUtils
35 import Util
36 import Outputable
37 import Pretty           ()
38 import Panic
39 import Maybes
40 import Bag              ( emptyBag, listToBag )
41
42 import Control.Exception
43 import Control.Monad
44 import System.Exit
45 import System.IO
46 import Data.List
47
48 #if !defined(__GLASGOW_HASKELL__) || __GLASGOW_HASKELL__ >= 601
49   -- already imported above
50 --import System.IO              ( openBinaryFile )
51 #else
52 import IOExts                   ( openFileEx, IOModeEx(..) )
53 #endif
54
55 #if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ < 601
56 openBinaryFile fp mode = openFileEx fp (BinaryMode mode)
57 #endif
58
59 getImports :: DynFlags -> StringBuffer -> FilePath -> FilePath
60     -> IO ([Located ModuleName], [Located ModuleName], Located ModuleName)
61 getImports dflags buf filename source_filename = do
62   let loc  = mkSrcLoc (mkFastString filename) 1 0
63   case unP parseHeader (mkPState buf loc dflags) of
64         PFailed span err -> parseError span err
65         POk pst rdr_module -> do
66           let ms = getMessages pst
67           printErrorsAndWarnings dflags ms
68           when (errorsFound dflags ms) $ exitWith (ExitFailure 1)
69           case rdr_module of
70             L _ (HsModule mb_mod _ imps _ _ _ _) ->
71               let
72                 main_loc = mkSrcLoc (mkFastString source_filename) 1 0
73                 mod = mb_mod `orElse` L (srcLocSpan main_loc) mAIN_NAME
74                 (src_idecls, ord_idecls) = partition isSourceIdecl (map unLoc imps)
75                 source_imps   = map getImpMod src_idecls        
76                 ordinary_imps = filter ((/= moduleName gHC_PRIM) . unLoc) 
77                                         (map getImpMod ord_idecls)
78                      -- GHC.Prim doesn't exist physically, so don't go looking for it.
79               in
80               return (source_imps, ordinary_imps, mod)
81   
82 parseError :: SrcSpan -> Message -> a
83 parseError span err = throwDyn $ mkPlainErrMsg span err
84
85 isSourceIdecl :: ImportDecl name -> Bool
86 isSourceIdecl (ImportDecl _ s _ _ _) = s
87
88 getImpMod :: ImportDecl name -> Located ModuleName
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:close:xs)
153               | ITdocOptions str <- getToken open
154               , ITclose_prag     <- getToken close
155               = map (L (getLoc open)) ["-haddock-opts", removeSpaces str]
156                 `combine` parseToks xs
157           parseToks (open:xs)
158               | ITdocOptionsOld str <- getToken open
159               = map (L (getLoc open)) ["-haddock-opts", removeSpaces str]
160                 `combine` parseToks xs
161           parseToks (open:xs)
162               | ITlanguage_prag <- getToken open
163               = parseLanguage xs
164           -- The last token before EOF could have been truncated.
165           -- We ignore it to be on the safe side.
166           parseToks [tok,eof]
167               | ITeof <- getToken eof
168               = (Just (getBuf tok),[])
169           parseToks (eof:_)
170               | ITeof <- getToken eof
171               = (Just (getBuf eof),[])
172           parseToks _ = (Nothing,[])
173           parseLanguage ((_buf,L loc (ITconid fs)):rest)
174               = checkExtension (L loc fs) `add`
175                 case rest of
176                   (_,L _loc ITcomma):more -> parseLanguage more
177                   (_,L _loc ITclose_prag):more -> parseToks more
178                   (_,L loc _):_ -> languagePragParseError loc
179           parseLanguage (tok:_)
180               = languagePragParseError (getLoc tok)
181           lexToken t = return t
182           lexAll state = case unP (lexer lexToken) state of
183                            POk _      t@(L _ ITeof) -> [(buffer state,t)]
184                            POk state' t -> (buffer state,t):lexAll state'
185                            _ -> [(buffer state,L (last_loc state) ITeof)]
186
187 checkExtension :: Located FastString -> Located String
188 checkExtension (L l ext)
189 -- Checks if a given extension is valid, and if so returns
190 -- its corresponding flag. Otherwise it throws an exception.
191  =  let ext' = unpackFS ext in
192     if ext' `elem` supportedLanguages
193        || ext' `elem` (map ("No"++) supportedLanguages)
194     then L l ("-X"++ext')
195     else unsupportedExtnError l ext'
196
197 languagePragParseError :: SrcSpan -> a
198 languagePragParseError loc =
199   pgmError 
200    (showSDoc (mkLocMessage loc (
201      text "cannot parse LANGUAGE pragma: comma-separated list expected")))
202
203 unsupportedExtnError :: SrcSpan -> String -> a
204 unsupportedExtnError loc unsup =
205   pgmError (showSDoc (mkLocMessage loc (
206                 text "unsupported extension: " <>
207                 text unsup)))
208
209
210 optionsErrorMsgs :: [String] -> [Located String] -> FilePath -> Messages
211 optionsErrorMsgs unhandled_flags flags_lines _filename
212   = (emptyBag, listToBag (map mkMsg unhandled_flags_lines))
213   where unhandled_flags_lines = [ L l f | f <- unhandled_flags, 
214                                           L l f' <- flags_lines, f == f' ]
215         mkMsg (L flagSpan flag) = 
216             ErrUtils.mkPlainErrMsg flagSpan $
217                     text "unknown flag in  {-# OPTIONS #-} pragma:" <+> text flag
218