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