2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[RnNames]{Extracting imported and top-level names in scope}
11 #include "HsVersions.h"
13 import CmdLineOpts ( DynFlags, DynFlag(..), dopt, opt_NoImplicitPrelude )
15 import HsSyn ( HsModule(..), HsDecl(..), IE(..), ieName, ImportDecl(..),
18 import RdrHsSyn ( RdrNameIE, RdrNameImportDecl,
19 RdrNameHsModule, RdrNameHsDecl
21 import RnIfaces ( getInterfaceExports, getDeclBinders,
22 recordLocalSlurps, checkModUsage,
23 outOfDate, findAndReadIface )
28 import PrelNames ( pRELUDE_Name, mAIN_Name, main_RDR )
29 import UniqFM ( lookupUFM )
30 import Bag ( bagToList )
31 import Module ( ModuleName, mkModuleInThisPackage, WhereFrom(..) )
33 import Name ( Name, nameSrcLoc,
34 setLocalNameSort, nameOccName, nameEnvElts )
35 import HscTypes ( Provenance(..), ImportReason(..), GlobalRdrEnv,
36 GenAvailInfo(..), AvailInfo, Avails, AvailEnv )
37 import RdrName ( RdrName, rdrNameOcc, setRdrNameOcc, mkRdrQual, mkRdrUnqual,
39 import OccName ( setOccNameSpace, dataName )
40 import NameSet ( elemNameSet, emptyNameSet )
42 import Maybes ( maybeToBool, catMaybes, mapMaybe )
43 import UniqFM ( emptyUFM, listToUFM )
44 import ListSetOps ( removeDups )
45 import Util ( sortLt )
46 import List ( partition )
51 %************************************************************************
53 \subsection{Get global names}
55 %************************************************************************
58 getGlobalNames :: RdrNameHsModule
59 -> RnMG (Maybe (GlobalRdrEnv, -- Maps all in-scope things
60 GlobalRdrEnv, -- Maps just *local* things
61 Avails, -- The exported stuff
62 AvailEnv, -- Maps a name to its parent AvailInfo
63 -- Just for in-scope things only
64 Maybe ParsedIface -- The old interface file, if any
66 -- Nothing => no need to recompile
68 getGlobalNames (HsModule this_mod _ exports imports decls _ mod_loc)
69 = -- These two fix-loops are to get the right
70 -- provenance information into a Name
71 fixRn ( \ ~(Just (rec_gbl_env, _, rec_export_avails, _, _)) ->
74 rec_unqual_fn :: Name -> Bool -- Is this chap in scope unqualified?
75 rec_unqual_fn = unQualInScope rec_gbl_env
77 rec_exp_fn :: Name -> Bool
78 rec_exp_fn = mk_export_fn (availsToNameSet rec_export_avails)
81 -- PROCESS LOCAL DECLS
82 -- Do these *first* so that the correct provenance gets
83 -- into the global name cache.
84 importsFromLocalDecls this_mod rec_exp_fn decls
85 `thenRn` \ (local_gbl_env, local_mod_avails) ->
87 -- PROCESS IMPORT DECLS
88 -- Do the non {- SOURCE -} ones first, so that we get a helpful
89 -- warning for {- SOURCE -} ones that are unnecessary
91 (source, ordinary) = partition is_source_import all_imports
92 is_source_import (ImportDecl _ ImportByUserSource _ _ _ _) = True
93 is_source_import other = False
95 mapAndUnzipRn (importsFromImportDecl rec_unqual_fn) ordinary
96 `thenRn` \ (imp_gbl_envs1, imp_avails_s1) ->
97 mapAndUnzipRn (importsFromImportDecl rec_unqual_fn) source
98 `thenRn` \ (imp_gbl_envs2, imp_avails_s2) ->
101 -- We put the local env second, so that a local provenance
102 -- "wins", even if a module imports itself.
104 gbl_env :: GlobalRdrEnv
105 imp_gbl_env = foldr plusGlobalRdrEnv emptyRdrEnv (imp_gbl_envs2 ++ imp_gbl_envs1)
106 gbl_env = imp_gbl_env `plusGlobalRdrEnv` local_gbl_env
108 all_avails :: ExportAvails
109 all_avails = foldr plusExportAvails local_mod_avails (imp_avails_s2 ++ imp_avails_s1)
110 (_, global_avail_env) = all_avails
113 -- TRY FOR EARLY EXIT
114 -- We can't go for an early exit before this because we have to check
115 -- for name clashes. Consider:
117 -- module A where module B where
121 -- Suppose I've compiled everything up, and then I add a
122 -- new definition to module B, that defines "f".
124 -- Then I must detect the name clash in A before going for an early
125 -- exit. The early-exit code checks what's actually needed from B
126 -- to compile A, and of course that doesn't include B.f. That's
127 -- why we wait till after the plusEnv stuff to do the early-exit.
129 -- Check For early exit
130 checkErrsRn `thenRn` \ no_errs_so_far ->
131 if not no_errs_so_far then
132 -- Found errors already, so exit now
135 checkEarlyExit this_mod `thenRn` \ (up_to_date, old_iface) ->
137 -- Interface files are sufficiently unchanged
138 putDocRn (text "Compilation IS NOT required") `thenRn_`
142 -- PROCESS EXPORT LISTS
143 exportsFromAvail this_mod exports all_avails gbl_env `thenRn` \ export_avails ->
147 returnRn (Just (gbl_env, local_gbl_env, export_avails, global_avail_env, old_iface))
150 all_imports = prel_imports ++ imports
152 -- NB: opt_NoImplicitPrelude is slightly different to import Prelude ();
153 -- because the former doesn't even look at Prelude.hi for instance declarations,
154 -- whereas the latter does.
155 prel_imports | this_mod == pRELUDE_Name ||
156 explicit_prelude_import ||
157 opt_NoImplicitPrelude
160 | otherwise = [ImportDecl pRELUDE_Name
162 False {- Not qualified -}
163 Nothing {- No "as" -}
164 Nothing {- No import list -}
167 explicit_prelude_import
168 = not (null [ () | (ImportDecl mod _ _ _ _ _) <- imports, mod == pRELUDE_Name ])
172 importsFromImportDecl :: (Name -> Bool) -- OK to omit qualifier
174 -> RnMG (GlobalRdrEnv,
177 importsFromImportDecl is_unqual (ImportDecl imp_mod_name from qual_only as_mod import_spec iloc)
178 = pushSrcLocRn iloc $
179 getInterfaceExports imp_mod_name from `thenRn` \ (imp_mod, avails) ->
182 -- If there's an error in getInterfaceExports, (e.g. interface
183 -- file not found) we get lots of spurious errors from 'filterImports'
184 returnRn (emptyRdrEnv, mkEmptyExportAvails imp_mod_name)
187 filterImports imp_mod_name import_spec avails `thenRn` \ (filtered_avails, hides, explicits) ->
190 mk_provenance name = NonLocalDef (UserImport imp_mod iloc (name `elemNameSet` explicits))
194 qualifyImports imp_mod_name
195 (not qual_only) -- Maybe want unqualified names
203 importsFromLocalDecls mod_name rec_exp_fn decls
204 = mapRn (getLocalDeclBinders mod rec_exp_fn) decls `thenRn` \ avails_s ->
207 avails = concat avails_s
209 all_names :: [Name] -- All the defns; no dups eliminated
210 all_names = [name | avail <- avails, name <- availNames avail]
213 (_, dups) = removeDups compare all_names
215 -- Check for duplicate definitions
216 mapRn_ (addErrRn . dupDeclErr) dups `thenRn_`
218 -- Record that locally-defined things are available
219 recordLocalSlurps avails `thenRn_`
221 -- Build the environment
222 qualifyImports mod_name
223 True -- Want unqualified names
226 (\n -> LocalDef) -- Provenance is local
229 mod = mkModuleInThisPackage mod_name
231 getLocalDeclBinders :: Module
232 -> (Name -> Bool) -- Is-exported predicate
233 -> RdrNameHsDecl -> RnMG Avails
234 getLocalDeclBinders mod rec_exp_fn (ValD binds)
235 = mapRn do_one (bagToList (collectTopBinders binds))
237 do_one (rdr_name, loc) = newLocalName mod rec_exp_fn rdr_name loc `thenRn` \ name ->
238 returnRn (Avail name)
240 getLocalDeclBinders mod rec_exp_fn decl
241 = getDeclBinders (newLocalName mod rec_exp_fn) decl `thenRn` \ maybe_avail ->
243 Nothing -> returnRn [] -- Instance decls and suchlike
244 Just avail -> returnRn [avail]
246 newLocalName mod rec_exp_fn rdr_name loc
247 = check_unqual rdr_name loc `thenRn_`
248 newTopBinder mod rdr_name loc `thenRn` \ name ->
249 returnRn (setLocalNameSort name (rec_exp_fn name))
251 -- There should never be a qualified name in a binding position (except in instance decls)
252 -- The parser doesn't check this because the same parser parses instance decls
253 check_unqual rdr_name loc
254 | isUnqual rdr_name = returnRn ()
255 | otherwise = qualNameErr (text "the binding for" <+> quotes (ppr rdr_name))
260 %************************************************************************
262 \subsection{Filtering imports}
264 %************************************************************************
266 @filterImports@ takes the @ExportEnv@ telling what the imported module makes
267 available, and filters it through the import spec (if any).
270 filterImports :: ModuleName -- The module being imported
271 -> Maybe (Bool, [RdrNameIE]) -- Import spec; True => hiding
272 -> [AvailInfo] -- What's available
273 -> RnMG ([AvailInfo], -- What's actually imported
274 [AvailInfo], -- What's to be hidden
275 -- (the unqualified version, that is)
276 -- (We need to return both the above sets, because
277 -- the qualified version is never hidden; so we can't
278 -- implement hiding by reducing what's imported.)
279 NameSet) -- What was imported explicitly
281 -- Complains if import spec mentions things that the module doesn't export
282 -- Warns/informs if import spec contains duplicates.
283 filterImports mod Nothing imports
284 = returnRn (imports, [], emptyNameSet)
286 filterImports mod (Just (want_hiding, import_items)) avails
287 = flatMapRn get_item import_items `thenRn` \ avails_w_explicits ->
289 (item_avails, explicits_s) = unzip avails_w_explicits
290 explicits = foldl addListToNameSet emptyNameSet explicits_s
294 -- All imported; item_avails to be hidden
295 returnRn (avails, item_avails, emptyNameSet)
297 -- Just item_avails imported; nothing to be hidden
298 returnRn (item_avails, [], explicits)
300 import_fm :: FiniteMap OccName AvailInfo
301 import_fm = listToFM [ (nameOccName name, avail)
303 name <- availNames avail]
304 -- Even though availNames returns data constructors too,
305 -- they won't make any difference because naked entities like T
306 -- in an import list map to TcOccs, not VarOccs.
308 bale_out item = addErrRn (badImportItemErr mod item) `thenRn_`
311 get_item item@(IEModuleContents _) = bale_out item
313 get_item item@(IEThingAll _)
314 = case check_item item of
315 Nothing -> bale_out item
316 Just avail@(AvailTC _ [n]) -> -- This occurs when you import T(..), but
317 -- only export T abstractly. The single [n]
318 -- in the AvailTC is the type or class itself
319 addWarnRn (dodgyImportWarn mod item) `thenRn_`
320 returnRn [(avail, [availName avail])]
321 Just avail -> returnRn [(avail, [availName avail])]
323 get_item item@(IEThingAbs n)
324 | want_hiding -- hiding( C )
325 -- Here the 'C' can be a data constructor *or* a type/class
326 = case catMaybes [check_item item, check_item (IEThingAbs data_n)] of
328 avails -> returnRn [(a, []) | a <- avails]
329 -- The 'explicits' list is irrelevant when hiding
331 data_n = setRdrNameOcc n (setOccNameSpace (rdrNameOcc n) dataName)
334 = case check_item item of
335 Nothing -> bale_out item
336 Just avail -> returnRn [(avail, availNames avail)]
339 | not (maybeToBool maybe_in_import_avails) ||
340 not (maybeToBool maybe_filtered_avail)
344 = Just filtered_avail
347 wanted_occ = rdrNameOcc (ieName item)
348 maybe_in_import_avails = lookupFM import_fm wanted_occ
350 Just avail = maybe_in_import_avails
351 maybe_filtered_avail = filterAvail item avail
352 Just filtered_avail = maybe_filtered_avail
357 %************************************************************************
359 \subsection{Qualifiying imports}
361 %************************************************************************
363 @qualifyImports@ takes the @ExportEnv@ after filtering through the import spec
364 of an import decl, and deals with producing an @RnEnv@ with the
365 right qualified names. It also turns the @Names@ in the @ExportEnv@ into
366 fully fledged @Names@.
369 qualifyImports :: ModuleName -- Imported module
370 -> Bool -- True <=> want unqualified import
371 -> Maybe ModuleName -- Optional "as M" part
372 -> [AvailInfo] -- What's to be hidden
373 -> (Name -> Provenance)
374 -> Avails -- Whats imported and how
375 -> RnMG (GlobalRdrEnv, ExportAvails)
377 qualifyImports this_mod unqual_imp as_mod hides mk_provenance avails
379 -- Make the name environment. We're talking about a
380 -- single module here, so there must be no name clashes.
381 -- In practice there only ever will be if it's the module
384 -- Add the things that are available
385 name_env1 = foldl add_avail emptyRdrEnv avails
387 -- Delete things that are hidden
388 name_env2 = foldl del_avail name_env1 hides
390 -- Create the export-availability info
391 export_avails = mkExportAvails qual_mod unqual_imp name_env2 avails
393 returnRn (name_env2, export_avails)
396 qual_mod = case as_mod of
398 Just another_name -> another_name
400 add_avail :: GlobalRdrEnv -> AvailInfo -> GlobalRdrEnv
401 add_avail env avail = foldl add_name env (availNames avail)
407 env1 = addOneToGlobalRdrEnv env (mkRdrQual qual_mod occ) (name,prov)
408 env2 = addOneToGlobalRdrEnv env1 (mkRdrUnqual occ) (name,prov)
409 occ = nameOccName name
410 prov = mk_provenance name
412 del_avail env avail = foldl delOneFromGlobalRdrEnv env rdr_names
414 rdr_names = map (mkRdrUnqual . nameOccName) (availNames avail)
417 mkEmptyExportAvails :: ModuleName -> ExportAvails
418 mkEmptyExportAvails mod_name = (unitFM mod_name [], emptyUFM)
420 mkExportAvails :: ModuleName -> Bool -> GlobalRdrEnv -> [AvailInfo] -> ExportAvails
421 mkExportAvails mod_name unqual_imp name_env avails
422 = (mod_avail_env, entity_avail_env)
424 mod_avail_env = unitFM mod_name unqual_avails
426 -- unqual_avails is the Avails that are visible in *unqualfied* form
427 -- (1.4 Report, Section 5.1.1)
429 -- import T hiding( f )
430 -- we delete f from avails
432 unqual_avails | not unqual_imp = [] -- Short cut when no unqualified imports
433 | otherwise = mapMaybe prune avails
435 prune (Avail n) | unqual_in_scope n = Just (Avail n)
436 prune (Avail n) | otherwise = Nothing
437 prune (AvailTC n ns) | null uqs = Nothing
438 | otherwise = Just (AvailTC n uqs)
440 uqs = filter unqual_in_scope ns
442 unqual_in_scope n = unQualInScope name_env n
444 entity_avail_env = listToUFM [ (name,avail) | avail <- avails,
445 name <- availNames avail]
447 plusExportAvails :: ExportAvails -> ExportAvails -> ExportAvails
448 plusExportAvails (m1, e1) (m2, e2)
449 = (plusFM_C (++) m1 m2, plusAvailEnv e1 e2)
450 -- ToDo: wasteful: we do this once for each constructor!
454 %************************************************************************
456 \subsection{Export list processing}
458 %************************************************************************
460 Processing the export list.
462 You might think that we should record things that appear in the export list
463 as ``occurrences'' (using @addOccurrenceName@), but you'd be wrong.
464 We do check (here) that they are in scope,
465 but there is no need to slurp in their actual declaration
466 (which is what @addOccurrenceName@ forces).
468 Indeed, doing so would big trouble when
469 compiling @PrelBase@, because it re-exports @GHC@, which includes @takeMVar#@,
470 whose type includes @ConcBase.StateAndSynchVar#@, and so on...
473 type ExportAccum -- The type of the accumulating parameter of
474 -- the main worker function in exportsFromAvail
475 = ([ModuleName], -- 'module M's seen so far
476 ExportOccMap, -- Tracks exported occurrence names
477 AvailEnv) -- The accumulated exported stuff, kept in an env
478 -- so we can common-up related AvailInfos
480 type ExportOccMap = FiniteMap OccName (Name, RdrNameIE)
481 -- Tracks what a particular exported OccName
482 -- in an export list refers to, and which item
483 -- it came from. It's illegal to export two distinct things
484 -- that have the same occurrence name
487 exportsFromAvail :: ModuleName
488 -> Maybe [RdrNameIE] -- Export spec
492 -- Complains if two distinct exports have same OccName
493 -- Warns about identical exports.
494 -- Complains about exports items not in scope
495 exportsFromAvail this_mod Nothing export_avails global_name_env
496 = exportsFromAvail this_mod true_exports export_avails global_name_env
498 true_exports = Just $ if this_mod == mAIN_Name
499 then [IEVar main_RDR]
500 -- export Main.main *only* unless otherwise specified,
501 else [IEModuleContents this_mod]
502 -- but for all other modules export everything.
504 exportsFromAvail this_mod (Just export_items)
505 (mod_avail_env, entity_avail_env)
507 = doptRn Opt_WarnDuplicateExports `thenRn` \ warn_dup_exports ->
508 foldlRn (exports_from_item warn_dup_exports)
509 ([], emptyFM, emptyAvailEnv) export_items
510 `thenRn` \ (_, _, export_avail_map) ->
512 export_avails :: [AvailInfo]
513 export_avails = nameEnvElts export_avail_map
515 returnRn export_avails
518 exports_from_item :: Bool -> ExportAccum -> RdrNameIE -> RnMG ExportAccum
520 exports_from_item warn_dups acc@(mods, occs, avails) ie@(IEModuleContents mod)
521 | mod `elem` mods -- Duplicate export of M
522 = warnCheckRn warn_dups (dupModuleExport mod) `thenRn_`
526 = case lookupFM mod_avail_env mod of
527 Nothing -> failWithRn acc (modExportErr mod)
528 Just mod_avails -> foldlRn (check_occs ie) occs mod_avails
531 avails' = foldl addAvail avails mod_avails
533 returnRn (mod:mods, occs', avails')
535 exports_from_item warn_dups acc@(mods, occs, avails) ie
536 | not (maybeToBool maybe_in_scope)
537 = failWithRn acc (unknownNameErr (ieName ie))
539 | not (null dup_names)
540 = addNameClashErrRn rdr_name ((name,prov):dup_names) `thenRn_`
544 -- I can't see why this should ever happen; if the thing is in scope
545 -- at all it ought to have some availability
546 | not (maybeToBool maybe_avail)
547 = pprTrace "exportsFromAvail: curious Nothing:" (ppr name)
552 = failWithRn acc (exportItemErr ie)
554 | otherwise -- Phew! It's OK! Now to check the occurrence stuff!
557 = warnCheckRn (ok_item ie avail) (dodgyExportWarn ie) `thenRn_`
558 check_occs ie occs export_avail `thenRn` \ occs' ->
559 returnRn (mods, occs', addAvail avails export_avail)
563 maybe_in_scope = lookupFM global_name_env rdr_name
564 Just ((name,prov):dup_names) = maybe_in_scope
565 maybe_avail = lookupUFM entity_avail_env name
566 Just avail = maybe_avail
567 maybe_export_avail = filterAvail ie avail
568 enough_avail = maybeToBool maybe_export_avail
569 Just export_avail = maybe_export_avail
571 ok_item (IEThingAll _) (AvailTC _ [n]) = False
572 -- This occurs when you import T(..), but
573 -- only export T abstractly. The single [n]
574 -- in the AvailTC is the type or class itself
577 check_occs :: RdrNameIE -> ExportOccMap -> AvailInfo -> RnMG ExportOccMap
578 check_occs ie occs avail
579 = doptRn Opt_WarnDuplicateExports `thenRn` \ warn_dup_exports ->
580 foldlRn (check warn_dup_exports) occs (availNames avail)
582 check warn_dup occs name
583 = case lookupFM occs name_occ of
584 Nothing -> returnRn (addToFM occs name_occ (name, ie))
586 | name == name' -> -- Duplicate export
588 (dupExportWarn name_occ ie ie')
589 `thenRn_` returnRn occs
591 | otherwise -> -- Same occ name but different names: an error
592 failWithRn occs (exportClashErr name_occ ie ie')
594 name_occ = nameOccName name
596 mk_export_fn :: NameSet -> (Name -> Bool) -- True => exported
597 mk_export_fn exported_names = \name -> name `elemNameSet` exported_names
600 %************************************************************************
604 %************************************************************************
607 badImportItemErr mod ie
608 = sep [ptext SLIT("Module"), quotes (ppr mod),
609 ptext SLIT("does not export"), quotes (ppr ie)]
611 dodgyImportWarn mod item = dodgyMsg (ptext SLIT("import")) item
612 dodgyExportWarn item = dodgyMsg (ptext SLIT("export")) item
614 dodgyMsg kind item@(IEThingAll tc)
615 = sep [ ptext SLIT("The") <+> kind <+> ptext SLIT("item") <+> quotes (ppr item),
616 ptext SLIT("suggests that") <+> quotes (ppr tc) <+> ptext SLIT("has constructor or class methods"),
617 ptext SLIT("but it has none; it is a type synonym or abstract type or class") ]
620 = hsep [ ptext SLIT("Unknown module in export list: module"), quotes (ppr mod)]
622 exportItemErr export_item
623 = sep [ ptext SLIT("The export item") <+> quotes (ppr export_item),
624 ptext SLIT("attempts to export constructors or class methods that are not visible here") ]
626 exportClashErr occ_name ie1 ie2
627 = hsep [ptext SLIT("The export items"), quotes (ppr ie1)
628 ,ptext SLIT("and"), quotes (ppr ie2)
629 ,ptext SLIT("create conflicting exports for"), quotes (ppr occ_name)]
632 = vcat [ptext SLIT("Multiple declarations of") <+> quotes (ppr n),
633 nest 4 (vcat (map ppr sorted_locs))]
635 sorted_locs = sortLt occ'ed_before (map nameSrcLoc (n:ns))
636 occ'ed_before a b = LT == compare a b
638 dupExportWarn occ_name ie1 ie2
639 = hsep [quotes (ppr occ_name),
640 ptext SLIT("is exported by"), quotes (ppr ie1),
641 ptext SLIT("and"), quotes (ppr ie2)]
644 = hsep [ptext SLIT("Duplicate"),
645 quotes (ptext SLIT("Module") <+> ppr mod),
646 ptext SLIT("in export list")]