[project @ 1997-05-19 00:12:10 by sof]
[ghc-hetmet.git] / ghc / compiler / rename / RnMonad.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1997
3 %
4 \section[RnMonad]{The monad used by the renamer}
5
6 \begin{code}
7 #include "HsVersions.h"
8
9 module RnMonad(
10         EXP_MODULE(RnMonad),
11          -- close it up (partly done to allow unfoldings)
12         EXP_MODULE(SST),
13         SYN_IE(Module),
14         FiniteMap,
15         Bag,
16         Name,
17         SYN_IE(RdrNameHsDecl),
18         SYN_IE(RdrNameInstDecl),
19         SYN_IE(Version),
20         SYN_IE(NameSet),
21         OccName,
22         Fixity
23     ) where
24
25 IMP_Ubiq(){-uitous-}
26
27 import SST
28 #if __GLASGOW_HASKELL__ <= 201
29 import PreludeGlaST     ( SYN_IE(ST), thenStrictlyST, returnStrictlyST )
30 #define MkIO
31 #else
32 import GlaExts
33 import IO
34 import ST
35 import IOBase
36 #define IOError13 IOError
37 #define MkIO IO
38 #endif
39
40 import HsSyn            
41 import RdrHsSyn
42 import ErrUtils         ( addErrLoc, addShortErrLocLine, addShortWarnLocLine,
43                           pprBagOfErrors, SYN_IE(Error), SYN_IE(Warning)
44                         )
45 import Name             ( SYN_IE(Module), Name, OccName, Provenance, SYN_IE(NameSet), emptyNameSet,
46                           isLocallyDefinedName,
47                           modAndOcc, NamedThing(..)
48                         )
49 import CmdLineOpts      ( opt_D_show_rn_trace, opt_IgnoreIfacePragmas )
50 import PrelInfo         ( builtinNames )
51 import TyCon            ( TyCon {- instance NamedThing -} )
52 import TysWiredIn       ( boolTyCon )
53 import Pretty
54 import PprStyle         ( PprStyle(..) )
55 import SrcLoc           ( SrcLoc, mkGeneratedSrcLoc )
56 import Unique           ( Unique )
57 import FiniteMap        ( FiniteMap, emptyFM, bagToFM )
58 import Bag              ( Bag, mapBag, emptyBag, isEmptyBag, snocBag )
59 import UniqSet
60 import Util
61 #if __GLASGOW_HASKELL__ >= 202
62 import UniqSupply
63 #endif
64
65 infixr 9 `thenRn`, `thenRn_`
66 \end{code}
67
68
69 %************************************************************************
70 %*                                                                      *
71 \subsection{Somewhat magical interface to other monads}
72 %*                                                                      *
73 %************************************************************************
74
75 \begin{code}
76 #if __GLASGOW_HASKELL__ >= 200
77 # define REAL_WORLD RealWorld
78 #else
79 # define REAL_WORLD _RealWorld
80 #endif
81 \end{code}
82
83 \begin{code}
84 sstToIO :: SST REAL_WORLD r -> IO r
85 sstToIO sst =
86     MkIO (
87     sstToST sst         `thenStrictlyST` \ r -> 
88     returnStrictlyST (Right r))
89
90 ioToRnMG :: IO r -> RnMG (Either IOError13 r)
91 ioToRnMG (MkIO io) rn_down g_down = stToSST io
92
93 traceRn :: Doc -> RnMG ()
94 traceRn msg | opt_D_show_rn_trace = ioToRnMG (hPutStr stderr (show msg) >> 
95                                               hPutStr stderr "\n")      `thenRn_`
96                                     returnRn ()
97             | otherwise           = returnRn ()
98 \end{code}
99
100
101 %************************************************************************
102 %*                                                                      *
103 \subsection{Data types}
104 %*                                                                      *
105 %************************************************************************
106
107 ===================================================
108                 MONAD TYPES
109 ===================================================
110
111 \begin{code}
112 type RnM s d r = RnDown s -> d -> SST s r
113 type RnMS s r   = RnM s          (SDown s) r            -- Renaming source
114 type RnMG r     = RnM REAL_WORLD GDown     r            -- Getting global names etc
115 type MutVar a  = MutableVar REAL_WORLD a                -- ToDo: there ought to be a standard defn of this
116
117         -- Common part
118 data RnDown s = RnDown
119                   SrcLoc
120                   (MutableVar s RnNameSupply)
121                   (MutableVar s (Bag Warning, Bag Error))
122                   (MutableVar s [(Name,Necessity)])             -- Occurrences
123
124 data Necessity = Compulsory | Optional          -- We *must* find definitions for
125                                                 -- compulsory occurrences; we *may* find them
126                                                 -- for optional ones.
127
128         -- For getting global names
129 data GDown = GDown
130                 SearchPath
131                 (MutVar Ifaces)
132
133         -- For renaming source code
134 data SDown s = SDown
135                   RnEnv                 -- Global envt
136                   NameEnv               -- Local name envt (includes global name envt, 
137                                         -- but may shadow it)
138                   Module
139                   RnSMode
140
141
142 data RnSMode    = SourceMode
143                 | InterfaceMode
144
145 type SearchPath = [(String,String)]     -- List of (directory,suffix) pairs to search 
146                                         -- for interface files.
147 type FreeVars   = NameSet
148 \end{code}
149
150 ===================================================
151                 ENVIRONMENTS
152 ===================================================
153
154 \begin{code}
155 type RnNameSupply = (UniqSupply, Int, FiniteMap (Module,OccName) Name)
156         -- Ensures that one (m,n) pair gets one unique
157         -- The Int is used to give a number to each instance declaration;
158         -- it's really a separate name supply.
159
160 data RnEnv      = RnEnv NameEnv FixityEnv
161 emptyRnEnv      = RnEnv emptyNameEnv emptyFixityEnv
162
163 type NameEnv    = FiniteMap RdrName Name
164 emptyNameEnv    = emptyFM
165
166 type FixityEnv          = FiniteMap RdrName (Fixity, Provenance)
167 emptyFixityEnv          = emptyFM
168         -- It's possible to have a different fixity for B.op than for op:
169         --
170         --      module A( op ) where            module B where
171         --      import qualified B( op )        infixr 2 op
172         --      infixl 9 `op`                   op = ...
173         --      op a b = a `B.op` b
174
175 data ExportEnv          = ExportEnv Avails Fixities
176 type Avails             = [AvailInfo]
177 type Fixities           = [(OccName, (Fixity, Provenance))]
178         -- Can contain duplicates, if one module defines the same fixity,
179         -- or the same type/class/id, more than once.   Hence a boring old list.
180         -- This allows us to report duplicates in just one place, namely plusRnEnv.
181         
182 type ModuleAvails       = FiniteMap Module Avails
183
184 data AvailInfo          = NotAvailable 
185                         | Avail Name            -- An ordinary identifier
186                         | AvailTC Name          -- The name of the type or class
187                                   [Name]        -- The available pieces of type/class. NB: If the type or
188                                                 -- class is itself to be in scope, it must be in this list.
189                                                 -- Thus, typically: AvailTC Eq [Eq, ==, /=]
190 \end{code}
191
192 ===================================================
193                 INTERFACE FILE STUFF
194 ===================================================
195
196 \begin{code}
197 type ExportItem          = (Module, [(OccName, [OccName])])
198 type VersionInfo name    = [ImportVersion name]
199 type ImportVersion name  = (Module, Version, [LocalVersion name])
200 type LocalVersion name   = (name, Version)
201
202 data ParsedIface
203   = ParsedIface
204       Module                    -- Module name
205       Version                   -- Module version number
206       [ImportVersion OccName]           -- Usages
207       [ExportItem]                      -- Exports
208       [Module]                          -- Special instance modules
209       [(OccName,Fixity)]                -- Fixities
210       [(Version, RdrNameHsDecl)]        -- Local definitions
211       [RdrNameInstDecl]                 -- Local instance declarations
212
213 type InterfaceDetails = (VersionInfo Name,      -- Version information
214                          ExportEnv,             -- What this module exports
215                          [Module])              -- Instance modules
216
217 type RdrNamePragma = ()                         -- Fudge for now
218 -------------------
219
220 data Ifaces = Ifaces
221                 Module                                                  -- Name of this module
222                 (FiniteMap Module Version)
223                 (FiniteMap Module (Avails, [(OccName,Fixity)]))         -- Exports
224                 DeclsMap
225
226                 NameSet                 -- All the names (whether "big" or "small", whether wired-in or not,
227                                         -- whether locally defined or not) that have been slurped in so far.
228
229                 [(Name,Version)]        -- All the (a) non-wired-in (b) "big" (c) non-locally-defined names that 
230                                         -- have been slurped in so far, with their versions. 
231                                         -- This is used to generate the "usage" information for this module.
232                                         -- Subset of the previous field.
233
234                 (Bag IfaceInst)         -- The as-yet un-slurped instance decls; this bag is depleted when we
235                                         -- slurp an instance decl so that we don't slurp the same one twice.
236
237                 (FiniteMap Name RdrNameTyDecl)
238                                         -- Deferred data type declarations; each has the following properties
239                                         --      * it's a data type decl
240                                         --      * its TyCon is needed
241                                         --      * the decl may or may not have been slurped, depending on whether any
242                                         --        of the constrs are needed.
243
244                 [Module]                -- Set of modules with "special" instance declarations
245                                         -- Excludes this module
246
247
248 type DeclsMap    = FiniteMap Name (Version, AvailInfo, RdrNameHsDecl)
249 type IfaceInst   = ((Module, RdrNameInstDecl),  -- Instance decl
250                     [Name])                     -- "Gate" names.  Slurp this instance decl when this
251                                                 -- list becomes empty.  It's depleted whenever we
252                                                 -- slurp another type or class decl.
253 \end{code}
254
255
256 %************************************************************************
257 %*                                                                      *
258 \subsection{Main monad code}
259 %*                                                                      *
260 %************************************************************************
261
262 \begin{code}
263 initRn :: Module -> UniqSupply -> SearchPath -> SrcLoc
264        -> RnMG r
265        -> IO (r, Bag Error, Bag Warning)
266
267 initRn mod us dirs loc do_rn
268   = sstToIO $
269     newMutVarSST (us, 1, builtins)      `thenSST` \ names_var ->
270     newMutVarSST (emptyBag,emptyBag)    `thenSST` \ errs_var ->
271     newMutVarSST (emptyIfaces mod)      `thenSST` \ iface_var -> 
272     newMutVarSST initOccs               `thenSST` \ occs_var ->
273     let
274         rn_down = RnDown loc names_var errs_var occs_var
275         g_down  = GDown dirs iface_var
276     in
277         -- do the buisness
278     do_rn rn_down g_down                `thenSST` \ res ->
279
280         -- grab errors and return
281     readMutVarSST errs_var                      `thenSST` \ (warns,errs) ->
282     returnSST (res, errs, warns)
283
284
285 initRnMS :: RnEnv -> Module -> RnSMode -> RnMS REAL_WORLD r -> RnMG r
286 initRnMS rn_env@(RnEnv name_env _) mod_name mode m rn_down g_down
287   = let
288         s_down = SDown rn_env name_env mod_name mode
289     in
290     m rn_down s_down
291
292
293 emptyIfaces :: Module -> Ifaces
294 emptyIfaces mod = Ifaces mod emptyFM emptyFM emptyFM emptyNameSet [] emptyBag emptyFM []
295
296 builtins :: FiniteMap (Module,OccName) Name
297 builtins = bagToFM (mapBag (\ name -> (modAndOcc name, name)) builtinNames)
298
299         -- Initial value for the occurrence pool.
300 initOccs :: [(Name,Necessity)]
301 initOccs = [(getName boolTyCon, Compulsory)]
302         -- Booleans occur implicitly a lot, so it's tiresome to keep recording the fact, and
303         -- rather implausible that not one will be used in the module.
304         -- We could add some other common types, notably lists, but the general idea is
305         -- to do as much as possible explicitly.
306 \end{code}
307
308 \end{code}
309
310
311 @renameSourceCode@ is used to rename stuff "out-of-line"; that is, not as part of
312 the main renamer.  Examples: pragmas (which we don't want to rename unless
313 we actually explore them); and derived definitions, which are only generated
314 in the type checker.
315
316 The @RnNameSupply@ includes a @UniqueSupply@, so if you call it more than
317 once you must either split it, or install a fresh unique supply.
318
319 \begin{code}
320 renameSourceCode :: Module 
321                  -> RnNameSupply 
322                  -> RnMS REAL_WORLD r
323                  -> r
324
325 -- Alas, we can't use the real runST, with the desired signature:
326 --      renameSourceCode :: RnNameSupply -> RnMS s r -> r
327 -- because we can't manufacture "new versions of runST".
328
329 renameSourceCode mod_name name_supply m
330   = runSST (
331         newMutVarSST name_supply                `thenSST` \ names_var ->
332         newMutVarSST (emptyBag,emptyBag)        `thenSST` \ errs_var ->
333         newMutVarSST []                         `thenSST` \ occs_var ->
334         let
335             rn_down = RnDown mkGeneratedSrcLoc names_var errs_var occs_var
336             s_down = SDown emptyRnEnv emptyNameEnv mod_name InterfaceMode
337         in
338         m rn_down s_down                        `thenSST` \ result ->
339         
340         readMutVarSST errs_var                  `thenSST` \ (warns,errs) ->
341
342         (if not (isEmptyBag errs) then
343                 trace ("Urk! renameSourceCode found errors" ++ display errs) 
344          else if not (isEmptyBag warns) then
345                 trace ("Urk! renameSourceCode found warnings" ++ display warns)
346          else
347                 id) $
348
349         returnSST result
350     )
351   where
352     display errs = show (pprBagOfErrors PprDebug errs)
353
354 {-# INLINE thenRn #-}
355 {-# INLINE thenRn_ #-}
356 {-# INLINE returnRn #-}
357 {-# INLINE andRn #-}
358
359 returnRn :: a -> RnM s d a
360 thenRn   :: RnM s d a -> (a -> RnM s d b) -> RnM s d b
361 thenRn_  :: RnM s d a -> RnM s d b -> RnM s d b
362 andRn    :: (a -> a -> a) -> RnM s d a -> RnM s d a -> RnM s d a
363 mapRn    :: (a -> RnM s d b) -> [a] -> RnM s d [b]
364 sequenceRn :: [RnM s d a] -> RnM s d [a]
365 foldlRn :: (b  -> a -> RnM s d b) -> b -> [a] -> RnM s d b
366 mapAndUnzipRn :: (a -> RnM s d (b,c)) -> [a] -> RnM s d ([b],[c])
367 fixRn    :: (a -> RnM s d a) -> RnM s d a
368
369 returnRn v gdown ldown  = returnSST v
370 thenRn m k gdown ldown  = m gdown ldown `thenSST` \ r -> k r gdown ldown
371 thenRn_ m k gdown ldown = m gdown ldown `thenSST_` k gdown ldown
372 fixRn m gdown ldown = fixSST (\r -> m r gdown ldown)
373 andRn combiner m1 m2 gdown ldown
374   = m1 gdown ldown `thenSST` \ res1 ->
375     m2 gdown ldown `thenSST` \ res2 ->
376     returnSST (combiner res1 res2)
377
378 sequenceRn []     = returnRn []
379 sequenceRn (m:ms) =  m                  `thenRn` \ r ->
380                      sequenceRn ms      `thenRn` \ rs ->
381                      returnRn (r:rs)
382
383 mapRn f []     = returnRn []
384 mapRn f (x:xs)
385   = f x         `thenRn` \ r ->
386     mapRn f xs  `thenRn` \ rs ->
387     returnRn (r:rs)
388
389 foldlRn k z [] = returnRn z
390 foldlRn k z (x:xs) = k z x      `thenRn` \ z' ->
391                      foldlRn k z' xs
392
393 mapAndUnzipRn f [] = returnRn ([],[])
394 mapAndUnzipRn f (x:xs)
395   = f x                 `thenRn` \ (r1,  r2)  ->
396     mapAndUnzipRn f xs  `thenRn` \ (rs1, rs2) ->
397     returnRn (r1:rs1, r2:rs2)
398
399 mapAndUnzip3Rn f [] = returnRn ([],[],[])
400 mapAndUnzip3Rn f (x:xs)
401   = f x                 `thenRn` \ (r1,  r2,  r3)  ->
402     mapAndUnzip3Rn f xs `thenRn` \ (rs1, rs2, rs3) ->
403     returnRn (r1:rs1, r2:rs2, r3:rs3)
404 \end{code}
405
406
407
408 %************************************************************************
409 %*                                                                      *
410 \subsection{Boring plumbing for common part}
411 %*                                                                      *
412 %************************************************************************
413
414
415 ================  Errors and warnings =====================
416
417 \begin{code}
418 failWithRn :: a -> Error -> RnM s d a
419 failWithRn res msg (RnDown loc names_var errs_var occs_var) l_down
420   = readMutVarSST  errs_var                                     `thenSST`  \ (warns,errs) ->
421     writeMutVarSST errs_var (warns, errs `snocBag` err)         `thenSST_` 
422     returnSST res
423   where
424     err = addShortErrLocLine loc msg
425
426 warnWithRn :: a -> Warning -> RnM s d a
427 warnWithRn res msg (RnDown loc names_var errs_var occs_var) l_down
428   = readMutVarSST  errs_var                                     `thenSST`  \ (warns,errs) ->
429     writeMutVarSST errs_var (warns `snocBag` warn, errs)        `thenSST_` 
430     returnSST res
431   where
432     warn = addShortWarnLocLine loc msg
433
434 addErrRn :: Error -> RnM s d ()
435 addErrRn err = failWithRn () err
436
437 checkRn :: Bool -> Error -> RnM s d ()  -- Check that a condition is true
438 checkRn False err  = addErrRn err
439 checkRn True err = returnRn ()
440
441 addWarnRn :: Warning -> RnM s d ()
442 addWarnRn warn = warnWithRn () warn
443
444 checkErrsRn :: RnM s d Bool             -- True <=> no errors so far
445 checkErrsRn  (RnDown loc names_var errs_var occs_var) l_down
446   = readMutVarSST  errs_var                                     `thenSST`  \ (warns,errs) ->
447     returnSST (isEmptyBag errs)
448 \end{code}
449
450
451 ================  Source location =====================
452
453 \begin{code}
454 pushSrcLocRn :: SrcLoc -> RnM s d a -> RnM s d a
455 pushSrcLocRn loc' m (RnDown loc names_var errs_var occs_var) l_down
456   = m (RnDown loc' names_var errs_var occs_var) l_down
457
458 getSrcLocRn :: RnM s d SrcLoc
459 getSrcLocRn (RnDown loc names_var errs_var occs_var) l_down
460   = returnSST loc
461 \end{code}
462
463 ================  Name supply =====================
464
465 \begin{code}
466 getNameSupplyRn :: RnM s d RnNameSupply
467 getNameSupplyRn (RnDown loc names_var errs_var occs_var) l_down
468   = readMutVarSST names_var
469
470 setNameSupplyRn :: RnNameSupply -> RnM s d ()
471 setNameSupplyRn names' (RnDown loc names_var errs_var occs_var) l_down
472   = writeMutVarSST names_var names'
473
474 -- The "instance-decl unique supply", inst, is just an integer that's used to
475 -- give a unique number for each instance declaration.
476 newInstUniq :: RnM s d Int
477 newInstUniq (RnDown loc names_var errs_var occs_var) l_down
478   = readMutVarSST names_var                             `thenSST` \ (us, inst, cache) ->
479     writeMutVarSST names_var (us, inst+1, cache)        `thenSST_` 
480     returnSST inst
481 \end{code}
482
483 ================  Occurrences =====================
484
485 \begin{code}
486 addOccurrenceName :: Necessity -> Name -> RnM s d Name  -- Same name returned as passed
487 addOccurrenceName necessity name (RnDown loc names_var errs_var occs_var) l_down
488   | isLocallyDefinedName name ||
489     not_necessary necessity
490   = returnSST name
491
492   | otherwise
493   = readMutVarSST occs_var                      `thenSST` \ occs ->
494     writeMutVarSST occs_var ((name,necessity) : occs)   `thenSST_`
495     returnSST name
496   where
497     not_necessary Compulsory = False
498     not_necessary Optional = opt_IgnoreIfacePragmas
499                 -- Never look for optional things if we're
500                 -- ignoring optional input interface information
501
502 addOccurrenceNames :: Necessity -> [Name] -> RnM s d ()
503 addOccurrenceNames necessity names (RnDown loc names_var errs_var occs_var) l_down
504   = readMutVarSST occs_var                      `thenSST` \ occs ->
505     writeMutVarSST occs_var ([(name,necessity) | name <- names, not (isLocallyDefinedName name)] ++ occs)
506
507 popOccurrenceName :: RnM s d (Maybe (Name,Necessity))
508 popOccurrenceName (RnDown loc names_var errs_var occs_var) l_down
509   = readMutVarSST occs_var                      `thenSST` \ occs ->
510     case occs of
511         []         -> returnSST Nothing
512         (occ:occs) -> writeMutVarSST occs_var occs      `thenSST_`
513                       returnSST (Just occ)
514
515 -- findOccurrencesRn does the enclosed thing with a *fresh* occurrences
516 -- variable, and returns the list of occurrences thus found.  It's useful
517 -- when loading instance decls and specialisation signatures, when we want to
518 -- know the names of the things in the types, but we don't want to treat them
519 -- as occurrences.
520
521 findOccurrencesRn :: RnM s d a -> RnM s d [Name]
522 findOccurrencesRn enclosed_thing (RnDown loc names_var errs_var occs_var) l_down
523   = newMutVarSST []                                                     `thenSST` \ new_occs_var ->
524     enclosed_thing (RnDown loc names_var errs_var new_occs_var) l_down  `thenSST_`
525     readMutVarSST new_occs_var                                          `thenSST` \ occs ->
526     returnSST (map fst occs)
527 \end{code}
528
529
530 %************************************************************************
531 %*                                                                      *
532 \subsection{Plumbing for rename-source part}
533 %*                                                                      *
534 %************************************************************************
535
536 ================  RnEnv  =====================
537
538 \begin{code}
539 getGlobalNameEnv :: RnMS s NameEnv
540 getGlobalNameEnv rn_down (SDown (RnEnv global_env fixity_env) local_env mod_name mode)
541   = returnSST global_env
542
543 getNameEnv :: RnMS s NameEnv
544 getNameEnv rn_down (SDown rn_env local_env mod_name mode)
545   = returnSST local_env
546
547 setNameEnv :: NameEnv -> RnMS s a -> RnMS s a
548 setNameEnv local_env' m rn_down (SDown rn_env local_env mod_name mode)
549   = m rn_down (SDown rn_env local_env' mod_name mode)
550
551 getFixityEnv :: RnMS s FixityEnv
552 getFixityEnv rn_down (SDown (RnEnv name_env fixity_env) local_env mod_name mode)
553   = returnSST fixity_env
554 \end{code}
555
556 ================  Module and Mode =====================
557
558 \begin{code}
559 getModuleRn :: RnMS s Module
560 getModuleRn rn_down (SDown rn_env local_env mod_name mode)
561   = returnSST mod_name
562 \end{code}
563
564 \begin{code}
565 getModeRn :: RnMS s RnSMode
566 getModeRn rn_down (SDown rn_env local_env mod_name mode)
567   = returnSST mode
568 \end{code}
569
570
571 %************************************************************************
572 %*                                                                      *
573 \subsection{Plumbing for rename-globals part}
574 %*                                                                      *
575 %************************************************************************
576
577 \begin{code}
578 getIfacesRn :: RnMG Ifaces
579 getIfacesRn rn_down (GDown dirs iface_var)
580   = readMutVarSST iface_var
581
582 setIfacesRn :: Ifaces -> RnMG ()
583 setIfacesRn ifaces rn_down (GDown dirs iface_var)
584   = writeMutVarSST iface_var ifaces
585
586 getSearchPathRn :: RnMG SearchPath
587 getSearchPathRn rn_down (GDown dirs iface_var)
588   = returnSST dirs
589 \end{code}