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 ( DynFlag(..), opt_NoImplicitPrelude )
15 import HsSyn ( HsModule(..), HsDecl(..), IE(..), ieName, ImportDecl(..),
18 import RdrHsSyn ( RdrNameIE, RdrNameImportDecl,
19 RdrNameHsModule, RdrNameHsDecl
21 import RnIfaces ( getInterfaceExports, recordLocalSlurps )
22 import RnHiFiles ( getDeclBinders )
27 import PrelNames ( pRELUDE_Name, mAIN_Name, main_RDR )
28 import UniqFM ( lookupUFM )
29 import Bag ( bagToList )
30 import Module ( ModuleName, mkModuleInThisPackage, WhereFrom(..) )
32 import Name ( Name, nameSrcLoc,
33 setLocalNameSort, nameOccName, nameEnvElts )
34 import HscTypes ( Provenance(..), ImportReason(..), GlobalRdrEnv,
35 GenAvailInfo(..), AvailInfo, Avails, AvailEnv )
36 import RdrName ( RdrName, rdrNameOcc, setRdrNameOcc, mkRdrQual, mkRdrUnqual, isUnqual )
37 import OccName ( setOccNameSpace, dataName )
38 import NameSet ( elemNameSet, emptyNameSet )
40 import Maybes ( maybeToBool, catMaybes, mapMaybe )
41 import UniqFM ( emptyUFM, listToUFM )
42 import ListSetOps ( removeDups )
43 import Util ( sortLt )
44 import List ( partition )
49 %************************************************************************
51 \subsection{Get global names}
53 %************************************************************************
56 getGlobalNames :: RdrNameHsModule
57 -> RnMG (Maybe (GlobalRdrEnv, -- Maps all in-scope things
58 GlobalRdrEnv, -- Maps just *local* things
59 Avails, -- The exported stuff
60 AvailEnv -- Maps a name to its parent AvailInfo
61 -- Just for in-scope things only
63 -- Nothing => no need to recompile
65 getGlobalNames (HsModule this_mod _ exports imports decls _ mod_loc)
66 = -- These two fix-loops are to get the right
67 -- provenance information into a Name
68 fixRn ( \ ~(Just (rec_gbl_env, _, rec_export_avails, _)) ->
71 rec_unqual_fn :: Name -> Bool -- Is this chap in scope unqualified?
72 rec_unqual_fn = unQualInScope rec_gbl_env
74 rec_exp_fn :: Name -> Bool
75 rec_exp_fn = mk_export_fn (availsToNameSet rec_export_avails)
78 -- PROCESS LOCAL DECLS
79 -- Do these *first* so that the correct provenance gets
80 -- into the global name cache.
81 importsFromLocalDecls this_mod rec_exp_fn decls
82 `thenRn` \ (local_gbl_env, local_mod_avails) ->
84 -- PROCESS IMPORT DECLS
85 -- Do the non {- SOURCE -} ones first, so that we get a helpful
86 -- warning for {- SOURCE -} ones that are unnecessary
88 (source, ordinary) = partition is_source_import all_imports
89 is_source_import (ImportDecl _ ImportByUserSource _ _ _ _) = True
90 is_source_import other = False
92 mapAndUnzipRn (importsFromImportDecl rec_unqual_fn) ordinary
93 `thenRn` \ (imp_gbl_envs1, imp_avails_s1) ->
94 mapAndUnzipRn (importsFromImportDecl rec_unqual_fn) source
95 `thenRn` \ (imp_gbl_envs2, imp_avails_s2) ->
98 -- We put the local env second, so that a local provenance
99 -- "wins", even if a module imports itself.
101 gbl_env :: GlobalRdrEnv
102 imp_gbl_env = foldr plusGlobalRdrEnv emptyRdrEnv (imp_gbl_envs2 ++ imp_gbl_envs1)
103 gbl_env = imp_gbl_env `plusGlobalRdrEnv` local_gbl_env
105 all_avails :: ExportAvails
106 all_avails = foldr plusExportAvails local_mod_avails (imp_avails_s2 ++ imp_avails_s1)
107 (_, global_avail_env) = all_avails
110 -- TRY FOR EARLY EXIT
111 -- We can't go for an early exit before this because we have to check
112 -- for name clashes. Consider:
114 -- module A where module B where
118 -- Suppose I've compiled everything up, and then I add a
119 -- new definition to module B, that defines "f".
121 -- Then I must detect the name clash in A before going for an early
122 -- exit. The early-exit code checks what's actually needed from B
123 -- to compile A, and of course that doesn't include B.f. That's
124 -- why we wait till after the plusEnv stuff to do the early-exit.
126 -- Check For early exit
127 checkErrsRn `thenRn` \ no_errs_so_far ->
128 if not no_errs_so_far then
129 -- Found errors already, so exit now
133 -- PROCESS EXPORT LISTS
134 exportsFromAvail this_mod exports all_avails gbl_env `thenRn` \ export_avails ->
138 returnRn (Just (gbl_env, local_gbl_env, export_avails, global_avail_env))
141 all_imports = prel_imports ++ imports
143 -- NB: opt_NoImplicitPrelude is slightly different to import Prelude ();
144 -- because the former doesn't even look at Prelude.hi for instance declarations,
145 -- whereas the latter does.
146 prel_imports | this_mod == pRELUDE_Name ||
147 explicit_prelude_import ||
148 opt_NoImplicitPrelude
151 | otherwise = [ImportDecl pRELUDE_Name
153 False {- Not qualified -}
154 Nothing {- No "as" -}
155 Nothing {- No import list -}
158 explicit_prelude_import
159 = not (null [ () | (ImportDecl mod _ _ _ _ _) <- imports, mod == pRELUDE_Name ])
163 importsFromImportDecl :: (Name -> Bool) -- OK to omit qualifier
165 -> RnMG (GlobalRdrEnv,
168 importsFromImportDecl is_unqual (ImportDecl imp_mod_name from qual_only as_mod import_spec iloc)
169 = pushSrcLocRn iloc $
170 getInterfaceExports imp_mod_name from `thenRn` \ (imp_mod, avails) ->
173 -- If there's an error in getInterfaceExports, (e.g. interface
174 -- file not found) we get lots of spurious errors from 'filterImports'
175 returnRn (emptyRdrEnv, mkEmptyExportAvails imp_mod_name)
178 filterImports imp_mod_name import_spec avails `thenRn` \ (filtered_avails, hides, explicits) ->
181 mk_provenance name = NonLocalDef (UserImport imp_mod iloc (name `elemNameSet` explicits))
185 qualifyImports imp_mod_name
186 (not qual_only) -- Maybe want unqualified names
194 importsFromLocalDecls mod_name rec_exp_fn decls
195 = mapRn (getLocalDeclBinders mod rec_exp_fn) decls `thenRn` \ avails_s ->
198 avails = concat avails_s
200 all_names :: [Name] -- All the defns; no dups eliminated
201 all_names = [name | avail <- avails, name <- availNames avail]
204 (_, dups) = removeDups compare all_names
206 -- Check for duplicate definitions
207 mapRn_ (addErrRn . dupDeclErr) dups `thenRn_`
209 -- Record that locally-defined things are available
210 recordLocalSlurps avails `thenRn_`
212 -- Build the environment
213 qualifyImports mod_name
214 True -- Want unqualified names
217 (\n -> LocalDef) -- Provenance is local
220 mod = mkModuleInThisPackage mod_name
222 getLocalDeclBinders :: Module
223 -> (Name -> Bool) -- Is-exported predicate
224 -> RdrNameHsDecl -> RnMG Avails
225 getLocalDeclBinders mod rec_exp_fn (ValD binds)
226 = mapRn do_one (bagToList (collectTopBinders binds))
228 do_one (rdr_name, loc) = newLocalName mod rec_exp_fn rdr_name loc `thenRn` \ name ->
229 returnRn (Avail name)
231 getLocalDeclBinders mod rec_exp_fn decl
232 = getDeclBinders (newLocalName mod rec_exp_fn) decl `thenRn` \ maybe_avail ->
234 Nothing -> returnRn [] -- Instance decls and suchlike
235 Just avail -> returnRn [avail]
237 newLocalName mod rec_exp_fn rdr_name loc
238 = check_unqual rdr_name loc `thenRn_`
239 newTopBinder mod rdr_name loc `thenRn` \ name ->
240 returnRn (setLocalNameSort name (rec_exp_fn name))
242 -- There should never be a qualified name in a binding position (except in instance decls)
243 -- The parser doesn't check this because the same parser parses instance decls
244 check_unqual rdr_name loc
245 | isUnqual rdr_name = returnRn ()
246 | otherwise = qualNameErr (text "the binding for" <+> quotes (ppr rdr_name))
251 %************************************************************************
253 \subsection{Filtering imports}
255 %************************************************************************
257 @filterImports@ takes the @ExportEnv@ telling what the imported module makes
258 available, and filters it through the import spec (if any).
261 filterImports :: ModuleName -- The module being imported
262 -> Maybe (Bool, [RdrNameIE]) -- Import spec; True => hiding
263 -> [AvailInfo] -- What's available
264 -> RnMG ([AvailInfo], -- What's actually imported
265 [AvailInfo], -- What's to be hidden
266 -- (the unqualified version, that is)
267 -- (We need to return both the above sets, because
268 -- the qualified version is never hidden; so we can't
269 -- implement hiding by reducing what's imported.)
270 NameSet) -- What was imported explicitly
272 -- Complains if import spec mentions things that the module doesn't export
273 -- Warns/informs if import spec contains duplicates.
274 filterImports mod Nothing imports
275 = returnRn (imports, [], emptyNameSet)
277 filterImports mod (Just (want_hiding, import_items)) avails
278 = flatMapRn get_item import_items `thenRn` \ avails_w_explicits ->
280 (item_avails, explicits_s) = unzip avails_w_explicits
281 explicits = foldl addListToNameSet emptyNameSet explicits_s
285 -- All imported; item_avails to be hidden
286 returnRn (avails, item_avails, emptyNameSet)
288 -- Just item_avails imported; nothing to be hidden
289 returnRn (item_avails, [], explicits)
291 import_fm :: FiniteMap OccName AvailInfo
292 import_fm = listToFM [ (nameOccName name, avail)
294 name <- availNames avail]
295 -- Even though availNames returns data constructors too,
296 -- they won't make any difference because naked entities like T
297 -- in an import list map to TcOccs, not VarOccs.
299 bale_out item = addErrRn (badImportItemErr mod item) `thenRn_`
302 get_item item@(IEModuleContents _) = bale_out item
304 get_item item@(IEThingAll _)
305 = case check_item item of
306 Nothing -> bale_out item
307 Just avail@(AvailTC _ [n]) -> -- This occurs when you import T(..), but
308 -- only export T abstractly. The single [n]
309 -- in the AvailTC is the type or class itself
310 addWarnRn (dodgyImportWarn mod item) `thenRn_`
311 returnRn [(avail, [availName avail])]
312 Just avail -> returnRn [(avail, [availName avail])]
314 get_item item@(IEThingAbs n)
315 | want_hiding -- hiding( C )
316 -- Here the 'C' can be a data constructor *or* a type/class
317 = case catMaybes [check_item item, check_item (IEThingAbs data_n)] of
319 avails -> returnRn [(a, []) | a <- avails]
320 -- The 'explicits' list is irrelevant when hiding
322 data_n = setRdrNameOcc n (setOccNameSpace (rdrNameOcc n) dataName)
325 = case check_item item of
326 Nothing -> bale_out item
327 Just avail -> returnRn [(avail, availNames avail)]
330 | not (maybeToBool maybe_in_import_avails) ||
331 not (maybeToBool maybe_filtered_avail)
335 = Just filtered_avail
338 wanted_occ = rdrNameOcc (ieName item)
339 maybe_in_import_avails = lookupFM import_fm wanted_occ
341 Just avail = maybe_in_import_avails
342 maybe_filtered_avail = filterAvail item avail
343 Just filtered_avail = maybe_filtered_avail
348 %************************************************************************
350 \subsection{Qualifiying imports}
352 %************************************************************************
354 @qualifyImports@ takes the @ExportEnv@ after filtering through the import spec
355 of an import decl, and deals with producing an @RnEnv@ with the
356 right qualified names. It also turns the @Names@ in the @ExportEnv@ into
357 fully fledged @Names@.
360 qualifyImports :: ModuleName -- Imported module
361 -> Bool -- True <=> want unqualified import
362 -> Maybe ModuleName -- Optional "as M" part
363 -> [AvailInfo] -- What's to be hidden
364 -> (Name -> Provenance)
365 -> Avails -- Whats imported and how
366 -> RnMG (GlobalRdrEnv, ExportAvails)
368 qualifyImports this_mod unqual_imp as_mod hides mk_provenance avails
370 -- Make the name environment. We're talking about a
371 -- single module here, so there must be no name clashes.
372 -- In practice there only ever will be if it's the module
375 -- Add the things that are available
376 name_env1 = foldl add_avail emptyRdrEnv avails
378 -- Delete things that are hidden
379 name_env2 = foldl del_avail name_env1 hides
381 -- Create the export-availability info
382 export_avails = mkExportAvails qual_mod unqual_imp name_env2 avails
384 returnRn (name_env2, export_avails)
387 qual_mod = case as_mod of
389 Just another_name -> another_name
391 add_avail :: GlobalRdrEnv -> AvailInfo -> GlobalRdrEnv
392 add_avail env avail = foldl add_name env (availNames avail)
398 env1 = addOneToGlobalRdrEnv env (mkRdrQual qual_mod occ) (name,prov)
399 env2 = addOneToGlobalRdrEnv env1 (mkRdrUnqual occ) (name,prov)
400 occ = nameOccName name
401 prov = mk_provenance name
403 del_avail env avail = foldl delOneFromGlobalRdrEnv env rdr_names
405 rdr_names = map (mkRdrUnqual . nameOccName) (availNames avail)
408 mkEmptyExportAvails :: ModuleName -> ExportAvails
409 mkEmptyExportAvails mod_name = (unitFM mod_name [], emptyUFM)
411 mkExportAvails :: ModuleName -> Bool -> GlobalRdrEnv -> [AvailInfo] -> ExportAvails
412 mkExportAvails mod_name unqual_imp name_env avails
413 = (mod_avail_env, entity_avail_env)
415 mod_avail_env = unitFM mod_name unqual_avails
417 -- unqual_avails is the Avails that are visible in *unqualfied* form
418 -- (1.4 Report, Section 5.1.1)
420 -- import T hiding( f )
421 -- we delete f from avails
423 unqual_avails | not unqual_imp = [] -- Short cut when no unqualified imports
424 | otherwise = mapMaybe prune avails
426 prune (Avail n) | unqual_in_scope n = Just (Avail n)
427 prune (Avail n) | otherwise = Nothing
428 prune (AvailTC n ns) | null uqs = Nothing
429 | otherwise = Just (AvailTC n uqs)
431 uqs = filter unqual_in_scope ns
433 unqual_in_scope n = unQualInScope name_env n
435 entity_avail_env = listToUFM [ (name,avail) | avail <- avails,
436 name <- availNames avail]
438 plusExportAvails :: ExportAvails -> ExportAvails -> ExportAvails
439 plusExportAvails (m1, e1) (m2, e2)
440 = (plusFM_C (++) m1 m2, plusAvailEnv e1 e2)
441 -- ToDo: wasteful: we do this once for each constructor!
445 %************************************************************************
447 \subsection{Export list processing}
449 %************************************************************************
451 Processing the export list.
453 You might think that we should record things that appear in the export list
454 as ``occurrences'' (using @addOccurrenceName@), but you'd be wrong.
455 We do check (here) that they are in scope,
456 but there is no need to slurp in their actual declaration
457 (which is what @addOccurrenceName@ forces).
459 Indeed, doing so would big trouble when
460 compiling @PrelBase@, because it re-exports @GHC@, which includes @takeMVar#@,
461 whose type includes @ConcBase.StateAndSynchVar#@, and so on...
464 type ExportAccum -- The type of the accumulating parameter of
465 -- the main worker function in exportsFromAvail
466 = ([ModuleName], -- 'module M's seen so far
467 ExportOccMap, -- Tracks exported occurrence names
468 AvailEnv) -- The accumulated exported stuff, kept in an env
469 -- so we can common-up related AvailInfos
471 type ExportOccMap = FiniteMap OccName (Name, RdrNameIE)
472 -- Tracks what a particular exported OccName
473 -- in an export list refers to, and which item
474 -- it came from. It's illegal to export two distinct things
475 -- that have the same occurrence name
478 exportsFromAvail :: ModuleName
479 -> Maybe [RdrNameIE] -- Export spec
483 -- Complains if two distinct exports have same OccName
484 -- Warns about identical exports.
485 -- Complains about exports items not in scope
486 exportsFromAvail this_mod Nothing export_avails global_name_env
487 = exportsFromAvail this_mod true_exports export_avails global_name_env
489 true_exports = Just $ if this_mod == mAIN_Name
490 then [IEVar main_RDR]
491 -- export Main.main *only* unless otherwise specified,
492 else [IEModuleContents this_mod]
493 -- but for all other modules export everything.
495 exportsFromAvail this_mod (Just export_items)
496 (mod_avail_env, entity_avail_env)
498 = doptRn Opt_WarnDuplicateExports `thenRn` \ warn_dup_exports ->
499 foldlRn (exports_from_item warn_dup_exports)
500 ([], emptyFM, emptyAvailEnv) export_items
501 `thenRn` \ (_, _, export_avail_map) ->
503 export_avails :: [AvailInfo]
504 export_avails = nameEnvElts export_avail_map
506 returnRn export_avails
509 exports_from_item :: Bool -> ExportAccum -> RdrNameIE -> RnMG ExportAccum
511 exports_from_item warn_dups acc@(mods, occs, avails) ie@(IEModuleContents mod)
512 | mod `elem` mods -- Duplicate export of M
513 = warnCheckRn warn_dups (dupModuleExport mod) `thenRn_`
517 = case lookupFM mod_avail_env mod of
518 Nothing -> failWithRn acc (modExportErr mod)
519 Just mod_avails -> foldlRn (check_occs ie) occs mod_avails
522 avails' = foldl addAvail avails mod_avails
524 returnRn (mod:mods, occs', avails')
526 exports_from_item warn_dups acc@(mods, occs, avails) ie
527 | not (maybeToBool maybe_in_scope)
528 = failWithRn acc (unknownNameErr (ieName ie))
530 | not (null dup_names)
531 = addNameClashErrRn rdr_name ((name,prov):dup_names) `thenRn_`
535 -- I can't see why this should ever happen; if the thing is in scope
536 -- at all it ought to have some availability
537 | not (maybeToBool maybe_avail)
538 = pprTrace "exportsFromAvail: curious Nothing:" (ppr name)
543 = failWithRn acc (exportItemErr ie)
545 | otherwise -- Phew! It's OK! Now to check the occurrence stuff!
548 = warnCheckRn (ok_item ie avail) (dodgyExportWarn ie) `thenRn_`
549 check_occs ie occs export_avail `thenRn` \ occs' ->
550 returnRn (mods, occs', addAvail avails export_avail)
554 maybe_in_scope = lookupFM global_name_env rdr_name
555 Just ((name,prov):dup_names) = maybe_in_scope
556 maybe_avail = lookupUFM entity_avail_env name
557 Just avail = maybe_avail
558 maybe_export_avail = filterAvail ie avail
559 enough_avail = maybeToBool maybe_export_avail
560 Just export_avail = maybe_export_avail
562 ok_item (IEThingAll _) (AvailTC _ [n]) = False
563 -- This occurs when you import T(..), but
564 -- only export T abstractly. The single [n]
565 -- in the AvailTC is the type or class itself
568 check_occs :: RdrNameIE -> ExportOccMap -> AvailInfo -> RnMG ExportOccMap
569 check_occs ie occs avail
570 = doptRn Opt_WarnDuplicateExports `thenRn` \ warn_dup_exports ->
571 foldlRn (check warn_dup_exports) occs (availNames avail)
573 check warn_dup occs name
574 = case lookupFM occs name_occ of
575 Nothing -> returnRn (addToFM occs name_occ (name, ie))
577 | name == name' -> -- Duplicate export
579 (dupExportWarn name_occ ie ie')
580 `thenRn_` returnRn occs
582 | otherwise -> -- Same occ name but different names: an error
583 failWithRn occs (exportClashErr name_occ ie ie')
585 name_occ = nameOccName name
587 mk_export_fn :: NameSet -> (Name -> Bool) -- True => exported
588 mk_export_fn exported_names = \name -> name `elemNameSet` exported_names
591 %************************************************************************
595 %************************************************************************
598 badImportItemErr mod ie
599 = sep [ptext SLIT("Module"), quotes (ppr mod),
600 ptext SLIT("does not export"), quotes (ppr ie)]
602 dodgyImportWarn mod item = dodgyMsg (ptext SLIT("import")) item
603 dodgyExportWarn item = dodgyMsg (ptext SLIT("export")) item
605 dodgyMsg kind item@(IEThingAll tc)
606 = sep [ ptext SLIT("The") <+> kind <+> ptext SLIT("item") <+> quotes (ppr item),
607 ptext SLIT("suggests that") <+> quotes (ppr tc) <+> ptext SLIT("has constructor or class methods"),
608 ptext SLIT("but it has none; it is a type synonym or abstract type or class") ]
611 = hsep [ ptext SLIT("Unknown module in export list: module"), quotes (ppr mod)]
613 exportItemErr export_item
614 = sep [ ptext SLIT("The export item") <+> quotes (ppr export_item),
615 ptext SLIT("attempts to export constructors or class methods that are not visible here") ]
617 exportClashErr occ_name ie1 ie2
618 = hsep [ptext SLIT("The export items"), quotes (ppr ie1)
619 ,ptext SLIT("and"), quotes (ppr ie2)
620 ,ptext SLIT("create conflicting exports for"), quotes (ppr occ_name)]
623 = vcat [ptext SLIT("Multiple declarations of") <+> quotes (ppr n),
624 nest 4 (vcat (map ppr sorted_locs))]
626 sorted_locs = sortLt occ'ed_before (map nameSrcLoc (n:ns))
627 occ'ed_before a b = LT == compare a b
629 dupExportWarn occ_name ie1 ie2
630 = hsep [quotes (ppr occ_name),
631 ptext SLIT("is exported by"), quotes (ppr ie1),
632 ptext SLIT("and"), quotes (ppr ie2)]
635 = hsep [ptext SLIT("Duplicate"),
636 quotes (ptext SLIT("Module") <+> ppr mod),
637 ptext SLIT("in export list")]