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