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