fix #2636: throw missing module errors as SourceErrors, not ErrMsg
[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,
21                     checkProcessArgsResult ) where
22
23 #include "HsVersions.h"
24
25 import HscTypes
26 import Parser           ( parseHeader )
27 import Lexer
28 import FastString
29 import HsSyn            ( ImportDecl(..), HsModule(..) )
30 import Module           ( ModuleName, moduleName )
31 import PrelNames        ( gHC_PRIM, mAIN_NAME )
32 import StringBuffer     ( StringBuffer(..), hGetStringBufferBlock
33                         , appendStringBuffers )
34 import SrcLoc
35 import DynFlags
36 import ErrUtils
37 import Util
38 import Outputable
39 import Pretty           ()
40 import Panic
41 import Maybes
42 import Bag              ( emptyBag, listToBag )
43
44 import Exception
45 import Control.Monad
46 import System.Exit
47 import System.IO
48 import Data.List
49
50 getImports :: DynFlags -> StringBuffer -> FilePath -> FilePath
51     -> IO ([Located ModuleName], [Located ModuleName], Located ModuleName)
52 getImports dflags buf filename source_filename = do
53   let loc  = mkSrcLoc (mkFastString filename) 1 0
54   case unP parseHeader (mkPState buf loc dflags) of
55         PFailed span err -> parseError span err
56         POk pst rdr_module -> do
57           let ms = getMessages pst
58           printErrorsAndWarnings dflags ms
59           when (errorsFound dflags ms) $ exitWith (ExitFailure 1)
60           case rdr_module of
61             L _ (HsModule mb_mod _ imps _ _ _ _) ->
62               let
63                 main_loc = mkSrcLoc (mkFastString source_filename) 1 0
64                 mod = mb_mod `orElse` L (srcLocSpan main_loc) mAIN_NAME
65                 imps' = filter isHomeImp (map unLoc imps)
66                 (src_idecls, ord_idecls) = partition isSourceIdecl imps'
67                 source_imps   = map getImpMod src_idecls
68                 ordinary_imps = filter ((/= moduleName gHC_PRIM) . unLoc) 
69                                         (map getImpMod ord_idecls)
70                      -- GHC.Prim doesn't exist physically, so don't go looking for it.
71               in
72               return (source_imps, ordinary_imps, mod)
73   
74 parseError :: SrcSpan -> Message -> IO a
75 parseError span err = throwOneError $ mkPlainErrMsg span err
76
77 -- we aren't interested in package imports here, filter them out
78 isHomeImp :: ImportDecl name -> Bool
79 isHomeImp (ImportDecl _ (Just p) _ _ _ _) = p == fsLit "this"
80 isHomeImp (ImportDecl _ Nothing  _ _ _ _) = True
81
82 isSourceIdecl :: ImportDecl name -> Bool
83 isSourceIdecl (ImportDecl _ _ s _ _ _) = s
84
85 getImpMod :: ImportDecl name -> Located ModuleName
86 getImpMod (ImportDecl located_mod _ _ _ _ _) = located_mod
87
88 --------------------------------------------------------------
89 -- Get options
90 --------------------------------------------------------------
91
92
93 getOptionsFromFile :: DynFlags
94                    -> FilePath            -- input file
95                    -> IO [Located String] -- options, if any
96 getOptionsFromFile dflags filename
97     = Exception.bracket
98               (openBinaryFile filename ReadMode)
99               (hClose)
100               (\handle ->
101                    do buf <- hGetStringBufferBlock handle blockSize
102                       loop handle buf)
103     where blockSize = 1024
104           loop handle buf
105               | len buf == 0 = return []
106               | otherwise
107               = case getOptions' dflags buf filename of
108                   (Nothing, opts) -> return opts
109                   (Just buf', opts) -> do nextBlock <- hGetStringBufferBlock handle blockSize
110                                           newBuf <- appendStringBuffers buf' nextBlock
111                                           if len newBuf == len buf
112                                              then return opts
113                                              else do opts' <- loop handle newBuf
114                                                      return (opts++opts')
115
116 getOptions :: DynFlags -> StringBuffer -> FilePath -> [Located String]
117 getOptions dflags buf filename
118     = case getOptions' dflags buf filename of
119         (_,opts) -> opts
120
121 -- The token parser is written manually because Happy can't
122 -- return a partial result when it encounters a lexer error.
123 -- We want to extract options before the buffer is passed through
124 -- CPP, so we can't use the same trick as 'getImports'.
125 getOptions' :: DynFlags
126             -> StringBuffer         -- Input buffer
127             -> FilePath             -- Source file. Used for msgs only.
128             -> ( Maybe StringBuffer -- Just => we can use more input
129                , [Located String]   -- Options.
130                )
131 getOptions' dflags buf filename
132     = parseToks (lexAll (pragState dflags buf loc))
133     where loc  = mkSrcLoc (mkFastString filename) 1 0
134
135           getToken (_buf,L _loc tok) = tok
136           getLoc (_buf,L loc _tok) = loc
137           getBuf (buf,_tok) = buf
138           combine opts (flag, opts') = (flag, opts++opts')
139           add opt (flag, opts) = (flag, opt:opts)
140
141           parseToks (open:close:xs)
142               | IToptions_prag str <- getToken open
143               , ITclose_prag       <- getToken close
144               = map (L (getLoc open)) (words str) `combine`
145                 parseToks xs
146           parseToks (open:close:xs)
147               | ITinclude_prag str <- getToken open
148               , ITclose_prag       <- getToken close
149               = map (L (getLoc open)) ["-#include",removeSpaces str] `combine`
150                 parseToks xs
151           parseToks (open:close:xs)
152               | ITdocOptions str <- getToken open
153               , ITclose_prag     <- getToken close
154               = map (L (getLoc open)) ["-haddock-opts", removeSpaces str]
155                 `combine` parseToks xs
156           parseToks (open:xs)
157               | ITdocOptionsOld str <- getToken open
158               = map (L (getLoc open)) ["-haddock-opts", removeSpaces str]
159                 `combine` parseToks xs
160           parseToks (open:xs)
161               | ITlanguage_prag <- getToken open
162               = parseLanguage xs
163           -- The last token before EOF could have been truncated.
164           -- We ignore it to be on the safe side.
165           parseToks [tok,eof]
166               | ITeof <- getToken eof
167               = (Just (getBuf tok),[])
168           parseToks (eof:_)
169               | ITeof <- getToken eof
170               = (Just (getBuf eof),[])
171           parseToks _ = (Nothing,[])
172           parseLanguage ((_buf,L loc (ITconid fs)):rest)
173               = checkExtension (L loc fs) `add`
174                 case rest of
175                   (_,L _loc ITcomma):more -> parseLanguage more
176                   (_,L _loc ITclose_prag):more -> parseToks more
177                   (_,L loc _):_ -> languagePragParseError loc
178           parseLanguage (tok:_)
179               = languagePragParseError (getLoc tok)
180           lexToken t = return t
181           lexAll state = case unP (lexer lexToken) state of
182                            POk _      t@(L _ ITeof) -> [(buffer state,t)]
183                            POk state' t -> (buffer state,t):lexAll state'
184                            _ -> [(buffer state,L (last_loc state) ITeof)]
185
186 -----------------------------------------------------------------------------
187 -- Complain about non-dynamic flags in OPTIONS pragmas
188
189 checkProcessArgsResult :: [Located String] -> IO ()
190 checkProcessArgsResult flags
191   = when (notNull flags) $
192         ghcError $ ProgramError $ showSDoc $ vcat $ map f flags
193     where f (L loc flag)
194               = hang (ppr loc <> char ':') 4
195                      (text "unknown flag in  {-# OPTIONS #-} pragma:" <+>
196                       text flag)
197
198 -----------------------------------------------------------------------------
199
200 checkExtension :: Located FastString -> Located String
201 checkExtension (L l ext)
202 -- Checks if a given extension is valid, and if so returns
203 -- its corresponding flag. Otherwise it throws an exception.
204  =  let ext' = unpackFS ext in
205     if ext' `elem` supportedLanguages
206        || ext' `elem` (map ("No"++) supportedLanguages)
207     then L l ("-X"++ext')
208     else unsupportedExtnError l ext'
209
210 languagePragParseError :: SrcSpan -> a
211 languagePragParseError loc =
212   pgmError 
213    (showSDoc (mkLocMessage loc (
214      text "cannot parse LANGUAGE pragma: comma-separated list expected")))
215
216 unsupportedExtnError :: SrcSpan -> String -> a
217 unsupportedExtnError loc unsup =
218   pgmError (showSDoc (mkLocMessage loc (
219                 text "unsupported extension: " <>
220                 text unsup)))
221
222
223 optionsErrorMsgs :: [String] -> [Located String] -> FilePath -> Messages
224 optionsErrorMsgs unhandled_flags flags_lines _filename
225   = (emptyBag, listToBag (map mkMsg unhandled_flags_lines))
226   where unhandled_flags_lines = [ L l f | f <- unhandled_flags, 
227                                           L l f' <- flags_lines, f == f' ]
228         mkMsg (L flagSpan flag) = 
229             ErrUtils.mkPlainErrMsg flagSpan $
230                     text "unknown flag in  {-# OPTIONS #-} pragma:" <+> text flag
231