Refactor type family instance abstract syntax declarations
[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 dfid@(DataFamInstDecl { dfid_eqn =
692 HsIB { hsib_body = ti_decl }})
693 = do { main_name <- lookupFamInstName mb_cls (feqn_tycon ti_decl)
694 ; let (bndrs, flds) = hsDataFamInstBinders dfid
695 ; sub_names <- mapM newTopSrcBinder bndrs
696 ; flds' <- mapM (newRecordSelector overload_ok sub_names) flds
697 ; let avail = AvailTC (unLoc main_name) sub_names flds'
698 -- main_name is not bound here!
699 fld_env = mk_fld_env (feqn_rhs ti_decl) sub_names flds'
700 ; return (avail, fld_env) }
701
702 new_loc_di :: Bool -> Maybe Name -> LDataFamInstDecl GhcPs
703 -> RnM (AvailInfo, [(Name, [FieldLabel])])
704 new_loc_di overload_ok mb_cls (L _ d) = new_di overload_ok mb_cls d
705
706 newRecordSelector :: Bool -> [Name] -> LFieldOcc GhcPs -> RnM FieldLabel
707 newRecordSelector _ [] _ = error "newRecordSelector: datatype has no constructors!"
708 newRecordSelector overload_ok (dc:_) (L loc (FieldOcc (L _ fld) _))
709 = do { selName <- newTopSrcBinder $ L loc $ field
710 ; return $ qualFieldLbl { flSelector = selName } }
711 where
712 fieldOccName = occNameFS $ rdrNameOcc fld
713 qualFieldLbl = mkFieldLabelOccs fieldOccName (nameOccName dc) overload_ok
714 field | isExact fld = fld
715 -- use an Exact RdrName as is to preserve the bindings
716 -- of an already renamer-resolved field and its use
717 -- sites. This is needed to correctly support record
718 -- selectors in Template Haskell. See Note [Binders in
719 -- Template Haskell] in Convert.hs and Note [Looking up
720 -- Exact RdrNames] in RnEnv.hs.
721 | otherwise = mkRdrUnqual (flSelector qualFieldLbl)
722
723 {-
724 Note [Looking up family names in family instances]
725 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
726 Consider
727
728 module M where
729 type family T a :: *
730 type instance M.T Int = Bool
731
732 We might think that we can simply use 'lookupOccRn' when processing the type
733 instance to look up 'M.T'. Alas, we can't! The type family declaration is in
734 the *same* HsGroup as the type instance declaration. Hence, as we are
735 currently collecting the binders declared in that HsGroup, these binders will
736 not have been added to the global environment yet.
737
738 Solution is simple: process the type family declarations first, extend
739 the environment, and then process the type instances.
740
741
742 ************************************************************************
743 * *
744 \subsection{Filtering imports}
745 * *
746 ************************************************************************
747
748 @filterImports@ takes the @ExportEnv@ telling what the imported module makes
749 available, and filters it through the import spec (if any).
750
751 Note [Dealing with imports]
752 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
753 For import M( ies ), we take the mi_exports of M, and make
754 imp_occ_env :: OccEnv (Name, AvailInfo, Maybe Name)
755 One entry for each Name that M exports; the AvailInfo is the
756 AvailInfo exported from M that exports that Name.
757
758 The situation is made more complicated by associated types. E.g.
759 module M where
760 class C a where { data T a }
761 instance C Int where { data T Int = T1 | T2 }
762 instance C Bool where { data T Int = T3 }
763 Then M's export_avails are (recall the AvailTC invariant from Avails.hs)
764 C(C,T), T(T,T1,T2,T3)
765 Notice that T appears *twice*, once as a child and once as a parent. From
766 this list we construct a raw list including
767 T -> (T, T( T1, T2, T3 ), Nothing)
768 T -> (C, C( C, T ), Nothing)
769 and we combine these (in function 'combine' in 'imp_occ_env' in
770 'filterImports') to get
771 T -> (T, T(T,T1,T2,T3), Just C)
772
773 So the overall imp_occ_env is
774 C -> (C, C(C,T), Nothing)
775 T -> (T, T(T,T1,T2,T3), Just C)
776 T1 -> (T1, T(T,T1,T2,T3), Nothing) -- similarly T2,T3
777
778 If we say
779 import M( T(T1,T2) )
780 then we get *two* Avails: C(T), T(T1,T2)
781
782 Note that the imp_occ_env will have entries for data constructors too,
783 although we never look up data constructors.
784 -}
785
786 filterImports
787 :: ModIface
788 -> ImpDeclSpec -- The span for the entire import decl
789 -> Maybe (Bool, Located [LIE GhcPs]) -- Import spec; True => hiding
790 -> RnM (Maybe (Bool, Located [LIE GhcRn]), -- Import spec w/ Names
791 [GlobalRdrElt]) -- Same again, but in GRE form
792 filterImports iface decl_spec Nothing
793 = return (Nothing, gresFromAvails (Just imp_spec) (mi_exports iface))
794 where
795 imp_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }
796
797
798 filterImports iface decl_spec (Just (want_hiding, L l import_items))
799 = do -- check for errors, convert RdrNames to Names
800 items1 <- mapM lookup_lie import_items
801
802 let items2 :: [(LIE GhcRn, AvailInfo)]
803 items2 = concat items1
804 -- NB the AvailInfo may have duplicates, and several items
805 -- for the same parent; e.g N(x) and N(y)
806
807 names = availsToNameSet (map snd items2)
808 keep n = not (n `elemNameSet` names)
809 pruned_avails = filterAvails keep all_avails
810 hiding_spec = ImpSpec { is_decl = decl_spec, is_item = ImpAll }
811
812 gres | want_hiding = gresFromAvails (Just hiding_spec) pruned_avails
813 | otherwise = concatMap (gresFromIE decl_spec) items2
814
815 return (Just (want_hiding, L l (map fst items2)), gres)
816 where
817 all_avails = mi_exports iface
818
819 -- See Note [Dealing with imports]
820 imp_occ_env :: OccEnv (Name, -- the name
821 AvailInfo, -- the export item providing the name
822 Maybe Name) -- the parent of associated types
823 imp_occ_env = mkOccEnv_C combine [ (nameOccName n, (n, a, Nothing))
824 | a <- all_avails, n <- availNames a]
825 where
826 -- See Note [Dealing with imports]
827 -- 'combine' is only called for associated data types which appear
828 -- twice in the all_avails. In the example, we combine
829 -- T(T,T1,T2,T3) and C(C,T) to give (T, T(T,T1,T2,T3), Just C)
830 -- NB: the AvailTC can have fields as well as data constructors (Trac #12127)
831 combine (name1, a1@(AvailTC p1 _ _), mp1)
832 (name2, a2@(AvailTC p2 _ _), mp2)
833 = ASSERT2( name1 == name2 && isNothing mp1 && isNothing mp2
834 , ppr name1 <+> ppr name2 <+> ppr mp1 <+> ppr mp2 )
835 if p1 == name1 then (name1, a1, Just p2)
836 else (name1, a2, Just p1)
837 combine x y = pprPanic "filterImports/combine" (ppr x $$ ppr y)
838
839 lookup_name :: RdrName -> IELookupM (Name, AvailInfo, Maybe Name)
840 lookup_name rdr | isQual rdr = failLookupWith (QualImportError rdr)
841 | Just succ <- mb_success = return succ
842 | otherwise = failLookupWith BadImport
843 where
844 mb_success = lookupOccEnv imp_occ_env (rdrNameOcc rdr)
845
846 lookup_lie :: LIE GhcPs -> TcRn [(LIE GhcRn, AvailInfo)]
847 lookup_lie (L loc ieRdr)
848 = do (stuff, warns) <- setSrcSpan loc $
849 liftM (fromMaybe ([],[])) $
850 run_lookup (lookup_ie ieRdr)
851 mapM_ emit_warning warns
852 return [ (L loc ie, avail) | (ie,avail) <- stuff ]
853 where
854 -- Warn when importing T(..) if T was exported abstractly
855 emit_warning (DodgyImport n) = whenWOptM Opt_WarnDodgyImports $
856 addWarn (Reason Opt_WarnDodgyImports) (dodgyImportWarn n)
857 emit_warning MissingImportList = whenWOptM Opt_WarnMissingImportList $
858 addWarn (Reason Opt_WarnMissingImportList) (missingImportListItem ieRdr)
859 emit_warning BadImportW = whenWOptM Opt_WarnDodgyImports $
860 addWarn (Reason Opt_WarnDodgyImports) (lookup_err_msg BadImport)
861
862 run_lookup :: IELookupM a -> TcRn (Maybe a)
863 run_lookup m = case m of
864 Failed err -> addErr (lookup_err_msg err) >> return Nothing
865 Succeeded a -> return (Just a)
866
867 lookup_err_msg err = case err of
868 BadImport -> badImportItemErr iface decl_spec ieRdr all_avails
869 IllegalImport -> illegalImportItemErr
870 QualImportError rdr -> qualImportItemErr rdr
871
872 -- For each import item, we convert its RdrNames to Names,
873 -- and at the same time construct an AvailInfo corresponding
874 -- to what is actually imported by this item.
875 -- Returns Nothing on error.
876 -- We return a list here, because in the case of an import
877 -- item like C, if we are hiding, then C refers to *both* a
878 -- type/class and a data constructor. Moreover, when we import
879 -- data constructors of an associated family, we need separate
880 -- AvailInfos for the data constructors and the family (as they have
881 -- different parents). See Note [Dealing with imports]
882 lookup_ie :: IE GhcPs
883 -> IELookupM ([(IE GhcRn, AvailInfo)], [IELookupWarning])
884 lookup_ie ie = handle_bad_import $ do
885 case ie of
886 IEVar (L l n) -> do
887 (name, avail, _) <- lookup_name $ ieWrappedName n
888 return ([(IEVar (L l (replaceWrappedName n name)),
889 trimAvail avail name)], [])
890
891 IEThingAll (L l tc) -> do
892 (name, avail, mb_parent) <- lookup_name $ ieWrappedName tc
893 let warns = case avail of
894 Avail {} -- e.g. f(..)
895 -> [DodgyImport $ ieWrappedName tc]
896
897 AvailTC _ subs fs
898 | null (drop 1 subs) && null fs -- e.g. T(..) where T is a synonym
899 -> [DodgyImport $ ieWrappedName tc]
900
901 | not (is_qual decl_spec) -- e.g. import M( T(..) )
902 -> [MissingImportList]
903
904 | otherwise
905 -> []
906
907 renamed_ie = IEThingAll (L l (replaceWrappedName tc name))
908 sub_avails = case avail of
909 Avail {} -> []
910 AvailTC name2 subs fs -> [(renamed_ie, AvailTC name2 (subs \\ [name]) fs)]
911 case mb_parent of
912 Nothing -> return ([(renamed_ie, avail)], warns)
913 -- non-associated ty/cls
914 Just parent -> return ((renamed_ie, AvailTC parent [name] []) : sub_avails, warns)
915 -- associated type
916
917 IEThingAbs (L l tc')
918 | want_hiding -- hiding ( C )
919 -- Here the 'C' can be a data constructor
920 -- *or* a type/class, or even both
921 -> let tc = ieWrappedName tc'
922 tc_name = lookup_name tc
923 dc_name = lookup_name (setRdrNameSpace tc srcDataName)
924 in
925 case catIELookupM [ tc_name, dc_name ] of
926 [] -> failLookupWith BadImport
927 names -> return ([mkIEThingAbs tc' l name | name <- names], [])
928 | otherwise
929 -> do nameAvail <- lookup_name (ieWrappedName tc')
930 return ([mkIEThingAbs tc' l nameAvail]
931 , [])
932
933 IEThingWith (L l rdr_tc) wc rdr_ns' rdr_fs ->
934 ASSERT2(null rdr_fs, ppr rdr_fs) do
935 (name, AvailTC _ ns subflds, mb_parent)
936 <- lookup_name (ieWrappedName rdr_tc)
937
938 -- Look up the children in the sub-names of the parent
939 let subnames = case ns of -- The tc is first in ns,
940 [] -> [] -- if it is there at all
941 -- See the AvailTC Invariant in Avail.hs
942 (n1:ns1) | n1 == name -> ns1
943 | otherwise -> ns
944 rdr_ns = map ieLWrappedName rdr_ns'
945 case lookupChildren (map Left subnames ++ map Right subflds) rdr_ns of
946 Nothing -> failLookupWith BadImport
947 Just (childnames, childflds) ->
948 case mb_parent of
949 -- non-associated ty/cls
950 Nothing
951 -> return ([(IEThingWith (L l name') wc childnames'
952 childflds,
953 AvailTC name (name:map unLoc childnames) (map unLoc childflds))],
954 [])
955 where name' = replaceWrappedName rdr_tc name
956 childnames' = map to_ie_post_rn childnames
957 -- childnames' = postrn_ies childnames
958 -- associated ty
959 Just parent
960 -> return ([(IEThingWith (L l name') wc childnames'
961 childflds,
962 AvailTC name (map unLoc childnames) (map unLoc childflds)),
963 (IEThingWith (L l name') wc childnames'
964 childflds,
965 AvailTC parent [name] [])],
966 [])
967 where name' = replaceWrappedName rdr_tc name
968 childnames' = map to_ie_post_rn childnames
969
970 _other -> failLookupWith IllegalImport
971 -- could be IEModuleContents, IEGroup, IEDoc, IEDocNamed
972 -- all errors.
973
974 where
975 mkIEThingAbs tc l (n, av, Nothing )
976 = (IEThingAbs (L l (replaceWrappedName tc n)), trimAvail av n)
977 mkIEThingAbs tc l (n, _, Just parent)
978 = (IEThingAbs (L l (replaceWrappedName tc n)), AvailTC parent [n] [])
979
980 handle_bad_import m = catchIELookup m $ \err -> case err of
981 BadImport | want_hiding -> return ([], [BadImportW])
982 _ -> failLookupWith err
983
984 type IELookupM = MaybeErr IELookupError
985
986 data IELookupWarning
987 = BadImportW
988 | MissingImportList
989 | DodgyImport RdrName
990 -- NB. use the RdrName for reporting a "dodgy" import
991
992 data IELookupError
993 = QualImportError RdrName
994 | BadImport
995 | IllegalImport
996
997 failLookupWith :: IELookupError -> IELookupM a
998 failLookupWith err = Failed err
999
1000 catchIELookup :: IELookupM a -> (IELookupError -> IELookupM a) -> IELookupM a
1001 catchIELookup m h = case m of
1002 Succeeded r -> return r
1003 Failed err -> h err
1004
1005 catIELookupM :: [IELookupM a] -> [a]
1006 catIELookupM ms = [ a | Succeeded a <- ms ]
1007
1008 {-
1009 ************************************************************************
1010 * *
1011 \subsection{Import/Export Utils}
1012 * *
1013 ************************************************************************
1014 -}
1015
1016 -- | Given an import\/export spec, construct the appropriate 'GlobalRdrElt's.
1017 gresFromIE :: ImpDeclSpec -> (LIE GhcRn, AvailInfo) -> [GlobalRdrElt]
1018 gresFromIE decl_spec (L loc ie, avail)
1019 = gresFromAvail prov_fn avail
1020 where
1021 is_explicit = case ie of
1022 IEThingAll (L _ name) -> \n -> n == ieWrappedName name
1023 _ -> \_ -> True
1024 prov_fn name
1025 = Just (ImpSpec { is_decl = decl_spec, is_item = item_spec })
1026 where
1027 item_spec = ImpSome { is_explicit = is_explicit name, is_iloc = loc }
1028
1029
1030 {-
1031 Note [Children for duplicate record fields]
1032 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1033 Consider the module
1034
1035 {-# LANGUAGE DuplicateRecordFields #-}
1036 module M (F(foo, MkFInt, MkFBool)) where
1037 data family F a
1038 data instance F Int = MkFInt { foo :: Int }
1039 data instance F Bool = MkFBool { foo :: Bool }
1040
1041 The `foo` in the export list refers to *both* selectors! For this
1042 reason, lookupChildren builds an environment that maps the FastString
1043 to a list of items, rather than a single item.
1044 -}
1045
1046 mkChildEnv :: [GlobalRdrElt] -> NameEnv [GlobalRdrElt]
1047 mkChildEnv gres = foldr add emptyNameEnv gres
1048 where
1049 add gre env = case gre_par gre of
1050 FldParent p _ -> extendNameEnv_Acc (:) singleton env p gre
1051 ParentIs p -> extendNameEnv_Acc (:) singleton env p gre
1052 NoParent -> env
1053
1054 findChildren :: NameEnv [a] -> Name -> [a]
1055 findChildren env n = lookupNameEnv env n `orElse` []
1056
1057 lookupChildren :: [Either Name FieldLabel] -> [Located RdrName]
1058 -> Maybe ([Located Name], [Located FieldLabel])
1059 -- (lookupChildren all_kids rdr_items) maps each rdr_item to its
1060 -- corresponding Name all_kids, if the former exists
1061 -- The matching is done by FastString, not OccName, so that
1062 -- Cls( meth, AssocTy )
1063 -- will correctly find AssocTy among the all_kids of Cls, even though
1064 -- the RdrName for AssocTy may have a (bogus) DataName namespace
1065 -- (Really the rdr_items should be FastStrings in the first place.)
1066 lookupChildren all_kids rdr_items
1067 = do xs <- mapM doOne rdr_items
1068 return (fmap concat (partitionEithers xs))
1069 where
1070 doOne (L l r) = case (lookupFsEnv kid_env . occNameFS . rdrNameOcc) r of
1071 Just [Left n] -> Just (Left (L l n))
1072 Just rs | all isRight rs -> Just (Right (map (L l) (rights rs)))
1073 _ -> Nothing
1074
1075 -- See Note [Children for duplicate record fields]
1076 kid_env = extendFsEnvList_C (++) emptyFsEnv
1077 [(either (occNameFS . nameOccName) flLabel x, [x]) | x <- all_kids]
1078
1079
1080
1081 -------------------------------
1082
1083 {-
1084 *********************************************************
1085 * *
1086 \subsection{Unused names}
1087 * *
1088 *********************************************************
1089 -}
1090
1091 reportUnusedNames :: Maybe (Located [LIE GhcPs]) -- Export list
1092 -> TcGblEnv -> RnM ()
1093 reportUnusedNames _export_decls gbl_env
1094 = do { traceRn "RUN" (ppr (tcg_dus gbl_env))
1095 ; warnUnusedImportDecls gbl_env
1096 ; warnUnusedTopBinds unused_locals
1097 ; warnMissingSignatures gbl_env }
1098 where
1099 used_names :: NameSet
1100 used_names = findUses (tcg_dus gbl_env) emptyNameSet
1101 -- NB: currently, if f x = g, we only treat 'g' as used if 'f' is used
1102 -- Hence findUses
1103
1104 -- Collect the defined names from the in-scope environment
1105 defined_names :: [GlobalRdrElt]
1106 defined_names = globalRdrEnvElts (tcg_rdr_env gbl_env)
1107
1108 -- Note that defined_and_used, defined_but_not_used
1109 -- are both [GRE]; that's why we need defined_and_used
1110 -- rather than just used_names
1111 _defined_and_used, defined_but_not_used :: [GlobalRdrElt]
1112 (_defined_and_used, defined_but_not_used)
1113 = partition (gre_is_used used_names) defined_names
1114
1115 kids_env = mkChildEnv defined_names
1116 -- This is done in mkExports too; duplicated work
1117
1118 gre_is_used :: NameSet -> GlobalRdrElt -> Bool
1119 gre_is_used used_names (GRE {gre_name = name})
1120 = name `elemNameSet` used_names
1121 || any (\ gre -> gre_name gre `elemNameSet` used_names) (findChildren kids_env name)
1122 -- A use of C implies a use of T,
1123 -- if C was brought into scope by T(..) or T(C)
1124
1125 -- Filter out the ones that are
1126 -- (a) defined in this module, and
1127 -- (b) not defined by a 'deriving' clause
1128 -- The latter have an Internal Name, so we can filter them out easily
1129 unused_locals :: [GlobalRdrElt]
1130 unused_locals = filter is_unused_local defined_but_not_used
1131 is_unused_local :: GlobalRdrElt -> Bool
1132 is_unused_local gre = isLocalGRE gre && isExternalName (gre_name gre)
1133
1134 {-
1135 *********************************************************
1136 * *
1137 \subsection{Unused imports}
1138 * *
1139 *********************************************************
1140
1141 This code finds which import declarations are unused. The
1142 specification and implementation notes are here:
1143 http://ghc.haskell.org/trac/ghc/wiki/Commentary/Compiler/UnusedImports
1144 -}
1145
1146 type ImportDeclUsage
1147 = ( LImportDecl GhcRn -- The import declaration
1148 , [AvailInfo] -- What *is* used (normalised)
1149 , [Name] ) -- What is imported but *not* used
1150
1151 warnUnusedImportDecls :: TcGblEnv -> RnM ()
1152 warnUnusedImportDecls gbl_env
1153 = do { uses <- readMutVar (tcg_used_gres gbl_env)
1154 ; let user_imports = filterOut (ideclImplicit . unLoc) (tcg_rn_imports gbl_env)
1155 -- This whole function deals only with *user* imports
1156 -- both for warning about unnecessary ones, and for
1157 -- deciding the minimal ones
1158 rdr_env = tcg_rdr_env gbl_env
1159 fld_env = mkFieldEnv rdr_env
1160
1161 ; let usage :: [ImportDeclUsage]
1162 usage = findImportUsage user_imports uses
1163
1164 ; traceRn "warnUnusedImportDecls" $
1165 (vcat [ text "Uses:" <+> ppr uses
1166 , text "Import usage" <+> ppr usage])
1167 ; whenWOptM Opt_WarnUnusedImports $
1168 mapM_ (warnUnusedImport Opt_WarnUnusedImports fld_env) usage
1169
1170 ; whenGOptM Opt_D_dump_minimal_imports $
1171 printMinimalImports usage }
1172
1173 -- | Warn the user about top level binders that lack type signatures.
1174 -- Called /after/ type inference, so that we can report the
1175 -- inferred type of the function
1176 warnMissingSignatures :: TcGblEnv -> RnM ()
1177 warnMissingSignatures gbl_env
1178 = do { let exports = availsToNameSet (tcg_exports gbl_env)
1179 sig_ns = tcg_sigs gbl_env
1180 -- We use sig_ns to exclude top-level bindings that are generated by GHC
1181 binds = collectHsBindsBinders $ tcg_binds gbl_env
1182 pat_syns = tcg_patsyns gbl_env
1183
1184 -- Warn about missing signatures
1185 -- Do this only when we we have a type to offer
1186 ; warn_missing_sigs <- woptM Opt_WarnMissingSignatures
1187 ; warn_only_exported <- woptM Opt_WarnMissingExportedSignatures
1188 ; warn_pat_syns <- woptM Opt_WarnMissingPatternSynonymSignatures
1189
1190 ; let add_sig_warns
1191 | warn_only_exported = add_warns Opt_WarnMissingExportedSignatures
1192 | warn_missing_sigs = add_warns Opt_WarnMissingSignatures
1193 | warn_pat_syns = add_warns Opt_WarnMissingPatternSynonymSignatures
1194 | otherwise = return ()
1195
1196 add_warns flag
1197 = when warn_pat_syns
1198 (mapM_ add_pat_syn_warn pat_syns) >>
1199 when (warn_missing_sigs || warn_only_exported)
1200 (mapM_ add_bind_warn binds)
1201 where
1202 add_pat_syn_warn p
1203 = add_warn name $
1204 hang (text "Pattern synonym with no type signature:")
1205 2 (text "pattern" <+> pprPrefixName name <+> dcolon <+> pp_ty)
1206 where
1207 name = patSynName p
1208 pp_ty = pprPatSynType p
1209
1210 add_bind_warn :: Id -> IOEnv (Env TcGblEnv TcLclEnv) ()
1211 add_bind_warn id
1212 = do { env <- tcInitTidyEnv -- Why not use emptyTidyEnv?
1213 ; let name = idName id
1214 (_, ty) = tidyOpenType env (idType id)
1215 ty_msg = pprSigmaType ty
1216 ; add_warn name $
1217 hang (text "Top-level binding with no type signature:")
1218 2 (pprPrefixName name <+> dcolon <+> ty_msg) }
1219
1220 add_warn name msg
1221 = when (name `elemNameSet` sig_ns && export_check name)
1222 (addWarnAt (Reason flag) (getSrcSpan name) msg)
1223
1224 export_check name
1225 = not warn_only_exported || name `elemNameSet` exports
1226
1227 ; add_sig_warns }
1228
1229 {-
1230 Note [The ImportMap]
1231 ~~~~~~~~~~~~~~~~~~~~
1232 The ImportMap is a short-lived intermediate data structure records, for
1233 each import declaration, what stuff brought into scope by that
1234 declaration is actually used in the module.
1235
1236 The SrcLoc is the location of the END of a particular 'import'
1237 declaration. Why *END*? Because we don't want to get confused
1238 by the implicit Prelude import. Consider (Trac #7476) the module
1239 import Foo( foo )
1240 main = print foo
1241 There is an implicit 'import Prelude(print)', and it gets a SrcSpan
1242 of line 1:1 (just the point, not a span). If we use the *START* of
1243 the SrcSpan to identify the import decl, we'll confuse the implicit
1244 import Prelude with the explicit 'import Foo'. So we use the END.
1245 It's just a cheap hack; we could equally well use the Span too.
1246
1247 The AvailInfos are the things imported from that decl (just a list,
1248 not normalised).
1249 -}
1250
1251 type ImportMap = Map SrcLoc [AvailInfo] -- See [The ImportMap]
1252
1253 findImportUsage :: [LImportDecl GhcRn]
1254 -> [GlobalRdrElt]
1255 -> [ImportDeclUsage]
1256
1257 findImportUsage imports used_gres
1258 = map unused_decl imports
1259 where
1260 import_usage :: ImportMap
1261 import_usage
1262 = foldr extendImportMap Map.empty used_gres
1263
1264 unused_decl decl@(L loc (ImportDecl { ideclHiding = imps }))
1265 = (decl, nubAvails used_avails, nameSetElemsStable unused_imps)
1266 where
1267 used_avails = Map.lookup (srcSpanEnd loc) import_usage `orElse` []
1268 -- srcSpanEnd: see Note [The ImportMap]
1269 used_names = availsToNameSetWithSelectors used_avails
1270 used_parents = mkNameSet [n | AvailTC n _ _ <- used_avails]
1271
1272 unused_imps -- Not trivial; see eg Trac #7454
1273 = case imps of
1274 Just (False, L _ imp_ies) ->
1275 foldr (add_unused . unLoc) emptyNameSet imp_ies
1276 _other -> emptyNameSet -- No explicit import list => no unused-name list
1277
1278 add_unused :: IE GhcRn -> NameSet -> NameSet
1279 add_unused (IEVar (L _ n)) acc
1280 = add_unused_name (ieWrappedName n) acc
1281 add_unused (IEThingAbs (L _ n)) acc
1282 = add_unused_name (ieWrappedName n) acc
1283 add_unused (IEThingAll (L _ n)) acc
1284 = add_unused_all (ieWrappedName n) acc
1285 add_unused (IEThingWith (L _ p) wc ns fs) acc =
1286 add_wc_all (add_unused_with (ieWrappedName p) xs acc)
1287 where xs = map (ieWrappedName . unLoc) ns
1288 ++ map (flSelector . unLoc) fs
1289 add_wc_all = case wc of
1290 NoIEWildcard -> id
1291 IEWildcard _ -> add_unused_all (ieWrappedName p)
1292 add_unused _ acc = acc
1293
1294 add_unused_name n acc
1295 | n `elemNameSet` used_names = acc
1296 | otherwise = acc `extendNameSet` n
1297 add_unused_all n acc
1298 | n `elemNameSet` used_names = acc
1299 | n `elemNameSet` used_parents = acc
1300 | otherwise = acc `extendNameSet` n
1301 add_unused_with p ns acc
1302 | all (`elemNameSet` acc1) ns = add_unused_name p acc1
1303 | otherwise = acc1
1304 where
1305 acc1 = foldr add_unused_name acc ns
1306 -- If you use 'signum' from Num, then the user may well have
1307 -- imported Num(signum). We don't want to complain that
1308 -- Num is not itself mentioned. Hence the two cases in add_unused_with.
1309
1310 extendImportMap :: GlobalRdrElt -> ImportMap -> ImportMap
1311 -- For each of a list of used GREs, find all the import decls that brought
1312 -- it into scope; choose one of them (bestImport), and record
1313 -- the RdrName in that import decl's entry in the ImportMap
1314 extendImportMap gre imp_map
1315 = add_imp gre (bestImport (gre_imp gre)) imp_map
1316 where
1317 add_imp :: GlobalRdrElt -> ImportSpec -> ImportMap -> ImportMap
1318 add_imp gre (ImpSpec { is_decl = imp_decl_spec }) imp_map
1319 = Map.insertWith add decl_loc [avail] imp_map
1320 where
1321 add _ avails = avail : avails -- add is really just a specialised (++)
1322 decl_loc = srcSpanEnd (is_dloc imp_decl_spec)
1323 -- For srcSpanEnd see Note [The ImportMap]
1324 avail = availFromGRE gre
1325
1326 warnUnusedImport :: WarningFlag -> NameEnv (FieldLabelString, Name)
1327 -> ImportDeclUsage -> RnM ()
1328 warnUnusedImport flag fld_env (L loc decl, used, unused)
1329 | Just (False,L _ []) <- ideclHiding decl
1330 = return () -- Do not warn for 'import M()'
1331
1332 | Just (True, L _ hides) <- ideclHiding decl
1333 , not (null hides)
1334 , pRELUDE_NAME == unLoc (ideclName decl)
1335 = return () -- Note [Do not warn about Prelude hiding]
1336 | null used = addWarnAt (Reason flag) loc msg1 -- Nothing used; drop entire decl
1337 | null unused = return () -- Everything imported is used; nop
1338 | otherwise = addWarnAt (Reason flag) loc msg2 -- Some imports are unused
1339 where
1340 msg1 = vcat [pp_herald <+> quotes pp_mod <+> pp_not_used,
1341 nest 2 (text "except perhaps to import instances from"
1342 <+> quotes pp_mod),
1343 text "To import instances alone, use:"
1344 <+> text "import" <+> pp_mod <> parens Outputable.empty ]
1345 msg2 = sep [pp_herald <+> quotes sort_unused,
1346 text "from module" <+> quotes pp_mod <+> pp_not_used]
1347 pp_herald = text "The" <+> pp_qual <+> text "import of"
1348 pp_qual
1349 | ideclQualified decl = text "qualified"
1350 | otherwise = Outputable.empty
1351 pp_mod = ppr (unLoc (ideclName decl))
1352 pp_not_used = text "is redundant"
1353
1354 ppr_possible_field n = case lookupNameEnv fld_env n of
1355 Just (fld, p) -> ppr p <> parens (ppr fld)
1356 Nothing -> ppr n
1357
1358 -- Print unused names in a deterministic (lexicographic) order
1359 sort_unused = pprWithCommas ppr_possible_field $
1360 sortBy (comparing nameOccName) unused
1361
1362 {-
1363 Note [Do not warn about Prelude hiding]
1364 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1365 We do not warn about
1366 import Prelude hiding( x, y )
1367 because even if nothing else from Prelude is used, it may be essential to hide
1368 x,y to avoid name-shadowing warnings. Example (Trac #9061)
1369 import Prelude hiding( log )
1370 f x = log where log = ()
1371
1372
1373
1374 Note [Printing minimal imports]
1375 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1376 To print the minimal imports we walk over the user-supplied import
1377 decls, and simply trim their import lists. NB that
1378
1379 * We do *not* change the 'qualified' or 'as' parts!
1380
1381 * We do not disard a decl altogether; we might need instances
1382 from it. Instead we just trim to an empty import list
1383 -}
1384
1385 printMinimalImports :: [ImportDeclUsage] -> RnM ()
1386 -- See Note [Printing minimal imports]
1387 printMinimalImports imports_w_usage
1388 = do { imports' <- mapM mk_minimal imports_w_usage
1389 ; this_mod <- getModule
1390 ; dflags <- getDynFlags
1391 ; liftIO $
1392 do { h <- openFile (mkFilename dflags this_mod) WriteMode
1393 ; printForUser dflags h neverQualify (vcat (map ppr imports')) }
1394 -- The neverQualify is important. We are printing Names
1395 -- but they are in the context of an 'import' decl, and
1396 -- we never qualify things inside there
1397 -- E.g. import Blag( f, b )
1398 -- not import Blag( Blag.f, Blag.g )!
1399 }
1400 where
1401 mkFilename dflags this_mod
1402 | Just d <- dumpDir dflags = d </> basefn
1403 | otherwise = basefn
1404 where
1405 basefn = moduleNameString (moduleName this_mod) ++ ".imports"
1406
1407 mk_minimal (L l decl, used, unused)
1408 | null unused
1409 , Just (False, _) <- ideclHiding decl
1410 = return (L l decl)
1411 | otherwise
1412 = do { let ImportDecl { ideclName = L _ mod_name
1413 , ideclSource = is_boot
1414 , ideclPkgQual = mb_pkg } = decl
1415 ; iface <- loadSrcInterface doc mod_name is_boot (fmap sl_fs mb_pkg)
1416 ; let lies = map (L l) (concatMap (to_ie iface) used)
1417 ; return (L l (decl { ideclHiding = Just (False, L l lies) })) }
1418 where
1419 doc = text "Compute minimal imports for" <+> ppr decl
1420
1421 to_ie :: ModIface -> AvailInfo -> [IE GhcRn]
1422 -- The main trick here is that if we're importing all the constructors
1423 -- we want to say "T(..)", but if we're importing only a subset we want
1424 -- to say "T(A,B,C)". So we have to find out what the module exports.
1425 to_ie _ (Avail n)
1426 = [IEVar (to_ie_post_rn $ noLoc n)]
1427 to_ie _ (AvailTC n [m] [])
1428 | n==m = [IEThingAbs (to_ie_post_rn $ noLoc n)]
1429 to_ie iface (AvailTC n ns fs)
1430 = case [(xs,gs) | AvailTC x xs gs <- mi_exports iface
1431 , x == n
1432 , x `elem` xs -- Note [Partial export]
1433 ] of
1434 [xs] | all_used xs -> [IEThingAll (to_ie_post_rn $ noLoc n)]
1435 | otherwise ->
1436 [IEThingWith (to_ie_post_rn $ noLoc n) NoIEWildcard
1437 (map (to_ie_post_rn . noLoc) (filter (/= n) ns))
1438 (map noLoc fs)]
1439 -- Note [Overloaded field import]
1440 _other | all_non_overloaded fs
1441 -> map (IEVar . to_ie_post_rn_var . noLoc) $ ns
1442 ++ map flSelector fs
1443 | otherwise ->
1444 [IEThingWith (to_ie_post_rn $ noLoc n) NoIEWildcard
1445 (map (to_ie_post_rn . noLoc) (filter (/= n) ns))
1446 (map noLoc fs)]
1447 where
1448
1449 fld_lbls = map flLabel fs
1450
1451 all_used (avail_occs, avail_flds)
1452 = all (`elem` ns) avail_occs
1453 && all (`elem` fld_lbls) (map flLabel avail_flds)
1454
1455 all_non_overloaded = all (not . flIsOverloaded)
1456
1457 to_ie_post_rn_var :: (HasOccName name) => Located name -> LIEWrappedName name
1458 to_ie_post_rn_var (L l n)
1459 | isDataOcc $ occName n = L l (IEPattern (L l n))
1460 | otherwise = L l (IEName (L l n))
1461
1462
1463 to_ie_post_rn :: (HasOccName name) => Located name -> LIEWrappedName name
1464 to_ie_post_rn (L l n)
1465 | isTcOcc occ && isSymOcc occ = L l (IEType (L l n))
1466 | otherwise = L l (IEName (L l n))
1467 where occ = occName n
1468
1469 {-
1470 Note [Partial export]
1471 ~~~~~~~~~~~~~~~~~~~~~
1472 Suppose we have
1473
1474 module A( op ) where
1475 class C a where
1476 op :: a -> a
1477
1478 module B where
1479 import A
1480 f = ..op...
1481
1482 Then the minimal import for module B is
1483 import A( op )
1484 not
1485 import A( C( op ) )
1486 which we would usually generate if C was exported from B. Hence
1487 the (x `elem` xs) test when deciding what to generate.
1488
1489
1490 Note [Overloaded field import]
1491 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1492 On the other hand, if we have
1493
1494 {-# LANGUAGE DuplicateRecordFields #-}
1495 module A where
1496 data T = MkT { foo :: Int }
1497
1498 module B where
1499 import A
1500 f = ...foo...
1501
1502 then the minimal import for module B must be
1503 import A ( T(foo) )
1504 because when DuplicateRecordFields is enabled, field selectors are
1505 not in scope without their enclosing datatype.
1506
1507
1508 ************************************************************************
1509 * *
1510 \subsection{Errors}
1511 * *
1512 ************************************************************************
1513 -}
1514
1515 qualImportItemErr :: RdrName -> SDoc
1516 qualImportItemErr rdr
1517 = hang (text "Illegal qualified name in import item:")
1518 2 (ppr rdr)
1519
1520 badImportItemErrStd :: ModIface -> ImpDeclSpec -> IE GhcPs -> SDoc
1521 badImportItemErrStd iface decl_spec ie
1522 = sep [text "Module", quotes (ppr (is_mod decl_spec)), source_import,
1523 text "does not export", quotes (ppr ie)]
1524 where
1525 source_import | mi_boot iface = text "(hi-boot interface)"
1526 | otherwise = Outputable.empty
1527
1528 badImportItemErrDataCon :: OccName -> ModIface -> ImpDeclSpec -> IE GhcPs
1529 -> SDoc
1530 badImportItemErrDataCon dataType_occ iface decl_spec ie
1531 = vcat [ text "In module"
1532 <+> quotes (ppr (is_mod decl_spec))
1533 <+> source_import <> colon
1534 , nest 2 $ quotes datacon
1535 <+> text "is a data constructor of"
1536 <+> quotes dataType
1537 , text "To import it use"
1538 , nest 2 $ text "import"
1539 <+> ppr (is_mod decl_spec)
1540 <> parens_sp (dataType <> parens_sp datacon)
1541 , text "or"
1542 , nest 2 $ text "import"
1543 <+> ppr (is_mod decl_spec)
1544 <> parens_sp (dataType <> text "(..)")
1545 ]
1546 where
1547 datacon_occ = rdrNameOcc $ ieName ie
1548 datacon = parenSymOcc datacon_occ (ppr datacon_occ)
1549 dataType = parenSymOcc dataType_occ (ppr dataType_occ)
1550 source_import | mi_boot iface = text "(hi-boot interface)"
1551 | otherwise = Outputable.empty
1552 parens_sp d = parens (space <> d <> space) -- T( f,g )
1553
1554 badImportItemErr :: ModIface -> ImpDeclSpec -> IE GhcPs -> [AvailInfo] -> SDoc
1555 badImportItemErr iface decl_spec ie avails
1556 = case find checkIfDataCon avails of
1557 Just con -> badImportItemErrDataCon (availOccName con) iface decl_spec ie
1558 Nothing -> badImportItemErrStd iface decl_spec ie
1559 where
1560 checkIfDataCon (AvailTC _ ns _) =
1561 case find (\n -> importedFS == nameOccNameFS n) ns of
1562 Just n -> isDataConName n
1563 Nothing -> False
1564 checkIfDataCon _ = False
1565 availOccName = nameOccName . availName
1566 nameOccNameFS = occNameFS . nameOccName
1567 importedFS = occNameFS . rdrNameOcc $ ieName ie
1568
1569 illegalImportItemErr :: SDoc
1570 illegalImportItemErr = text "Illegal import item"
1571
1572 dodgyImportWarn :: RdrName -> SDoc
1573 dodgyImportWarn item
1574 = dodgyMsg (text "import") item (dodgyMsgInsert item :: IE GhcPs)
1575
1576 dodgyMsg :: (Outputable a, Outputable b) => SDoc -> a -> b -> SDoc
1577 dodgyMsg kind tc ie
1578 = sep [ text "The" <+> kind <+> ptext (sLit "item")
1579 -- <+> quotes (ppr (IEThingAll (noLoc (IEName $ noLoc tc))))
1580 <+> quotes (ppr ie)
1581 <+> text "suggests that",
1582 quotes (ppr tc) <+> text "has (in-scope) constructors or class methods,",
1583 text "but it has none" ]
1584
1585 dodgyMsgInsert :: forall p . IdP p -> IE p
1586 dodgyMsgInsert tc = IEThingAll ii
1587 where
1588 ii :: LIEWrappedName (IdP p)
1589 ii = noLoc (IEName $ noLoc tc)
1590
1591
1592 addDupDeclErr :: [GlobalRdrElt] -> TcRn ()
1593 addDupDeclErr [] = panic "addDupDeclErr: empty list"
1594 addDupDeclErr gres@(gre : _)
1595 = addErrAt (getSrcSpan (last sorted_names)) $
1596 -- Report the error at the later location
1597 vcat [text "Multiple declarations of" <+>
1598 quotes (ppr (nameOccName name)),
1599 -- NB. print the OccName, not the Name, because the
1600 -- latter might not be in scope in the RdrEnv and so will
1601 -- be printed qualified.
1602 text "Declared at:" <+>
1603 vcat (map (ppr . nameSrcLoc) sorted_names)]
1604 where
1605 name = gre_name gre
1606 sorted_names = sortWith nameSrcLoc (map gre_name gres)
1607
1608
1609
1610 missingImportListWarn :: ModuleName -> SDoc
1611 missingImportListWarn mod
1612 = text "The module" <+> quotes (ppr mod) <+> ptext (sLit "does not have an explicit import list")
1613
1614 missingImportListItem :: IE GhcPs -> SDoc
1615 missingImportListItem ie
1616 = text "The import item" <+> quotes (ppr ie) <+> ptext (sLit "does not have an explicit import list")
1617
1618 moduleWarn :: ModuleName -> WarningTxt -> SDoc
1619 moduleWarn mod (WarningTxt _ txt)
1620 = sep [ text "Module" <+> quotes (ppr mod) <> ptext (sLit ":"),
1621 nest 2 (vcat (map (ppr . sl_fs . unLoc) txt)) ]
1622 moduleWarn mod (DeprecatedTxt _ txt)
1623 = sep [ text "Module" <+> quotes (ppr mod)
1624 <+> text "is deprecated:",
1625 nest 2 (vcat (map (ppr . sl_fs . unLoc) txt)) ]
1626
1627 packageImportErr :: SDoc
1628 packageImportErr
1629 = text "Package-qualified imports are not enabled; use PackageImports"
1630
1631 -- This data decl will parse OK
1632 -- data T = a Int
1633 -- treating "a" as the constructor.
1634 -- It is really hard to make the parser spot this malformation.
1635 -- So the renamer has to check that the constructor is legal
1636 --
1637 -- We can get an operator as the constructor, even in the prefix form:
1638 -- data T = :% Int Int
1639 -- from interface files, which always print in prefix form
1640
1641 checkConName :: RdrName -> TcRn ()
1642 checkConName name = checkErr (isRdrDataCon name) (badDataCon name)
1643
1644 badDataCon :: RdrName -> SDoc
1645 badDataCon name
1646 = hsep [text "Illegal data constructor name", quotes (ppr name)]