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