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