Refactor treatment of wildcards
[ghc.git] / compiler / rename / RnEnv.hs
1 {-
2 (c) The GRASP/AQUA Project, Glasgow University, 1992-2006
3
4 \section[RnEnv]{Environment manipulation for the renamer monad}
5 -}
6
7 {-# LANGUAGE CPP #-}
8
9 module RnEnv (
10 newTopSrcBinder,
11 lookupLocatedTopBndrRn, lookupTopBndrRn,
12 lookupLocatedOccRn, lookupOccRn, lookupOccRn_maybe,
13 lookupLocalOccRn_maybe, lookupInfoOccRn,
14 lookupLocalOccThLvl_maybe,
15 lookupTypeOccRn, lookupKindOccRn,
16 lookupGlobalOccRn, lookupGlobalOccRn_maybe,
17 lookupOccRn_overloaded, lookupGlobalOccRn_overloaded,
18 reportUnboundName, unknownNameSuggestions,
19 addNameClashErrRn,
20
21 HsSigCtxt(..), lookupLocalTcNames, lookupSigOccRn,
22 lookupSigCtxtOccRn,
23
24 lookupFixityRn, lookupTyFixityRn,
25 lookupInstDeclBndr, lookupRecFieldOcc, lookupFamInstName,
26 lookupConstructorFields,
27 lookupSyntaxName, lookupSyntaxNames, lookupIfThenElse,
28 lookupGreAvailRn,
29 getLookupOccRn,mkUnboundName, mkUnboundNameRdr, isUnboundName,
30 addUsedGRE, addUsedGREs, addUsedDataCons,
31
32 newLocalBndrRn, newLocalBndrsRn,
33 bindLocalNames, bindLocalNamesFV,
34 MiniFixityEnv,
35 addLocalFixities,
36 bindLocatedLocalsFV, bindLocatedLocalsRn,
37 extendTyVarEnvFVRn,
38
39 checkDupRdrNames, checkShadowedRdrNames,
40 checkDupNames, checkDupAndShadowedNames, checkTupSize,
41 addFvRn, mapFvRn, mapMaybeFvRn, mapFvRnCPS,
42 warnUnusedMatches,
43 warnUnusedTopBinds, warnUnusedLocalBinds,
44 mkFieldEnv,
45 dataTcOccs, kindSigErr, perhapsForallMsg, unknownSubordinateErr,
46 HsDocContext(..), pprHsDocContext,
47 inHsDocContext, withHsDocContext
48 ) where
49
50 #include "HsVersions.h"
51
52 import LoadIface ( loadInterfaceForName, loadSrcInterface_maybe )
53 import IfaceEnv
54 import HsSyn
55 import RdrName
56 import HscTypes
57 import TcEnv
58 import TcRnMonad
59 import RdrHsSyn ( setRdrNameSpace )
60 import Name
61 import NameSet
62 import NameEnv
63 import Avail
64 import Module
65 import ConLike
66 import DataCon
67 import TyCon
68 import PrelNames ( mkUnboundName, isUnboundName, rOOT_MAIN, forall_tv_RDR )
69 import ErrUtils ( MsgDoc )
70 import BasicTypes ( Fixity(..), FixityDirection(..), minPrecedence, defaultFixity )
71 import SrcLoc
72 import Outputable
73 import Util
74 import Maybes
75 import BasicTypes ( TopLevelFlag(..) )
76 import ListSetOps ( removeDups )
77 import DynFlags
78 import FastString
79 import Control.Monad
80 import Data.List
81 import Data.Function ( on )
82 import ListSetOps ( minusList )
83 import Constants ( mAX_TUPLE_SIZE )
84
85 {-
86 *********************************************************
87 * *
88 Source-code binders
89 * *
90 *********************************************************
91
92 Note [Signature lazy interface loading]
93 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
94
95 GHC's lazy interface loading can be a bit confusing, so this Note is an
96 empirical description of what happens in one interesting case. When
97 compiling a signature module against an its implementation, we do NOT
98 load interface files associated with its names until after the type
99 checking phase. For example:
100
101 module ASig where
102 data T
103 f :: T -> T
104
105 Suppose we compile this with -sig-of "A is ASig":
106
107 module B where
108 data T = T
109 f T = T
110
111 module A(module B) where
112 import B
113
114 During type checking, we'll load A.hi because we need to know what the
115 RdrEnv for the module is, but we DO NOT load the interface for B.hi!
116 It's wholly unnecessary: our local definition 'data T' in ASig is all
117 the information we need to finish type checking. This is contrast to
118 type checking of ordinary Haskell files, in which we would not have the
119 local definition "data T" and would need to consult B.hi immediately.
120 (Also, this situation never occurs for hs-boot files, since you're not
121 allowed to reexport from another module.)
122
123 After type checking, we then check that the types we provided are
124 consistent with the backing implementation (in checkHiBootOrHsigIface).
125 At this point, B.hi is loaded, because we need something to compare
126 against.
127
128 I discovered this behavior when trying to figure out why type class
129 instances for Data.Map weren't in the EPS when I was type checking a
130 test very much like ASig (sigof02dm): the associated interface hadn't
131 been loaded yet! (The larger issue is a moot point, since an instance
132 declared in a signature can never be a duplicate.)
133
134 This behavior might change in the future. Consider this
135 alternate module B:
136
137 module B where
138 {-# DEPRECATED T, f "Don't use" #-}
139 data T = T
140 f T = T
141
142 One might conceivably want to report deprecation warnings when compiling
143 ASig with -sig-of B, in which case we need to look at B.hi to find the
144 deprecation warnings during renaming. At the moment, you don't get any
145 warning until you use the identifier further downstream. This would
146 require adjusting addUsedGRE so that during signature compilation,
147 we do not report deprecation warnings for LocalDef. See also
148 Note [Handling of deprecations]
149 -}
150
151 newTopSrcBinder :: Located RdrName -> RnM Name
152 newTopSrcBinder (L loc rdr_name)
153 | Just name <- isExact_maybe rdr_name
154 = -- This is here to catch
155 -- (a) Exact-name binders created by Template Haskell
156 -- (b) The PrelBase defn of (say) [] and similar, for which
157 -- the parser reads the special syntax and returns an Exact RdrName
158 -- We are at a binding site for the name, so check first that it
159 -- the current module is the correct one; otherwise GHC can get
160 -- very confused indeed. This test rejects code like
161 -- data T = (,) Int Int
162 -- unless we are in GHC.Tup
163 if isExternalName name then
164 do { this_mod <- getModule
165 ; unless (this_mod == nameModule name)
166 (addErrAt loc (badOrigBinding rdr_name))
167 ; return name }
168 else -- See Note [Binders in Template Haskell] in Convert.hs
169 do { this_mod <- getModule
170 ; externaliseName this_mod name }
171
172 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
173 = do { this_mod <- getModule
174 ; unless (rdr_mod == this_mod || rdr_mod == rOOT_MAIN)
175 (addErrAt loc (badOrigBinding rdr_name))
176 -- When reading External Core we get Orig names as binders,
177 -- but they should agree with the module gotten from the monad
178 --
179 -- We can get built-in syntax showing up here too, sadly. If you type
180 -- data T = (,,,)
181 -- the constructor is parsed as a type, and then RdrHsSyn.tyConToDataCon
182 -- uses setRdrNameSpace to make it into a data constructors. At that point
183 -- the nice Exact name for the TyCon gets swizzled to an Orig name.
184 -- Hence the badOrigBinding error message.
185 --
186 -- Except for the ":Main.main = ..." definition inserted into
187 -- the Main module; ugh!
188
189 -- Because of this latter case, we call newGlobalBinder with a module from
190 -- the RdrName, not from the environment. In principle, it'd be fine to
191 -- have an arbitrary mixture of external core definitions in a single module,
192 -- (apart from module-initialisation issues, perhaps).
193 ; newGlobalBinder rdr_mod rdr_occ loc }
194
195 | otherwise
196 = do { unless (not (isQual rdr_name))
197 (addErrAt loc (badQualBndrErr rdr_name))
198 -- Binders should not be qualified; if they are, and with a different
199 -- module name, we we get a confusing "M.T is not in scope" error later
200
201 ; stage <- getStage
202 ; env <- getGblEnv
203 ; if isBrackStage stage then
204 -- We are inside a TH bracket, so make an *Internal* name
205 -- See Note [Top-level Names in Template Haskell decl quotes] in RnNames
206 do { uniq <- newUnique
207 ; return (mkInternalName uniq (rdrNameOcc rdr_name) loc) }
208 else case tcg_impl_rdr_env env of
209 Just gr ->
210 -- We're compiling --sig-of, so resolve with respect to this
211 -- module.
212 -- See Note [Signature parameters in TcGblEnv and DynFlags]
213 do { case lookupGlobalRdrEnv gr (rdrNameOcc rdr_name) of
214 -- Be sure to override the loc so that we get accurate
215 -- information later
216 [GRE{ gre_name = n }] -> do
217 -- NB: Just adding this line will not work:
218 -- addUsedGRE True gre
219 -- see Note [Signature lazy interface loading] for
220 -- more details.
221 return (setNameLoc n loc)
222 _ -> do
223 { -- NB: cannot use reportUnboundName rdr_name
224 -- because it looks up in the wrong RdrEnv
225 -- ToDo: more helpful error messages
226 ; addErr (unknownNameErr (pprNonVarNameSpace
227 (occNameSpace (rdrNameOcc rdr_name))) rdr_name)
228 ; return (mkUnboundNameRdr rdr_name)
229 }
230 }
231 Nothing ->
232 -- Normal case
233 do { this_mod <- getModule
234 ; traceRn (text "newTopSrcBinder" <+> (ppr this_mod $$ ppr rdr_name $$ ppr loc))
235 ; newGlobalBinder this_mod (rdrNameOcc rdr_name) loc } }
236
237 {-
238 *********************************************************
239 * *
240 Source code occurrences
241 * *
242 *********************************************************
243
244 Looking up a name in the RnEnv.
245
246 Note [Type and class operator definitions]
247 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
248 We want to reject all of these unless we have -XTypeOperators (Trac #3265)
249 data a :*: b = ...
250 class a :*: b where ...
251 data (:*:) a b = ....
252 class (:*:) a b where ...
253 The latter two mean that we are not just looking for a
254 *syntactically-infix* declaration, but one that uses an operator
255 OccName. We use OccName.isSymOcc to detect that case, which isn't
256 terribly efficient, but there seems to be no better way.
257 -}
258
259 lookupTopBndrRn :: RdrName -> RnM Name
260 lookupTopBndrRn n = do nopt <- lookupTopBndrRn_maybe n
261 case nopt of
262 Just n' -> return n'
263 Nothing -> do traceRn $ (text "lookupTopBndrRn fail" <+> ppr n)
264 unboundName WL_LocalTop n
265
266 lookupLocatedTopBndrRn :: Located RdrName -> RnM (Located Name)
267 lookupLocatedTopBndrRn = wrapLocM lookupTopBndrRn
268
269 lookupTopBndrRn_maybe :: RdrName -> RnM (Maybe Name)
270 -- Look up a top-level source-code binder. We may be looking up an unqualified 'f',
271 -- and there may be several imported 'f's too, which must not confuse us.
272 -- For example, this is OK:
273 -- import Foo( f )
274 -- infix 9 f -- The 'f' here does not need to be qualified
275 -- f x = x -- Nor here, of course
276 -- So we have to filter out the non-local ones.
277 --
278 -- A separate function (importsFromLocalDecls) reports duplicate top level
279 -- decls, so here it's safe just to choose an arbitrary one.
280 --
281 -- There should never be a qualified name in a binding position in Haskell,
282 -- but there can be if we have read in an external-Core file.
283 -- The Haskell parser checks for the illegal qualified name in Haskell
284 -- source files, so we don't need to do so here.
285
286 lookupTopBndrRn_maybe rdr_name
287 | Just name <- isExact_maybe rdr_name
288 = do { name' <- lookupExactOcc name; return (Just name') }
289
290 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
291 -- This deals with the case of derived bindings, where
292 -- we don't bother to call newTopSrcBinder first
293 -- We assume there is no "parent" name
294 = do { loc <- getSrcSpanM
295 ; n <- newGlobalBinder rdr_mod rdr_occ loc
296 ; return (Just n)}
297
298 | otherwise
299 = do { -- Check for operators in type or class declarations
300 -- See Note [Type and class operator definitions]
301 let occ = rdrNameOcc rdr_name
302 ; when (isTcOcc occ && isSymOcc occ)
303 (do { op_ok <- xoptM Opt_TypeOperators
304 ; unless op_ok (addErr (opDeclErr rdr_name)) })
305
306 ; env <- getGlobalRdrEnv
307 ; case filter isLocalGRE (lookupGRE_RdrName rdr_name env) of
308 [gre] -> return (Just (gre_name gre))
309 _ -> return Nothing -- Ambiguous (can't happen) or unbound
310 }
311
312 -----------------------------------------------
313 -- | Lookup an @Exact@ @RdrName@. See Note [Looking up Exact RdrNames].
314 -- This adds an error if the name cannot be found.
315 lookupExactOcc :: Name -> RnM Name
316 lookupExactOcc name
317 = do { result <- lookupExactOcc_either name
318 ; case result of
319 Left err -> do { addErr err
320 ; return name }
321 Right name' -> return name' }
322
323 -- | Lookup an @Exact@ @RdrName@. See Note [Looking up Exact RdrNames].
324 -- This never adds an error, but it may return one.
325 lookupExactOcc_either :: Name -> RnM (Either MsgDoc Name)
326 -- See Note [Looking up Exact RdrNames]
327 lookupExactOcc_either name
328 | Just thing <- wiredInNameTyThing_maybe name
329 , Just tycon <- case thing of
330 ATyCon tc -> Just tc
331 AConLike (RealDataCon dc) -> Just (dataConTyCon dc)
332 _ -> Nothing
333 , isTupleTyCon tycon
334 = do { checkTupSize (tyConArity tycon)
335 ; return (Right name) }
336
337 | isExternalName name
338 = return (Right name)
339
340 | otherwise
341 = do { env <- getGlobalRdrEnv
342 ; let -- See Note [Splicing Exact names]
343 main_occ = nameOccName name
344 demoted_occs = case demoteOccName main_occ of
345 Just occ -> [occ]
346 Nothing -> []
347 gres = [ gre | occ <- main_occ : demoted_occs
348 , gre <- lookupGlobalRdrEnv env occ
349 , gre_name gre == name ]
350 ; case gres of
351 [gre] -> return (Right (gre_name gre))
352
353 [] -> -- See Note [Splicing Exact names]
354 do { lcl_env <- getLocalRdrEnv
355 ; if name `inLocalRdrEnvScope` lcl_env
356 then return (Right name)
357 else
358 #ifdef GHCI
359 do { th_topnames_var <- fmap tcg_th_topnames getGblEnv
360 ; th_topnames <- readTcRef th_topnames_var
361 ; if name `elemNameSet` th_topnames
362 then return (Right name)
363 else return (Left exact_nm_err)
364 }
365 #else /* !GHCI */
366 return (Left exact_nm_err)
367 #endif /* !GHCI */
368 }
369 gres -> return (Left (sameNameErr gres)) -- Ugh! See Note [Template Haskell ambiguity]
370 }
371 where
372 exact_nm_err = hang (ptext (sLit "The exact Name") <+> quotes (ppr name) <+> ptext (sLit "is not in scope"))
373 2 (vcat [ ptext (sLit "Probable cause: you used a unique Template Haskell name (NameU), ")
374 , ptext (sLit "perhaps via newName, but did not bind it")
375 , ptext (sLit "If that's it, then -ddump-splices might be useful") ])
376
377 sameNameErr :: [GlobalRdrElt] -> MsgDoc
378 sameNameErr [] = panic "addSameNameErr: empty list"
379 sameNameErr gres@(_ : _)
380 = hang (ptext (sLit "Same exact name in multiple name-spaces:"))
381 2 (vcat (map pp_one sorted_names) $$ th_hint)
382 where
383 sorted_names = sortWith nameSrcLoc (map gre_name gres)
384 pp_one name
385 = hang (pprNameSpace (occNameSpace (getOccName name))
386 <+> quotes (ppr name) <> comma)
387 2 (ptext (sLit "declared at:") <+> ppr (nameSrcLoc name))
388
389 th_hint = vcat [ ptext (sLit "Probable cause: you bound a unique Template Haskell name (NameU),")
390 , ptext (sLit "perhaps via newName, in different name-spaces.")
391 , ptext (sLit "If that's it, then -ddump-splices might be useful") ]
392
393
394 -----------------------------------------------
395 lookupInstDeclBndr :: Name -> SDoc -> RdrName -> RnM Name
396 -- This is called on the method name on the left-hand side of an
397 -- instance declaration binding. eg. instance Functor T where
398 -- fmap = ...
399 -- ^^^^ called on this
400 -- Regardless of how many unqualified fmaps are in scope, we want
401 -- the one that comes from the Functor class.
402 --
403 -- Furthermore, note that we take no account of whether the
404 -- name is only in scope qualified. I.e. even if method op is
405 -- in scope as M.op, we still allow plain 'op' on the LHS of
406 -- an instance decl
407 --
408 -- The "what" parameter says "method" or "associated type",
409 -- depending on what we are looking up
410 lookupInstDeclBndr cls what rdr
411 = do { when (isQual rdr)
412 (addErr (badQualBndrErr rdr))
413 -- In an instance decl you aren't allowed
414 -- to use a qualified name for the method
415 -- (Although it'd make perfect sense.)
416 ; mb_name <- lookupSubBndrOcc
417 False -- False => we don't give deprecated
418 -- warnings when a deprecated class
419 -- method is defined. We only warn
420 -- when it's used
421 cls doc rdr
422 ; case mb_name of
423 Left err -> do { addErr err; return (mkUnboundNameRdr rdr) }
424 Right nm -> return nm }
425 where
426 doc = what <+> ptext (sLit "of class") <+> quotes (ppr cls)
427
428
429 -----------------------------------------------
430 lookupFamInstName :: Maybe Name -> Located RdrName -> RnM (Located Name)
431 -- Used for TyData and TySynonym family instances only,
432 -- See Note [Family instance binders]
433 lookupFamInstName (Just cls) tc_rdr -- Associated type; c.f RnBinds.rnMethodBind
434 = wrapLocM (lookupInstDeclBndr cls (ptext (sLit "associated type"))) tc_rdr
435 lookupFamInstName Nothing tc_rdr -- Family instance; tc_rdr is an *occurrence*
436 = lookupLocatedOccRn tc_rdr
437
438 -----------------------------------------------
439 lookupConstructorFields :: Name -> RnM [FieldLabel]
440 -- Look up the fields of a given constructor
441 -- * For constructors from this module, use the record field env,
442 -- which is itself gathered from the (as yet un-typechecked)
443 -- data type decls
444 --
445 -- * For constructors from imported modules, use the *type* environment
446 -- since imported modles are already compiled, the info is conveniently
447 -- right there
448
449 lookupConstructorFields con_name
450 = do { this_mod <- getModule
451 ; if nameIsLocalOrFrom this_mod con_name then
452 do { field_env <- getRecFieldEnv
453 ; traceTc "lookupCF" (ppr con_name $$ ppr (lookupNameEnv field_env con_name) $$ ppr field_env)
454 ; return (lookupNameEnv field_env con_name `orElse` []) }
455 else
456 do { con <- tcLookupDataCon con_name
457 ; traceTc "lookupCF 2" (ppr con)
458 ; return (dataConFieldLabels con) } }
459
460 -----------------------------------------------
461 -- Used for record construction and pattern matching
462 -- When the -XDisambiguateRecordFields flag is on, take account of the
463 -- constructor name to disambiguate which field to use; it's just the
464 -- same as for instance decls
465 --
466 -- NB: Consider this:
467 -- module Foo where { data R = R { fld :: Int } }
468 -- module Odd where { import Foo; fld x = x { fld = 3 } }
469 -- Arguably this should work, because the reference to 'fld' is
470 -- unambiguous because there is only one field id 'fld' in scope.
471 -- But currently it's rejected.
472
473 lookupRecFieldOcc :: Maybe Name -- Nothing => just look it up as usual
474 -- Just tycon => use tycon to disambiguate
475 -> SDoc -> RdrName
476 -> RnM Name
477 lookupRecFieldOcc parent doc rdr_name
478 | Just tc_name <- parent
479 = do { mb_name <- lookupSubBndrOcc True tc_name doc rdr_name
480 ; case mb_name of
481 Left err -> do { addErr err; return (mkUnboundNameRdr rdr_name) }
482 Right n -> return n }
483
484 | otherwise
485 = lookupGlobalOccRn rdr_name
486
487 lookupSubBndrOcc :: Bool
488 -> Name -- Parent
489 -> SDoc
490 -> RdrName
491 -> RnM (Either MsgDoc Name)
492 -- Find all the things the rdr-name maps to
493 -- and pick the one with the right parent namep
494 lookupSubBndrOcc warn_if_deprec the_parent doc rdr_name
495 | Just n <- isExact_maybe rdr_name -- This happens in derived code
496 = do { n <- lookupExactOcc n
497 ; return (Right n) }
498
499 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
500 = do { n <- lookupOrig rdr_mod rdr_occ
501 ; return (Right n) }
502
503 | isUnboundName the_parent
504 -- Avoid an error cascade from malformed decls:
505 -- instance Int where { foo = e }
506 -- We have already generated an error in rnLHsInstDecl
507 = return (Right (mkUnboundNameRdr rdr_name))
508
509 | otherwise
510 = do { env <- getGlobalRdrEnv
511 ; let gres = lookupGlobalRdrEnv env (rdrNameOcc rdr_name)
512 -- NB: lookupGlobalRdrEnv, not lookupGRE_RdrName!
513 -- The latter does pickGREs, but we want to allow 'x'
514 -- even if only 'M.x' is in scope
515 ; traceRn (text "lookupSubBndrOcc" <+> vcat [ppr the_parent, ppr rdr_name, ppr gres, ppr (pick_gres rdr_name gres)])
516 ; case pick_gres rdr_name gres of
517 (gre:_) -> do { addUsedGRE warn_if_deprec gre
518 -- Add a usage; this is an *occurrence* site
519 -- Note [Usage for sub-bndrs]
520 ; return (Right (gre_name gre)) }
521 -- If there is more than one local GRE for the
522 -- same OccName 'f', that will be reported separately
523 -- as a duplicate top-level binding for 'f'
524 [] -> do { ns <- lookupQualifiedNameGHCi rdr_name
525 ; case ns of
526 (n:_) -> return (Right n) -- Unlikely to be more than one...?
527 [] -> return (Left (unknownSubordinateErr doc rdr_name))
528 } }
529 where
530 -- If Parent = NoParent, just do a normal lookup
531 -- If Parent = Parent p then find all GREs that
532 -- (a) have parent p
533 -- (b) for Unqual, are in scope qualified or unqualified
534 -- for Qual, are in scope with that qualification
535 pick_gres rdr_name gres
536 | isUnqual rdr_name = filter right_parent gres
537 | otherwise = filter right_parent (pickGREs rdr_name gres)
538
539 right_parent (GRE { gre_par = p })
540 | ParentIs parent <- p = parent == the_parent
541 | FldParent { par_is = parent } <- p = parent == the_parent
542 | otherwise = False
543
544 {-
545 Note [Family instance binders]
546 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
547 Consider
548 data family F a
549 data instance F T = X1 | X2
550
551 The 'data instance' decl has an *occurrence* of F (and T), and *binds*
552 X1 and X2. (This is unlike a normal data type declaration which would
553 bind F too.) So we want an AvailTC F [X1,X2].
554
555 Now consider a similar pair:
556 class C a where
557 data G a
558 instance C S where
559 data G S = Y1 | Y2
560
561 The 'data G S' *binds* Y1 and Y2, and has an *occurrence* of G.
562
563 But there is a small complication: in an instance decl, we don't use
564 qualified names on the LHS; instead we use the class to disambiguate.
565 Thus:
566 module M where
567 import Blib( G )
568 class C a where
569 data G a
570 instance C S where
571 data G S = Y1 | Y2
572 Even though there are two G's in scope (M.G and Blib.G), the occurrence
573 of 'G' in the 'instance C S' decl is unambiguous, because C has only
574 one associated type called G. This is exactly what happens for methods,
575 and it is only consistent to do the same thing for types. That's the
576 role of the function lookupTcdName; the (Maybe Name) give the class of
577 the encloseing instance decl, if any.
578
579 Note [Looking up Exact RdrNames]
580 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
581 Exact RdrNames are generated by Template Haskell. See Note [Binders
582 in Template Haskell] in Convert.
583
584 For data types and classes have Exact system Names in the binding
585 positions for constructors, TyCons etc. For example
586 [d| data T = MkT Int |]
587 when we splice in and Convert to HsSyn RdrName, we'll get
588 data (Exact (system Name "T")) = (Exact (system Name "MkT")) ...
589 These System names are generated by Convert.thRdrName
590
591 But, constructors and the like need External Names, not System Names!
592 So we do the following
593
594 * In RnEnv.newTopSrcBinder we spot Exact RdrNames that wrap a
595 non-External Name, and make an External name for it. This is
596 the name that goes in the GlobalRdrEnv
597
598 * When looking up an occurrence of an Exact name, done in
599 RnEnv.lookupExactOcc, we find the Name with the right unique in the
600 GlobalRdrEnv, and use the one from the envt -- it will be an
601 External Name in the case of the data type/constructor above.
602
603 * Exact names are also use for purely local binders generated
604 by TH, such as \x_33. x_33
605 Both binder and occurrence are Exact RdrNames. The occurrence
606 gets looked up in the LocalRdrEnv by RnEnv.lookupOccRn, and
607 misses, because lookupLocalRdrEnv always returns Nothing for
608 an Exact Name. Now we fall through to lookupExactOcc, which
609 will find the Name is not in the GlobalRdrEnv, so we just use
610 the Exact supplied Name.
611
612 Note [Splicing Exact names]
613 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
614 Consider the splice $(do { x <- newName "x"; return (VarE x) })
615 This will generate a (HsExpr RdrName) term that mentions the
616 Exact RdrName "x_56" (or whatever), but does not bind it. So
617 when looking such Exact names we want to check that it's in scope,
618 otherwise the type checker will get confused. To do this we need to
619 keep track of all the Names in scope, and the LocalRdrEnv does just that;
620 we consult it with RdrName.inLocalRdrEnvScope.
621
622 There is another wrinkle. With TH and -XDataKinds, consider
623 $( [d| data Nat = Zero
624 data T = MkT (Proxy 'Zero) |] )
625 After splicing, but before renaming we get this:
626 data Nat_77{tc} = Zero_78{d}
627 data T_79{tc} = MkT_80{d} (Proxy 'Zero_78{tc}) |] )
628 The occurrence of 'Zero in the data type for T has the right unique,
629 but it has a TcClsName name-space in its OccName. (This is set by
630 the ctxt_ns argument of Convert.thRdrName.) When we check that is
631 in scope in the GlobalRdrEnv, we need to look up the DataName namespace
632 too. (An alternative would be to make the GlobalRdrEnv also have
633 a Name -> GRE mapping.)
634
635 Note [Template Haskell ambiguity]
636 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
637 The GlobalRdrEnv invariant says that if
638 occ -> [gre1, ..., gren]
639 then the gres have distinct Names (INVARIANT 1 of GlobalRdrEnv).
640 This is guaranteed by extendGlobalRdrEnvRn (the dups check in add_gre).
641
642 So how can we get multiple gres in lookupExactOcc_maybe? Because in
643 TH we might use the same TH NameU in two different name spaces.
644 eg (Trac #7241):
645 $(newName "Foo" >>= \o -> return [DataD [] o [] [RecC o []] [''Show]])
646 Here we generate a type constructor and data constructor with the same
647 unique, but differnt name spaces.
648
649 It'd be nicer to rule this out in extendGlobalRdrEnvRn, but that would
650 mean looking up the OccName in every name-space, just in case, and that
651 seems a bit brutal. So it's just done here on lookup. But we might
652 need to revisit that choice.
653
654 Note [Usage for sub-bndrs]
655 ~~~~~~~~~~~~~~~~~~~~~~~~~~
656 If you have this
657 import qualified M( C( f ) )
658 instance M.C T where
659 f x = x
660 then is the qualified import M.f used? Obviously yes.
661 But the RdrName used in the instance decl is unqualified. In effect,
662 we fill in the qualification by looking for f's whose class is M.C
663 But when adding to the UsedRdrNames we must make that qualification
664 explicit (saying "used M.f"), otherwise we get "Redundant import of M.f".
665
666 So we make up a suitable (fake) RdrName. But be careful
667 import qualifed M
668 import M( C(f) )
669 instance C T where
670 f x = x
671 Here we want to record a use of 'f', not of 'M.f', otherwise
672 we'll miss the fact that the qualified import is redundant.
673
674 --------------------------------------------------
675 -- Occurrences
676 --------------------------------------------------
677 -}
678
679 getLookupOccRn :: RnM (Name -> Maybe Name)
680 getLookupOccRn
681 = do local_env <- getLocalRdrEnv
682 return (lookupLocalRdrOcc local_env . nameOccName)
683
684 mkUnboundNameRdr :: RdrName -> Name
685 mkUnboundNameRdr rdr = mkUnboundName (rdrNameOcc rdr)
686
687 lookupLocatedOccRn :: Located RdrName -> RnM (Located Name)
688 lookupLocatedOccRn = wrapLocM lookupOccRn
689
690 lookupLocalOccRn_maybe :: RdrName -> RnM (Maybe Name)
691 -- Just look in the local environment
692 lookupLocalOccRn_maybe rdr_name
693 = do { local_env <- getLocalRdrEnv
694 ; return (lookupLocalRdrEnv local_env rdr_name) }
695
696 lookupLocalOccThLvl_maybe :: Name -> RnM (Maybe (TopLevelFlag, ThLevel))
697 -- Just look in the local environment
698 lookupLocalOccThLvl_maybe name
699 = do { lcl_env <- getLclEnv
700 ; return (lookupNameEnv (tcl_th_bndrs lcl_env) name) }
701
702 -- lookupOccRn looks up an occurrence of a RdrName
703 lookupOccRn :: RdrName -> RnM Name
704 lookupOccRn rdr_name
705 = do { mb_name <- lookupOccRn_maybe rdr_name
706 ; case mb_name of
707 Just name -> return name
708 Nothing -> reportUnboundName rdr_name }
709
710 lookupKindOccRn :: RdrName -> RnM Name
711 -- Looking up a name occurring in a kind
712 lookupKindOccRn rdr_name
713 = do { mb_name <- lookupOccRn_maybe rdr_name
714 ; case mb_name of
715 Just name -> return name
716 Nothing -> reportUnboundName rdr_name }
717
718 -- lookupPromotedOccRn looks up an optionally promoted RdrName.
719 lookupTypeOccRn :: RdrName -> RnM Name
720 -- see Note [Demotion]
721 lookupTypeOccRn rdr_name
722 = do { mb_name <- lookupOccRn_maybe rdr_name
723 ; case mb_name of {
724 Just name -> return name ;
725 Nothing -> lookup_demoted rdr_name } }
726
727 lookup_demoted :: RdrName -> RnM Name
728 lookup_demoted rdr_name
729 | Just demoted_rdr <- demoteRdrName rdr_name
730 -- Maybe it's the name of a *data* constructor
731 = do { data_kinds <- xoptM Opt_DataKinds
732 ; mb_demoted_name <- lookupOccRn_maybe demoted_rdr
733 ; case mb_demoted_name of
734 Nothing -> reportUnboundName rdr_name
735 Just demoted_name
736 | data_kinds ->
737 do { whenWOptM Opt_WarnUntickedPromotedConstructors $
738 addWarn (untickedPromConstrWarn demoted_name)
739 ; return demoted_name }
740 | otherwise -> unboundNameX WL_Any rdr_name suggest_dk }
741
742 | otherwise
743 = reportUnboundName rdr_name
744
745 where
746 suggest_dk = ptext (sLit "A data constructor of that name is in scope; did you mean DataKinds?")
747 untickedPromConstrWarn name =
748 text "Unticked promoted constructor" <> colon <+> quotes (ppr name) <> dot
749 $$
750 hsep [ text "Use"
751 , quotes (char '\'' <> ppr name)
752 , text "instead of"
753 , quotes (ppr name) <> dot ]
754
755 {-
756 Note [Demotion]
757 ~~~~~~~~~~~~~~~
758 When the user writes:
759 data Nat = Zero | Succ Nat
760 foo :: f Zero -> Int
761
762 'Zero' in the type signature of 'foo' is parsed as:
763 HsTyVar ("Zero", TcClsName)
764
765 When the renamer hits this occurrence of 'Zero' it's going to realise
766 that it's not in scope. But because it is renaming a type, it knows
767 that 'Zero' might be a promoted data constructor, so it will demote
768 its namespace to DataName and do a second lookup.
769
770 The final result (after the renamer) will be:
771 HsTyVar ("Zero", DataName)
772 -}
773
774 -- Use this version to get tracing
775 --
776 -- lookupOccRn_maybe, lookupOccRn_maybe' :: RdrName -> RnM (Maybe Name)
777 -- lookupOccRn_maybe rdr_name
778 -- = do { mb_res <- lookupOccRn_maybe' rdr_name
779 -- ; gbl_rdr_env <- getGlobalRdrEnv
780 -- ; local_rdr_env <- getLocalRdrEnv
781 -- ; traceRn $ text "lookupOccRn_maybe" <+>
782 -- vcat [ ppr rdr_name <+> ppr (getUnique (rdrNameOcc rdr_name))
783 -- , ppr mb_res
784 -- , text "Lcl env" <+> ppr local_rdr_env
785 -- , text "Gbl env" <+> ppr [ (getUnique (nameOccName (gre_name (head gres'))),gres') | gres <- occEnvElts gbl_rdr_env
786 -- , let gres' = filter isLocalGRE gres, not (null gres') ] ]
787 -- ; return mb_res }
788
789 lookupOccRn_maybe :: RdrName -> RnM (Maybe Name)
790 -- lookupOccRn looks up an occurrence of a RdrName
791 lookupOccRn_maybe rdr_name
792 = do { local_env <- getLocalRdrEnv
793 ; case lookupLocalRdrEnv local_env rdr_name of {
794 Just name -> return (Just name) ;
795 Nothing -> do
796 ; lookupGlobalOccRn_maybe rdr_name } }
797
798 lookupGlobalOccRn_maybe :: RdrName -> RnM (Maybe Name)
799 -- Looks up a RdrName occurrence in the top-level
800 -- environment, including using lookupQualifiedNameGHCi
801 -- for the GHCi case
802 -- No filter function; does not report an error on failure
803 -- Uses addUsedRdrName to record use and deprecations
804 lookupGlobalOccRn_maybe rdr_name
805 | Just n <- isExact_maybe rdr_name -- This happens in derived code
806 = do { n' <- lookupExactOcc n; return (Just n') }
807
808 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
809 = do { n <- lookupOrig rdr_mod rdr_occ
810 ; return (Just n) }
811
812 | otherwise
813 = do { mb_gre <- lookupGreRn_maybe rdr_name
814 ; case mb_gre of {
815 Just gre -> return (Just (gre_name gre)) ;
816 Nothing ->
817 do { ns <- lookupQualifiedNameGHCi rdr_name
818 -- This test is not expensive,
819 -- and only happens for failed lookups
820 ; case ns of
821 (n:_) -> return (Just n) -- Unlikely to be more than one...?
822 [] -> return Nothing } } }
823
824 lookupGlobalOccRn :: RdrName -> RnM Name
825 -- lookupGlobalOccRn is like lookupOccRn, except that it looks in the global
826 -- environment. Adds an error message if the RdrName is not in scope.
827 lookupGlobalOccRn rdr_name
828 = do { mb_name <- lookupGlobalOccRn_maybe rdr_name
829 ; case mb_name of
830 Just n -> return n
831 Nothing -> do { traceRn (text "lookupGlobalOccRn" <+> ppr rdr_name)
832 ; unboundName WL_Global rdr_name } }
833
834 lookupInfoOccRn :: RdrName -> RnM [Name]
835 -- lookupInfoOccRn is intended for use in GHCi's ":info" command
836 -- It finds all the GREs that RdrName could mean, not complaining
837 -- about ambiguity, but rather returning them all
838 -- C.f. Trac #9881
839 lookupInfoOccRn rdr_name
840 | Just n <- isExact_maybe rdr_name -- e.g. (->)
841 = return [n]
842
843 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
844 = do { n <- lookupOrig rdr_mod rdr_occ
845 ; return [n] }
846
847 | otherwise
848 = do { rdr_env <- getGlobalRdrEnv
849 ; let ns = map gre_name (lookupGRE_RdrName rdr_name rdr_env)
850 ; qual_ns <- lookupQualifiedNameGHCi rdr_name
851 ; return (ns ++ (qual_ns `minusList` ns)) }
852
853 -- | Like 'lookupOccRn_maybe', but with a more informative result if
854 -- the 'RdrName' happens to be a record selector:
855 --
856 -- * Nothing -> name not in scope (no error reported)
857 -- * Just (Left x) -> name uniquely refers to x,
858 -- or there is a name clash (reported)
859 -- * Just (Right xs) -> name refers to one or more record selectors;
860 -- if overload_ok was False, this list will be
861 -- a singleton.
862 lookupOccRn_overloaded :: Bool -> RdrName -> RnM (Maybe (Either Name [FieldOcc Name]))
863 lookupOccRn_overloaded overload_ok rdr_name
864 = do { local_env <- getLocalRdrEnv
865 ; case lookupLocalRdrEnv local_env rdr_name of {
866 Just name -> return (Just (Left name)) ;
867 Nothing -> do
868 { mb_name <- lookupGlobalOccRn_overloaded overload_ok rdr_name
869 ; case mb_name of {
870 Just name -> return (Just name) ;
871 Nothing -> do
872 { ns <- lookupQualifiedNameGHCi rdr_name
873 -- This test is not expensive,
874 -- and only happens for failed lookups
875 ; case ns of
876 (n:_) -> return $ Just $ Left n -- Unlikely to be more than one...?
877 [] -> return Nothing } } } } }
878
879 lookupGlobalOccRn_overloaded :: Bool -> RdrName -> RnM (Maybe (Either Name [FieldOcc Name]))
880 lookupGlobalOccRn_overloaded overload_ok rdr_name
881 | Just n <- isExact_maybe rdr_name -- This happens in derived code
882 = do { n' <- lookupExactOcc n; return (Just (Left n')) }
883
884 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
885 = do { n <- lookupOrig rdr_mod rdr_occ
886 ; return (Just (Left n)) }
887
888 | otherwise
889 = do { env <- getGlobalRdrEnv
890 ; case lookupGRE_RdrName rdr_name env of
891 [] -> return Nothing
892 [gre] | isRecFldGRE gre
893 -> do { addUsedGRE True gre
894 ; let fld_occ :: FieldOcc Name
895 fld_occ = FieldOcc rdr_name (gre_name gre)
896 ; return (Just (Right [fld_occ])) }
897 | otherwise
898 -> do { addUsedGRE True gre
899 ; return (Just (Left (gre_name gre))) }
900 gres | all isRecFldGRE gres && overload_ok
901 -- Don't record usage for ambiguous selectors
902 -- until we know which is meant
903 -> return (Just (Right (map (FieldOcc rdr_name . gre_name) gres)))
904 gres -> do { addNameClashErrRn rdr_name gres
905 ; return (Just (Left (gre_name (head gres)))) } }
906
907
908 --------------------------------------------------
909 -- Lookup in the Global RdrEnv of the module
910 --------------------------------------------------
911
912 lookupGreRn_maybe :: RdrName -> RnM (Maybe GlobalRdrElt)
913 -- Look up the RdrName in the GlobalRdrEnv
914 -- Exactly one binding: records it as "used", return (Just gre)
915 -- No bindings: return Nothing
916 -- Many bindings: report "ambiguous", return an arbitrary (Just gre)
917 -- (This API is a bit strange; lookupGRERn2_maybe is simpler.
918 -- But it works and I don't want to fiddle too much.)
919 -- Uses addUsedRdrName to record use and deprecations
920 lookupGreRn_maybe rdr_name
921 = do { env <- getGlobalRdrEnv
922 ; case lookupGRE_RdrName rdr_name env of
923 [] -> return Nothing
924 [gre] -> do { addUsedGRE True gre
925 ; return (Just gre) }
926 gres -> do { addNameClashErrRn rdr_name gres
927 ; traceRn (text "name clash" <+> (ppr rdr_name $$ ppr gres $$ ppr env))
928 ; return (Just (head gres)) } }
929
930 lookupGreRn2_maybe :: RdrName -> RnM (Maybe GlobalRdrElt)
931 -- Look up the RdrName in the GlobalRdrEnv
932 -- Exactly one binding: record it as "used", return (Just gre)
933 -- No bindings: report "not in scope", return Nothing
934 -- Many bindings: report "ambiguous", return Nothing
935 -- Uses addUsedRdrName to record use and deprecations
936 lookupGreRn2_maybe rdr_name
937 = do { env <- getGlobalRdrEnv
938 ; case lookupGRE_RdrName rdr_name env of
939 [] -> do { _ <- unboundName WL_Global rdr_name
940 ; return Nothing }
941 [gre] -> do { addUsedGRE True gre
942 ; return (Just gre) }
943 gres -> do { addNameClashErrRn rdr_name gres
944 ; traceRn (text "name clash" <+> (ppr rdr_name $$ ppr gres $$ ppr env))
945 ; return Nothing } }
946
947 lookupGreAvailRn :: RdrName -> RnM (Name, AvailInfo)
948 -- Used in export lists
949 -- If not found or ambiguous, add error message, and fake with UnboundName
950 -- Uses addUsedRdrName to record use and deprecations
951 lookupGreAvailRn rdr_name
952 = do { mb_gre <- lookupGreRn2_maybe rdr_name
953 ; case mb_gre of {
954 Just gre -> return (gre_name gre, availFromGRE gre) ;
955 Nothing ->
956 do { traceRn (text "lookupGreRn" <+> ppr rdr_name)
957 ; let name = mkUnboundNameRdr rdr_name
958 ; return (name, avail name) } } }
959
960 {-
961 *********************************************************
962 * *
963 Deprecations
964 * *
965 *********************************************************
966
967 Note [Handling of deprecations]
968 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
969 * We report deprecations at each *occurrence* of the deprecated thing
970 (see Trac #5867)
971
972 * We do not report deprecations for locally-defined names. For a
973 start, we may be exporting a deprecated thing. Also we may use a
974 deprecated thing in the defn of another deprecated things. We may
975 even use a deprecated thing in the defn of a non-deprecated thing,
976 when changing a module's interface.
977
978 * addUsedGREs: we do not report deprecations for sub-binders:
979 - the ".." completion for records
980 - the ".." in an export item 'T(..)'
981 - the things exported by a module export 'module M'
982 -}
983
984 addUsedDataCons :: GlobalRdrEnv -> TyCon -> RnM ()
985 -- Remember use of in-scope data constructors (Trac #7969)
986 addUsedDataCons rdr_env tycon
987 = addUsedGREs [ gre
988 | dc <- tyConDataCons tycon
989 , gre : _ <- [lookupGRE_Name rdr_env (dataConName dc) ] ]
990
991 addUsedGRE :: Bool -> GlobalRdrElt -> RnM ()
992 -- Called for both local and imported things
993 -- Add usage *and* warn if deprecated
994 addUsedGRE warn_if_deprec gre
995 = do { when warn_if_deprec (warnIfDeprecated gre)
996 ; unless (isLocalGRE gre) $
997 do { env <- getGblEnv
998 ; traceRn (text "addUsedGRE" <+> ppr gre)
999 ; updMutVar (tcg_used_gres env) (gre :) } }
1000
1001 addUsedGREs :: [GlobalRdrElt] -> RnM ()
1002 -- Record uses of any *imported* GREs
1003 -- Used for recording used sub-bndrs
1004 -- NB: no call to warnIfDeprecated; see Note [Handling of deprecations]
1005 addUsedGREs gres
1006 | null imp_gres = return ()
1007 | otherwise = do { env <- getGblEnv
1008 ; traceRn (text "addUsedGREs" <+> ppr imp_gres)
1009 ; updMutVar (tcg_used_gres env) (imp_gres ++) }
1010 where
1011 imp_gres = filterOut isLocalGRE gres
1012
1013 warnIfDeprecated :: GlobalRdrElt -> RnM ()
1014 warnIfDeprecated gre@(GRE { gre_name = name, gre_imp = iss })
1015 | (imp_spec : _) <- iss
1016 = do { dflags <- getDynFlags
1017 ; this_mod <- getModule
1018 ; when (wopt Opt_WarnWarningsDeprecations dflags &&
1019 not (nameIsLocalOrFrom this_mod name)) $
1020 -- See Note [Handling of deprecations]
1021 do { iface <- loadInterfaceForName doc name
1022 ; case lookupImpDeprec iface gre of
1023 Just txt -> addWarn (mk_msg imp_spec txt)
1024 Nothing -> return () } }
1025 | otherwise
1026 = return ()
1027 where
1028 occ = greOccName gre
1029 name_mod = ASSERT2( isExternalName name, ppr name ) nameModule name
1030 doc = ptext (sLit "The name") <+> quotes (ppr occ) <+> ptext (sLit "is mentioned explicitly")
1031
1032 mk_msg imp_spec txt
1033 = sep [ sep [ ptext (sLit "In the use of")
1034 <+> pprNonVarNameSpace (occNameSpace occ)
1035 <+> quotes (ppr occ)
1036 , parens imp_msg <> colon ]
1037 , ppr txt ]
1038 where
1039 imp_mod = importSpecModule imp_spec
1040 imp_msg = ptext (sLit "imported from") <+> ppr imp_mod <> extra
1041 extra | imp_mod == moduleName name_mod = Outputable.empty
1042 | otherwise = ptext (sLit ", but defined in") <+> ppr name_mod
1043
1044 lookupImpDeprec :: ModIface -> GlobalRdrElt -> Maybe WarningTxt
1045 lookupImpDeprec iface gre
1046 = mi_warn_fn iface (gre_name gre) `mplus` -- Bleat if the thing,
1047 case gre_par gre of -- or its parent, is warn'd
1048 ParentIs p -> mi_warn_fn iface p
1049 FldParent { par_is = p } -> mi_warn_fn iface p
1050 NoParent -> Nothing
1051 PatternSynonym -> Nothing
1052
1053 {-
1054 Note [Used names with interface not loaded]
1055 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1056 It's (just) possible to find a used
1057 Name whose interface hasn't been loaded:
1058
1059 a) It might be a WiredInName; in that case we may not load
1060 its interface (although we could).
1061
1062 b) It might be GHC.Real.fromRational, or GHC.Num.fromInteger
1063 These are seen as "used" by the renamer (if -XRebindableSyntax)
1064 is on), but the typechecker may discard their uses
1065 if in fact the in-scope fromRational is GHC.Read.fromRational,
1066 (see tcPat.tcOverloadedLit), and the typechecker sees that the type
1067 is fixed, say, to GHC.Base.Float (see Inst.lookupSimpleInst).
1068 In that obscure case it won't force the interface in.
1069
1070 In both cases we simply don't permit deprecations;
1071 this is, after all, wired-in stuff.
1072
1073
1074 *********************************************************
1075 * *
1076 GHCi support
1077 * *
1078 *********************************************************
1079
1080 A qualified name on the command line can refer to any module at
1081 all: we try to load the interface if we don't already have it, just
1082 as if there was an "import qualified M" declaration for every
1083 module.
1084
1085 If we fail we just return Nothing, rather than bleating
1086 about "attempting to use module ā€˜Dā€™ (./D.hs) which is not loaded"
1087 which is what loadSrcInterface does.
1088
1089 Note [Safe Haskell and GHCi]
1090 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1091 We DONT do this Safe Haskell as we need to check imports. We can
1092 and should instead check the qualified import but at the moment
1093 this requires some refactoring so leave as a TODO
1094 -}
1095
1096 lookupQualifiedNameGHCi :: RdrName -> RnM [Name]
1097 lookupQualifiedNameGHCi rdr_name
1098 = -- We want to behave as we would for a source file import here,
1099 -- and respect hiddenness of modules/packages, hence loadSrcInterface.
1100 do { dflags <- getDynFlags
1101 ; is_ghci <- getIsGHCi
1102 ; go_for_it dflags is_ghci }
1103
1104 where
1105 go_for_it dflags is_ghci
1106 | Just (mod,occ) <- isQual_maybe rdr_name
1107 , is_ghci
1108 , gopt Opt_ImplicitImportQualified dflags -- Enables this GHCi behaviour
1109 , not (safeDirectImpsReq dflags) -- See Note [Safe Haskell and GHCi]
1110 = do { res <- loadSrcInterface_maybe doc mod False Nothing
1111 ; case res of
1112 Succeeded iface
1113 -> return [ name
1114 | avail <- mi_exports iface
1115 , name <- availNames avail
1116 , nameOccName name == occ ]
1117
1118 _ -> -- Either we couldn't load the interface, or
1119 -- we could but we didn't find the name in it
1120 do { traceRn (text "lookupQualifiedNameGHCi" <+> ppr rdr_name)
1121 ; return [] } }
1122
1123 | otherwise
1124 = do { traceRn (text "lookupQualifedNameGHCi: off" <+> ppr rdr_name)
1125 ; return [] }
1126
1127 doc = ptext (sLit "Need to find") <+> ppr rdr_name
1128
1129 {-
1130 Note [Looking up signature names]
1131 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1132 lookupSigOccRn is used for type signatures and pragmas
1133 Is this valid?
1134 module A
1135 import M( f )
1136 f :: Int -> Int
1137 f x = x
1138 It's clear that the 'f' in the signature must refer to A.f
1139 The Haskell98 report does not stipulate this, but it will!
1140 So we must treat the 'f' in the signature in the same way
1141 as the binding occurrence of 'f', using lookupBndrRn
1142
1143 However, consider this case:
1144 import M( f )
1145 f :: Int -> Int
1146 g x = x
1147 We don't want to say 'f' is out of scope; instead, we want to
1148 return the imported 'f', so that later on the reanamer will
1149 correctly report "misplaced type sig".
1150
1151 Note [Signatures for top level things]
1152 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1153 data HsSigCtxt = ... | TopSigCtxt NameSet | ....
1154
1155 * The NameSet says what is bound in this group of bindings.
1156 We can't use isLocalGRE from the GlobalRdrEnv, because of this:
1157 f x = x
1158 $( ...some TH splice... )
1159 f :: Int -> Int
1160 When we encounter the signature for 'f', the binding for 'f'
1161 will be in the GlobalRdrEnv, and will be a LocalDef. Yet the
1162 signature is mis-placed
1163
1164 * For type signatures the NameSet should be the names bound by the
1165 value bindings; for fixity declarations, the NameSet should also
1166 include class sigs and record selectors
1167
1168 infix 3 `f` -- Yes, ok
1169 f :: C a => a -> a -- No, not ok
1170 class C a where
1171 f :: a -> a
1172 -}
1173
1174 data HsSigCtxt
1175 = TopSigCtxt NameSet -- At top level, binding these names
1176 -- See Note [Signatures for top level things]
1177 | LocalBindCtxt NameSet -- In a local binding, binding these names
1178 | ClsDeclCtxt Name -- Class decl for this class
1179 | InstDeclCtxt NameSet -- Instance decl whose user-written method
1180 -- bindings are for these methods
1181 | HsBootCtxt -- Top level of a hs-boot file
1182 | RoleAnnotCtxt NameSet -- A role annotation, with the names of all types
1183 -- in the group
1184
1185 lookupSigOccRn :: HsSigCtxt
1186 -> Sig RdrName
1187 -> Located RdrName -> RnM (Located Name)
1188 lookupSigOccRn ctxt sig = lookupSigCtxtOccRn ctxt (hsSigDoc sig)
1189
1190 -- | Lookup a name in relation to the names in a 'HsSigCtxt'
1191 lookupSigCtxtOccRn :: HsSigCtxt
1192 -> SDoc -- ^ description of thing we're looking up,
1193 -- like "type family"
1194 -> Located RdrName -> RnM (Located Name)
1195 lookupSigCtxtOccRn ctxt what
1196 = wrapLocM $ \ rdr_name ->
1197 do { mb_name <- lookupBindGroupOcc ctxt what rdr_name
1198 ; case mb_name of
1199 Left err -> do { addErr err; return (mkUnboundNameRdr rdr_name) }
1200 Right name -> return name }
1201
1202 lookupBindGroupOcc :: HsSigCtxt
1203 -> SDoc
1204 -> RdrName -> RnM (Either MsgDoc Name)
1205 -- Looks up the RdrName, expecting it to resolve to one of the
1206 -- bound names passed in. If not, return an appropriate error message
1207 --
1208 -- See Note [Looking up signature names]
1209 lookupBindGroupOcc ctxt what rdr_name
1210 | Just n <- isExact_maybe rdr_name
1211 = lookupExactOcc_either n -- allow for the possibility of missing Exacts;
1212 -- see Note [dataTcOccs and Exact Names]
1213 -- Maybe we should check the side conditions
1214 -- but it's a pain, and Exact things only show
1215 -- up when you know what you are doing
1216
1217 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
1218 = do { n' <- lookupOrig rdr_mod rdr_occ
1219 ; return (Right n') }
1220
1221 | otherwise
1222 = case ctxt of
1223 HsBootCtxt -> lookup_top (const True)
1224 TopSigCtxt ns -> lookup_top (`elemNameSet` ns)
1225 RoleAnnotCtxt ns -> lookup_top (`elemNameSet` ns)
1226 LocalBindCtxt ns -> lookup_group ns
1227 ClsDeclCtxt cls -> lookup_cls_op cls
1228 InstDeclCtxt ns -> lookup_top (`elemNameSet` ns)
1229 where
1230 lookup_cls_op cls
1231 = lookupSubBndrOcc True cls doc rdr_name
1232 where
1233 doc = ptext (sLit "method of class") <+> quotes (ppr cls)
1234
1235 lookup_top keep_me
1236 = do { env <- getGlobalRdrEnv
1237 ; let all_gres = lookupGlobalRdrEnv env (rdrNameOcc rdr_name)
1238 ; case filter (keep_me . gre_name) all_gres of
1239 [] | null all_gres -> bale_out_with Outputable.empty
1240 | otherwise -> bale_out_with local_msg
1241 (gre:_) -> return (Right (gre_name gre)) }
1242
1243 lookup_group bound_names -- Look in the local envt (not top level)
1244 = do { local_env <- getLocalRdrEnv
1245 ; case lookupLocalRdrEnv local_env rdr_name of
1246 Just n
1247 | n `elemNameSet` bound_names -> return (Right n)
1248 | otherwise -> bale_out_with local_msg
1249 Nothing -> bale_out_with Outputable.empty }
1250
1251 bale_out_with msg
1252 = return (Left (sep [ ptext (sLit "The") <+> what
1253 <+> ptext (sLit "for") <+> quotes (ppr rdr_name)
1254 , nest 2 $ ptext (sLit "lacks an accompanying binding")]
1255 $$ nest 2 msg))
1256
1257 local_msg = parens $ ptext (sLit "The") <+> what <+> ptext (sLit "must be given where")
1258 <+> quotes (ppr rdr_name) <+> ptext (sLit "is declared")
1259
1260
1261 ---------------
1262 lookupLocalTcNames :: HsSigCtxt -> SDoc -> RdrName -> RnM [Name]
1263 -- GHC extension: look up both the tycon and data con or variable.
1264 -- Used for top-level fixity signatures and deprecations.
1265 -- Complain if neither is in scope.
1266 -- See Note [Fixity signature lookup]
1267 lookupLocalTcNames ctxt what rdr_name
1268 = do { mb_gres <- mapM lookup (dataTcOccs rdr_name)
1269 ; let (errs, names) = splitEithers mb_gres
1270 ; when (null names) $ addErr (head errs) -- Bleat about one only
1271 ; return names }
1272 where
1273 lookup = lookupBindGroupOcc ctxt what
1274
1275 dataTcOccs :: RdrName -> [RdrName]
1276 -- Return both the given name and the same name promoted to the TcClsName
1277 -- namespace. This is useful when we aren't sure which we are looking at.
1278 -- See also Note [dataTcOccs and Exact Names]
1279 dataTcOccs rdr_name
1280 | isDataOcc occ || isVarOcc occ
1281 = [rdr_name, rdr_name_tc]
1282 | otherwise
1283 = [rdr_name]
1284 where
1285 occ = rdrNameOcc rdr_name
1286 rdr_name_tc = setRdrNameSpace rdr_name tcName
1287
1288 {-
1289 Note [dataTcOccs and Exact Names]
1290 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1291 Exact RdrNames can occur in code generated by Template Haskell, and generally
1292 those references are, well, exact. However, the TH `Name` type isn't expressive
1293 enough to always track the correct namespace information, so we sometimes get
1294 the right Unique but wrong namespace. Thus, we still have to do the double-lookup
1295 for Exact RdrNames.
1296
1297 There is also an awkward situation for built-in syntax. Example in GHCi
1298 :info []
1299 This parses as the Exact RdrName for nilDataCon, but we also want
1300 the list type constructor.
1301
1302 Note that setRdrNameSpace on an Exact name requires the Name to be External,
1303 which it always is for built in syntax.
1304
1305 *********************************************************
1306 * *
1307 Fixities
1308 * *
1309 *********************************************************
1310
1311 Note [Fixity signature lookup]
1312 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1313 A fixity declaration like
1314
1315 infixr 2 ?
1316
1317 can refer to a value-level operator, e.g.:
1318
1319 (?) :: String -> String -> String
1320
1321 or a type-level operator, like:
1322
1323 data (?) a b = A a | B b
1324
1325 so we extend the lookup of the reader name '?' to the TcClsName namespace, as
1326 well as the original namespace.
1327
1328 The extended lookup is also used in other places, like resolution of
1329 deprecation declarations, and lookup of names in GHCi.
1330 -}
1331
1332 --------------------------------
1333 type MiniFixityEnv = FastStringEnv (Located Fixity)
1334 -- Mini fixity env for the names we're about
1335 -- to bind, in a single binding group
1336 --
1337 -- It is keyed by the *FastString*, not the *OccName*, because
1338 -- the single fixity decl infix 3 T
1339 -- affects both the data constructor T and the type constrctor T
1340 --
1341 -- We keep the location so that if we find
1342 -- a duplicate, we can report it sensibly
1343
1344 --------------------------------
1345 -- Used for nested fixity decls to bind names along with their fixities.
1346 -- the fixities are given as a UFM from an OccName's FastString to a fixity decl
1347
1348 addLocalFixities :: MiniFixityEnv -> [Name] -> RnM a -> RnM a
1349 addLocalFixities mini_fix_env names thing_inside
1350 = extendFixityEnv (mapMaybe find_fixity names) thing_inside
1351 where
1352 find_fixity name
1353 = case lookupFsEnv mini_fix_env (occNameFS occ) of
1354 Just (L _ fix) -> Just (name, FixItem occ fix)
1355 Nothing -> Nothing
1356 where
1357 occ = nameOccName name
1358
1359 {-
1360 --------------------------------
1361 lookupFixity is a bit strange.
1362
1363 * Nested local fixity decls are put in the local fixity env, which we
1364 find with getFixtyEnv
1365
1366 * Imported fixities are found in the HIT or PIT
1367
1368 * Top-level fixity decls in this module may be for Names that are
1369 either Global (constructors, class operations)
1370 or Local/Exported (everything else)
1371 (See notes with RnNames.getLocalDeclBinders for why we have this split.)
1372 We put them all in the local fixity environment
1373 -}
1374
1375 lookupFixityRn :: Name -> RnM Fixity
1376 lookupFixityRn name
1377 | isUnboundName name
1378 = return (Fixity minPrecedence InfixL)
1379 -- Minimise errors from ubound names; eg
1380 -- a>0 `foo` b>0
1381 -- where 'foo' is not in scope, should not give an error (Trac #7937)
1382
1383 | otherwise
1384 = do { local_fix_env <- getFixityEnv
1385 ; case lookupNameEnv local_fix_env name of {
1386 Just (FixItem _ fix) -> return fix ;
1387 Nothing ->
1388
1389 do { this_mod <- getModule
1390 ; if nameIsLocalOrFrom this_mod name
1391 -- Local (and interactive) names are all in the
1392 -- fixity env, and don't have entries in the HPT
1393 then return defaultFixity
1394 else lookup_imported } } }
1395 where
1396 lookup_imported
1397 -- For imported names, we have to get their fixities by doing a
1398 -- loadInterfaceForName, and consulting the Ifaces that comes back
1399 -- from that, because the interface file for the Name might not
1400 -- have been loaded yet. Why not? Suppose you import module A,
1401 -- which exports a function 'f', thus;
1402 -- module CurrentModule where
1403 -- import A( f )
1404 -- module A( f ) where
1405 -- import B( f )
1406 -- Then B isn't loaded right away (after all, it's possible that
1407 -- nothing from B will be used). When we come across a use of
1408 -- 'f', we need to know its fixity, and it's then, and only
1409 -- then, that we load B.hi. That is what's happening here.
1410 --
1411 -- loadInterfaceForName will find B.hi even if B is a hidden module,
1412 -- and that's what we want.
1413 = do { iface <- loadInterfaceForName doc name
1414 ; traceRn (text "lookupFixityRn: looking up name in iface cache and found:" <+>
1415 vcat [ppr name, ppr $ mi_fix_fn iface (nameOccName name)])
1416 ; return (mi_fix_fn iface (nameOccName name)) }
1417
1418 doc = ptext (sLit "Checking fixity for") <+> ppr name
1419
1420 ---------------
1421 lookupTyFixityRn :: Located Name -> RnM Fixity
1422 lookupTyFixityRn (L _ n) = lookupFixityRn n
1423
1424 {-
1425 ************************************************************************
1426 * *
1427 Rebindable names
1428 Dealing with rebindable syntax is driven by the
1429 Opt_RebindableSyntax dynamic flag.
1430
1431 In "deriving" code we don't want to use rebindable syntax
1432 so we switch off the flag locally
1433
1434 * *
1435 ************************************************************************
1436
1437 Haskell 98 says that when you say "3" you get the "fromInteger" from the
1438 Standard Prelude, regardless of what is in scope. However, to experiment
1439 with having a language that is less coupled to the standard prelude, we're
1440 trying a non-standard extension that instead gives you whatever "Prelude.fromInteger"
1441 happens to be in scope. Then you can
1442 import Prelude ()
1443 import MyPrelude as Prelude
1444 to get the desired effect.
1445
1446 At the moment this just happens for
1447 * fromInteger, fromRational on literals (in expressions and patterns)
1448 * negate (in expressions)
1449 * minus (arising from n+k patterns)
1450 * "do" notation
1451
1452 We store the relevant Name in the HsSyn tree, in
1453 * HsIntegral/HsFractional/HsIsString
1454 * NegApp
1455 * NPlusKPat
1456 * HsDo
1457 respectively. Initially, we just store the "standard" name (PrelNames.fromIntegralName,
1458 fromRationalName etc), but the renamer changes this to the appropriate user
1459 name if Opt_NoImplicitPrelude is on. That is what lookupSyntaxName does.
1460
1461 We treat the orignal (standard) names as free-vars too, because the type checker
1462 checks the type of the user thing against the type of the standard thing.
1463 -}
1464
1465 lookupIfThenElse :: RnM (Maybe (SyntaxExpr Name), FreeVars)
1466 -- Different to lookupSyntaxName because in the non-rebindable
1467 -- case we desugar directly rather than calling an existing function
1468 -- Hence the (Maybe (SyntaxExpr Name)) return type
1469 lookupIfThenElse
1470 = do { rebindable_on <- xoptM Opt_RebindableSyntax
1471 ; if not rebindable_on
1472 then return (Nothing, emptyFVs)
1473 else do { ite <- lookupOccRn (mkVarUnqual (fsLit "ifThenElse"))
1474 ; return (Just (HsVar (noLoc ite)), unitFV ite) } }
1475
1476 lookupSyntaxName :: Name -- The standard name
1477 -> RnM (SyntaxExpr Name, FreeVars) -- Possibly a non-standard name
1478 lookupSyntaxName std_name
1479 = do { rebindable_on <- xoptM Opt_RebindableSyntax
1480 ; if not rebindable_on then
1481 return (HsVar (noLoc std_name), emptyFVs)
1482 else
1483 -- Get the similarly named thing from the local environment
1484 do { usr_name <- lookupOccRn (mkRdrUnqual (nameOccName std_name))
1485 ; return (HsVar (noLoc usr_name), unitFV usr_name) } }
1486
1487 lookupSyntaxNames :: [Name] -- Standard names
1488 -> RnM ([HsExpr Name], FreeVars) -- See comments with HsExpr.ReboundNames
1489 lookupSyntaxNames std_names
1490 = do { rebindable_on <- xoptM Opt_RebindableSyntax
1491 ; if not rebindable_on then
1492 return (map (HsVar . noLoc) std_names, emptyFVs)
1493 else
1494 do { usr_names <- mapM (lookupOccRn . mkRdrUnqual . nameOccName) std_names
1495 ; return (map (HsVar . noLoc) usr_names, mkFVs usr_names) } }
1496
1497 {-
1498 *********************************************************
1499 * *
1500 \subsection{Binding}
1501 * *
1502 *********************************************************
1503 -}
1504
1505 newLocalBndrRn :: Located RdrName -> RnM Name
1506 -- Used for non-top-level binders. These should
1507 -- never be qualified.
1508 newLocalBndrRn (L loc rdr_name)
1509 | Just name <- isExact_maybe rdr_name
1510 = return name -- This happens in code generated by Template Haskell
1511 -- See Note [Binders in Template Haskell] in Convert.hs
1512 | otherwise
1513 = do { unless (isUnqual rdr_name)
1514 (addErrAt loc (badQualBndrErr rdr_name))
1515 ; uniq <- newUnique
1516 ; return (mkInternalName uniq (rdrNameOcc rdr_name) loc) }
1517
1518 newLocalBndrsRn :: [Located RdrName] -> RnM [Name]
1519 newLocalBndrsRn = mapM newLocalBndrRn
1520
1521 ---------------------
1522 bindLocatedLocalsRn :: [Located RdrName]
1523 -> ([Name] -> RnM a)
1524 -> RnM a
1525 bindLocatedLocalsRn rdr_names_w_loc enclosed_scope
1526 = do { checkDupRdrNames rdr_names_w_loc
1527 ; checkShadowedRdrNames rdr_names_w_loc
1528
1529 -- Make fresh Names and extend the environment
1530 ; names <- newLocalBndrsRn rdr_names_w_loc
1531 ; bindLocalNames names (enclosed_scope names) }
1532
1533 bindLocalNames :: [Name] -> RnM a -> RnM a
1534 bindLocalNames names enclosed_scope
1535 = do { lcl_env <- getLclEnv
1536 ; let th_level = thLevel (tcl_th_ctxt lcl_env)
1537 th_bndrs' = extendNameEnvList (tcl_th_bndrs lcl_env)
1538 [ (n, (NotTopLevel, th_level)) | n <- names ]
1539 rdr_env' = extendLocalRdrEnvList (tcl_rdr lcl_env) names
1540 ; setLclEnv (lcl_env { tcl_th_bndrs = th_bndrs'
1541 , tcl_rdr = rdr_env' })
1542 enclosed_scope }
1543
1544 bindLocalNamesFV :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
1545 bindLocalNamesFV names enclosed_scope
1546 = do { (result, fvs) <- bindLocalNames names enclosed_scope
1547 ; return (result, delFVs names fvs) }
1548
1549
1550 -------------------------------------
1551 -- binLocalsFVRn is the same as bindLocalsRn
1552 -- except that it deals with free vars
1553 bindLocatedLocalsFV :: [Located RdrName]
1554 -> ([Name] -> RnM (a,FreeVars)) -> RnM (a, FreeVars)
1555 bindLocatedLocalsFV rdr_names enclosed_scope
1556 = bindLocatedLocalsRn rdr_names $ \ names ->
1557 do (thing, fvs) <- enclosed_scope names
1558 return (thing, delFVs names fvs)
1559
1560 -------------------------------------
1561
1562 extendTyVarEnvFVRn :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
1563 -- This function is used only in rnSourceDecl on InstDecl
1564 extendTyVarEnvFVRn tyvars thing_inside = bindLocalNamesFV tyvars thing_inside
1565
1566 -------------------------------------
1567 checkDupRdrNames :: [Located RdrName] -> RnM ()
1568 -- Check for duplicated names in a binding group
1569 checkDupRdrNames rdr_names_w_loc
1570 = mapM_ (dupNamesErr getLoc) dups
1571 where
1572 (_, dups) = removeDups (\n1 n2 -> unLoc n1 `compare` unLoc n2) rdr_names_w_loc
1573
1574 checkDupNames :: [Name] -> RnM ()
1575 -- Check for duplicated names in a binding group
1576 checkDupNames names = check_dup_names (filterOut isSystemName names)
1577 -- See Note [Binders in Template Haskell] in Convert
1578
1579 check_dup_names :: [Name] -> RnM ()
1580 check_dup_names names
1581 = mapM_ (dupNamesErr nameSrcSpan) dups
1582 where
1583 (_, dups) = removeDups (\n1 n2 -> nameOccName n1 `compare` nameOccName n2) names
1584
1585 ---------------------
1586 checkShadowedRdrNames :: [Located RdrName] -> RnM ()
1587 checkShadowedRdrNames loc_rdr_names
1588 = do { envs <- getRdrEnvs
1589 ; checkShadowedOccs envs get_loc_occ filtered_rdrs }
1590 where
1591 filtered_rdrs = filterOut (isExact . unLoc) loc_rdr_names
1592 -- See Note [Binders in Template Haskell] in Convert
1593 get_loc_occ (L loc rdr) = (loc,rdrNameOcc rdr)
1594
1595 checkDupAndShadowedNames :: (GlobalRdrEnv, LocalRdrEnv) -> [Name] -> RnM ()
1596 checkDupAndShadowedNames envs names
1597 = do { check_dup_names filtered_names
1598 ; checkShadowedOccs envs get_loc_occ filtered_names }
1599 where
1600 filtered_names = filterOut isSystemName names
1601 -- See Note [Binders in Template Haskell] in Convert
1602 get_loc_occ name = (nameSrcSpan name, nameOccName name)
1603
1604 -------------------------------------
1605 checkShadowedOccs :: (GlobalRdrEnv, LocalRdrEnv)
1606 -> (a -> (SrcSpan, OccName))
1607 -> [a] -> RnM ()
1608 checkShadowedOccs (global_env,local_env) get_loc_occ ns
1609 = whenWOptM Opt_WarnNameShadowing $
1610 do { traceRn (text "shadow" <+> ppr (map get_loc_occ ns))
1611 ; mapM_ check_shadow ns }
1612 where
1613 check_shadow n
1614 | startsWithUnderscore occ = return () -- Do not report shadowing for "_x"
1615 -- See Trac #3262
1616 | Just n <- mb_local = complain [ptext (sLit "bound at") <+> ppr (nameSrcLoc n)]
1617 | otherwise = do { gres' <- filterM is_shadowed_gre gres
1618 ; complain (map pprNameProvenance gres') }
1619 where
1620 (loc,occ) = get_loc_occ n
1621 mb_local = lookupLocalRdrOcc local_env occ
1622 gres = lookupGRE_RdrName (mkRdrUnqual occ) global_env
1623 -- Make an Unqualified RdrName and look that up, so that
1624 -- we don't find any GREs that are in scope qualified-only
1625
1626 complain [] = return ()
1627 complain pp_locs = addWarnAt loc (shadowedNameWarn occ pp_locs)
1628
1629 is_shadowed_gre :: GlobalRdrElt -> RnM Bool
1630 -- Returns False for record selectors that are shadowed, when
1631 -- punning or wild-cards are on (cf Trac #2723)
1632 is_shadowed_gre gre | isRecFldGRE gre
1633 = do { dflags <- getDynFlags
1634 ; return $ not (xopt Opt_RecordPuns dflags || xopt Opt_RecordWildCards dflags) }
1635 is_shadowed_gre _other = return True
1636
1637 {-
1638 ************************************************************************
1639 * *
1640 What to do when a lookup fails
1641 * *
1642 ************************************************************************
1643 -}
1644
1645 data WhereLooking = WL_Any -- Any binding
1646 | WL_Global -- Any top-level binding (local or imported)
1647 | WL_LocalTop -- Any top-level binding in this module
1648
1649 reportUnboundName :: RdrName -> RnM Name
1650 reportUnboundName rdr = unboundName WL_Any rdr
1651
1652 unboundName :: WhereLooking -> RdrName -> RnM Name
1653 unboundName wl rdr = unboundNameX wl rdr Outputable.empty
1654
1655 unboundNameX :: WhereLooking -> RdrName -> SDoc -> RnM Name
1656 unboundNameX where_look rdr_name extra
1657 = do { dflags <- getDynFlags
1658 ; let show_helpful_errors = gopt Opt_HelpfulErrors dflags
1659 what = pprNonVarNameSpace (occNameSpace (rdrNameOcc rdr_name))
1660 err = unknownNameErr what rdr_name $$ extra
1661 ; if not show_helpful_errors
1662 then addErr err
1663 else do { local_env <- getLocalRdrEnv
1664 ; global_env <- getGlobalRdrEnv
1665 ; impInfo <- getImports
1666 ; let suggestions = unknownNameSuggestions_ where_look
1667 dflags global_env local_env impInfo rdr_name
1668 ; addErr (err $$ suggestions) }
1669 ; return (mkUnboundNameRdr rdr_name) }
1670
1671 unknownNameErr :: SDoc -> RdrName -> SDoc
1672 unknownNameErr what rdr_name
1673 = vcat [ hang (ptext (sLit "Not in scope:"))
1674 2 (what <+> quotes (ppr rdr_name))
1675 , extra ]
1676 where
1677 extra | rdr_name == forall_tv_RDR = perhapsForallMsg
1678 | otherwise = Outputable.empty
1679
1680 type HowInScope = Either SrcSpan ImpDeclSpec
1681 -- Left loc => locally bound at loc
1682 -- Right ispec => imported as specified by ispec
1683
1684
1685 -- | Called from the typechecker (TcErrors) when we find an unbound variable
1686 unknownNameSuggestions :: DynFlags
1687 -> GlobalRdrEnv -> LocalRdrEnv -> ImportAvails
1688 -> RdrName -> SDoc
1689 unknownNameSuggestions = unknownNameSuggestions_ WL_Any
1690
1691 unknownNameSuggestions_ :: WhereLooking -> DynFlags
1692 -> GlobalRdrEnv -> LocalRdrEnv -> ImportAvails
1693 -> RdrName -> SDoc
1694 unknownNameSuggestions_ where_look dflags global_env local_env imports tried_rdr_name =
1695 similarNameSuggestions where_look dflags global_env local_env tried_rdr_name $$
1696 importSuggestions dflags imports tried_rdr_name
1697
1698
1699 similarNameSuggestions :: WhereLooking -> DynFlags
1700 -> GlobalRdrEnv -> LocalRdrEnv
1701 -> RdrName -> SDoc
1702 similarNameSuggestions where_look dflags global_env
1703 local_env tried_rdr_name
1704 = case suggest of
1705 [] -> Outputable.empty
1706 [p] -> perhaps <+> pp_item p
1707 ps -> sep [ perhaps <+> ptext (sLit "one of these:")
1708 , nest 2 (pprWithCommas pp_item ps) ]
1709 where
1710 all_possibilities :: [(String, (RdrName, HowInScope))]
1711 all_possibilities
1712 = [ (showPpr dflags r, (r, Left loc))
1713 | (r,loc) <- local_possibilities local_env ]
1714 ++ [ (showPpr dflags r, rp) | (r, rp) <- global_possibilities global_env ]
1715
1716 suggest = fuzzyLookup (showPpr dflags tried_rdr_name) all_possibilities
1717 perhaps = ptext (sLit "Perhaps you meant")
1718
1719 pp_item :: (RdrName, HowInScope) -> SDoc
1720 pp_item (rdr, Left loc) = pp_ns rdr <+> quotes (ppr rdr) <+> loc' -- Locally defined
1721 where loc' = case loc of
1722 UnhelpfulSpan l -> parens (ppr l)
1723 RealSrcSpan l -> parens (ptext (sLit "line") <+> int (srcSpanStartLine l))
1724 pp_item (rdr, Right is) = pp_ns rdr <+> quotes (ppr rdr) <+> -- Imported
1725 parens (ptext (sLit "imported from") <+> ppr (is_mod is))
1726
1727 pp_ns :: RdrName -> SDoc
1728 pp_ns rdr | ns /= tried_ns = pprNameSpace ns
1729 | otherwise = Outputable.empty
1730 where ns = rdrNameSpace rdr
1731
1732 tried_occ = rdrNameOcc tried_rdr_name
1733 tried_is_sym = isSymOcc tried_occ
1734 tried_ns = occNameSpace tried_occ
1735 tried_is_qual = isQual tried_rdr_name
1736
1737 correct_name_space occ = nameSpacesRelated (occNameSpace occ) tried_ns
1738 && isSymOcc occ == tried_is_sym
1739 -- Treat operator and non-operators as non-matching
1740 -- This heuristic avoids things like
1741 -- Not in scope 'f'; perhaps you meant '+' (from Prelude)
1742
1743 local_ok = case where_look of { WL_Any -> True; _ -> False }
1744 local_possibilities :: LocalRdrEnv -> [(RdrName, SrcSpan)]
1745 local_possibilities env
1746 | tried_is_qual = []
1747 | not local_ok = []
1748 | otherwise = [ (mkRdrUnqual occ, nameSrcSpan name)
1749 | name <- localRdrEnvElts env
1750 , let occ = nameOccName name
1751 , correct_name_space occ]
1752
1753 gre_ok :: GlobalRdrElt -> Bool
1754 gre_ok = case where_look of
1755 WL_LocalTop -> isLocalGRE
1756 _ -> \_ -> True
1757
1758 global_possibilities :: GlobalRdrEnv -> [(RdrName, (RdrName, HowInScope))]
1759 global_possibilities global_env
1760 | tried_is_qual = [ (rdr_qual, (rdr_qual, how))
1761 | gre <- globalRdrEnvElts global_env
1762 , gre_ok gre
1763 , let name = gre_name gre
1764 occ = nameOccName name
1765 , correct_name_space occ
1766 , (mod, how) <- quals_in_scope gre
1767 , let rdr_qual = mkRdrQual mod occ ]
1768
1769 | otherwise = [ (rdr_unqual, pair)
1770 | gre <- globalRdrEnvElts global_env
1771 , gre_ok gre
1772 , let name = gre_name gre
1773 occ = nameOccName name
1774 rdr_unqual = mkRdrUnqual occ
1775 , correct_name_space occ
1776 , pair <- case (unquals_in_scope gre, quals_only gre) of
1777 (how:_, _) -> [ (rdr_unqual, how) ]
1778 ([], pr:_) -> [ pr ] -- See Note [Only-quals]
1779 ([], []) -> [] ]
1780
1781 -- Note [Only-quals]
1782 -- The second alternative returns those names with the same
1783 -- OccName as the one we tried, but live in *qualified* imports
1784 -- e.g. if you have:
1785 --
1786 -- > import qualified Data.Map as Map
1787 -- > foo :: Map
1788 --
1789 -- then we suggest @Map.Map@.
1790
1791 --------------------
1792 unquals_in_scope :: GlobalRdrElt -> [HowInScope]
1793 unquals_in_scope (GRE { gre_name = n, gre_lcl = lcl, gre_imp = is })
1794 | lcl = [ Left (nameSrcSpan n) ]
1795 | otherwise = [ Right ispec
1796 | i <- is, let ispec = is_decl i
1797 , not (is_qual ispec) ]
1798
1799 --------------------
1800 quals_in_scope :: GlobalRdrElt -> [(ModuleName, HowInScope)]
1801 -- Ones for which the qualified version is in scope
1802 quals_in_scope (GRE { gre_name = n, gre_lcl = lcl, gre_imp = is })
1803 | lcl = case nameModule_maybe n of
1804 Nothing -> []
1805 Just m -> [(moduleName m, Left (nameSrcSpan n))]
1806 | otherwise = [ (is_as ispec, Right ispec)
1807 | i <- is, let ispec = is_decl i ]
1808
1809 --------------------
1810 quals_only :: GlobalRdrElt -> [(RdrName, HowInScope)]
1811 -- Ones for which *only* the qualified version is in scope
1812 quals_only (GRE { gre_name = n, gre_imp = is })
1813 = [ (mkRdrQual (is_as ispec) (nameOccName n), Right ispec)
1814 | i <- is, let ispec = is_decl i, is_qual ispec ]
1815
1816 -- | Generate helpful suggestions if a qualified name Mod.foo is not in scope.
1817 importSuggestions :: DynFlags -> ImportAvails -> RdrName -> SDoc
1818 importSuggestions _dflags imports rdr_name
1819 | not (isQual rdr_name || isUnqual rdr_name) = Outputable.empty
1820 | null interesting_imports
1821 , Just name <- mod_name
1822 = hsep
1823 [ ptext (sLit "No module named")
1824 , quotes (ppr name)
1825 , ptext (sLit "is imported.")
1826 ]
1827 | is_qualified
1828 , null helpful_imports
1829 , [(mod,_)] <- interesting_imports
1830 = hsep
1831 [ ptext (sLit "Module")
1832 , quotes (ppr mod)
1833 , ptext (sLit "does not export")
1834 , quotes (ppr occ_name) <> dot
1835 ]
1836 | is_qualified
1837 , null helpful_imports
1838 , mods <- map fst interesting_imports
1839 = hsep
1840 [ ptext (sLit "Neither")
1841 , quotedListWithNor (map ppr mods)
1842 , ptext (sLit "exports")
1843 , quotes (ppr occ_name) <> dot
1844 ]
1845 | [(mod,imv)] <- helpful_imports_non_hiding
1846 = fsep
1847 [ ptext (sLit "Perhaps you want to add")
1848 , quotes (ppr occ_name)
1849 , ptext (sLit "to the import list")
1850 , ptext (sLit "in the import of")
1851 , quotes (ppr mod)
1852 , parens (ppr (imv_span imv)) <> dot
1853 ]
1854 | not (null helpful_imports_non_hiding)
1855 = fsep
1856 [ ptext (sLit "Perhaps you want to add")
1857 , quotes (ppr occ_name)
1858 , ptext (sLit "to one of these import lists:")
1859 ]
1860 $$
1861 nest 2 (vcat
1862 [ quotes (ppr mod) <+> parens (ppr (imv_span imv))
1863 | (mod,imv) <- helpful_imports_non_hiding
1864 ])
1865 | [(mod,imv)] <- helpful_imports_hiding
1866 = fsep
1867 [ ptext (sLit "Perhaps you want to remove")
1868 , quotes (ppr occ_name)
1869 , ptext (sLit "from the explicit hiding list")
1870 , ptext (sLit "in the import of")
1871 , quotes (ppr mod)
1872 , parens (ppr (imv_span imv)) <> dot
1873 ]
1874 | not (null helpful_imports_hiding)
1875 = fsep
1876 [ ptext (sLit "Perhaps you want to remove")
1877 , quotes (ppr occ_name)
1878 , ptext (sLit "from the hiding clauses")
1879 , ptext (sLit "in one of these imports:")
1880 ]
1881 $$
1882 nest 2 (vcat
1883 [ quotes (ppr mod) <+> parens (ppr (imv_span imv))
1884 | (mod,imv) <- helpful_imports_hiding
1885 ])
1886 | otherwise
1887 = Outputable.empty
1888 where
1889 is_qualified = isQual rdr_name
1890 (mod_name, occ_name) = case rdr_name of
1891 Unqual occ_name -> (Nothing, occ_name)
1892 Qual mod_name occ_name -> (Just mod_name, occ_name)
1893 _ -> error "importSuggestions: dead code"
1894
1895
1896 -- What import statements provide "Mod" at all
1897 -- or, if this is an unqualified name, are not qualified imports
1898 interesting_imports = [ (mod, imp)
1899 | (mod, mod_imports) <- moduleEnvToList (imp_mods imports)
1900 , Just imp <- return $ pick mod_imports
1901 ]
1902
1903 -- We want to keep only one for each original module; preferably one with an
1904 -- explicit import list (for no particularly good reason)
1905 pick :: [ImportedModsVal] -> Maybe ImportedModsVal
1906 pick = listToMaybe . sortBy (compare `on` prefer) . filter select
1907 where select imv = case mod_name of Just name -> imv_name imv == name
1908 Nothing -> not (imv_qualified imv)
1909 prefer imv = (imv_is_hiding imv, imv_span imv)
1910
1911 -- Which of these would export a 'foo'
1912 -- (all of these are restricted imports, because if they were not, we
1913 -- wouldn't have an out-of-scope error in the first place)
1914 helpful_imports = filter helpful interesting_imports
1915 where helpful (_,imv)
1916 = not . null $ lookupGlobalRdrEnv (imv_all_exports imv) occ_name
1917
1918 -- Which of these do that because of an explicit hiding list resp. an
1919 -- explicit import list
1920 (helpful_imports_hiding, helpful_imports_non_hiding)
1921 = partition (imv_is_hiding . snd) helpful_imports
1922
1923 {-
1924 ************************************************************************
1925 * *
1926 \subsection{Free variable manipulation}
1927 * *
1928 ************************************************************************
1929 -}
1930
1931 -- A useful utility
1932 addFvRn :: FreeVars -> RnM (thing, FreeVars) -> RnM (thing, FreeVars)
1933 addFvRn fvs1 thing_inside = do { (res, fvs2) <- thing_inside
1934 ; return (res, fvs1 `plusFV` fvs2) }
1935
1936 mapFvRn :: (a -> RnM (b, FreeVars)) -> [a] -> RnM ([b], FreeVars)
1937 mapFvRn f xs = do stuff <- mapM f xs
1938 case unzip stuff of
1939 (ys, fvs_s) -> return (ys, plusFVs fvs_s)
1940
1941 mapMaybeFvRn :: (a -> RnM (b, FreeVars)) -> Maybe a -> RnM (Maybe b, FreeVars)
1942 mapMaybeFvRn _ Nothing = return (Nothing, emptyFVs)
1943 mapMaybeFvRn f (Just x) = do { (y, fvs) <- f x; return (Just y, fvs) }
1944
1945 -- because some of the rename functions are CPSed:
1946 -- maps the function across the list from left to right;
1947 -- collects all the free vars into one set
1948 mapFvRnCPS :: (a -> (b -> RnM c) -> RnM c)
1949 -> [a] -> ([b] -> RnM c) -> RnM c
1950
1951 mapFvRnCPS _ [] cont = cont []
1952 mapFvRnCPS f (x:xs) cont = f x $ \ x' ->
1953 mapFvRnCPS f xs $ \ xs' ->
1954 cont (x':xs')
1955
1956 {-
1957 ************************************************************************
1958 * *
1959 \subsection{Envt utility functions}
1960 * *
1961 ************************************************************************
1962 -}
1963
1964 warnUnusedTopBinds :: [GlobalRdrElt] -> RnM ()
1965 warnUnusedTopBinds gres
1966 = whenWOptM Opt_WarnUnusedTopBinds
1967 $ do env <- getGblEnv
1968 let isBoot = tcg_src env == HsBootFile
1969 let noParent gre = case gre_par gre of
1970 NoParent -> True
1971 PatternSynonym -> True
1972 _ -> False
1973 -- Don't warn about unused bindings with parents in
1974 -- .hs-boot files, as you are sometimes required to give
1975 -- unused bindings (trac #3449).
1976 -- HOWEVER, in a signature file, you are never obligated to put a
1977 -- definition in the main text. Thus, if you define something
1978 -- and forget to export it, we really DO want to warn.
1979 gres' = if isBoot then filter noParent gres
1980 else gres
1981 warnUnusedGREs gres'
1982
1983 warnUnusedLocalBinds, warnUnusedMatches :: [Name] -> FreeVars -> RnM ()
1984 warnUnusedLocalBinds = check_unused Opt_WarnUnusedLocalBinds
1985 warnUnusedMatches = check_unused Opt_WarnUnusedMatches
1986
1987 check_unused :: WarningFlag -> [Name] -> FreeVars -> RnM ()
1988 check_unused flag bound_names used_names
1989 = whenWOptM flag (warnUnusedLocals (filterOut (`elemNameSet` used_names) bound_names))
1990
1991 -------------------------
1992 -- Helpers
1993 warnUnusedGREs :: [GlobalRdrElt] -> RnM ()
1994 warnUnusedGREs gres = mapM_ warnUnusedGRE gres
1995
1996 warnUnusedLocals :: [Name] -> RnM ()
1997 warnUnusedLocals names = do
1998 fld_env <- mkFieldEnv <$> getGlobalRdrEnv
1999 mapM_ (warnUnusedLocal fld_env) names
2000
2001 warnUnusedLocal :: NameEnv (FieldLabelString, Name) -> Name -> RnM ()
2002 warnUnusedLocal fld_env name
2003 = when (reportable name) $
2004 addUnusedWarning occ (nameSrcSpan name)
2005 (ptext (sLit "Defined but not used"))
2006 where
2007 occ = case lookupNameEnv fld_env name of
2008 Just (fl, _) -> mkVarOccFS fl
2009 Nothing -> nameOccName name
2010
2011 warnUnusedGRE :: GlobalRdrElt -> RnM ()
2012 warnUnusedGRE gre@(GRE { gre_name = name, gre_lcl = lcl, gre_imp = is })
2013 | lcl = do fld_env <- mkFieldEnv <$> getGlobalRdrEnv
2014 warnUnusedLocal fld_env name
2015 | otherwise = when (reportable name) (mapM_ warn is)
2016 where
2017 occ = greOccName gre
2018 warn spec = addUnusedWarning occ span msg
2019 where
2020 span = importSpecLoc spec
2021 pp_mod = quotes (ppr (importSpecModule spec))
2022 msg = ptext (sLit "Imported from") <+> pp_mod <+> ptext (sLit "but not used")
2023
2024 -- | Make a map from selector names to field labels and parent tycon
2025 -- names, to be used when reporting unused record fields.
2026 mkFieldEnv :: GlobalRdrEnv -> NameEnv (FieldLabelString, Name)
2027 mkFieldEnv rdr_env = mkNameEnv [ (gre_name gre, (lbl, par_is (gre_par gre)))
2028 | gres <- occEnvElts rdr_env
2029 , gre <- gres
2030 , Just lbl <- [greLabel gre]
2031 ]
2032
2033 reportable :: Name -> Bool
2034 reportable name
2035 | isWiredInName name = False -- Don't report unused wired-in names
2036 -- Otherwise we get a zillion warnings
2037 -- from Data.Tuple
2038 | otherwise = not (startsWithUnderscore (nameOccName name))
2039
2040 addUnusedWarning :: OccName -> SrcSpan -> SDoc -> RnM ()
2041 addUnusedWarning occ span msg
2042 = addWarnAt span $
2043 sep [msg <> colon,
2044 nest 2 $ pprNonVarNameSpace (occNameSpace occ)
2045 <+> quotes (ppr occ)]
2046
2047 addNameClashErrRn :: RdrName -> [GlobalRdrElt] -> RnM ()
2048 addNameClashErrRn rdr_name gres
2049 | all isLocalGRE gres && not (all isRecFldGRE gres)
2050 -- If there are two or more *local* defns, we'll have reported
2051 = return () -- that already, and we don't want an error cascade
2052 | otherwise
2053 = addErr (vcat [ptext (sLit "Ambiguous occurrence") <+> quotes (ppr rdr_name),
2054 ptext (sLit "It could refer to") <+> vcat (msg1 : msgs)])
2055 where
2056 (np1:nps) = gres
2057 msg1 = ptext (sLit "either") <+> mk_ref np1
2058 msgs = [ptext (sLit " or") <+> mk_ref np | np <- nps]
2059 mk_ref gre = sep [nom <> comma, pprNameProvenance gre]
2060 where nom = case gre_par gre of
2061 FldParent { par_lbl = Just lbl } -> text "the field" <+> quotes (ppr lbl)
2062 _ -> quotes (ppr (gre_name gre))
2063
2064 shadowedNameWarn :: OccName -> [SDoc] -> SDoc
2065 shadowedNameWarn occ shadowed_locs
2066 = sep [ptext (sLit "This binding for") <+> quotes (ppr occ)
2067 <+> ptext (sLit "shadows the existing binding") <> plural shadowed_locs,
2068 nest 2 (vcat shadowed_locs)]
2069
2070 perhapsForallMsg :: SDoc
2071 perhapsForallMsg
2072 = vcat [ ptext (sLit "Perhaps you intended to use ExplicitForAll or similar flag")
2073 , ptext (sLit "to enable explicit-forall syntax: forall <tvs>. <type>")]
2074
2075 unknownSubordinateErr :: SDoc -> RdrName -> SDoc
2076 unknownSubordinateErr doc op -- Doc is "method of class" or
2077 -- "field of constructor"
2078 = quotes (ppr op) <+> ptext (sLit "is not a (visible)") <+> doc
2079
2080 badOrigBinding :: RdrName -> SDoc
2081 badOrigBinding name
2082 = ptext (sLit "Illegal binding of built-in syntax:") <+> ppr (rdrNameOcc name)
2083 -- The rdrNameOcc is because we don't want to print Prelude.(,)
2084
2085 dupNamesErr :: Outputable n => (n -> SrcSpan) -> [n] -> RnM ()
2086 dupNamesErr get_loc names
2087 = addErrAt big_loc $
2088 vcat [ptext (sLit "Conflicting definitions for") <+> quotes (ppr (head names)),
2089 locations]
2090 where
2091 locs = map get_loc names
2092 big_loc = foldr1 combineSrcSpans locs
2093 locations = ptext (sLit "Bound at:") <+> vcat (map ppr (sort locs))
2094
2095 kindSigErr :: Outputable a => a -> SDoc
2096 kindSigErr thing
2097 = hang (ptext (sLit "Illegal kind signature for") <+> quotes (ppr thing))
2098 2 (ptext (sLit "Perhaps you intended to use KindSignatures"))
2099
2100 badQualBndrErr :: RdrName -> SDoc
2101 badQualBndrErr rdr_name
2102 = ptext (sLit "Qualified name in binding position:") <+> ppr rdr_name
2103
2104 opDeclErr :: RdrName -> SDoc
2105 opDeclErr n
2106 = hang (ptext (sLit "Illegal declaration of a type or class operator") <+> quotes (ppr n))
2107 2 (ptext (sLit "Use TypeOperators to declare operators in type and declarations"))
2108
2109 checkTupSize :: Int -> RnM ()
2110 checkTupSize tup_size
2111 | tup_size <= mAX_TUPLE_SIZE
2112 = return ()
2113 | otherwise
2114 = addErr (sep [ptext (sLit "A") <+> int tup_size <> ptext (sLit "-tuple is too large for GHC"),
2115 nest 2 (parens (ptext (sLit "max size is") <+> int mAX_TUPLE_SIZE)),
2116 nest 2 (ptext (sLit "Workaround: use nested tuples or define a data type"))])
2117
2118 {-
2119 ************************************************************************
2120 * *
2121 \subsection{Contexts for renaming errors}
2122 * *
2123 ************************************************************************
2124 -}
2125
2126 data HsDocContext
2127 = TypeSigCtx SDoc
2128 | PatCtx
2129 | SpecInstSigCtx
2130 | DefaultDeclCtx
2131 | ForeignDeclCtx (Located RdrName)
2132 | DerivDeclCtx
2133 | RuleCtx FastString
2134 | TyDataCtx (Located RdrName)
2135 | TySynCtx (Located RdrName)
2136 | TyFamilyCtx (Located RdrName)
2137 | FamPatCtx (Located RdrName) -- The patterns of a type/data family instance
2138 | ConDeclCtx [Located RdrName]
2139 | ClassDeclCtx (Located RdrName)
2140 | ExprWithTySigCtx
2141 | TypBrCtx
2142 | HsTypeCtx
2143 | GHCiCtx
2144 | SpliceTypeCtx (LHsType RdrName)
2145 | ClassInstanceCtx
2146 | VectDeclCtx (Located RdrName)
2147 | GenericCtx SDoc -- Maybe we want to use this more!
2148
2149 withHsDocContext :: HsDocContext -> SDoc -> SDoc
2150 withHsDocContext ctxt doc = doc $$ inHsDocContext ctxt
2151
2152 inHsDocContext :: HsDocContext -> SDoc
2153 inHsDocContext ctxt = ptext (sLit "In") <+> pprHsDocContext ctxt
2154
2155 pprHsDocContext :: HsDocContext -> SDoc
2156 pprHsDocContext (GenericCtx doc) = doc
2157 pprHsDocContext (TypeSigCtx doc) = text "the type signature for" <+> doc
2158 pprHsDocContext PatCtx = text "a pattern type-signature"
2159 pprHsDocContext SpecInstSigCtx = text "a SPECIALISE instance pragma"
2160 pprHsDocContext DefaultDeclCtx = text "a `default' declaration"
2161 pprHsDocContext DerivDeclCtx = text "a deriving declaration"
2162 pprHsDocContext (RuleCtx name) = text "the transformation rule" <+> ftext name
2163 pprHsDocContext (TyDataCtx tycon) = text "the data type declaration for" <+> quotes (ppr tycon)
2164 pprHsDocContext (FamPatCtx tycon) = text "a type pattern of family instance for" <+> quotes (ppr tycon)
2165 pprHsDocContext (TySynCtx name) = text "the declaration for type synonym" <+> quotes (ppr name)
2166 pprHsDocContext (TyFamilyCtx name) = text "the declaration for type family" <+> quotes (ppr name)
2167 pprHsDocContext (ClassDeclCtx name) = text "the declaration for class" <+> quotes (ppr name)
2168 pprHsDocContext ExprWithTySigCtx = text "an expression type signature"
2169 pprHsDocContext TypBrCtx = text "a Template-Haskell quoted type"
2170 pprHsDocContext HsTypeCtx = text "a type argument"
2171 pprHsDocContext GHCiCtx = text "GHCi input"
2172 pprHsDocContext (SpliceTypeCtx hs_ty) = text "the spliced type" <+> quotes (ppr hs_ty)
2173 pprHsDocContext ClassInstanceCtx = text "TcSplice.reifyInstances"
2174
2175 pprHsDocContext (ForeignDeclCtx name)
2176 = ptext (sLit "the foreign declaration for") <+> quotes (ppr name)
2177 pprHsDocContext (ConDeclCtx [name])
2178 = text "the definition of data constructor" <+> quotes (ppr name)
2179 pprHsDocContext (ConDeclCtx names)
2180 = text "the definition of data constructors" <+> interpp'SP names
2181 pprHsDocContext (VectDeclCtx tycon)
2182 = ptext (sLit "the VECTORISE pragma for type constructor") <+> quotes (ppr tycon)