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