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