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