We now need to pass a version to extensionsToGHCFlag
[ghc-hetmet.git] / compiler / main / HeaderInfo.hs
1 -----------------------------------------------------------------------------
2 --
3 -- Parsing the top of a Haskell source file to get its module name,
4 -- imports and options.
5 --
6 -- (c) Simon Marlow 2005
7 -- (c) Lemmih 2006
8 --
9 -----------------------------------------------------------------------------
10
11 module HeaderInfo ( getImportsFromFile, getImports
12                   , getOptionsFromFile, getOptions
13                   , optionsErrorMsgs ) where
14
15 #include "HsVersions.h"
16
17 import Parser           ( parseHeader )
18 import Lexer
19 import FastString
20 import HsSyn            ( ImportDecl(..), HsModule(..) )
21 import Module           ( ModuleName, moduleName )
22 import PrelNames        ( gHC_PRIM, mAIN_NAME )
23 import StringBuffer     ( StringBuffer(..), hGetStringBuffer, hGetStringBufferBlock
24                         , appendStringBuffers )
25 import Config
26 import SrcLoc
27 import DynFlags
28 import ErrUtils
29 import Util
30 import Outputable
31 import Pretty           ()
32 import Panic
33 import Maybes
34 import Bag              ( emptyBag, listToBag )
35
36 import Distribution.Compiler
37 import Distribution.Version
38
39 import Control.Exception
40 import Control.Monad
41 import System.Exit
42 import System.IO
43 import Data.List
44
45 #if __GLASGOW_HASKELL__ >= 601
46 import System.IO                ( openBinaryFile )
47 #else
48 import IOExts                   ( openFileEx, IOModeEx(..) )
49 #endif
50
51 #if __GLASGOW_HASKELL__ < 601
52 openBinaryFile fp mode = openFileEx fp (BinaryMode mode)
53 #endif
54
55 -- getImportsFromFile is careful to close the file afterwards, otherwise
56 -- we can end up with a large number of open handles before the garbage
57 -- collector gets around to closing them.
58 getImportsFromFile :: DynFlags -> FilePath
59    -> IO ([Located ModuleName], [Located ModuleName], Located ModuleName)
60 getImportsFromFile dflags filename = do
61   buf <- hGetStringBuffer filename
62   getImports dflags buf filename
63
64 getImports :: DynFlags -> StringBuffer -> FilePath
65     -> IO ([Located ModuleName], [Located ModuleName], Located ModuleName)
66 getImports dflags buf filename = do
67   let loc  = mkSrcLoc (mkFastString filename) 1 0
68   case unP parseHeader (mkPState buf loc dflags) of
69         PFailed span err -> parseError span err
70         POk pst rdr_module -> do
71           let ms = getMessages pst
72           printErrorsAndWarnings dflags ms
73           when (errorsFound dflags ms) $ exitWith (ExitFailure 1)
74           case rdr_module of
75             L _ (HsModule mb_mod _ imps _ _ _ _ _) ->
76               let
77                 mod = mb_mod `orElse` L (srcLocSpan loc) mAIN_NAME
78                 (src_idecls, ord_idecls) = partition isSourceIdecl (map unLoc imps)
79                 source_imps   = map getImpMod src_idecls        
80                 ordinary_imps = filter ((/= moduleName gHC_PRIM) . unLoc) 
81                                         (map getImpMod ord_idecls)
82                      -- GHC.Prim doesn't exist physically, so don't go looking for it.
83               in
84               return (source_imps, ordinary_imps, mod)
85   
86 parseError span err = throwDyn $ mkPlainErrMsg span err
87
88 isSourceIdecl (ImportDecl _ s _ _ _) = s
89
90 getImpMod (ImportDecl located_mod _ _ _ _) = located_mod
91
92 --------------------------------------------------------------
93 -- Get options
94 --------------------------------------------------------------
95
96
97 getOptionsFromFile :: FilePath            -- input file
98                    -> IO [Located String] -- options, if any
99 getOptionsFromFile 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' 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 :: StringBuffer -> FilePath -> [Located String]
120 getOptions buf filename
121     = case getOptions' 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' :: StringBuffer         -- Input buffer
129             -> FilePath             -- Source file. Used for msgs only.
130             -> ( Maybe StringBuffer -- Just => we can use more input
131                , [Located String]   -- Options.
132                )
133 getOptions' buf filename
134     = parseToks (lexAll (pragState buf loc))
135     where loc  = mkSrcLoc (mkFastString filename) 1 0
136
137           getToken (buf,L _loc tok) = tok
138           getLoc (buf,L loc _tok) = loc
139           getBuf (buf,_tok) = buf
140           combine opts (flag, opts') = (flag, opts++opts')
141           add opt (flag, opts) = (flag, opt:opts)
142
143           parseToks (open:close:xs)
144               | IToptions_prag str <- getToken open
145               , ITclose_prag       <- getToken close
146               = map (L (getLoc open)) (words str) `combine`
147                 parseToks xs
148           parseToks (open:close:xs)
149               | ITinclude_prag str <- getToken open
150               , ITclose_prag       <- getToken close
151               = map (L (getLoc open)) ["-#include",removeSpaces str] `combine`
152                 parseToks xs
153           parseToks (open:xs)
154               | ITlanguage_prag <- getToken open
155               = parseLanguage xs
156           -- The last token before EOF could have been truncated.
157           -- We ignore it to be on the safe side.
158           parseToks [tok,eof]
159               | ITeof <- getToken eof
160               = (Just (getBuf tok),[])
161           parseToks (eof:_)
162               | ITeof <- getToken eof
163               = (Just (getBuf eof),[])
164           parseToks _ = (Nothing,[])
165           parseLanguage ((_buf,L loc (ITconid fs)):rest)
166               = checkExtension (L loc fs) `add`
167                 case rest of
168                   (_,L loc ITcomma):more -> parseLanguage more
169                   (_,L loc ITclose_prag):more -> parseToks more
170                   (_,L loc _):_ -> languagePragParseError loc
171           parseLanguage (tok:_)
172               = languagePragParseError (getLoc tok)
173           lexToken t = return t
174           lexAll state = case unP (lexer lexToken) state of
175                            POk state' t@(L _ ITeof) -> [(buffer state,t)]
176                            POk state' t -> (buffer state,t):lexAll state'
177                            _ -> [(buffer state,L (last_loc state) ITeof)]
178
179 checkExtension :: Located FastString -> Located String
180 checkExtension (L l ext)
181  = case reads (unpackFS ext) of
182        [] -> languagePragParseError l
183        (okExt,""):_ ->
184            case readVersion cProjectVersion of
185                Just version ->
186                    case extensionsToGHCFlag version [okExt] of
187                        ([],[opt]) -> L l opt
188                        _ -> unsupportedExtnError l okExt
189                Nothing ->
190                    panic ("Can't parse version: " ++ show cProjectVersion)
191
192 languagePragParseError loc =
193   pgmError (showSDoc (mkLocMessage loc (
194                 text "cannot parse LANGUAGE pragma")))
195
196 unsupportedExtnError loc unsup =
197   pgmError (showSDoc (mkLocMessage loc (
198                 text "unsupported extension: " <>
199                 (text.show) unsup)))
200
201
202 optionsErrorMsgs :: [String] -> [Located String] -> FilePath -> Messages
203 optionsErrorMsgs unhandled_flags flags_lines filename
204   = (emptyBag, listToBag (map mkMsg unhandled_flags_lines))
205   where unhandled_flags_lines = [ L l f | f <- unhandled_flags, 
206                                           L l f' <- flags_lines, f == f' ]
207         mkMsg (L flagSpan flag) = 
208             ErrUtils.mkPlainErrMsg flagSpan $
209                     text "unknown flag in  {-# OPTIONS #-} pragma:" <+> text flag
210