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