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 ( opt_NoImplicitPrelude, opt_WarnDuplicateExports )
15 import HsSyn ( HsModule(..), HsDecl(..), IE(..), ieName, ImportDecl(..),
18 import RdrHsSyn ( RdrNameIE, RdrNameImportDecl,
19 RdrNameHsModule, RdrNameHsDecl
21 import RnIfaces ( getInterfaceExports, getDeclBinders,
22 recordLocalSlurps, checkModUsage, findAndReadIface, outOfDate
28 import PrelNames ( pRELUDE_Name, mAIN_Name, main_RDR )
29 import UniqFM ( lookupUFM )
30 import Bag ( bagToList )
31 import Module ( ModuleName, mkThisModule, pprModuleName, WhereFrom(..) )
33 import Name ( Name, ExportFlag(..), ImportReason(..), Provenance(..),
35 nameOccName, getSrcLoc, pprProvenance, getNameProvenance,
38 import RdrName ( RdrName, rdrNameOcc, setRdrNameOcc, mkRdrQual, mkRdrUnqual, isQual, isUnqual )
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 -> ExportFlag
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 eacly 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 -- RECORD BETTER PROVENANCES IN THE CACHE
143 -- The names in the envirnoment have better provenances (e.g. imported on line x)
144 -- than the names in the name cache. We update the latter now, so that we
145 -- we start renaming declarations we'll get the good names
146 -- The isQual is because the qualified name is always in scope
147 updateProvenances (concat [names | (rdr_name, names) <- rdrEnvToList gbl_env,
148 isQual rdr_name]) `thenRn_`
150 -- PROCESS EXPORT LISTS
151 exportsFromAvail this_mod exports all_avails gbl_env `thenRn` \ export_avails ->
155 returnRn (Just (gbl_env, local_gbl_env, export_avails, global_avail_env, old_iface))
158 all_imports = prel_imports ++ imports
160 -- NB: opt_NoImplicitPrelude is slightly different to import Prelude ();
161 -- because the former doesn't even look at Prelude.hi for instance declarations,
162 -- whereas the latter does.
163 prel_imports | this_mod == pRELUDE_Name ||
164 explicit_prelude_import ||
165 opt_NoImplicitPrelude
168 | otherwise = [ImportDecl pRELUDE_Name
170 False {- Not qualified -}
171 Nothing {- No "as" -}
172 Nothing {- No import list -}
175 explicit_prelude_import
176 = not (null [ () | (ImportDecl mod _ _ _ _ _) <- imports, mod == pRELUDE_Name ])
180 checkEarlyExit mod_name
181 = traceRn (text "Considering whether compilation is required...") `thenRn_`
183 -- Read the old interface file, if any, for the module being compiled
184 findAndReadIface doc_str mod_name False {- Not hi-boot -} `thenRn` \ maybe_iface ->
186 -- CHECK WHETHER WE HAVE IT ALREADY
188 Left err -> -- Old interface file not found, so we'd better bail out
189 traceRn (vcat [ptext SLIT("No old interface file for") <+> pprModuleName mod_name,
191 returnRn (outOfDate, Nothing)
194 | panic "checkEarlyExit: ???: not opt_SourceUnchanged"
195 -> -- Source code changed
196 traceRn (nest 4 (text "source file changed or recompilation check turned off")) `thenRn_`
197 returnRn (False, Just iface)
200 -> -- Source code unchanged and no errors yet... carry on
201 checkModUsage (pi_usages iface) `thenRn` \ up_to_date ->
202 returnRn (up_to_date, Just iface)
204 -- Only look in current directory, with suffix .hi
205 doc_str = sep [ptext SLIT("need usage info from"), pprModuleName mod_name]
209 importsFromImportDecl :: (Name -> Bool) -- OK to omit qualifier
211 -> RnMG (GlobalRdrEnv,
214 importsFromImportDecl is_unqual (ImportDecl imp_mod_name from qual_only as_mod import_spec iloc)
215 = pushSrcLocRn iloc $
216 getInterfaceExports imp_mod_name from `thenRn` \ (imp_mod, avails) ->
219 -- If there's an error in getInterfaceExports, (e.g. interface
220 -- file not found) we get lots of spurious errors from 'filterImports'
221 returnRn (emptyRdrEnv, mkEmptyExportAvails imp_mod_name)
224 filterImports imp_mod_name import_spec avails `thenRn` \ (filtered_avails, hides, explicits) ->
226 qualifyImports imp_mod_name
227 (not qual_only) -- Maybe want unqualified names
229 (improveAvails imp_mod iloc explicits
230 is_unqual filtered_avails)
233 improveAvails imp_mod iloc explicits is_unqual avails
234 -- We 'improve' the provenance by setting
235 -- (a) the import-reason field, so that the Name says how it came into scope
236 -- including whether it's explicitly imported
237 -- (b) the print-unqualified field
238 = map improve_avail avails
240 improve_avail (Avail n) = Avail (improve n)
241 improve_avail (AvailTC n ns) = AvailTC (improve n) (map improve ns)
243 improve name = setNameProvenance name
244 (NonLocalDef (UserImport imp_mod iloc (is_explicit name))
246 is_explicit name = name `elemNameSet` explicits
251 importsFromLocalDecls mod_name rec_exp_fn decls
252 = mapRn (getLocalDeclBinders mod rec_exp_fn) decls `thenRn` \ avails_s ->
255 avails = concat avails_s
257 all_names :: [Name] -- All the defns; no dups eliminated
258 all_names = [name | avail <- avails, name <- availNames avail]
261 (_, dups) = removeDups compare all_names
263 -- Check for duplicate definitions
264 mapRn_ (addErrRn . dupDeclErr) dups `thenRn_`
266 -- Record that locally-defined things are available
267 recordLocalSlurps avails `thenRn_`
269 -- Build the environment
270 qualifyImports mod_name
271 True -- Want unqualified names
277 mod = mkThisModule mod_name
279 getLocalDeclBinders :: Module -> (Name -> ExportFlag)
280 -> RdrNameHsDecl -> RnMG Avails
281 getLocalDeclBinders mod rec_exp_fn (ValD binds)
282 = mapRn do_one (bagToList (collectTopBinders binds))
284 do_one (rdr_name, loc) = newLocalName mod rec_exp_fn rdr_name loc `thenRn` \ name ->
285 returnRn (Avail name)
287 getLocalDeclBinders mod rec_exp_fn decl
288 = getDeclBinders (newLocalName mod rec_exp_fn) decl `thenRn` \ maybe_avail ->
290 Nothing -> returnRn [] -- Instance decls and suchlike
291 Just avail -> returnRn [avail]
293 newLocalName mod rec_exp_fn rdr_name loc
294 = check_unqual rdr_name loc `thenRn_`
295 newTopBinder mod (rdrNameOcc rdr_name) `thenRn` \ name ->
296 returnRn (setNameProvenance name (LocalDef loc (rec_exp_fn name)))
298 -- There should never be a qualified name in a binding position (except in instance decls)
299 -- The parser doesn't check this because the same parser parses instance decls
300 check_unqual rdr_name loc
301 | isUnqual rdr_name = returnRn ()
302 | otherwise = qualNameErr (text "the binding for" <+> quotes (ppr rdr_name))
307 %************************************************************************
309 \subsection{Filtering imports}
311 %************************************************************************
313 @filterImports@ takes the @ExportEnv@ telling what the imported module makes
314 available, and filters it through the import spec (if any).
317 filterImports :: ModuleName -- The module being imported
318 -> Maybe (Bool, [RdrNameIE]) -- Import spec; True => hiding
319 -> [AvailInfo] -- What's available
320 -> RnMG ([AvailInfo], -- What's actually imported
321 [AvailInfo], -- What's to be hidden
322 -- (the unqualified version, that is)
323 -- (We need to return both the above sets, because
324 -- the qualified version is never hidden; so we can't
325 -- implement hiding by reducing what's imported.)
326 NameSet) -- What was imported explicitly
328 -- Complains if import spec mentions things that the module doesn't export
329 -- Warns/informs if import spec contains duplicates.
330 filterImports mod Nothing imports
331 = returnRn (imports, [], emptyNameSet)
333 filterImports mod (Just (want_hiding, import_items)) avails
334 = flatMapRn get_item import_items `thenRn` \ avails_w_explicits ->
336 (item_avails, explicits_s) = unzip avails_w_explicits
337 explicits = foldl addListToNameSet emptyNameSet explicits_s
341 -- All imported; item_avails to be hidden
342 returnRn (avails, item_avails, emptyNameSet)
344 -- Just item_avails imported; nothing to be hidden
345 returnRn (item_avails, [], explicits)
347 import_fm :: FiniteMap OccName AvailInfo
348 import_fm = listToFM [ (nameOccName name, avail)
350 name <- availNames avail]
351 -- Even though availNames returns data constructors too,
352 -- they won't make any difference because naked entities like T
353 -- in an import list map to TcOccs, not VarOccs.
355 bale_out item = addErrRn (badImportItemErr mod item) `thenRn_`
358 get_item item@(IEModuleContents _) = bale_out item
360 get_item item@(IEThingAll _)
361 = case check_item item of
362 Nothing -> bale_out item
363 Just avail@(AvailTC _ [n]) -> -- This occurs when you import T(..), but
364 -- only export T abstractly. The single [n]
365 -- in the AvailTC is the type or class itself
366 addWarnRn (dodgyImportWarn mod item) `thenRn_`
367 returnRn [(avail, [availName avail])]
368 Just avail -> returnRn [(avail, [availName avail])]
370 get_item item@(IEThingAbs n)
371 | want_hiding -- hiding( C )
372 -- Here the 'C' can be a data constructor *or* a type/class
373 = case catMaybes [check_item item, check_item (IEThingAbs data_n)] of
375 avails -> returnRn [(a, []) | a <- avails]
376 -- The 'explicits' list is irrelevant when hiding
378 data_n = setRdrNameOcc n (setOccNameSpace (rdrNameOcc n) dataName)
381 = case check_item item of
382 Nothing -> bale_out item
383 Just avail -> returnRn [(avail, availNames avail)]
386 | not (maybeToBool maybe_in_import_avails) ||
387 not (maybeToBool maybe_filtered_avail)
391 = Just filtered_avail
394 wanted_occ = rdrNameOcc (ieName item)
395 maybe_in_import_avails = lookupFM import_fm wanted_occ
397 Just avail = maybe_in_import_avails
398 maybe_filtered_avail = filterAvail item avail
399 Just filtered_avail = maybe_filtered_avail
404 %************************************************************************
406 \subsection{Qualifiying imports}
408 %************************************************************************
410 @qualifyImports@ takes the @ExportEnv@ after filtering through the import spec
411 of an import decl, and deals with producing an @RnEnv@ with the
412 right qualified names. It also turns the @Names@ in the @ExportEnv@ into
413 fully fledged @Names@.
416 qualifyImports :: ModuleName -- Imported module
417 -> Bool -- True <=> want unqualified import
418 -> Maybe ModuleName -- Optional "as M" part
419 -> [AvailInfo] -- What's to be hidden
420 -> Avails -- Whats imported and how
421 -> RnMG (GlobalRdrEnv, ExportAvails)
423 qualifyImports this_mod unqual_imp as_mod hides avails
425 -- Make the name environment. We're talking about a
426 -- single module here, so there must be no name clashes.
427 -- In practice there only ever will be if it's the module
430 -- Add the things that are available
431 name_env1 = foldl add_avail emptyRdrEnv avails
433 -- Delete things that are hidden
434 name_env2 = foldl del_avail name_env1 hides
436 -- Create the export-availability info
437 export_avails = mkExportAvails qual_mod unqual_imp name_env2 avails
439 returnRn (name_env2, export_avails)
442 qual_mod = case as_mod of
444 Just another_name -> another_name
446 add_avail :: GlobalRdrEnv -> AvailInfo -> GlobalRdrEnv
447 add_avail env avail = foldl add_name env (availNames avail)
453 env1 = addOneToGlobalRdrEnv env (mkRdrQual qual_mod occ) name
454 env2 = addOneToGlobalRdrEnv env1 (mkRdrUnqual occ) name
455 occ = nameOccName name
457 del_avail env avail = foldl delOneFromGlobalRdrEnv env rdr_names
459 rdr_names = map (mkRdrUnqual . nameOccName) (availNames avail)
462 mkEmptyExportAvails :: ModuleName -> ExportAvails
463 mkEmptyExportAvails mod_name = (unitFM mod_name [], emptyUFM)
465 mkExportAvails :: ModuleName -> Bool -> GlobalRdrEnv -> [AvailInfo] -> ExportAvails
466 mkExportAvails mod_name unqual_imp name_env avails
467 = (mod_avail_env, entity_avail_env)
469 mod_avail_env = unitFM mod_name unqual_avails
471 -- unqual_avails is the Avails that are visible in *unqualfied* form
472 -- (1.4 Report, Section 5.1.1)
474 -- import T hiding( f )
475 -- we delete f from avails
477 unqual_avails | not unqual_imp = [] -- Short cut when no unqualified imports
478 | otherwise = mapMaybe prune avails
480 prune (Avail n) | unqual_in_scope n = Just (Avail n)
481 prune (Avail n) | otherwise = Nothing
482 prune (AvailTC n ns) | null uqs = Nothing
483 | otherwise = Just (AvailTC n uqs)
485 uqs = filter unqual_in_scope ns
487 unqual_in_scope n = unQualInScope name_env n
489 entity_avail_env = listToUFM [ (name,avail) | avail <- avails,
490 name <- availNames avail]
492 plusExportAvails :: ExportAvails -> ExportAvails -> ExportAvails
493 plusExportAvails (m1, e1) (m2, e2)
494 = (plusFM_C (++) m1 m2, plusAvailEnv e1 e2)
495 -- ToDo: wasteful: we do this once for each constructor!
499 %************************************************************************
501 \subsection{Export list processing}
503 %************************************************************************
505 Processing the export list.
507 You might think that we should record things that appear in the export list
508 as ``occurrences'' (using @addOccurrenceName@), but you'd be wrong.
509 We do check (here) that they are in scope,
510 but there is no need to slurp in their actual declaration
511 (which is what @addOccurrenceName@ forces).
513 Indeed, doing so would big trouble when
514 compiling @PrelBase@, because it re-exports @GHC@, which includes @takeMVar#@,
515 whose type includes @ConcBase.StateAndSynchVar#@, and so on...
518 type ExportAccum -- The type of the accumulating parameter of
519 -- the main worker function in exportsFromAvail
520 = ([ModuleName], -- 'module M's seen so far
521 ExportOccMap, -- Tracks exported occurrence names
522 AvailEnv) -- The accumulated exported stuff, kept in an env
523 -- so we can common-up related AvailInfos
525 type ExportOccMap = FiniteMap OccName (Name, RdrNameIE)
526 -- Tracks what a particular exported OccName
527 -- in an export list refers to, and which item
528 -- it came from. It's illegal to export two distinct things
529 -- that have the same occurrence name
532 exportsFromAvail :: ModuleName
533 -> Maybe [RdrNameIE] -- Export spec
537 -- Complains if two distinct exports have same OccName
538 -- Warns about identical exports.
539 -- Complains about exports items not in scope
540 exportsFromAvail this_mod Nothing export_avails global_name_env
541 = exportsFromAvail this_mod true_exports export_avails global_name_env
543 true_exports = Just $ if this_mod == mAIN_Name
544 then [IEVar main_RDR]
545 -- export Main.main *only* unless otherwise specified,
546 else [IEModuleContents this_mod]
547 -- but for all other modules export everything.
549 exportsFromAvail this_mod (Just export_items)
550 (mod_avail_env, entity_avail_env)
552 = foldlRn exports_from_item
553 ([], emptyFM, emptyAvailEnv) export_items `thenRn` \ (_, _, export_avail_map) ->
555 export_avails :: [AvailInfo]
556 export_avails = nameEnvElts export_avail_map
558 returnRn export_avails
561 exports_from_item :: ExportAccum -> RdrNameIE -> RnMG ExportAccum
563 exports_from_item acc@(mods, occs, avails) ie@(IEModuleContents mod)
564 | mod `elem` mods -- Duplicate export of M
565 = warnCheckRn opt_WarnDuplicateExports
566 (dupModuleExport mod) `thenRn_`
570 = case lookupFM mod_avail_env mod of
571 Nothing -> failWithRn acc (modExportErr mod)
572 Just mod_avails -> foldlRn (check_occs ie) occs mod_avails
575 avails' = foldl addAvail avails mod_avails
577 returnRn (mod:mods, occs', avails')
579 exports_from_item acc@(mods, occs, avails) ie
580 | not (maybeToBool maybe_in_scope)
581 = failWithRn acc (unknownNameErr (ieName ie))
583 | not (null dup_names)
584 = addNameClashErrRn rdr_name (name:dup_names) `thenRn_`
588 -- I can't see why this should ever happen; if the thing is in scope
589 -- at all it ought to have some availability
590 | not (maybeToBool maybe_avail)
591 = pprTrace "exportsFromAvail: curious Nothing:" (ppr name)
596 = failWithRn acc (exportItemErr ie)
598 | otherwise -- Phew! It's OK! Now to check the occurrence stuff!
601 = warnCheckRn (ok_item ie avail) (dodgyExportWarn ie) `thenRn_`
602 check_occs ie occs export_avail `thenRn` \ occs' ->
603 returnRn (mods, occs', addAvail avails export_avail)
607 maybe_in_scope = lookupFM global_name_env rdr_name
608 Just (name:dup_names) = maybe_in_scope
609 maybe_avail = lookupUFM entity_avail_env name
610 Just avail = maybe_avail
611 maybe_export_avail = filterAvail ie avail
612 enough_avail = maybeToBool maybe_export_avail
613 Just export_avail = maybe_export_avail
615 ok_item (IEThingAll _) (AvailTC _ [n]) = False
616 -- This occurs when you import T(..), but
617 -- only export T abstractly. The single [n]
618 -- in the AvailTC is the type or class itself
621 check_occs :: RdrNameIE -> ExportOccMap -> AvailInfo -> RnMG ExportOccMap
622 check_occs ie occs avail
623 = foldlRn check occs (availNames avail)
626 = case lookupFM occs name_occ of
627 Nothing -> returnRn (addToFM occs name_occ (name, ie))
629 | name == name' -> -- Duplicate export
630 warnCheckRn opt_WarnDuplicateExports
631 (dupExportWarn name_occ ie ie')
632 `thenRn_` returnRn occs
634 | otherwise -> -- Same occ name but different names: an error
635 failWithRn occs (exportClashErr name_occ ie ie')
637 name_occ = nameOccName name
639 mk_export_fn :: NameSet -> (Name -> ExportFlag)
640 mk_export_fn exported_names
641 = \name -> if name `elemNameSet` exported_names
646 %************************************************************************
650 %************************************************************************
653 badImportItemErr mod ie
654 = sep [ptext SLIT("Module"), quotes (pprModuleName mod),
655 ptext SLIT("does not export"), quotes (ppr ie)]
657 dodgyImportWarn mod item = dodgyMsg (ptext SLIT("import")) item
658 dodgyExportWarn item = dodgyMsg (ptext SLIT("export")) item
660 dodgyMsg kind item@(IEThingAll tc)
661 = sep [ ptext SLIT("The") <+> kind <+> ptext SLIT("item") <+> quotes (ppr item),
662 ptext SLIT("suggests that") <+> quotes (ppr tc) <+> ptext SLIT("has constructor or class methods"),
663 ptext SLIT("but it has none; it is a type synonym or abstract type or class") ]
666 = hsep [ ptext SLIT("Unknown module in export list: module"), quotes (pprModuleName mod)]
668 exportItemErr export_item
669 = sep [ ptext SLIT("The export item") <+> quotes (ppr export_item),
670 ptext SLIT("attempts to export constructors or class methods that are not visible here") ]
672 exportClashErr occ_name ie1 ie2
673 = hsep [ptext SLIT("The export items"), quotes (ppr ie1)
674 ,ptext SLIT("and"), quotes (ppr ie2)
675 ,ptext SLIT("create conflicting exports for"), quotes (ppr occ_name)]
678 = vcat [ptext SLIT("Multiple declarations of") <+> quotes (ppr n),
679 nest 4 (vcat (map pp sorted_ns))]
681 sorted_ns = sortLt occ'ed_before (n:ns)
683 occ'ed_before a b = LT == compare (getSrcLoc a) (getSrcLoc b)
685 pp n = pprProvenance (getNameProvenance n)
687 dupExportWarn occ_name ie1 ie2
688 = hsep [quotes (ppr occ_name),
689 ptext SLIT("is exported by"), quotes (ppr ie1),
690 ptext SLIT("and"), quotes (ppr ie2)]
693 = hsep [ptext SLIT("Duplicate"),
694 quotes (ptext SLIT("Module") <+> pprModuleName mod),
695 ptext SLIT("in export list")]