[project @ 1996-05-20 13:15:10 by partain]
[ghc-hetmet.git] / ghc / compiler / rename / RnNames.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
3 %
4 \section[RnNames]{Extracting imported and top-level names in scope}
5
6 \begin{code}
7 #include "HsVersions.h"
8
9 module RnNames (
10         getGlobalNames,
11         GlobalNameInfo(..)
12     ) where
13
14 import PreludeGlaST     ( MutableVar(..) )
15
16 import Ubiq
17
18 import HsSyn
19 import RdrHsSyn
20 import RnHsSyn
21
22 import RnMonad
23 import RnIfaces         ( IfaceCache(..), cachedIface, cachedDecl )
24 import RnUtils          ( RnEnv(..), emptyRnEnv, extendGlobalRnEnv,
25                           lubExportFlag, qualNameErr, dupNamesErr
26                         )
27 import ParseUtils       ( ParsedIface(..), RdrIfaceDecl(..), RdrIfaceInst )
28
29
30 import Bag              ( emptyBag, unitBag, consBag, snocBag, unionBags,
31                           unionManyBags, mapBag, filterBag, listToBag, bagToList )
32 import CmdLineOpts      ( opt_NoImplicitPrelude )
33 import ErrUtils         ( Error(..), Warning(..), addErrLoc, addShortErrLocLine, addShortWarnLocLine )
34 import FiniteMap        ( emptyFM, addListToFM, lookupFM, fmToList, eltsFM, delListFromFM )
35 import Id               ( GenId )
36 import Maybes           ( maybeToBool, catMaybes, MaybeErr(..) )
37 import Name             ( RdrName(..), Name, isQual, mkTopLevName, origName,
38                           mkImportedName, nameExportFlag, nameImportFlag,
39                           getLocalName, getSrcLoc, getImpLocs, moduleNamePair,
40                           pprNonSym, isLexCon, isRdrLexCon, ExportFlag(..)
41                         )
42 import PrelInfo         ( BuiltinNames(..), BuiltinKeys(..) )
43 import PrelMods         ( fromPrelude, pRELUDE, rATIO, iX )
44 import Pretty
45 import SrcLoc           ( SrcLoc, mkBuiltinSrcLoc )
46 import TyCon            ( tyConDataCons )
47 import UniqFM           ( emptyUFM, addListToUFM_C, lookupUFM )
48 import UniqSupply       ( splitUniqSupply )
49 import Util             ( isIn, assoc, cmpPString, sortLt, removeDups,
50                           equivClasses, panic, assertPanic )
51 \end{code}
52
53
54 \begin{code}
55 type GlobalNameInfo = (BuiltinNames,
56                        BuiltinKeys,
57                        Name -> ExportFlag,      -- export flag
58                        Name -> [RdrName])       -- occurence names
59
60 type RnM_Info s r = RnMonad GlobalNameInfo s r
61
62 getGlobalNames ::
63            IfaceCache           
64         -> GlobalNameInfo       
65         -> UniqSupply
66         -> RdrNameHsModule
67         -> IO (RnEnv,
68                [Module],                -- directly imported modules
69                Bag (Module,RnName),     -- unqualified imports from module
70                Bag RenamedFixityDecl,   -- imported fixity decls
71                Bag Error,
72                Bag Warning)
73
74 getGlobalNames iface_cache info us
75                (HsModule mod _ _ imports _ ty_decls _ cls_decls _ _ _ binds _ _)
76   = case initRn True mod emptyRnEnv us1 
77                 (setExtraRn info $
78                  getSourceNames ty_decls cls_decls binds)
79     of { ((src_vals, src_tcs), src_errs, src_warns) ->
80
81     doImportDecls iface_cache info us2 imports  >>=
82         \ (imp_vals, imp_tcs, imp_mods, unqual_imps, imp_fixes, imp_errs, imp_warns) ->
83
84     let
85         unqual_vals = map (\rn -> (Unqual (getLocalName rn), rn)) (bagToList src_vals)
86         unqual_tcs  = map (\rn -> (Unqual (getLocalName rn), rn)) (bagToList src_tcs)
87
88         (src_env, src_dups) = extendGlobalRnEnv emptyRnEnv unqual_vals unqual_tcs
89         (all_env, imp_dups) = extendGlobalRnEnv src_env (bagToList imp_vals) (bagToList imp_tcs)
90
91         -- remove dups of the same imported thing
92         diff_imp_dups = filterBag diff_orig imp_dups
93         diff_orig (_,rn1,rn2) = origName rn1 /= origName rn2
94
95         all_dups = bagToList (src_dups `unionBags` diff_imp_dups)
96         dup_errs = map dup_err (equivClasses cmp_rdr all_dups)
97         cmp_rdr (rdr1,_,_) (rdr2,_,_) = cmp rdr1 rdr2
98         dup_err ((rdr,rn1,rn2):rest) = globalDupNamesErr rdr (rn1:rn2: [rn|(_,_,rn)<-rest])
99
100         all_errs  = src_errs  `unionBags` imp_errs `unionBags` listToBag dup_errs
101         all_warns = src_warns `unionBags` imp_warns
102     in
103     return (all_env, imp_mods, unqual_imps, imp_fixes, all_errs, all_warns)
104     }
105   where
106     (us1, us2) = splitUniqSupply us
107 \end{code}
108
109 *********************************************************
110 *                                                       *
111 \subsection{Top-level source names}
112 *                                                       *
113 *********************************************************
114
115 \begin{code}
116 getSourceNames ::
117            [RdrNameTyDecl]
118         -> [RdrNameClassDecl]
119         -> RdrNameHsBinds
120         -> RnM_Info s (Bag RnName,      -- values
121                        Bag RnName)      -- tycons/classes
122
123 getSourceNames ty_decls cls_decls binds
124   = mapAndUnzip3Rn getTyDeclNames ty_decls      `thenRn` \ (tycon_s, constrs_s, fields_s) ->
125     mapAndUnzipRn  getClassNames cls_decls      `thenRn` \ (cls_s, cls_ops_s) ->
126     getTopBindsNames binds                      `thenRn` \ bind_names ->
127     returnRn (unionManyBags constrs_s `unionBags`
128               unionManyBags fields_s  `unionBags`
129               unionManyBags cls_ops_s `unionBags` bind_names,
130               listToBag tycon_s `unionBags` listToBag cls_s)
131
132
133 getTyDeclNames :: RdrNameTyDecl
134                -> RnM_Info s (RnName, Bag RnName, Bag RnName)   -- tycon, constrs and fields
135
136 getTyDeclNames (TyData _ tycon _ condecls _ _ src_loc)
137   = newGlobalName src_loc Nothing tycon `thenRn` \ tycon_name ->
138     getConFieldNames (Just (nameExportFlag tycon_name)) emptyBag emptyBag emptyFM
139                      condecls           `thenRn` \ (con_names, field_names) ->
140     let
141         rn_tycon   = RnData tycon_name con_names field_names
142         rn_constrs = [ RnConstr name tycon_name | name <- con_names]
143         rn_fields  = [ RnField name tycon_name | name <- field_names]
144     in
145     returnRn (rn_tycon, listToBag rn_constrs, listToBag rn_fields)
146
147 getTyDeclNames (TyNew _ tycon _ [NewConDecl con _ con_loc] _ _ src_loc)
148   = newGlobalName src_loc Nothing tycon `thenRn` \ tycon_name ->
149     newGlobalName con_loc (Just (nameExportFlag tycon_name)) con
150                                         `thenRn` \ con_name ->
151     returnRn (RnData tycon_name [con_name] [],
152               unitBag (RnConstr con_name tycon_name),
153               emptyBag)
154
155 getTyDeclNames (TySynonym tycon _ _ src_loc)
156   = newGlobalName src_loc Nothing tycon `thenRn` \ tycon_name ->
157     returnRn (RnSyn tycon_name, emptyBag, emptyBag)
158
159
160 getConFieldNames exp constrs fields have []
161   = returnRn (bagToList constrs, bagToList fields)
162
163 getConFieldNames exp constrs fields have (ConDecl con _ src_loc : rest)
164   = newGlobalName src_loc exp con       `thenRn` \ con_name ->
165     getConFieldNames exp (constrs `snocBag` con_name) fields have rest
166
167 getConFieldNames exp constrs fields have (ConOpDecl _ con _ src_loc : rest)
168   = newGlobalName src_loc exp con       `thenRn` \ con_name ->
169     getConFieldNames exp (constrs `snocBag` con_name) fields have rest
170
171 getConFieldNames exp constrs fields have (RecConDecl con fielddecls src_loc : rest)
172   = mapRn (addErrRn . dupFieldErr con src_loc) dups     `thenRn_`
173     newGlobalName src_loc exp con                       `thenRn` \ con_name ->
174     mapRn (newGlobalName src_loc exp) new_fields        `thenRn` \ field_names ->
175     let
176         all_constrs = constrs `snocBag` con_name
177         all_fields  = fields  `unionBags` listToBag field_names
178     in
179     getConFieldNames exp all_constrs all_fields new_have rest
180   where
181     (uniq_fields, dups) = removeDups cmp (concat (map fst fielddecls))
182     new_fields = filter (not . maybeToBool . lookupFM have) uniq_fields
183     new_have   = addListToFM have (zip new_fields (repeat ()))
184
185 getClassNames :: RdrNameClassDecl
186               -> RnM_Info s (RnName, Bag RnName)        -- class and class ops
187
188 getClassNames (ClassDecl _ cname _ sigs _ _ src_loc)
189   = newGlobalName src_loc Nothing cname `thenRn` \ class_name ->
190     getClassOpNames (Just (nameExportFlag class_name))
191                                   sigs  `thenRn` \ op_names ->
192     returnRn (RnClass class_name op_names,
193               listToBag (map (\ n -> RnClassOp n class_name) op_names))
194
195 getClassOpNames exp []
196   = returnRn []
197 getClassOpNames exp (ClassOpSig op _ _ src_loc : sigs)
198   = newGlobalName src_loc exp op `thenRn` \ op_name ->
199     getClassOpNames exp sigs     `thenRn` \ op_names ->
200     returnRn (op_name : op_names)
201 getClassOpNames exp (_ : sigs)
202   = getClassOpNames exp sigs
203 \end{code}
204
205 *********************************************************
206 *                                                       *
207 \subsection{Bindings}
208 *                                                       *
209 *********************************************************
210
211 \begin{code}
212 getTopBindsNames :: RdrNameHsBinds
213                  -> RnM_Info s (Bag RnName)
214
215 getTopBindsNames binds = doBinds binds
216
217 doBinds EmptyBinds           = returnRn emptyBag
218 doBinds (SingleBind bind)    = doBind bind
219 doBinds (BindWith bind sigs) = doBind bind
220 doBinds (ThenBinds binds1 binds2)
221   = andRn unionBags (doBinds binds1) (doBinds binds2)
222
223 doBind EmptyBind          = returnRn emptyBag
224 doBind (NonRecBind mbind) = doMBinds mbind
225 doBind (RecBind mbind)    = doMBinds mbind
226
227 doMBinds EmptyMonoBinds                         = returnRn emptyBag
228 doMBinds (PatMonoBind pat grhss_and_binds locn) = doPat locn pat
229 doMBinds (FunMonoBind p_name _ _ locn)          = doName locn p_name
230 doMBinds (AndMonoBinds mbinds1 mbinds2)
231   = andRn unionBags (doMBinds mbinds1) (doMBinds mbinds2)
232
233 doPats locn pats
234   = mapRn (doPat locn) pats     `thenRn` \ pats_s ->
235     returnRn (unionManyBags pats_s)
236
237 doPat locn WildPatIn             = returnRn emptyBag
238 doPat locn (LitPatIn _)          = returnRn emptyBag
239 doPat locn (LazyPatIn pat)       = doPat locn pat
240 doPat locn (VarPatIn var)        = doName locn var
241 doPat locn (NegPatIn pat)        = doPat locn pat
242 doPat locn (ParPatIn pat)        = doPat locn pat
243 doPat locn (ListPatIn pats)      = doPats locn pats
244 doPat locn (TuplePatIn pats)     = doPats locn pats
245 doPat locn (ConPatIn name pats)  = doPats locn pats
246 doPat locn (ConOpPatIn p1 op p2)
247   = andRn unionBags (doPat locn p1) (doPat locn p2)
248 doPat locn (AsPatIn as_name pat)
249   = andRn unionBags (doName locn as_name) (doPat locn pat)
250 doPat locn (RecPatIn name fields)
251   = mapRn (doField locn) fields `thenRn` \ fields_s ->
252     returnRn (unionManyBags fields_s)
253
254 doField locn (_, pat, _) = doPat locn pat
255
256 doName locn rdr
257   = newGlobalName locn Nothing rdr `thenRn` \ name ->
258     returnRn (unitBag (RnName name))
259 \end{code}
260
261 *********************************************************
262 *                                                       *
263 \subsection{Creating a new global name}
264 *                                                       *
265 *********************************************************
266
267 \begin{code}
268 newGlobalName :: SrcLoc -> Maybe ExportFlag
269               -> RdrName -> RnM_Info s Name
270
271 -- ToDo: b_names and b_keys being defined in this module !!!
272
273 newGlobalName locn maybe_exp rdr
274   = getExtraRn                  `thenRn` \ (_,b_keys,exp_fn,occ_fn) ->
275     getModuleRn                 `thenRn` \ mod ->
276     rnGetUnique                 `thenRn` \ u ->
277     let
278         (uniq, unqual)
279           = case rdr of
280               Qual m n -> (u, n)
281               Unqual n -> case (lookupFM b_keys n) of
282                             Nothing      -> (u,   n)
283                             Just (key,_) -> (key, n)
284
285         orig   = if fromPrelude mod
286                  then (Unqual unqual)
287                  else (Qual mod unqual)
288
289         exp = case maybe_exp of
290                Just exp -> exp
291                Nothing  -> exp_fn n
292
293         n = mkTopLevName uniq orig locn exp (occ_fn n) -- NB: two "n"s
294     in
295     addErrIfRn (isQual rdr) (qualNameErr "name in definition" (rdr, locn)) `thenRn_`
296     returnRn n    
297 \end{code}
298
299 *********************************************************
300 *                                                       *
301 \subsection{Imported names}
302 *                                                       *
303 *********************************************************
304
305 \begin{code}
306 type ImportNameInfo = (GlobalNameInfo,
307                        FiniteMap (Module,FAST_STRING) RnName,   -- values imported so far
308                        FiniteMap (Module,FAST_STRING) RnName,   -- tycons/classes imported so far
309                        Name -> (ExportFlag, [SrcLoc]))          -- import flag and src locns
310                 
311 type RnM_IInfo s r = RnMonad ImportNameInfo s r
312
313 doImportDecls ::
314            IfaceCache
315         -> GlobalNameInfo                       -- builtin and knot name info
316         -> UniqSupply
317         -> [RdrNameImportDecl]                  -- import declarations
318         -> IO (Bag (RdrName,RnName),            -- imported values in scope
319                Bag (RdrName,RnName),            -- imported tycons/classes in scope
320                [Module],                        -- directly imported modules
321                Bag (Module,RnName),             -- unqualified import from module
322                Bag RenamedFixityDecl,           -- fixity info for imported names
323                Bag Error,
324                Bag Warning)
325
326 doImportDecls iface_cache g_info us src_imps
327   = fixIO ( \ ~(_, _, _, _, _, _, rec_imp_stuff) ->
328         let
329             rec_imp_fm = addListToUFM_C add_stuff emptyUFM (bagToList rec_imp_stuff)
330             add_stuff (imp1,locns1) (imp2,locns2) = (lubExportFlag imp1 imp2, locns1 `unionBags` locns2)
331
332             rec_imp_fn :: Name -> (ExportFlag, [SrcLoc])
333             rec_imp_fn n = case lookupUFM rec_imp_fm n of
334                              Nothing            -> panic "RnNames:rec_imp_fn"
335                              Just (flag, locns) -> (flag, bagToList locns)
336
337             i_info = (g_info, emptyFM, emptyFM, rec_imp_fn)
338         in
339         -- cache the imported modules
340         -- this ensures that all directly imported modules
341         -- will have their original name iface in scope
342         accumulate (map (cachedIface False iface_cache) imp_mods) >>
343
344         -- process the imports
345         doImports iface_cache i_info us all_imps
346
347     ) >>= \ (vals, tcs, unquals, fixes, errs, warns, _) ->
348
349     return (vals, tcs, imp_mods, unquals, fixes,
350             imp_errs `unionBags` errs,
351             imp_warns `unionBags` warns)
352   where
353     the_imps = implicit_prel ++ src_imps
354     all_imps = implicit_qprel ++ the_imps
355
356     implicit_qprel = if opt_NoImplicitPrelude
357                      then [{- no "import qualified Prelude" -}]
358                      else [ImportDecl pRELUDE True Nothing Nothing prel_loc]
359
360     explicit_prelude_imp = not (null [ () | (ImportDecl mod qual _ _ _) <- src_imps,
361                                             mod == pRELUDE ])
362
363     implicit_prel  = if explicit_prelude_imp || opt_NoImplicitPrelude
364                      then [{- no "import Prelude" -}]
365                      else [ImportDecl pRELUDE False Nothing Nothing prel_loc]
366
367     prel_loc = mkBuiltinSrcLoc
368
369     (uniq_imps, imp_dups) = removeDups cmp_mod the_imps
370     cmp_mod (ImportDecl m1 _ _ _ _) (ImportDecl m2 _ _ _ _) = cmpPString m1 m2
371
372     qprel_imps = [ imp | imp@(ImportDecl mod True Nothing _ _) <- src_imps,
373                          fromPrelude mod ]
374
375     qual_mods = [ (qual_name mod as_mod, imp) | imp@(ImportDecl mod True as_mod _ _) <- src_imps ]
376     qual_name mod (Just as_mod) = as_mod
377     qual_name mod Nothing       = mod
378
379     (_, qual_dups) = removeDups cmp_qual qual_mods
380     bad_qual_dups = filter (not . all_same_mod) qual_dups
381
382     cmp_qual (q1,_) (q2,_) = cmpPString q1 q2
383     all_same_mod ((q,ImportDecl mod _ _ _ _):rest)
384       = all has_same_mod rest
385       where
386         has_same_mod (q,ImportDecl mod2 _ _ _ _) = mod == mod2
387
388
389     imp_mods  = [ mod | ImportDecl mod _ _ _ _ <- uniq_imps ]
390
391     imp_warns = listToBag (map dupImportWarn imp_dups)
392                 `unionBags`
393                 listToBag (map qualPreludeImportWarn qprel_imps)
394
395     imp_errs  = listToBag (map dupQualImportErr bad_qual_dups)
396
397 doImports iface_cache i_info us []
398   = return (emptyBag, emptyBag, emptyBag, emptyBag, emptyBag, emptyBag, emptyBag)
399 doImports iface_cache i_info@(g_info,done_vals,done_tcs,imp_fn) us (imp:imps)
400   = doImport iface_cache i_info us1 imp
401         >>= \ (vals1, tcs1, unquals1, fixes1, errs1, warns1, imps1) ->
402     let
403         new_vals = [ (moduleNamePair rn, rn) | (_,rn) <- bagToList vals1,
404                         not (maybeToBool (lookupFM done_vals (moduleNamePair rn))) ]
405                         -- moduleNamePair computed twice
406         ext_vals = addListToFM done_vals new_vals
407
408         new_tcs  = [ (moduleNamePair rn, rn) | (_,rn) <- bagToList tcs1,
409                         not (maybeToBool (lookupFM done_tcs (moduleNamePair rn))) ]
410         ext_tcs  = addListToFM done_tcs new_tcs
411     in
412     doImports iface_cache (g_info,ext_vals,ext_tcs,imp_fn) us2 imps
413         >>= \ (vals2, tcs2, unquals2, fixes2, errs2, warns2, imps2) ->
414     return (vals1    `unionBags` vals2,
415             tcs1     `unionBags` tcs2,
416             unquals1 `unionBags` unquals2,
417             fixes1   `unionBags` fixes2,
418             errs1    `unionBags` errs2,
419             warns1   `unionBags` warns2,
420             imps1    `unionBags` imps2)
421   where
422     (us1, us2) = splitUniqSupply us
423
424
425 doImport :: IfaceCache
426          -> ImportNameInfo
427          -> UniqSupply
428          -> RdrNameImportDecl
429          -> IO (Bag (RdrName,RnName),                   -- values
430                 Bag (RdrName,RnName),                   -- tycons/classes
431                 Bag (Module,RnName),                    -- unqual imports
432                 Bag RenamedFixityDecl,
433                 Bag Error,
434                 Bag Warning,
435                 Bag (RnName,(ExportFlag,Bag SrcLoc)))   -- import flags and src locs
436
437 doImport iface_cache info us (ImportDecl mod qual maybe_as maybe_spec src_loc)
438   = cachedIface False iface_cache mod   >>= \ maybe_iface ->
439     case maybe_iface of
440       Failed err ->
441         return (emptyBag, emptyBag, emptyBag, emptyBag,
442                 unitBag err, emptyBag, emptyBag)
443       Succeeded iface -> 
444         let
445             (b_vals, b_tcs, maybe_spec') = getBuiltins info mod maybe_spec 
446             (ies, chk_ies, get_errs)     = getOrigIEs iface maybe_spec'
447         in
448         doOrigIEs iface_cache info mod src_loc us ies 
449                 >>= \ (ie_vals, ie_tcs, imp_flags, errs, warns) ->
450         accumulate (map (checkOrigIE iface_cache) chk_ies)
451                 >>= \ chk_errs_warns ->
452         let
453             final_vals = mapBag fst_occ b_vals `unionBags` mapBag pair_occ ie_vals
454             final_tcs  = mapBag fst_occ b_tcs  `unionBags` mapBag pair_occ ie_tcs
455         in
456         accumulate (map (getFixityDecl iface_cache) (bagToList final_vals))
457                 >>= \ fix_maybes_errs ->
458         let
459             (chk_errs, chk_warns)  = unzip chk_errs_warns
460             (fix_maybes, fix_errs) = unzip fix_maybes_errs
461
462             unquals    = if qual then emptyBag
463                          else mapBag pair_as (ie_vals `unionBags` ie_tcs)
464
465             final_fixes = listToBag (catMaybes fix_maybes)
466
467             final_errs  = mapBag (\ err -> err mod src_loc) (unionManyBags (get_errs:chk_errs))
468                           `unionBags` errs `unionBags` unionManyBags fix_errs
469             final_warns = mapBag (\ warn -> warn mod src_loc) (unionManyBags chk_warns)
470                           `unionBags` warns
471             imp_stuff   = mapBag (\ (n,imp) -> (n,(imp,unitBag src_loc))) imp_flags
472         in
473         return (final_vals, final_tcs, unquals, final_fixes,
474                 final_errs, final_warns, imp_stuff)
475   where
476     as_mod = case maybe_as of {Nothing -> mod; Just as_this -> as_this}
477     mk_occ str = if qual then Qual as_mod str else Unqual str
478
479     fst_occ (str, rn) = (mk_occ str, rn)
480     pair_occ rn       = (mk_occ (getLocalName rn), rn)
481     pair_as  rn       = (as_mod, rn)
482
483
484 getBuiltins _ mod maybe_spec
485   | not ((fromPrelude mod) || mod == iX || mod == rATIO )
486   = (emptyBag, emptyBag, maybe_spec)
487
488 getBuiltins (((b_val_names,b_tc_names),_,_,_),_,_,_) mod maybe_spec
489   = case maybe_spec of 
490       Nothing           -> (all_vals, all_tcs, Nothing)
491
492       Just (True, ies)  -> -- hiding does not work for builtin names
493                            trace "getBuiltins: import Prelude hiding ( ... )" $
494                            (all_vals, all_tcs, maybe_spec)
495
496       Just (False, ies) -> let 
497                               (vals,tcs,ies_left) = do_builtin ies
498                            in
499                            (vals, tcs, Just (False, ies_left))
500   where
501     all_vals = do_all_builtin (fmToList b_val_names)
502     all_tcs  = do_all_builtin (fmToList b_tc_names)
503
504     filter_mod = if fromPrelude mod then pRELUDE else mod
505
506     do_all_builtin [] = emptyBag
507     do_all_builtin (((str,mod),rn):rest)
508       | mod == filter_mod
509       = (str, rn) `consBag` do_all_builtin rest
510       | otherwise
511       = do_all_builtin rest
512
513     do_builtin [] = (emptyBag,emptyBag,[]) 
514     do_builtin (ie:ies)
515       = let str = unqual_str (ie_name ie)
516         in
517         case (lookupFM b_tc_names (str,mod)) of         -- NB: we favour the tycon/class FM...
518           Just rn -> case (ie,rn) of
519              (IEThingAbs _, WiredInTyCon tc)
520                 -> (vals, (str, rn) `consBag` tcs, ies_left)
521              (IEThingAll _, WiredInTyCon tc)
522                 -> (listToBag (map (\ id -> (getLocalName id, WiredInId id)) 
523                                    (tyConDataCons tc))
524                     `unionBags` vals,
525                     (str,rn) `consBag` tcs, ies_left)
526              (IEThingWith _ _, WiredInTyCon tc) -- No checking of With...
527                 -> (listToBag (map (\ id -> (getLocalName id, WiredInId id)) 
528                                    (tyConDataCons tc))
529                     `unionBags` vals,
530                     (str,rn) `consBag` tcs, ies_left)
531              _ -> panic "importing builtin names (1)"
532
533           Nothing ->
534             case (lookupFM b_val_names (str,mod)) of
535               Nothing -> (vals, tcs, ie:ies_left)
536               Just rn -> case (ie,rn) of
537                  (IEVar _, WiredInId _)        
538                     -> ((str, rn) `consBag` vals, tcs, ies_left)
539                  _ -> panic "importing builtin names (2)"
540       where
541         (vals, tcs, ies_left) = do_builtin ies
542
543
544 getOrigIEs (ParsedIface _ _ _ _ _ _ exps _ _ _ _ _ _) Nothing                   -- import all
545   = (map mkAllIE (eltsFM exps), [], emptyBag)
546
547 getOrigIEs (ParsedIface _ _ _ _ _ _ exps _ _ _ _ _ _) (Just (True, ies))        -- import hiding
548   = (map mkAllIE (eltsFM exps_left), found_ies, errs)
549   where
550     (found_ies, errs) = lookupIEs exps ies
551     exps_left = delListFromFM exps (map (getLocalName.ie_name.fst) found_ies)
552
553 getOrigIEs (ParsedIface _ _ _ _ _ _ exps _ _ _ _ _ _) (Just (False, ies))       -- import these
554   = (map fst found_ies, found_ies, errs)
555   where
556     (found_ies, errs) = lookupIEs exps ies
557
558
559 mkAllIE (orig,ExportAbs)
560   = ASSERT(isLexCon (getLocalName orig))
561     IEThingAbs orig
562 mkAllIE (orig, ExportAll)
563   | isLexCon (getLocalName orig)
564   = IEThingAll orig
565   | otherwise
566   = IEVar orig
567
568
569 lookupIEs exps [] 
570   = ([], emptyBag)
571 lookupIEs exps (ie:ies)
572   = case lookupFM exps (unqual_str (ie_name ie)) of 
573       Nothing ->
574         (orig_ies, unknownImpSpecErr ie `consBag` errs)
575       Just (orig,flag) ->
576         (orig_ie orig flag ie ++ orig_ies,
577          adderr_if (seen_ie orig orig_ies) (duplicateImpSpecErr ie) errs)
578   where
579     (orig_ies, errs) = lookupIEs exps ies
580
581     orig_ie orig flag (IEVar n)          = [(IEVar orig, flag)]
582     orig_ie orig flag (IEThingAbs n)     = [(IEThingAbs orig, flag)]
583     orig_ie orig flag (IEThingAll n)     = [(IEThingAll orig, flag)]
584     orig_ie orig flag (IEThingWith n ns) = [(IEThingWith orig ns, flag)]
585
586     seen_ie orig seen_ies = any (\ (ie,_) -> orig == ie_name ie) seen_ies
587
588
589 doOrigIEs iface_cache info mod src_loc us []
590   = return (emptyBag,emptyBag,emptyBag,emptyBag,emptyBag)
591
592 doOrigIEs iface_cache info mod src_loc us (ie:ies)
593   = doOrigIE iface_cache info mod src_loc us1 ie 
594         >>= \ (vals1, tcs1, imps1, errs1, warns1) ->
595     doOrigIEs iface_cache info mod src_loc us2 ies
596         >>= \ (vals2, tcs2, imps2, errs2, warns2) ->
597     return (vals1    `unionBags` vals2,
598             tcs1     `unionBags` tcs2,
599             imps1    `unionBags` imps2,
600             errs1    `unionBags` errs2,
601             warns1   `unionBags` warns2)
602   where
603     (us1, us2) = splitUniqSupply us
604
605 doOrigIE iface_cache info mod src_loc us ie
606   = with_decl iface_cache (ie_name ie)
607         (\ err  -> (emptyBag, emptyBag, emptyBag, unitBag err, emptyBag))
608         (\ decl -> case initRn True mod emptyRnEnv us
609                                (setExtraRn info $
610                                 pushSrcLocRn src_loc $
611                                 getIfaceDeclNames ie decl)
612                    of
613                    ((vals, tcs, imps), errs, warns) -> (vals, tcs, imps, errs, warns))
614
615 checkOrigIE iface_cache (IEThingAll n, ExportAbs)
616   = with_decl iface_cache n
617         (\ err  -> (unitBag (\ mod locn -> err), emptyBag))
618         (\ decl -> case decl of
619                 TypeSig _ _ _ -> (emptyBag, unitBag (allWhenSynImpSpecWarn n))
620                 other         -> (unitBag (allWhenAbsImpSpecErr n), emptyBag))
621
622 checkOrigIE iface_cache (IEThingWith n ns, ExportAbs)
623   = return (unitBag (withWhenAbsImpSpecErr n), emptyBag)
624
625 checkOrigIE iface_cache (IEThingWith n ns, ExportAll)
626   = with_decl iface_cache n
627         (\ err  -> (unitBag (\ mod locn -> err), emptyBag))
628         (\ decl -> case decl of
629                 NewTypeSig _ con _ _         -> (check_with "constructrs" [con] ns, emptyBag)
630                 DataSig    _ cons fields _ _ -> (check_with "constructrs (and fields)" (cons++fields) ns, emptyBag)
631                 ClassSig   _ ops _ _         -> (check_with "class ops"   ops   ns, emptyBag))
632   where
633     check_with str has rdrs
634       | sortLt (<) (map getLocalName has) == sortLt (<) (map unqual_str rdrs)
635       = emptyBag
636       | otherwise
637       = unitBag (withImpSpecErr str n has rdrs)
638
639 checkOrigIE iface_cache other
640   = return (emptyBag, emptyBag)
641
642
643 with_decl iface_cache n do_err do_decl
644   = cachedDecl iface_cache (isRdrLexCon n) n   >>= \ maybe_decl ->
645     case maybe_decl of
646       Failed err     -> return (do_err err)
647       Succeeded decl -> return (do_decl decl)
648
649
650 getFixityDecl iface_cache (_,rn)
651   = let
652         (mod, str) = moduleNamePair rn
653     in
654     cachedIface True iface_cache mod    >>= \ maybe_iface ->
655     case maybe_iface of
656       Failed err ->
657         return (Nothing, unitBag err)
658       Succeeded (ParsedIface _ _ _ _ _ _ _ _ fixes _ _ _ _) ->
659         case lookupFM fixes str of
660           Nothing           -> return (Nothing, emptyBag)
661           Just (InfixL _ i) -> return (Just (InfixL rn i), emptyBag)
662           Just (InfixR _ i) -> return (Just (InfixR rn i), emptyBag)
663           Just (InfixN _ i) -> return (Just (InfixN rn i), emptyBag)
664
665 ie_name (IEVar n)         = n
666 ie_name (IEThingAbs n)    = n
667 ie_name (IEThingAll n)    = n
668 ie_name (IEThingWith n _) = n
669
670 unqual_str (Unqual str) = str
671 unqual_str q@(Qual _ _) = panic "unqual_str"
672
673 adderr_if True err errs  = err `consBag` errs
674 adderr_if False err errs = errs
675 \end{code}
676
677 *********************************************************
678 *                                                       *
679 \subsection{Actually creating the imported names}
680 *                                                       *
681 *********************************************************
682
683 \begin{code}
684 getIfaceDeclNames :: RdrNameIE -> RdrIfaceDecl
685                   -> RnM_IInfo s (Bag RnName,                   -- values
686                                   Bag RnName,                   -- tycons/classes
687                                   Bag (RnName,ExportFlag))      -- import flags
688
689 getIfaceDeclNames ie (ValSig val src_loc _)
690   = newImportedName False src_loc Nothing Nothing val   `thenRn` \ val_name ->
691     returnRn (unitBag (RnName val_name),
692               emptyBag,
693               unitBag (RnName val_name, ExportAll))
694
695 getIfaceDeclNames ie (TypeSig tycon src_loc _)
696   = newImportedName True src_loc Nothing Nothing tycon  `thenRn` \ tycon_name ->
697     returnRn (emptyBag,
698               unitBag (RnSyn tycon_name),
699               unitBag (RnSyn tycon_name, ExportAll))
700
701 getIfaceDeclNames ie (NewTypeSig tycon con src_loc _)
702   = newImportedName True src_loc Nothing Nothing tycon  `thenRn` \ tycon_name ->
703     newImportedName False src_loc (Just (nameExportFlag tycon_name))
704                                   (Just (nameImportFlag tycon_name))
705                                   con                   `thenRn` \ con_name ->
706     returnRn (if imp_all (imp_flag ie) then
707                   unitBag (RnConstr con_name tycon_name)
708               else
709                   emptyBag,
710               unitBag (RnData tycon_name [con_name] []),
711               unitBag (RnData tycon_name [con_name] [], imp_flag ie))
712
713 getIfaceDeclNames ie (DataSig tycon cons fields src_loc _)
714   = newImportedName True src_loc Nothing Nothing tycon `thenRn` \ tycon_name ->
715     mapRn (newImportedName False src_loc (Just (nameExportFlag tycon_name))
716                                          (Just (nameImportFlag tycon_name)))
717                                              cons `thenRn` \ con_names ->
718     mapRn (newImportedName False src_loc (Just (nameExportFlag tycon_name))
719                                          (Just (nameImportFlag tycon_name)))
720                                            fields `thenRn` \ field_names ->
721     let
722         rn_tycon   = RnData tycon_name con_names field_names
723         rn_constrs = [ RnConstr name tycon_name | name <- con_names ]
724         rn_fields  = [ RnField name tycon_name | name <- field_names ]
725     in
726     returnRn (if imp_all (imp_flag ie) then
727                   listToBag rn_constrs `unionBags` listToBag rn_fields
728               else
729                   emptyBag,
730               unitBag rn_tycon,
731               unitBag (rn_tycon, imp_flag ie))
732
733 getIfaceDeclNames ie (ClassSig cls ops src_loc _)
734   = newImportedName True src_loc Nothing Nothing cls `thenRn` \ cls_name ->
735     mapRn (newImportedName False src_loc (Just (nameExportFlag cls_name))
736                                          (Just (nameImportFlag cls_name)))
737                                             ops `thenRn` \ op_names ->
738     returnRn (if imp_all (imp_flag ie) then
739                   listToBag (map (\ n -> RnClassOp n cls_name) op_names)
740               else
741                   emptyBag,
742               unitBag (RnClass cls_name op_names),
743               unitBag (RnClass cls_name op_names, imp_flag ie))
744
745
746 imp_all ExportAll = True
747 imp_all _         = False
748
749 imp_flag (IEThingAbs _)    = ExportAbs
750 imp_flag (IEThingAll _)    = ExportAll
751 imp_flag (IEThingWith _ _) = ExportAll
752 \end{code}
753
754 *********************************************************
755 *                                                       *
756 \subsection{Creating a new imported name}
757 *                                                       *
758 *********************************************************
759
760 \begin{code}
761 newImportedName :: Bool                 -- True => tycon or class
762                 -> SrcLoc
763                 -> Maybe ExportFlag     -- maybe export flag
764                 -> Maybe ExportFlag     -- maybe import flag
765                 -> RdrName              -- orig name
766                 -> RnM_IInfo s Name
767
768 newImportedName tycon_or_class locn maybe_exp maybe_imp rdr
769   = getExtraRn `thenRn` \ ((_,b_keys,exp_fn,occ_fn),done_vals,done_tcs,imp_fn) ->
770     case if tycon_or_class
771          then lookupFM done_tcs  (moduleNamePair rdr)
772          else lookupFM done_vals (moduleNamePair rdr)
773     of
774     Just rn -> returnRn (getName rn)
775     Nothing -> 
776         rnGetUnique     `thenRn` \ u ->
777         let 
778             uniq = case rdr of
779                      Qual m n -> u
780                      Unqual n -> case lookupFM b_keys n of
781                                    Nothing      -> u
782                                    Just (key,_) -> key
783
784             exp  = case maybe_exp of
785                      Just exp -> exp
786                      Nothing  -> exp_fn n
787
788             imp  = case maybe_imp of
789                      Just imp -> imp
790                      Nothing  -> imp_flag
791
792             (imp_flag, imp_locs) = imp_fn n
793
794             n = mkImportedName uniq rdr imp locn imp_locs exp (occ_fn n) -- NB: two "n"s
795         in
796         returnRn n
797 \end{code}
798
799 \begin{code}
800 globalDupNamesErr rdr rns sty
801   = ppAboves (message : map pp_dup rns)
802   where
803     message   = ppBesides [ppStr "multiple declarations of `", pprNonSym sty rdr, ppStr "'"]
804
805     pp_dup rn = addShortErrLocLine (get_loc rn) (\ sty ->
806                 ppCat [pp_descrip rn, pprNonSym sty rn]) sty
807
808     get_loc rn = case getImpLocs rn of
809                      []   -> getSrcLoc rn
810                      locs -> head locs
811
812     pp_descrip (RnName _)      = ppStr "as a value:"
813     pp_descrip (RnSyn  _)      = ppStr "as a type synonym:"
814     pp_descrip (RnData _ _ _)  = ppStr "as a data type:"
815     pp_descrip (RnConstr _ _)  = ppStr "as a data constructor:"
816     pp_descrip (RnField _ _)   = ppStr "as a record field:"
817     pp_descrip (RnClass _ _)   = ppStr "as a class:"
818     pp_descrip (RnClassOp _ _) = ppStr "as a class method:"
819     pp_descrip _               = ppNil 
820
821 dupImportWarn (ImportDecl m1 _ _ _ locn1 : dup_imps) sty
822   = ppAboves (item1 : map dup_item dup_imps)
823   where
824     item1 = addShortWarnLocLine locn1 (\ sty ->
825             ppCat [ppStr "multiple imports from module", ppPStr m1]) sty
826
827     dup_item (ImportDecl m _ _ _ locn)
828           = addShortWarnLocLine locn (\ sty ->
829             ppCat [ppStr "here was another import from module", ppPStr m]) sty
830
831 qualPreludeImportWarn (ImportDecl m _ _ _ locn)
832   = addShortWarnLocLine locn (\ sty ->
833     ppCat [ppStr "qualified import of prelude module", ppPStr m])
834
835 dupQualImportErr ((q1,ImportDecl _ _ _ _ locn1):dup_quals) sty
836   = ppAboves (item1 : map dup_item dup_quals)
837   where
838     item1 = addShortErrLocLine locn1 (\ sty ->
839             ppCat [ppStr "multiple imports (from different modules) with same qualified name", ppPStr q1]) sty
840
841     dup_item (q,ImportDecl _ _ _ _ locn)
842           = addShortErrLocLine locn (\ sty ->
843             ppCat [ppStr "here was another import with qualified name", ppPStr q]) sty
844
845 unknownImpSpecErr ie imp_mod locn
846   = addShortErrLocLine locn (\ sty ->
847     ppBesides [ppStr "module ", ppPStr imp_mod, ppStr " does not export `", ppr sty (ie_name ie), ppStr "'"])
848
849 duplicateImpSpecErr ie imp_mod locn
850   = addShortErrLocLine locn (\ sty ->
851     ppBesides [ppStr "`", ppr sty (ie_name ie), ppStr "' already seen in import list"])
852
853 allWhenSynImpSpecWarn n imp_mod locn
854   = addShortWarnLocLine locn (\ sty ->
855     ppBesides [ppStr "type synonym `", ppr sty n, ppStr "' should not be imported with (..)"])
856
857 allWhenAbsImpSpecErr n imp_mod locn
858   = addShortErrLocLine locn (\ sty ->
859     ppBesides [ppStr "module ", ppPStr imp_mod, ppStr " only exports `", ppr sty n, ppStr "' abstractly"])
860
861 withWhenAbsImpSpecErr n imp_mod locn
862   = addShortErrLocLine locn (\ sty ->
863     ppBesides [ppStr "module ", ppPStr imp_mod, ppStr " only exports `", ppr sty n, ppStr "' abstractly"])
864
865 withImpSpecErr str n has ns imp_mod locn
866   = addErrLoc locn "" (\ sty ->
867     ppAboves [ ppBesides [ppStr "inconsistent list of", ppStr str, ppStr "in import list for `", ppr sty n, ppStr "'"],
868                ppCat [ppStr "    expected:", ppInterleave ppComma (map (ppr sty) has)],
869                ppCat [ppStr "    found:   ", ppInterleave ppComma (map (ppr sty) ns)] ])
870
871 dupFieldErr con locn (dup:rest)
872   = addShortErrLocLine locn (\ sty ->
873     ppBesides [ppStr "record field `", ppr sty dup, ppStr "declared multiple times in `", ppr sty con, ppStr "'"])
874 \end{code}