7142645435a97b89dc767169cd6740cb7792757a
[ghc-hetmet.git] / compiler / main / HeaderInfo.hs
1 {-# OPTIONS -w #-}
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(..), hGetStringBuffer, hGetStringBufferBlock
31                         , appendStringBuffers )
32 import Config
33 import SrcLoc
34 import DynFlags
35 import ErrUtils
36 import Util
37 import Outputable
38 import Pretty           ()
39 import Panic
40 import Maybes
41 import Bag              ( emptyBag, listToBag )
42
43 import Control.Exception
44 import Control.Monad
45 import System.Exit
46 import System.IO
47 import Data.List
48
49 #if __GLASGOW_HASKELL__ >= 601
50 import System.IO                ( openBinaryFile )
51 #else
52 import IOExts                   ( openFileEx, IOModeEx(..) )
53 #endif
54
55 #if __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 span err = throwDyn $ mkPlainErrMsg span err
83
84 isSourceIdecl (ImportDecl _ s _ _ _) = s
85
86 getImpMod (ImportDecl located_mod _ _ _ _) = located_mod
87
88 --------------------------------------------------------------
89 -- Get options
90 --------------------------------------------------------------
91
92
93 getOptionsFromFile :: FilePath            -- input file
94                    -> IO [Located String] -- options, if any
95 getOptionsFromFile filename
96     = Control.Exception.bracket
97               (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:close:xs)
150               | ITdocOptions str <- getToken open
151               , ITclose_prag     <- getToken close
152               = map (L (getLoc open)) ["-haddock-opts", removeSpaces str]
153                 `combine` parseToks xs
154           parseToks (open:xs)
155               | ITdocOptionsOld str <- getToken open
156               = map (L (getLoc open)) ["-haddock-opts", removeSpaces str]
157                 `combine` parseToks xs
158           parseToks (open:xs)
159               | ITlanguage_prag <- getToken open
160               = parseLanguage xs
161           -- The last token before EOF could have been truncated.
162           -- We ignore it to be on the safe side.
163           parseToks [tok,eof]
164               | ITeof <- getToken eof
165               = (Just (getBuf tok),[])
166           parseToks (eof:_)
167               | ITeof <- getToken eof
168               = (Just (getBuf eof),[])
169           parseToks _ = (Nothing,[])
170           parseLanguage ((_buf,L loc (ITconid fs)):rest)
171               = checkExtension (L loc fs) `add`
172                 case rest of
173                   (_,L loc ITcomma):more -> parseLanguage more
174                   (_,L loc ITclose_prag):more -> parseToks more
175                   (_,L loc _):_ -> languagePragParseError loc
176           parseLanguage (tok:_)
177               = languagePragParseError (getLoc tok)
178           lexToken t = return t
179           lexAll state = case unP (lexer lexToken) state of
180                            POk state' t@(L _ ITeof) -> [(buffer state,t)]
181                            POk state' t -> (buffer state,t):lexAll state'
182                            _ -> [(buffer state,L (last_loc state) ITeof)]
183
184 checkExtension :: Located FastString -> Located String
185 checkExtension (L l ext)
186 -- Checks if a given extension is valid, and if so returns
187 -- its corresponding flag. Otherwise it throws an exception.
188  =  let ext' = unpackFS ext in
189     if ext' `elem` supportedLanguages
190        || ext' `elem` (map ("No"++) supportedLanguages)
191     then L l ("-X"++ext')
192     else unsupportedExtnError l ext'
193
194 languagePragParseError loc =
195   pgmError (showSDoc (mkLocMessage loc (
196                 text "cannot parse LANGUAGE pragma")))
197
198 unsupportedExtnError loc unsup =
199   pgmError (showSDoc (mkLocMessage loc (
200                 text "unsupported extension: " <>
201                 text unsup)))
202
203
204 optionsErrorMsgs :: [String] -> [Located String] -> FilePath -> Messages
205 optionsErrorMsgs unhandled_flags flags_lines filename
206   = (emptyBag, listToBag (map mkMsg unhandled_flags_lines))
207   where unhandled_flags_lines = [ L l f | f <- unhandled_flags, 
208                                           L l f' <- flags_lines, f == f' ]
209         mkMsg (L flagSpan flag) = 
210             ErrUtils.mkPlainErrMsg flagSpan $
211                     text "unknown flag in  {-# OPTIONS #-} pragma:" <+> text flag
212