Add trailing comma to fix the build.
[ghc.git] / compiler / rename / RnNames.hs
1 {-
2 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3
4 \section[RnNames]{Extracting imported and top-level names in scope}
5 -}
6
7 {-# LANGUAGE CPP, NondecreasingIndentation, MultiWayIf, NamedFieldPuns #-}
8
9 module RnNames (
10 rnImports, getLocalNonValBinders, newRecordSelector,
11 extendGlobalRdrEnvRn,
12 gresFromAvails,
13 calculateAvails,
14 reportUnusedNames,
15 plusAvail,
16 checkConName,
17 nubAvails,
18 mkChildEnv,
19 findChildren,
20 dodgyMsg
21 ) where
22
23 #include "HsVersions.h"
24
25 import DynFlags
26 import HsSyn
27 import TcEnv
28 import RnEnv
29 import LoadIface ( loadSrcInterface )
30 import TcRnMonad
31 import PrelNames
32 import Module
33 import Name
34 import NameEnv
35 import NameSet
36 import Avail
37 import FieldLabel
38 import HscTypes
39 import RdrName
40 import RdrHsSyn ( setRdrNameSpace )
41 import Outputable
42 import Maybes
43 import SrcLoc
44 import BasicTypes ( TopLevelFlag(..), StringLiteral(..) )
45 import Util
46 import FastString
47 import FastStringEnv
48 import ListSetOps
49 import Id
50 import Type
51 import PatSyn
52 import qualified GHC.LanguageExtensions as LangExt
53
54 import Control.Monad
55 import Data.Either ( partitionEithers, isRight, rights )
56 -- import qualified Data.Foldable as Foldable
57 import Data.Map ( Map )
58 import qualified Data.Map as Map
59 import Data.Ord ( comparing )
60 import Data.List ( partition, (\\), find, sortBy )
61 -- import qualified Data.Set as Set
62 import System.FilePath ((</>))
63 import System.IO
64
65 {-
66 ************************************************************************
67 * *
68 \subsection{rnImports}
69 * *
70 ************************************************************************
71
72 Note [Tracking Trust Transitively]
73 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
74 When we import a package as well as checking that the direct imports are safe
75 according to the rules outlined in the Note [HscMain . Safe Haskell Trust Check]
76 we must also check that these rules hold transitively for all dependent modules
77 and packages. Doing this without caching any trust information would be very
78 slow as we would need to touch all packages and interface files a module depends
79 on. To avoid this we make use of the property that if a modules Safe Haskell
80 mode changes, this triggers a recompilation from that module in the dependcy
81 graph. So we can just worry mostly about direct imports.
82
83 There is one trust property that can change for a package though without
84 recompliation being triggered: package trust. So we must check that all
85 packages a module tranitively depends on to be trusted are still trusted when
86 we are compiling this module (as due to recompilation avoidance some modules
87 below may not be considered trusted any more without recompilation being
88 triggered).
89
90 We handle this by augmenting the existing transitive list of packages a module M
91 depends on with a bool for each package that says if it must be trusted when the
92 module M is being checked for trust. This list of trust required packages for a
93 single import is gathered in the rnImportDecl function and stored in an
94 ImportAvails data structure. The union of these trust required packages for all
95 imports is done by the rnImports function using the combine function which calls
96 the plusImportAvails function that is a union operation for the ImportAvails
97 type. This gives us in an ImportAvails structure all packages required to be
98 trusted for the module we are currently compiling. Checking that these packages
99 are still trusted (and that direct imports are trusted) is done in
100 HscMain.checkSafeImports.
101
102 See the note below, [Trust Own Package] for a corner case in this method and
103 how its handled.
104
105
106 Note [Trust Own Package]
107 ~~~~~~~~~~~~~~~~~~~~~~~~
108 There is a corner case of package trust checking that the usual transitive check
109 doesn't cover. (For how the usual check operates see the Note [Tracking Trust
110 Transitively] below). The case is when you import a -XSafe module M and M
111 imports a -XTrustworthy module N. If N resides in a different package than M,
112 then the usual check works as M will record a package dependency on N's package
113 and mark it as required to be trusted. If N resides in the same package as M
114 though, then importing M should require its own package be trusted due to N
115 (since M is -XSafe so doesn't create this requirement by itself). The usual
116 check fails as a module doesn't record a package dependency of its own package.
117 So instead we now have a bool field in a modules interface file that simply
118 states if the module requires its own package to be trusted. This field avoids
119 us having to load all interface files that the module depends on to see if one
120 is trustworthy.
121
122
123 Note [Trust Transitive Property]
124 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
125 So there is an interesting design question in regards to transitive trust
126 checking. Say I have a module B compiled with -XSafe. B is dependent on a bunch
127 of modules and packages, some packages it requires to be trusted as its using
128 -XTrustworthy modules from them. Now if I have a module A that doesn't use safe
129 haskell at all and simply imports B, should A inherit all the the trust
130 requirements from B? Should A now also require that a package p is trusted since
131 B required it?
132
133 We currently say no but saying yes also makes sense. The difference is, if a
134 module M that doesn't use Safe Haskell imports a module N that does, should all
135 the trusted package requirements be dropped since M didn't declare that it cares
136 about Safe Haskell (so -XSafe is more strongly associated with the module doing
137 the importing) or should it be done still since the author of the module N that
138 uses Safe Haskell said they cared (so -XSafe is more strongly associated with
139 the module that was compiled that used it).
140
141 Going with yes is a simpler semantics we think and harder for the user to stuff
142 up but it does mean that Safe Haskell will affect users who don't care about
143 Safe Haskell as they might grab a package from Cabal which uses safe haskell (say
144 network) and that packages imports -XTrustworthy modules from another package
145 (say bytestring), so requires that package is trusted. The user may now get
146 compilation errors in code that doesn't do anything with Safe Haskell simply
147 because they are using the network package. They will have to call 'ghc-pkg
148 trust network' to get everything working. Due to this invasive nature of going
149 with yes we have gone with no for now.
150 -}
151
152 -- | Process Import Decls. See 'rnImportDecl' for a description of what
153 -- the return types represent.
154 -- Note: Do the non SOURCE ones first, so that we get a helpful warning
155 -- for SOURCE ones that are unnecessary
156 rnImports :: [LImportDecl RdrName]
157 -> RnM ([LImportDecl Name], GlobalRdrEnv, ImportAvails, AnyHpcUsage)
158 rnImports imports = do
159 tcg_env <- getGblEnv
160 -- NB: want an identity module here, because it's OK for a signature
161 -- module to import from its implementor
162 let this_mod = tcg_mod tcg_env
163 let (source, ordinary) = partition is_source_import imports
164 is_source_import d = ideclSource (unLoc d)
165 stuff1 <- mapAndReportM (rnImportDecl this_mod) ordinary
166 stuff2 <- mapAndReportM (rnImportDecl this_mod) source
167 -- Safe Haskell: See Note [Tracking Trust Transitively]
168 let (decls, rdr_env, imp_avails, hpc_usage) = combine (stuff1 ++ stuff2)
169 return (decls, rdr_env, imp_avails, hpc_usage)
170
171 where
172 combine :: [(LImportDecl Name, GlobalRdrEnv, ImportAvails, AnyHpcUsage)]
173 -> ([LImportDecl Name], GlobalRdrEnv, ImportAvails, AnyHpcUsage)
174 combine = foldr plus ([], emptyGlobalRdrEnv, emptyImportAvails, False)
175
176 plus (decl, gbl_env1, imp_avails1,hpc_usage1)
177 (decls, gbl_env2, imp_avails2,hpc_usage2)
178 = ( decl:decls,
179 gbl_env1 `plusGlobalRdrEnv` gbl_env2,
180 imp_avails1 `plusImportAvails` imp_avails2,
181 hpc_usage1 || hpc_usage2 )
182
183 -- | Given a located import declaration @decl@ from @this_mod@,
184 -- calculate the following pieces of information:
185 --
186 -- 1. An updated 'LImportDecl', where all unresolved 'RdrName' in
187 -- the entity lists have been resolved into 'Name's,
188 --
189 -- 2. A 'GlobalRdrEnv' representing the new identifiers that were
190 -- brought into scope (taking into account module qualification
191 -- and hiding),
192 --
193 -- 3. 'ImportAvails' summarizing the identifiers that were imported
194 -- by this declaration, and
195 --
196 -- 4. A boolean 'AnyHpcUsage' which is true if the imported module
197 -- used HPC.
198 rnImportDecl :: Module -> LImportDecl RdrName
199 -> RnM (LImportDecl Name, GlobalRdrEnv, ImportAvails, AnyHpcUsage)
200 rnImportDecl this_mod
201 (L loc decl@(ImportDecl { ideclName = loc_imp_mod_name, ideclPkgQual = mb_pkg
202 , ideclSource = want_boot, ideclSafe = mod_safe
203 , ideclQualified = qual_only, ideclImplicit = implicit
204 , ideclAs = as_mod, ideclHiding = imp_details }))
205 = setSrcSpan loc $ do
206
207 when (isJust mb_pkg) $ do
208 pkg_imports <- xoptM LangExt.PackageImports
209 when (not pkg_imports) $ addErr packageImportErr
210
211 -- If there's an error in loadInterface, (e.g. interface
212 -- file not found) we get lots of spurious errors from 'filterImports'
213 let imp_mod_name = unLoc loc_imp_mod_name
214 doc = ppr imp_mod_name <+> text "is directly imported"
215
216 -- Check for self-import, which confuses the typechecker (Trac #9032)
217 -- ghc --make rejects self-import cycles already, but batch-mode may not
218 -- at least not until TcIface.tcHiBootIface, which is too late to avoid
219 -- typechecker crashes. (Indirect self imports are not caught until
220 -- TcIface, see #10337 tracking how to make this error better.)
221 --
222 -- Originally, we also allowed 'import {-# SOURCE #-} M', but this
223 -- caused bug #10182: in one-shot mode, we should never load an hs-boot
224 -- file for the module we are compiling into the EPS. In principle,
225 -- it should be possible to support this mode of use, but we would have to
226 -- extend Provenance to support a local definition in a qualified location.
227 -- For now, we don't support it, but see #10336
228 when (imp_mod_name == moduleName this_mod &&
229 (case mb_pkg of -- If we have import "<pkg>" M, then we should
230 -- check that "<pkg>" is "this" (which is magic)
231 -- or the name of this_mod's package. Yurgh!
232 -- c.f. GHC.findModule, and Trac #9997
233 Nothing -> True
234 Just (StringLiteral _ pkg_fs) -> pkg_fs == fsLit "this" ||
235 fsToUnitId pkg_fs == moduleUnitId this_mod))
236 (addErr (text "A module cannot import itself:" <+> ppr imp_mod_name))
237
238 -- Check for a missing import list (Opt_WarnMissingImportList also
239 -- checks for T(..) items but that is done in checkDodgyImport below)
240 case imp_details of
241 Just (False, _) -> return () -- Explicit import list
242 _ | implicit -> return () -- Do not bleat for implicit imports
243 | qual_only -> return ()
244 | otherwise -> whenWOptM Opt_WarnMissingImportList $
245 addWarn (Reason Opt_WarnMissingImportList)
246 (missingImportListWarn imp_mod_name)
247
248 iface <- loadSrcInterface doc imp_mod_name want_boot (fmap sl_fs mb_pkg)
249
250 -- Compiler sanity check: if the import didn't say
251 -- {-# SOURCE #-} we should not get a hi-boot file
252 WARN( not want_boot && mi_boot iface, ppr imp_mod_name ) do
253
254 -- Issue a user warning for a redundant {- SOURCE -} import
255 -- NB that we arrange to read all the ordinary imports before
256 -- any of the {- SOURCE -} imports.
257 --
258 -- in --make and GHCi, the compilation manager checks for this,
259 -- and indeed we shouldn't do it here because the existence of
260 -- the non-boot module depends on the compilation order, which
261 -- is not deterministic. The hs-boot test can show this up.
262 dflags <- getDynFlags
263 warnIf NoReason
264 (want_boot && not (mi_boot iface) && isOneShot (ghcMode dflags))
265 (warnRedundantSourceImport imp_mod_name)
266 when (mod_safe && not (safeImportsOn dflags)) $
267 addErr (text "safe import can't be used as Safe Haskell isn't on!"
268 $+$ ptext (sLit $ "please enable Safe Haskell through either "
269 ++ "Safe, Trustworthy or Unsafe"))
270
271 let
272 qual_mod_name = as_mod `orElse` imp_mod_name
273 imp_spec = ImpDeclSpec { is_mod = imp_mod_name, is_qual = qual_only,
274 is_dloc = loc, is_as = qual_mod_name }
275
276 -- filter the imports according to the import declaration
277 (new_imp_details, gres) <- filterImports iface imp_spec imp_details
278
279 -- for certain error messages, we’d like to know what could be imported
280 -- here, if everything were imported
281 potential_gres <- mkGlobalRdrEnv . snd <$> filterImports iface imp_spec Nothing
282
283 let gbl_env = mkGlobalRdrEnv gres
284
285 is_hiding | Just (True,_) <- imp_details = True
286 | otherwise = False
287
288 -- should the import be safe?
289 mod_safe' = mod_safe
290 || (not implicit && safeDirectImpsReq dflags)
291 || (implicit && safeImplicitImpsReq dflags)
292
293 let imv = ImportedModsVal
294 { imv_name = qual_mod_name
295 , imv_span = loc
296 , imv_is_safe = mod_safe'
297 , imv_is_hiding = is_hiding
298 , imv_all_exports = potential_gres
299 , imv_qualified = qual_only
300 }
301 let imports
302 = (calculateAvails dflags iface mod_safe' want_boot)
303 { imp_mods = unitModuleEnv (mi_module iface) [imv] }
304
305 -- Complain if we import a deprecated module
306 whenWOptM Opt_WarnWarningsDeprecations (
307 case (mi_warns iface) of
308 WarnAll txt -> addWarn (Reason Opt_WarnWarningsDeprecations)
309 (moduleWarn imp_mod_name txt)
310 _ -> return ()
311 )
312
313 let new_imp_decl = L loc (decl { ideclSafe = mod_safe'
314 , ideclHiding = new_imp_details })
315
316 return (new_imp_decl, gbl_env, imports, mi_hpc iface)
317
318 -- | Calculate the 'ImportAvails' induced by an import of a particular
319 -- interface, but without 'imp_mods'.
320 calculateAvails :: DynFlags
321 -> ModIface
322 -> IsSafeImport
323 -> IsBootInterface
324 -> ImportAvails
325 calculateAvails dflags iface mod_safe' want_boot =
326 let imp_mod = mi_module iface
327 orph_iface = mi_orphan iface
328 has_finsts = mi_finsts iface
329 deps = mi_deps iface
330 trust = getSafeMode $ mi_trust iface
331 trust_pkg = mi_trust_pkg iface
332
333 -- If the module exports anything defined in this module, just
334 -- ignore it. Reason: otherwise it looks as if there are two
335 -- local definition sites for the thing, and an error gets
336 -- reported. Easiest thing is just to filter them out up
337 -- front. This situation only arises if a module imports
338 -- itself, or another module that imported it. (Necessarily,
339 -- this invoves a loop.)
340 --
341 -- We do this *after* filterImports, so that if you say
342 -- module A where
343 -- import B( AType )
344 -- type AType = ...
345 --
346 -- module B( AType ) where
347 -- import {-# SOURCE #-} A( AType )
348 --
349 -- then you won't get a 'B does not export AType' message.
350
351
352 -- Compute new transitive dependencies
353
354 orphans | orph_iface = ASSERT( not (imp_mod `elem` dep_orphs deps) )
355 imp_mod : dep_orphs deps
356 | otherwise = dep_orphs deps
357
358 finsts | has_finsts = ASSERT( not (imp_mod `elem` dep_finsts deps) )
359 imp_mod : dep_finsts deps
360 | otherwise = dep_finsts deps
361
362 pkg = moduleUnitId (mi_module iface)
363 ipkg = toInstalledUnitId pkg
364
365 -- Does this import mean we now require our own pkg
366 -- to be trusted? See Note [Trust Own Package]
367 ptrust = trust == Sf_Trustworthy || trust_pkg
368
369 (dependent_mods, dependent_pkgs, pkg_trust_req)
370 | pkg == thisPackage dflags =
371 -- Imported module is from the home package
372 -- Take its dependent modules and add imp_mod itself
373 -- Take its dependent packages unchanged
374 --
375 -- NB: (dep_mods deps) might include a hi-boot file
376 -- for the module being compiled, CM. Do *not* filter
377 -- this out (as we used to), because when we've
378 -- finished dealing with the direct imports we want to
379 -- know if any of them depended on CM.hi-boot, in
380 -- which case we should do the hi-boot consistency
381 -- check. See LoadIface.loadHiBootInterface
382 ((moduleName imp_mod,want_boot):dep_mods deps,dep_pkgs deps,ptrust)
383
384 | otherwise =
385 -- Imported module is from another package
386 -- Dump the dependent modules
387 -- Add the package imp_mod comes from to the dependent packages
388 ASSERT2( not (ipkg `elem` (map fst $ dep_pkgs deps))
389 , ppr ipkg <+> ppr (dep_pkgs deps) )
390 ([], (ipkg, False) : dep_pkgs deps, False)
391
392 in ImportAvails {
393 imp_mods = emptyModuleEnv, -- this gets filled in later
394 imp_orphs = orphans,
395 imp_finsts = finsts,
396 imp_dep_mods = mkModDeps dependent_mods,
397 imp_dep_pkgs = map fst $ dependent_pkgs,
398 -- Add in the imported modules trusted package
399 -- requirements. ONLY do this though if we import the
400 -- module as a safe import.
401 -- See Note [Tracking Trust Transitively]
402 -- and Note [Trust Transitive Property]
403 imp_trust_pkgs = if mod_safe'
404 then map fst $ filter snd dependent_pkgs
405 else [],
406 -- Do we require our own pkg to be trusted?
407 -- See Note [Trust Own Package]
408 imp_trust_own_pkg = pkg_trust_req
409 }
410
411
412 warnRedundantSourceImport :: ModuleName -> SDoc
413 warnRedundantSourceImport mod_name
414 = text "Unnecessary {-# SOURCE #-} in the import of module"
415 <+> quotes (ppr mod_name)
416
417 {-
418 ************************************************************************
419 * *
420 \subsection{importsFromLocalDecls}
421 * *
422 ************************************************************************
423
424 From the top-level declarations of this module produce
425 * the lexical environment
426 * the ImportAvails
427 created by its bindings.
428
429 Note [Top-level Names in Template Haskell decl quotes]
430 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
431 See also: Note [Interactively-bound Ids in GHCi] in HscTypes
432 Note [Looking up Exact RdrNames] in RnEnv
433
434 Consider a Template Haskell declaration quotation like this:
435 module M where
436 f x = h [d| f = 3 |]
437 When renaming the declarations inside [d| ...|], we treat the
438 top level binders specially in two ways
439
440 1. We give them an Internal Name, not (as usual) an External one.
441 This is done by RnEnv.newTopSrcBinder.
442
443 2. We make them *shadow* the outer bindings.
444 See Note [GlobalRdrEnv shadowing]
445
446 3. We find out whether we are inside a [d| ... |] by testing the TH
447 stage. This is a slight hack, because the stage field was really
448 meant for the type checker, and here we are not interested in the
449 fields of Brack, hence the error thunks in thRnBrack.
450 -}
451
452 extendGlobalRdrEnvRn :: [AvailInfo]
453 -> MiniFixityEnv
454 -> RnM (TcGblEnv, TcLclEnv)
455 -- Updates both the GlobalRdrEnv and the FixityEnv
456 -- We return a new TcLclEnv only because we might have to
457 -- delete some bindings from it;
458 -- see Note [Top-level Names in Template Haskell decl quotes]
459
460 extendGlobalRdrEnvRn avails new_fixities
461 = do { (gbl_env, lcl_env) <- getEnvs
462 ; stage <- getStage
463 ; isGHCi <- getIsGHCi
464 ; let rdr_env = tcg_rdr_env gbl_env
465 fix_env = tcg_fix_env gbl_env
466 th_bndrs = tcl_th_bndrs lcl_env
467 th_lvl = thLevel stage
468
469 -- Delete new_occs from global and local envs
470 -- If we are in a TemplateHaskell decl bracket,
471 -- we are going to shadow them
472 -- See Note [GlobalRdrEnv shadowing]
473 inBracket = isBrackStage stage
474
475 lcl_env_TH = lcl_env { tcl_rdr = delLocalRdrEnvList (tcl_rdr lcl_env) new_occs }
476 -- See Note [GlobalRdrEnv shadowing]
477
478 lcl_env2 | inBracket = lcl_env_TH
479 | otherwise = lcl_env
480
481 -- Deal with shadowing: see Note [GlobalRdrEnv shadowing]
482 want_shadowing = isGHCi || inBracket
483 rdr_env1 | want_shadowing = shadowNames rdr_env new_names
484 | otherwise = rdr_env
485
486 lcl_env3 = lcl_env2 { tcl_th_bndrs = extendNameEnvList th_bndrs
487 [ (n, (TopLevel, th_lvl))
488 | n <- new_names ] }
489
490 ; rdr_env2 <- foldlM add_gre rdr_env1 new_gres
491
492 ; let fix_env' = foldl extend_fix_env fix_env new_gres
493 gbl_env' = gbl_env { tcg_rdr_env = rdr_env2, tcg_fix_env = fix_env' }
494
495 ; traceRn (text "extendGlobalRdrEnvRn 2" <+> (pprGlobalRdrEnv True rdr_env2))
496 ; return (gbl_env', lcl_env3) }
497 where
498 new_names = concatMap availNames avails
499 new_occs = map nameOccName new_names
500
501 -- If there is a fixity decl for the gre, add it to the fixity env
502 extend_fix_env fix_env gre
503 | Just (L _ fi) <- lookupFsEnv new_fixities (occNameFS occ)
504 = extendNameEnv fix_env name (FixItem occ fi)
505 | otherwise
506 = fix_env
507 where
508 name = gre_name gre
509 occ = greOccName gre
510
511 new_gres :: [GlobalRdrElt] -- New LocalDef GREs, derived from avails
512 new_gres = concatMap localGREsFromAvail avails
513
514 add_gre :: GlobalRdrEnv -> GlobalRdrElt -> RnM GlobalRdrEnv
515 -- Extend the GlobalRdrEnv with a LocalDef GRE
516 -- If there is already a LocalDef GRE with the same OccName,
517 -- report an error and discard the new GRE
518 -- This establishes INVARIANT 1 of GlobalRdrEnvs
519 add_gre env gre
520 | not (null dups) -- Same OccName defined twice
521 = do { addDupDeclErr (gre : dups); return env }
522
523 | otherwise
524 = return (extendGlobalRdrEnv env gre)
525 where
526 name = gre_name gre
527 occ = nameOccName name
528 dups = filter isLocalGRE (lookupGlobalRdrEnv env occ)
529
530
531 {- *********************************************************************
532 * *
533 getLocalDeclBindersd@ returns the names for an HsDecl
534 It's used for source code.
535
536 *** See Note [The Naming story] in HsDecls ****
537 * *
538 ********************************************************************* -}
539
540 getLocalNonValBinders :: MiniFixityEnv -> HsGroup RdrName
541 -> RnM ((TcGblEnv, TcLclEnv), NameSet)
542 -- Get all the top-level binders bound the group *except*
543 -- for value bindings, which are treated separately
544 -- Specifically we return AvailInfo for
545 -- * type decls (incl constructors and record selectors)
546 -- * class decls (including class ops)
547 -- * associated types
548 -- * foreign imports
549 -- * value signatures (in hs-boot files only)
550
551 getLocalNonValBinders fixity_env
552 (HsGroup { hs_valds = binds,
553 hs_tyclds = tycl_decls,
554 hs_fords = foreign_decls })
555 = do { -- Process all type/class decls *except* family instances
556 ; let inst_decls = tycl_decls >>= group_instds
557 ; overload_ok <- xoptM LangExt.DuplicateRecordFields
558 ; (tc_avails, tc_fldss)
559 <- fmap unzip $ mapM (new_tc overload_ok)
560 (tyClGroupTyClDecls tycl_decls)
561 ; traceRn (text "getLocalNonValBinders 1" <+> ppr tc_avails)
562 ; envs <- extendGlobalRdrEnvRn tc_avails fixity_env
563 ; setEnvs envs $ do {
564 -- Bring these things into scope first
565 -- See Note [Looking up family names in family instances]
566
567 -- Process all family instances
568 -- to bring new data constructors into scope
569 ; (nti_availss, nti_fldss) <- mapAndUnzipM (new_assoc overload_ok)
570 inst_decls
571
572 -- Finish off with value binders:
573 -- foreign decls and pattern synonyms for an ordinary module
574 -- type sigs in case of a hs-boot file only
575 ; is_boot <- tcIsHsBootOrSig
576 ; let val_bndrs | is_boot = hs_boot_sig_bndrs
577 | otherwise = for_hs_bndrs
578 ; val_avails <- mapM new_simple val_bndrs
579
580 ; let avails = concat nti_availss ++ val_avails
581 new_bndrs = availsToNameSetWithSelectors avails `unionNameSet`
582 availsToNameSetWithSelectors tc_avails
583 flds = concat nti_fldss ++ concat tc_fldss
584 ; traceRn (text "getLocalNonValBinders 2" <+> ppr avails)
585 ; (tcg_env, tcl_env) <- extendGlobalRdrEnvRn avails fixity_env
586
587 -- Extend tcg_field_env with new fields (this used to be the
588 -- work of extendRecordFieldEnv)
589 ; let field_env = extendNameEnvList (tcg_field_env tcg_env) flds
590 envs = (tcg_env { tcg_field_env = field_env }, tcl_env)
591
592 ; traceRn (text "getLocalNonValBinders 3" <+> vcat [ppr flds, ppr field_env])
593 ; return (envs, new_bndrs) } }
594 where
595 ValBindsIn _val_binds val_sigs = binds
596
597 for_hs_bndrs :: [Located RdrName]
598 for_hs_bndrs = hsForeignDeclsBinders foreign_decls
599
600 -- In a hs-boot file, the value binders come from the
601 -- *signatures*, and there should be no foreign binders
602 hs_boot_sig_bndrs = [ L decl_loc (unLoc n)
603 | L decl_loc (TypeSig ns _) <- val_sigs, n <- ns]
604
605 -- the SrcSpan attached to the input should be the span of the
606 -- declaration, not just the name
607 new_simple :: Located RdrName -> RnM AvailInfo
608 new_simple rdr_name = do{ nm <- newTopSrcBinder rdr_name
609 ; return (avail nm) }
610
611 new_tc :: Bool -> LTyClDecl RdrName
612 -> RnM (AvailInfo, [(Name, [FieldLabel])])
613 new_tc overload_ok tc_decl -- NOT for type/data instances
614 = do { let (bndrs, flds) = hsLTyClDeclBinders tc_decl
615 ; names@(main_name : sub_names) <- mapM newTopSrcBinder bndrs
616 ; flds' <- mapM (newRecordSelector overload_ok sub_names) flds
617 ; let fld_env = case unLoc tc_decl of
618 DataDecl { tcdDataDefn = d } -> mk_fld_env d names flds'
619 _ -> []
620 ; return (AvailTC main_name names flds', fld_env) }
621
622
623 -- Calculate the mapping from constructor names to fields, which
624 -- will go in tcg_field_env. It's convenient to do this here where
625 -- we are working with a single datatype definition.
626 mk_fld_env :: HsDataDefn RdrName -> [Name] -> [FieldLabel] -> [(Name, [FieldLabel])]
627 mk_fld_env d names flds = concatMap find_con_flds (dd_cons d)
628 where
629 find_con_flds (L _ (ConDeclH98 { con_name = L _ rdr
630 , con_details = RecCon cdflds }))
631 = [( find_con_name rdr
632 , concatMap find_con_decl_flds (unLoc cdflds) )]
633 find_con_flds (L _ (ConDeclGADT
634 { con_names = rdrs
635 , con_type = (HsIB { hsib_body = res_ty})}))
636 = map (\ (L _ rdr) -> ( find_con_name rdr
637 , concatMap find_con_decl_flds cdflds))
638 rdrs
639 where
640 (_tvs, _cxt, tau) = splitLHsSigmaTy res_ty
641 cdflds = case tau of
642 L _ (HsFunTy
643 (L _ (HsAppsTy
644 [L _ (HsAppPrefix (L _ (HsRecTy flds)))])) _) -> flds
645 L _ (HsFunTy (L _ (HsRecTy flds)) _) -> flds
646 _ -> []
647 find_con_flds _ = []
648
649 find_con_name rdr
650 = expectJust "getLocalNonValBinders/find_con_name" $
651 find (\ n -> nameOccName n == rdrNameOcc rdr) names
652 find_con_decl_flds (L _ x)
653 = map find_con_decl_fld (cd_fld_names x)
654 find_con_decl_fld (L _ (FieldOcc (L _ rdr) _))
655 = expectJust "getLocalNonValBinders/find_con_decl_fld" $
656 find (\ fl -> flLabel fl == lbl) flds
657 where lbl = occNameFS (rdrNameOcc rdr)
658
659 new_assoc :: Bool -> LInstDecl RdrName
660 -> RnM ([AvailInfo], [(Name, [FieldLabel])])
661 new_assoc _ (L _ (TyFamInstD {})) = return ([], [])
662 -- type instances don't bind new names
663
664 new_assoc overload_ok (L _ (DataFamInstD d))
665 = do { (avail, flds) <- new_di overload_ok Nothing d
666 ; return ([avail], flds) }
667 new_assoc overload_ok (L _ (ClsInstD (ClsInstDecl { cid_poly_ty = inst_ty
668 , cid_datafam_insts = adts })))
669 | Just (L loc cls_rdr) <- getLHsInstDeclClass_maybe inst_ty
670 = do { cls_nm <- setSrcSpan loc $ lookupGlobalOccRn cls_rdr
671 ; (avails, fldss)
672 <- mapAndUnzipM (new_loc_di overload_ok (Just cls_nm)) adts
673 ; return (avails, concat fldss) }
674 | otherwise
675 = return ([], []) -- Do not crash on ill-formed instances
676 -- Eg instance !Show Int Trac #3811c
677
678 new_di :: Bool -> Maybe Name -> DataFamInstDecl RdrName
679 -> RnM (AvailInfo, [(Name, [FieldLabel])])
680 new_di overload_ok mb_cls ti_decl
681 = do { main_name <- lookupFamInstName mb_cls (dfid_tycon ti_decl)
682 ; let (bndrs, flds) = hsDataFamInstBinders ti_decl
683 ; sub_names <- mapM newTopSrcBinder bndrs
684 ; flds' <- mapM (newRecordSelector overload_ok sub_names) flds
685 ; let avail = AvailTC (unLoc main_name) sub_names flds'
686 -- main_name is not bound here!
687 fld_env = mk_fld_env (dfid_defn ti_decl) sub_names flds'
688 ; return (avail, fld_env) }
689
690 new_loc_di :: Bool -> Maybe Name -> LDataFamInstDecl RdrName
691 -> RnM (AvailInfo, [(Name, [FieldLabel])])
692 new_loc_di overload_ok mb_cls (L _ d) = new_di overload_ok mb_cls d
693
694 newRecordSelector :: Bool -> [Name] -> LFieldOcc RdrName -> RnM FieldLabel
695 newRecordSelector _ [] _ = error "newRecordSelector: datatype has no constructors!"
696 newRecordSelector overload_ok (dc:_) (L loc (FieldOcc (L _ fld) _))
697 = do { selName <- newTopSrcBinder $ L loc $ field
698 ; return $ qualFieldLbl { flSelector = selName } }
699 where
700 fieldOccName = occNameFS $ rdrNameOcc fld
701 qualFieldLbl = mkFieldLabelOccs fieldOccName (nameOccName dc) overload_ok
702 field | isExact fld = fld
703 -- use an Exact RdrName as is to preserve the bindings
704 -- of an already renamer-resolved field and its use
705 -- sites. This is needed to correctly support record
706 -- selectors in Template Haskell. See Note [Binders in
707 -- Template Haskell] in Convert.hs and Note [Looking up
708 -- Exact RdrNames] in RnEnv.hs.
709 | otherwise = mkRdrUnqual (flSelector qualFieldLbl)
710
711 {-
712 Note [Looking up family names in family instances]
713 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
714 Consider
715
716 module M where
717 type family T a :: *
718 type instance M.T Int = Bool
719
720 We might think that we can simply use 'lookupOccRn' when processing the type
721 instance to look up 'M.T'. Alas, we can't! The type family declaration is in
722 the *same* HsGroup as the type instance declaration. Hence, as we are
723 currently collecting the binders declared in that HsGroup, these binders will
724 not have been added to the global environment yet.
725
726 Solution is simple: process the type family declarations first, extend
727 the environment, and then process the type instances.
728
729
730 ************************************************************************
731 * *
732 \subsection{Filtering imports}
733 * *
734 ************************************************************************
735
736 @filterImports@ takes the @ExportEnv@ telling what the imported module makes
737 available, and filters it through the import spec (if any).
738
739 Note [Dealing with imports]
740 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
741 For import M( ies ), we take the mi_exports of M, and make
742 imp_occ_env :: OccEnv (Name, AvailInfo, Maybe Name)
743 One entry for each Name that M exports; the AvailInfo is the
744 AvailInfo exported from M that exports that Name.
745
746 The situation is made more complicated by associated types. E.g.
747 module M where
748 class C a where { data T a }
749 instance C Int where { data T Int = T1 | T2 }
750 instance C Bool where { data T Int = T3 }
751 Then M's export_avails are (recall the AvailTC invariant from Avails.hs)
752 C(C,T), T(T,T1,T2,T3)
753 Notice that T appears *twice*, once as a child and once as a parent. From
754 this list we construt a raw list including
755 T -> (T, T( T1, T2, T3 ), Nothing)
756 T -> (C, C( C, T ), Nothing)
757 and we combine these (in function 'combine' in 'imp_occ_env' in
758 'filterImports') to get
759 T -> (T, T(T,T1,T2,T3), Just C)
760
761 So the overall imp_occ_env is
762 C -> (C, C(C,T), Nothing)
763 T -> (T, T(T,T1,T2,T3), Just C)
764 T1 -> (T1, T(T,T1,T2,T3), Nothing) -- similarly T2,T3
765
766 If we say
767 import M( T(T1,T2) )
768 then we get *two* Avails: C(T), T(T1,T2)
769
770 Note that the imp_occ_env will have entries for data constructors too,
771 although we never look up data constructors.
772 -}
773
774 filterImports
775 :: ModIface
776 -> ImpDeclSpec -- The span for the entire import decl
777 -> Maybe (Bool, Located [LIE RdrName]) -- Import spec; True => hiding
778 -> RnM (Maybe (Bool, Located [LIE Name]), -- Import spec w/ Names
779 [GlobalRdrElt]) -- Same again, but in GRE form
780 filterImports iface decl_spec Nothing
781 = return (Nothing, gresFromAvails (Just imp_spec) (mi_exports iface))
782 where
783 imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }
784
785
786 filterImports iface decl_spec (Just (want_hiding, L l import_items))
787 = do -- check for errors, convert RdrNames to Names
788 items1 <- mapM lookup_lie import_items
789
790 let items2 :: [(LIE Name, AvailInfo)]
791 items2 = concat items1
792 -- NB the AvailInfo may have duplicates, and several items
793 -- for the same parent; e.g N(x) and N(y)
794
795 names = availsToNameSet (map snd items2)
796 keep n = not (n `elemNameSet` names)
797 pruned_avails = filterAvails keep all_avails
798 hiding_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }
799
800 gres | want_hiding = gresFromAvails (Just hiding_spec) pruned_avails
801 | otherwise = concatMap (gresFromIE decl_spec) items2
802
803 return (Just (want_hiding, L l (map fst items2)), gres)
804 where
805 all_avails = mi_exports iface
806
807 -- See Note [Dealing with imports]
808 imp_occ_env :: OccEnv (Name, -- the name
809 AvailInfo, -- the export item providing the name
810 Maybe Name) -- the parent of associated types
811 imp_occ_env = mkOccEnv_C combine [ (nameOccName n, (n, a, Nothing))
812 | a <- all_avails, n <- availNames a]
813 where
814 -- See Note [Dealing with imports]
815 -- 'combine' is only called for associated data types which appear
816 -- twice in the all_avails. In the example, we combine
817 -- T(T,T1,T2,T3) and C(C,T) to give (T, T(T,T1,T2,T3), Just C)
818 -- NB: the AvailTC can have fields as well as data constructors (Trac #12127)
819 combine (name1, a1@(AvailTC p1 _ _), mp1)
820 (name2, a2@(AvailTC p2 _ _), mp2)
821 = ASSERT2( name1 == name2 && isNothing mp1 && isNothing mp2
822 , ppr name1 <+> ppr name2 <+> ppr mp1 <+> ppr mp2 )
823 if p1 == name1 then (name1, a1, Just p2)
824 else (name1, a2, Just p1)
825 combine x y = pprPanic "filterImports/combine" (ppr x $$ ppr y)
826
827 lookup_name :: RdrName -> IELookupM (Name, AvailInfo, Maybe Name)
828 lookup_name rdr | isQual rdr = failLookupWith (QualImportError rdr)
829 | Just succ <- mb_success = return succ
830 | otherwise = failLookupWith BadImport
831 where
832 mb_success = lookupOccEnv imp_occ_env (rdrNameOcc rdr)
833
834 lookup_lie :: LIE RdrName -> TcRn [(LIE Name, AvailInfo)]
835 lookup_lie (L loc ieRdr)
836 = do (stuff, warns) <- setSrcSpan loc $
837 liftM (fromMaybe ([],[])) $
838 run_lookup (lookup_ie ieRdr)
839 mapM_ emit_warning warns
840 return [ (L loc ie, avail) | (ie,avail) <- stuff ]
841 where
842 -- Warn when importing T(..) if T was exported abstractly
843 emit_warning (DodgyImport n) = whenWOptM Opt_WarnDodgyImports $
844 addWarn (Reason Opt_WarnDodgyImports) (dodgyImportWarn n)
845 emit_warning MissingImportList = whenWOptM Opt_WarnMissingImportList $
846 addWarn (Reason Opt_WarnMissingImportList) (missingImportListItem ieRdr)
847 emit_warning BadImportW = whenWOptM Opt_WarnDodgyImports $
848 addWarn (Reason Opt_WarnDodgyImports) (lookup_err_msg BadImport)
849
850 run_lookup :: IELookupM a -> TcRn (Maybe a)
851 run_lookup m = case m of
852 Failed err -> addErr (lookup_err_msg err) >> return Nothing
853 Succeeded a -> return (Just a)
854
855 lookup_err_msg err = case err of
856 BadImport -> badImportItemErr iface decl_spec ieRdr all_avails
857 IllegalImport -> illegalImportItemErr
858 QualImportError rdr -> qualImportItemErr rdr
859
860 -- For each import item, we convert its RdrNames to Names,
861 -- and at the same time construct an AvailInfo corresponding
862 -- to what is actually imported by this item.
863 -- Returns Nothing on error.
864 -- We return a list here, because in the case of an import
865 -- item like C, if we are hiding, then C refers to *both* a
866 -- type/class and a data constructor. Moreover, when we import
867 -- data constructors of an associated family, we need separate
868 -- AvailInfos for the data constructors and the family (as they have
869 -- different parents). See Note [Dealing with imports]
870 lookup_ie :: IE RdrName -> IELookupM ([(IE Name, AvailInfo)], [IELookupWarning])
871 lookup_ie ie = handle_bad_import $ do
872 case ie of
873 IEVar (L l n) -> do
874 (name, avail, _) <- lookup_name n
875 return ([(IEVar (L l name), trimAvail avail name)], [])
876
877 IEThingAll (L l tc) -> do
878 (name, avail, mb_parent) <- lookup_name tc
879 let warns = case avail of
880 Avail {} -- e.g. f(..)
881 -> [DodgyImport tc]
882
883 AvailTC _ subs fs
884 | null (drop 1 subs) && null fs -- e.g. T(..) where T is a synonym
885 -> [DodgyImport tc]
886
887 | not (is_qual decl_spec) -- e.g. import M( T(..) )
888 -> [MissingImportList]
889
890 | otherwise
891 -> []
892
893 renamed_ie = IEThingAll (L l name)
894 sub_avails = case avail of
895 Avail {} -> []
896 AvailTC name2 subs fs -> [(renamed_ie, AvailTC name2 (subs \\ [name]) fs)]
897 case mb_parent of
898 Nothing -> return ([(renamed_ie, avail)], warns)
899 -- non-associated ty/cls
900 Just parent -> return ((renamed_ie, AvailTC parent [name] []) : sub_avails, warns)
901 -- associated type
902
903 IEThingAbs (L l tc)
904 | want_hiding -- hiding ( C )
905 -- Here the 'C' can be a data constructor
906 -- *or* a type/class, or even both
907 -> let tc_name = lookup_name tc
908 dc_name = lookup_name (setRdrNameSpace tc srcDataName)
909 in
910 case catIELookupM [ tc_name, dc_name ] of
911 [] -> failLookupWith BadImport
912 names -> return ([mkIEThingAbs l name | name <- names], [])
913 | otherwise
914 -> do nameAvail <- lookup_name tc
915 return ([mkIEThingAbs l nameAvail], [])
916
917 IEThingWith (L l rdr_tc) wc rdr_ns rdr_fs ->
918 ASSERT2(null rdr_fs, ppr rdr_fs) do
919 (name, AvailTC _ ns subflds, mb_parent) <- lookup_name rdr_tc
920
921 -- Look up the children in the sub-names of the parent
922 let subnames = case ns of -- The tc is first in ns,
923 [] -> [] -- if it is there at all
924 -- See the AvailTC Invariant in Avail.hs
925 (n1:ns1) | n1 == name -> ns1
926 | otherwise -> ns
927 case lookupChildren (map Left subnames ++ map Right subflds) rdr_ns of
928 Nothing -> failLookupWith BadImport
929 Just (childnames, childflds) ->
930 case mb_parent of
931 -- non-associated ty/cls
932 Nothing
933 -> return ([(IEThingWith (L l name) wc childnames childflds,
934 AvailTC name (name:map unLoc childnames) (map unLoc childflds))],
935 [])
936 -- associated ty
937 Just parent
938 -> return ([(IEThingWith (L l name) wc childnames childflds,
939 AvailTC name (map unLoc childnames) (map unLoc childflds)),
940 (IEThingWith (L l name) wc childnames childflds,
941 AvailTC parent [name] [])],
942 [])
943
944 _other -> failLookupWith IllegalImport
945 -- could be IEModuleContents, IEGroup, IEDoc, IEDocNamed
946 -- all errors.
947
948 where
949 mkIEThingAbs l (n, av, Nothing ) = (IEThingAbs (L l n),
950 trimAvail av n)
951 mkIEThingAbs l (n, _, Just parent) = (IEThingAbs (L l n),
952 AvailTC parent [n] [])
953
954 handle_bad_import m = catchIELookup m $ \err -> case err of
955 BadImport | want_hiding -> return ([], [BadImportW])
956 _ -> failLookupWith err
957
958 type IELookupM = MaybeErr IELookupError
959
960 data IELookupWarning
961 = BadImportW
962 | MissingImportList
963 | DodgyImport RdrName
964 -- NB. use the RdrName for reporting a "dodgy" import
965
966 data IELookupError
967 = QualImportError RdrName
968 | BadImport
969 | IllegalImport
970
971 failLookupWith :: IELookupError -> IELookupM a
972 failLookupWith err = Failed err
973
974 catchIELookup :: IELookupM a -> (IELookupError -> IELookupM a) -> IELookupM a
975 catchIELookup m h = case m of
976 Succeeded r -> return r
977 Failed err -> h err
978
979 catIELookupM :: [IELookupM a] -> [a]
980 catIELookupM ms = [ a | Succeeded a <- ms ]
981
982 {-
983 ************************************************************************
984 * *
985 \subsection{Import/Export Utils}
986 * *
987 ************************************************************************
988 -}
989
990 plusAvail :: AvailInfo -> AvailInfo -> AvailInfo
991 plusAvail a1 a2
992 | debugIsOn && availName a1 /= availName a2
993 = pprPanic "RnEnv.plusAvail names differ" (hsep [ppr a1,ppr a2])
994 plusAvail a1@(Avail {}) (Avail {}) = a1
995 plusAvail (AvailTC _ [] []) a2@(AvailTC {}) = a2
996 plusAvail a1@(AvailTC {}) (AvailTC _ [] []) = a1
997 plusAvail (AvailTC n1 (s1:ss1) fs1) (AvailTC n2 (s2:ss2) fs2)
998 = case (n1==s1, n2==s2) of -- Maintain invariant the parent is first
999 (True,True) -> AvailTC n1 (s1 : (ss1 `unionLists` ss2))
1000 (fs1 `unionLists` fs2)
1001 (True,False) -> AvailTC n1 (s1 : (ss1 `unionLists` (s2:ss2)))
1002 (fs1 `unionLists` fs2)
1003 (False,True) -> AvailTC n1 (s2 : ((s1:ss1) `unionLists` ss2))
1004 (fs1 `unionLists` fs2)
1005 (False,False) -> AvailTC n1 ((s1:ss1) `unionLists` (s2:ss2))
1006 (fs1 `unionLists` fs2)
1007 plusAvail (AvailTC n1 ss1 fs1) (AvailTC _ [] fs2)
1008 = AvailTC n1 ss1 (fs1 `unionLists` fs2)
1009 plusAvail (AvailTC n1 [] fs1) (AvailTC _ ss2 fs2)
1010 = AvailTC n1 ss2 (fs1 `unionLists` fs2)
1011 plusAvail a1 a2 = pprPanic "RnEnv.plusAvail" (hsep [ppr a1,ppr a2])
1012
1013 -- | trims an 'AvailInfo' to keep only a single name
1014 trimAvail :: AvailInfo -> Name -> AvailInfo
1015 trimAvail (Avail n) _ = Avail n
1016 trimAvail (AvailTC n ns fs) m = case find ((== m) . flSelector) fs of
1017 Just x -> AvailTC n [] [x]
1018 Nothing -> ASSERT( m `elem` ns ) AvailTC n [m] []
1019
1020 -- | filters 'AvailInfo's by the given predicate
1021 filterAvails :: (Name -> Bool) -> [AvailInfo] -> [AvailInfo]
1022 filterAvails keep avails = foldr (filterAvail keep) [] avails
1023
1024 -- | filters an 'AvailInfo' by the given predicate
1025 filterAvail :: (Name -> Bool) -> AvailInfo -> [AvailInfo] -> [AvailInfo]
1026 filterAvail keep ie rest =
1027 case ie of
1028 Avail n | keep n -> ie : rest
1029 | otherwise -> rest
1030 AvailTC tc ns fs ->
1031 let ns' = filter keep ns
1032 fs' = filter (keep . flSelector) fs in
1033 if null ns' && null fs' then rest else AvailTC tc ns' fs' : rest
1034
1035 -- | Given an import\/export spec, construct the appropriate 'GlobalRdrElt's.
1036 gresFromIE :: ImpDeclSpec -> (LIE Name, AvailInfo) -> [GlobalRdrElt]
1037 gresFromIE decl_spec (L loc ie, avail)
1038 = gresFromAvail prov_fn avail
1039 where
1040 is_explicit = case ie of
1041 IEThingAll (L _ name) -> \n -> n == name
1042 _ -> \_ -> True
1043 prov_fn name
1044 = Just (ImpSpec { is_decl = decl_spec, is_item = item_spec })
1045 where
1046 item_spec = ImpSome { is_explicit = is_explicit name, is_iloc = loc }
1047
1048
1049 {-
1050 Note [Children for duplicate record fields]
1051 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1052 Consider the module
1053
1054 {-# LANGUAGE DuplicateRecordFields #-}
1055 module M (F(foo, MkFInt, MkFBool)) where
1056 data family F a
1057 data instance F Int = MkFInt { foo :: Int }
1058 data instance F Bool = MkFBool { foo :: Bool }
1059
1060 The `foo` in the export list refers to *both* selectors! For this
1061 reason, lookupChildren builds an environment that maps the FastString
1062 to a list of items, rather than a single item.
1063 -}
1064
1065 mkChildEnv :: [GlobalRdrElt] -> NameEnv [GlobalRdrElt]
1066 mkChildEnv gres = foldr add emptyNameEnv gres
1067 where
1068 add gre env = case gre_par gre of
1069 FldParent p _ -> extendNameEnv_Acc (:) singleton env p gre
1070 ParentIs p -> extendNameEnv_Acc (:) singleton env p gre
1071 NoParent -> env
1072
1073 findChildren :: NameEnv [a] -> Name -> [a]
1074 findChildren env n = lookupNameEnv env n `orElse` []
1075
1076 lookupChildren :: [Either Name FieldLabel] -> [Located RdrName]
1077 -> Maybe ([Located Name], [Located FieldLabel])
1078 -- (lookupChildren all_kids rdr_items) maps each rdr_item to its
1079 -- corresponding Name all_kids, if the former exists
1080 -- The matching is done by FastString, not OccName, so that
1081 -- Cls( meth, AssocTy )
1082 -- will correctly find AssocTy among the all_kids of Cls, even though
1083 -- the RdrName for AssocTy may have a (bogus) DataName namespace
1084 -- (Really the rdr_items should be FastStrings in the first place.)
1085 lookupChildren all_kids rdr_items
1086 = do xs <- mapM doOne rdr_items
1087 return (fmap concat (partitionEithers xs))
1088 where
1089 doOne (L l r) = case (lookupFsEnv kid_env . occNameFS . rdrNameOcc) r of
1090 Just [Left n] -> Just (Left (L l n))
1091 Just rs | all isRight rs -> Just (Right (map (L l) (rights rs)))
1092 _ -> Nothing
1093
1094 -- See Note [Children for duplicate record fields]
1095 kid_env = extendFsEnvList_C (++) emptyFsEnv
1096 [(either (occNameFS . nameOccName) flLabel x, [x]) | x <- all_kids]
1097
1098
1099
1100
1101 -- | Combines 'AvailInfo's from the same family
1102 -- 'avails' may have several items with the same availName
1103 -- E.g import Ix( Ix(..), index )
1104 -- will give Ix(Ix,index,range) and Ix(index)
1105 -- We want to combine these; addAvail does that
1106 nubAvails :: [AvailInfo] -> [AvailInfo]
1107 nubAvails avails = nameEnvElts (foldl add emptyNameEnv avails)
1108 where
1109 add env avail = extendNameEnv_C plusAvail env (availName avail) avail
1110
1111
1112 -------------------------------
1113
1114 {-
1115 *********************************************************
1116 * *
1117 \subsection{Unused names}
1118 * *
1119 *********************************************************
1120 -}
1121
1122 reportUnusedNames :: Maybe (Located [LIE RdrName]) -- Export list
1123 -> TcGblEnv -> RnM ()
1124 reportUnusedNames _export_decls gbl_env
1125 = do { traceRn ((text "RUN") <+> (ppr (tcg_dus gbl_env)))
1126 ; warnUnusedImportDecls gbl_env
1127 ; warnUnusedTopBinds unused_locals
1128 ; warnMissingSignatures gbl_env }
1129 where
1130 used_names :: NameSet
1131 used_names = findUses (tcg_dus gbl_env) emptyNameSet
1132 -- NB: currently, if f x = g, we only treat 'g' as used if 'f' is used
1133 -- Hence findUses
1134
1135 -- Collect the defined names from the in-scope environment
1136 defined_names :: [GlobalRdrElt]
1137 defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)
1138
1139 -- Note that defined_and_used, defined_but_not_used
1140 -- are both [GRE]; that's why we need defined_and_used
1141 -- rather than just used_names
1142 _defined_and_used, defined_but_not_used :: [GlobalRdrElt]
1143 (_defined_and_used, defined_but_not_used)
1144 = partition (gre_is_used used_names) defined_names
1145
1146 kids_env = mkChildEnv defined_names
1147 -- This is done in mkExports too; duplicated work
1148
1149 gre_is_used :: NameSet -> GlobalRdrElt -> Bool
1150 gre_is_used used_names (GRE {gre_name = name})
1151 = name `elemNameSet` used_names
1152 || any (\ gre -> gre_name gre `elemNameSet` used_names) (findChildren kids_env name)
1153 -- A use of C implies a use of T,
1154 -- if C was brought into scope by T(..) or T(C)
1155
1156 -- Filter out the ones that are
1157 -- (a) defined in this module, and
1158 -- (b) not defined by a 'deriving' clause
1159 -- The latter have an Internal Name, so we can filter them out easily
1160 unused_locals :: [GlobalRdrElt]
1161 unused_locals = filter is_unused_local defined_but_not_used
1162 is_unused_local :: GlobalRdrElt -> Bool
1163 is_unused_local gre = isLocalGRE gre && isExternalName (gre_name gre)
1164
1165 {-
1166 *********************************************************
1167 * *
1168 \subsection{Unused imports}
1169 * *
1170 *********************************************************
1171
1172 This code finds which import declarations are unused. The
1173 specification and implementation notes are here:
1174 http://ghc.haskell.org/trac/ghc/wiki/Commentary/Compiler/UnusedImports
1175 -}
1176
1177 type ImportDeclUsage
1178 = ( LImportDecl Name -- The import declaration
1179 , [AvailInfo] -- What *is* used (normalised)
1180 , [Name] ) -- What is imported but *not* used
1181
1182 warnUnusedImportDecls :: TcGblEnv -> RnM ()
1183 warnUnusedImportDecls gbl_env
1184 = do { uses <- readMutVar (tcg_used_gres gbl_env)
1185 ; let user_imports = filterOut (ideclImplicit . unLoc) (tcg_rn_imports gbl_env)
1186 -- This whole function deals only with *user* imports
1187 -- both for warning about unnecessary ones, and for
1188 -- deciding the minimal ones
1189 rdr_env = tcg_rdr_env gbl_env
1190 fld_env = mkFieldEnv rdr_env
1191
1192 ; let usage :: [ImportDeclUsage]
1193 usage = findImportUsage user_imports uses
1194
1195 ; traceRn (vcat [ text "Uses:" <+> ppr uses
1196 , text "Import usage" <+> ppr usage])
1197 ; whenWOptM Opt_WarnUnusedImports $
1198 mapM_ (warnUnusedImport Opt_WarnUnusedImports fld_env) usage
1199
1200 ; whenGOptM Opt_D_dump_minimal_imports $
1201 printMinimalImports usage }
1202
1203 -- | Warn the user about top level binders that lack type signatures.
1204 warnMissingSignatures :: TcGblEnv -> RnM ()
1205 warnMissingSignatures gbl_env
1206 = do { let exports = availsToNameSet (tcg_exports gbl_env)
1207 sig_ns = tcg_sigs gbl_env
1208 -- We use sig_ns to exclude top-level bindings that are generated by GHC
1209 binds = collectHsBindsBinders $ tcg_binds gbl_env
1210 pat_syns = tcg_patsyns gbl_env
1211
1212 -- Warn about missing signatures
1213 -- Do this only when we we have a type to offer
1214 ; warn_missing_sigs <- woptM Opt_WarnMissingSignatures
1215 ; warn_only_exported <- woptM Opt_WarnMissingExportedSignatures
1216 ; warn_pat_syns <- woptM Opt_WarnMissingPatternSynonymSignatures
1217
1218 ; let add_sig_warns
1219 | warn_only_exported = add_warns Opt_WarnMissingExportedSignatures
1220 | warn_missing_sigs = add_warns Opt_WarnMissingSignatures
1221 | warn_pat_syns = add_warns Opt_WarnMissingPatternSynonymSignatures
1222 | otherwise = return ()
1223
1224 add_warns flag
1225 = when warn_pat_syns
1226 (mapM_ add_pat_syn_warn pat_syns) >>
1227 when (warn_missing_sigs || warn_only_exported)
1228 (mapM_ add_bind_warn binds)
1229 where
1230 add_pat_syn_warn p
1231 = add_warn name $
1232 hang (text "Pattern synonym with no type signature:")
1233 2 (text "pattern" <+> pprPrefixName name <+> dcolon <+> pp_ty)
1234 where
1235 name = patSynName p
1236 pp_ty = pprPatSynType p
1237
1238 add_bind_warn id
1239 = do { env <- tcInitTidyEnv -- Why not use emptyTidyEnv?
1240 ; let name = idName id
1241 (_, ty) = tidyOpenType env (idType id)
1242 ty_msg = pprSigmaType ty
1243 ; add_warn name $
1244 hang (text "Top-level binding with no type signature:")
1245 2 (pprPrefixName name <+> dcolon <+> ty_msg) }
1246
1247 add_warn name msg
1248 = when (name `elemNameSet` sig_ns && export_check name)
1249 (addWarnAt (Reason flag) (getSrcSpan name) msg)
1250
1251 export_check name
1252 = not warn_only_exported || name `elemNameSet` exports
1253
1254 ; add_sig_warns }
1255
1256 {-
1257 Note [The ImportMap]
1258 ~~~~~~~~~~~~~~~~~~~~
1259 The ImportMap is a short-lived intermediate data struture records, for
1260 each import declaration, what stuff brought into scope by that
1261 declaration is actually used in the module.
1262
1263 The SrcLoc is the location of the END of a particular 'import'
1264 declaration. Why *END*? Because we don't want to get confused
1265 by the implicit Prelude import. Consider (Trac #7476) the module
1266 import Foo( foo )
1267 main = print foo
1268 There is an implicit 'import Prelude(print)', and it gets a SrcSpan
1269 of line 1:1 (just the point, not a span). If we use the *START* of
1270 the SrcSpan to identify the import decl, we'll confuse the implicit
1271 import Prelude with the explicit 'import Foo'. So we use the END.
1272 It's just a cheap hack; we could equally well use the Span too.
1273
1274 The AvailInfos are the things imported from that decl (just a list,
1275 not normalised).
1276 -}
1277
1278 type ImportMap = Map SrcLoc [AvailInfo] -- See [The ImportMap]
1279
1280 findImportUsage :: [LImportDecl Name]
1281 -> [GlobalRdrElt]
1282 -> [ImportDeclUsage]
1283
1284 findImportUsage imports used_gres
1285 = map unused_decl imports
1286 where
1287 import_usage :: ImportMap
1288 import_usage
1289 = foldr extendImportMap Map.empty used_gres
1290
1291 unused_decl decl@(L loc (ImportDecl { ideclHiding = imps }))
1292 = (decl, nubAvails used_avails, nameSetElemsStable unused_imps)
1293 where
1294 used_avails = Map.lookup (srcSpanEnd loc) import_usage `orElse` []
1295 -- srcSpanEnd: see Note [The ImportMap]
1296 used_names = availsToNameSetWithSelectors used_avails
1297 used_parents = mkNameSet [n | AvailTC n _ _ <- used_avails]
1298
1299 unused_imps -- Not trivial; see eg Trac #7454
1300 = case imps of
1301 Just (False, L _ imp_ies) ->
1302 foldr (add_unused . unLoc) emptyNameSet imp_ies
1303 _other -> emptyNameSet -- No explicit import list => no unused-name list
1304
1305 add_unused :: IE Name -> NameSet -> NameSet
1306 add_unused (IEVar (L _ n)) acc = add_unused_name n acc
1307 add_unused (IEThingAbs (L _ n)) acc = add_unused_name n acc
1308 add_unused (IEThingAll (L _ n)) acc = add_unused_all n acc
1309 add_unused (IEThingWith (L _ p) wc ns fs) acc =
1310 add_wc_all (add_unused_with p xs acc)
1311 where xs = map unLoc ns ++ map (flSelector . unLoc) fs
1312 add_wc_all = case wc of
1313 NoIEWildcard -> id
1314 IEWildcard _ -> add_unused_all p
1315 add_unused _ acc = acc
1316
1317 add_unused_name n acc
1318 | n `elemNameSet` used_names = acc
1319 | otherwise = acc `extendNameSet` n
1320 add_unused_all n acc
1321 | n `elemNameSet` used_names = acc
1322 | n `elemNameSet` used_parents = acc
1323 | otherwise = acc `extendNameSet` n
1324 add_unused_with p ns acc
1325 | all (`elemNameSet` acc1) ns = add_unused_name p acc1
1326 | otherwise = acc1
1327 where
1328 acc1 = foldr add_unused_name acc ns
1329 -- If you use 'signum' from Num, then the user may well have
1330 -- imported Num(signum). We don't want to complain that
1331 -- Num is not itself mentioned. Hence the two cases in add_unused_with.
1332
1333 extendImportMap :: GlobalRdrElt -> ImportMap -> ImportMap
1334 -- For each of a list of used GREs, find all the import decls that brought
1335 -- it into scope; choose one of them (bestImport), and record
1336 -- the RdrName in that import decl's entry in the ImportMap
1337 extendImportMap gre imp_map
1338 = add_imp gre (bestImport (gre_imp gre)) imp_map
1339 where
1340 add_imp :: GlobalRdrElt -> ImportSpec -> ImportMap -> ImportMap
1341 add_imp gre (ImpSpec { is_decl = imp_decl_spec }) imp_map
1342 = Map.insertWith add decl_loc [avail] imp_map
1343 where
1344 add _ avails = avail : avails -- add is really just a specialised (++)
1345 decl_loc = srcSpanEnd (is_dloc imp_decl_spec)
1346 -- For srcSpanEnd see Note [The ImportMap]
1347 avail = availFromGRE gre
1348
1349 warnUnusedImport :: WarningFlag -> NameEnv (FieldLabelString, Name)
1350 -> ImportDeclUsage -> RnM ()
1351 warnUnusedImport flag fld_env (L loc decl, used, unused)
1352 | Just (False,L _ []) <- ideclHiding decl
1353 = return () -- Do not warn for 'import M()'
1354
1355 | Just (True, L _ hides) <- ideclHiding decl
1356 , not (null hides)
1357 , pRELUDE_NAME == unLoc (ideclName decl)
1358 = return () -- Note [Do not warn about Prelude hiding]
1359 | null used = addWarnAt (Reason flag) loc msg1 -- Nothing used; drop entire decl
1360 | null unused = return () -- Everything imported is used; nop
1361 | otherwise = addWarnAt (Reason flag) loc msg2 -- Some imports are unused
1362 where
1363 msg1 = vcat [pp_herald <+> quotes pp_mod <+> pp_not_used,
1364 nest 2 (text "except perhaps to import instances from"
1365 <+> quotes pp_mod),
1366 text "To import instances alone, use:"
1367 <+> text "import" <+> pp_mod <> parens Outputable.empty ]
1368 msg2 = sep [pp_herald <+> quotes sort_unused,
1369 text "from module" <+> quotes pp_mod <+> pp_not_used]
1370 pp_herald = text "The" <+> pp_qual <+> text "import of"
1371 pp_qual
1372 | ideclQualified decl = text "qualified"
1373 | otherwise = Outputable.empty
1374 pp_mod = ppr (unLoc (ideclName decl))
1375 pp_not_used = text "is redundant"
1376
1377 ppr_possible_field n = case lookupNameEnv fld_env n of
1378 Just (fld, p) -> ppr p <> parens (ppr fld)
1379 Nothing -> ppr n
1380
1381 -- Print unused names in a deterministic (lexicographic) order
1382 sort_unused = pprWithCommas ppr_possible_field $
1383 sortBy (comparing nameOccName) unused
1384
1385 {-
1386 Note [Do not warn about Prelude hiding]
1387 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1388 We do not warn about
1389 import Prelude hiding( x, y )
1390 because even if nothing else from Prelude is used, it may be essential to hide
1391 x,y to avoid name-shadowing warnings. Example (Trac #9061)
1392 import Prelude hiding( log )
1393 f x = log where log = ()
1394
1395
1396
1397 Note [Printing minimal imports]
1398 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1399 To print the minimal imports we walk over the user-supplied import
1400 decls, and simply trim their import lists. NB that
1401
1402 * We do *not* change the 'qualified' or 'as' parts!
1403
1404 * We do not disard a decl altogether; we might need instances
1405 from it. Instead we just trim to an empty import list
1406 -}
1407
1408 printMinimalImports :: [ImportDeclUsage] -> RnM ()
1409 -- See Note [Printing minimal imports]
1410 printMinimalImports imports_w_usage
1411 = do { imports' <- mapM mk_minimal imports_w_usage
1412 ; this_mod <- getModule
1413 ; dflags <- getDynFlags
1414 ; liftIO $
1415 do { h <- openFile (mkFilename dflags this_mod) WriteMode
1416 ; printForUser dflags h neverQualify (vcat (map ppr imports')) }
1417 -- The neverQualify is important. We are printing Names
1418 -- but they are in the context of an 'import' decl, and
1419 -- we never qualify things inside there
1420 -- E.g. import Blag( f, b )
1421 -- not import Blag( Blag.f, Blag.g )!
1422 }
1423 where
1424 mkFilename dflags this_mod
1425 | Just d <- dumpDir dflags = d </> basefn
1426 | otherwise = basefn
1427 where
1428 basefn = moduleNameString (moduleName this_mod) ++ ".imports"
1429
1430 mk_minimal (L l decl, used, unused)
1431 | null unused
1432 , Just (False, _) <- ideclHiding decl
1433 = return (L l decl)
1434 | otherwise
1435 = do { let ImportDecl { ideclName = L _ mod_name
1436 , ideclSource = is_boot
1437 , ideclPkgQual = mb_pkg } = decl
1438 ; iface <- loadSrcInterface doc mod_name is_boot (fmap sl_fs mb_pkg)
1439 ; let lies = map (L l) (concatMap (to_ie iface) used)
1440 ; return (L l (decl { ideclHiding = Just (False, L l lies) })) }
1441 where
1442 doc = text "Compute minimal imports for" <+> ppr decl
1443
1444 to_ie :: ModIface -> AvailInfo -> [IE Name]
1445 -- The main trick here is that if we're importing all the constructors
1446 -- we want to say "T(..)", but if we're importing only a subset we want
1447 -- to say "T(A,B,C)". So we have to find out what the module exports.
1448 to_ie _ (Avail n)
1449 = [IEVar (noLoc n)]
1450 to_ie _ (AvailTC n [m] [])
1451 | n==m = [IEThingAbs (noLoc n)]
1452 to_ie iface (AvailTC n ns fs)
1453 = case [(xs,gs) | AvailTC x xs gs <- mi_exports iface
1454 , x == n
1455 , x `elem` xs -- Note [Partial export]
1456 ] of
1457 [xs] | all_used xs -> [IEThingAll (noLoc n)]
1458 | otherwise -> [IEThingWith (noLoc n) NoIEWildcard
1459 (map noLoc (filter (/= n) ns))
1460 (map noLoc fs)]
1461 -- Note [Overloaded field import]
1462 _other | all_non_overloaded fs
1463 -> map (IEVar . noLoc) $ ns ++ map flSelector fs
1464 | otherwise -> [IEThingWith (noLoc n) NoIEWildcard
1465 (map noLoc (filter (/= n) ns)) (map noLoc fs)]
1466 where
1467 fld_lbls = map flLabel fs
1468
1469 all_used (avail_occs, avail_flds)
1470 = all (`elem` ns) avail_occs
1471 && all (`elem` fld_lbls) (map flLabel avail_flds)
1472
1473 all_non_overloaded = all (not . flIsOverloaded)
1474
1475 {-
1476 Note [Partial export]
1477 ~~~~~~~~~~~~~~~~~~~~~
1478 Suppose we have
1479
1480 module A( op ) where
1481 class C a where
1482 op :: a -> a
1483
1484 module B where
1485 import A
1486 f = ..op...
1487
1488 Then the minimal import for module B is
1489 import A( op )
1490 not
1491 import A( C( op ) )
1492 which we would usually generate if C was exported from B. Hence
1493 the (x `elem` xs) test when deciding what to generate.
1494
1495
1496 Note [Overloaded field import]
1497 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1498 On the other hand, if we have
1499
1500 {-# LANGUAGE DuplicateRecordFields #-}
1501 module A where
1502 data T = MkT { foo :: Int }
1503
1504 module B where
1505 import A
1506 f = ...foo...
1507
1508 then the minimal import for module B must be
1509 import A ( T(foo) )
1510 because when DuplicateRecordFields is enabled, field selectors are
1511 not in scope without their enclosing datatype.
1512
1513
1514 ************************************************************************
1515 * *
1516 \subsection{Errors}
1517 * *
1518 ************************************************************************
1519 -}
1520
1521 qualImportItemErr :: RdrName -> SDoc
1522 qualImportItemErr rdr
1523 = hang (text "Illegal qualified name in import item:")
1524 2 (ppr rdr)
1525
1526 badImportItemErrStd :: ModIface -> ImpDeclSpec -> IE RdrName -> SDoc
1527 badImportItemErrStd iface decl_spec ie
1528 = sep [text "Module", quotes (ppr (is_mod decl_spec)), source_import,
1529 text "does not export", quotes (ppr ie)]
1530 where
1531 source_import | mi_boot iface = text "(hi-boot interface)"
1532 | otherwise = Outputable.empty
1533
1534 badImportItemErrDataCon :: OccName -> ModIface -> ImpDeclSpec -> IE RdrName -> SDoc
1535 badImportItemErrDataCon dataType_occ iface decl_spec ie
1536 = vcat [ text "In module"
1537 <+> quotes (ppr (is_mod decl_spec))
1538 <+> source_import <> colon
1539 , nest 2 $ quotes datacon
1540 <+> text "is a data constructor of"
1541 <+> quotes dataType
1542 , text "To import it use"
1543 , nest 2 $ quotes (text "import")
1544 <+> ppr (is_mod decl_spec)
1545 <> parens_sp (dataType <> parens_sp datacon)
1546 , text "or"
1547 , nest 2 $ quotes (text "import")
1548 <+> ppr (is_mod decl_spec)
1549 <> parens_sp (dataType <> text "(..)")
1550 ]
1551 where
1552 datacon_occ = rdrNameOcc $ ieName ie
1553 datacon = parenSymOcc datacon_occ (ppr datacon_occ)
1554 dataType = parenSymOcc dataType_occ (ppr dataType_occ)
1555 source_import | mi_boot iface = text "(hi-boot interface)"
1556 | otherwise = Outputable.empty
1557 parens_sp d = parens (space <> d <> space) -- T( f,g )
1558
1559 badImportItemErr :: ModIface -> ImpDeclSpec -> IE RdrName -> [AvailInfo] -> SDoc
1560 badImportItemErr iface decl_spec ie avails
1561 = case find checkIfDataCon avails of
1562 Just con -> badImportItemErrDataCon (availOccName con) iface decl_spec ie
1563 Nothing -> badImportItemErrStd iface decl_spec ie
1564 where
1565 checkIfDataCon (AvailTC _ ns _) =
1566 case find (\n -> importedFS == nameOccNameFS n) ns of
1567 Just n -> isDataConName n
1568 Nothing -> False
1569 checkIfDataCon _ = False
1570 availOccName = nameOccName . availName
1571 nameOccNameFS = occNameFS . nameOccName
1572 importedFS = occNameFS . rdrNameOcc $ ieName ie
1573
1574 illegalImportItemErr :: SDoc
1575 illegalImportItemErr = text "Illegal import item"
1576
1577 dodgyImportWarn :: RdrName -> SDoc
1578 dodgyImportWarn item = dodgyMsg (text "import") item
1579
1580 dodgyMsg :: (OutputableBndr n, HasOccName n) => SDoc -> n -> SDoc
1581 dodgyMsg kind tc
1582 = sep [ text "The" <+> kind <+> ptext (sLit "item")
1583 <+> quotes (ppr (IEThingAll (noLoc tc)))
1584 <+> text "suggests that",
1585 quotes (ppr tc) <+> text "has (in-scope) constructors or class methods,",
1586 text "but it has none" ]
1587
1588
1589 addDupDeclErr :: [GlobalRdrElt] -> TcRn ()
1590 addDupDeclErr [] = panic "addDupDeclErr: empty list"
1591 addDupDeclErr gres@(gre : _)
1592 = addErrAt (getSrcSpan (last sorted_names)) $
1593 -- Report the error at the later location
1594 vcat [text "Multiple declarations of" <+>
1595 quotes (ppr (nameOccName name)),
1596 -- NB. print the OccName, not the Name, because the
1597 -- latter might not be in scope in the RdrEnv and so will
1598 -- be printed qualified.
1599 text "Declared at:" <+>
1600 vcat (map (ppr . nameSrcLoc) sorted_names)]
1601 where
1602 name = gre_name gre
1603 sorted_names = sortWith nameSrcLoc (map gre_name gres)
1604
1605
1606
1607 missingImportListWarn :: ModuleName -> SDoc
1608 missingImportListWarn mod
1609 = text "The module" <+> quotes (ppr mod) <+> ptext (sLit "does not have an explicit import list")
1610
1611 missingImportListItem :: IE RdrName -> SDoc
1612 missingImportListItem ie
1613 = text "The import item" <+> quotes (ppr ie) <+> ptext (sLit "does not have an explicit import list")
1614
1615 moduleWarn :: ModuleName -> WarningTxt -> SDoc
1616 moduleWarn mod (WarningTxt _ txt)
1617 = sep [ text "Module" <+> quotes (ppr mod) <> ptext (sLit ":"),
1618 nest 2 (vcat (map (ppr . sl_fs . unLoc) txt)) ]
1619 moduleWarn mod (DeprecatedTxt _ txt)
1620 = sep [ text "Module" <+> quotes (ppr mod)
1621 <+> text "is deprecated:",
1622 nest 2 (vcat (map (ppr . sl_fs . unLoc) txt)) ]
1623
1624 packageImportErr :: SDoc
1625 packageImportErr
1626 = text "Package-qualified imports are not enabled; use PackageImports"
1627
1628 -- This data decl will parse OK
1629 -- data T = a Int
1630 -- treating "a" as the constructor.
1631 -- It is really hard to make the parser spot this malformation.
1632 -- So the renamer has to check that the constructor is legal
1633 --
1634 -- We can get an operator as the constructor, even in the prefix form:
1635 -- data T = :% Int Int
1636 -- from interface files, which always print in prefix form
1637
1638 checkConName :: RdrName -> TcRn ()
1639 checkConName name = checkErr (isRdrDataCon name) (badDataCon name)
1640
1641 badDataCon :: RdrName -> SDoc
1642 badDataCon name
1643 = hsep [text "Illegal data constructor name", quotes (ppr name)]