Lexer: Suggest adding 'let' on unexpected '=' token
[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,
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 { addErr (unknownSubordinateErr doc rdr_name)
486 ; return (mkUnboundName rdr_name) }
487 gres -> do { addNameClashErrRn rdr_name gres
488 ; return (gre_name (head gres)) } }
489 where
490 -- Note [Usage for sub-bndrs]
491 used_rdr_name gre
492 | isQual rdr_name = rdr_name
493 | otherwise = greUsedRdrName gre
494
495 lookupSubBndrGREs :: GlobalRdrEnv -> Parent -> RdrName -> [GlobalRdrElt]
496 -- If Parent = NoParent, just do a normal lookup
497 -- If Parent = Parent p then find all GREs that
498 -- (a) have parent p
499 -- (b) for Unqual, are in scope qualified or unqualified
500 -- for Qual, are in scope with that qualification
501 lookupSubBndrGREs env parent rdr_name
502 = case parent of
503 NoParent -> pickGREs rdr_name gres
504 ParentIs p
505 | isUnqual rdr_name -> filter (parent_is p) gres
506 | otherwise -> filter (parent_is p) (pickGREs rdr_name gres)
507
508 where
509 gres = lookupGlobalRdrEnv env (rdrNameOcc rdr_name)
510
511 parent_is p (GRE { gre_par = ParentIs p' }) = p == p'
512 parent_is _ _ = False
513
514 {-
515 Note [Family instance binders]
516 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
517 Consider
518 data family F a
519 data instance F T = X1 | X2
520
521 The 'data instance' decl has an *occurrence* of F (and T), and *binds*
522 X1 and X2. (This is unlike a normal data type declaration which would
523 bind F too.) So we want an AvailTC F [X1,X2].
524
525 Now consider a similar pair:
526 class C a where
527 data G a
528 instance C S where
529 data G S = Y1 | Y2
530
531 The 'data G S' *binds* Y1 and Y2, and has an *occurrence* of G.
532
533 But there is a small complication: in an instance decl, we don't use
534 qualified names on the LHS; instead we use the class to disambiguate.
535 Thus:
536 module M where
537 import Blib( G )
538 class C a where
539 data G a
540 instance C S where
541 data G S = Y1 | Y2
542 Even though there are two G's in scope (M.G and Blib.G), the occurrence
543 of 'G' in the 'instance C S' decl is unambiguous, because C has only
544 one associated type called G. This is exactly what happens for methods,
545 and it is only consistent to do the same thing for types. That's the
546 role of the function lookupTcdName; the (Maybe Name) give the class of
547 the encloseing instance decl, if any.
548
549 Note [Looking up Exact RdrNames]
550 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
551 Exact RdrNames are generated by Template Haskell. See Note [Binders
552 in Template Haskell] in Convert.
553
554 For data types and classes have Exact system Names in the binding
555 positions for constructors, TyCons etc. For example
556 [d| data T = MkT Int |]
557 when we splice in and Convert to HsSyn RdrName, we'll get
558 data (Exact (system Name "T")) = (Exact (system Name "MkT")) ...
559 These System names are generated by Convert.thRdrName
560
561 But, constructors and the like need External Names, not System Names!
562 So we do the following
563
564 * In RnEnv.newTopSrcBinder we spot Exact RdrNames that wrap a
565 non-External Name, and make an External name for it. This is
566 the name that goes in the GlobalRdrEnv
567
568 * When looking up an occurrence of an Exact name, done in
569 RnEnv.lookupExactOcc, we find the Name with the right unique in the
570 GlobalRdrEnv, and use the one from the envt -- it will be an
571 External Name in the case of the data type/constructor above.
572
573 * Exact names are also use for purely local binders generated
574 by TH, such as \x_33. x_33
575 Both binder and occurrence are Exact RdrNames. The occurrence
576 gets looked up in the LocalRdrEnv by RnEnv.lookupOccRn, and
577 misses, because lookupLocalRdrEnv always returns Nothing for
578 an Exact Name. Now we fall through to lookupExactOcc, which
579 will find the Name is not in the GlobalRdrEnv, so we just use
580 the Exact supplied Name.
581
582 Note [Splicing Exact names]
583 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
584 Consider the splice $(do { x <- newName "x"; return (VarE x) })
585 This will generate a (HsExpr RdrName) term that mentions the
586 Exact RdrName "x_56" (or whatever), but does not bind it. So
587 when looking such Exact names we want to check that it's in scope,
588 otherwise the type checker will get confused. To do this we need to
589 keep track of all the Names in scope, and the LocalRdrEnv does just that;
590 we consult it with RdrName.inLocalRdrEnvScope.
591
592 There is another wrinkle. With TH and -XDataKinds, consider
593 $( [d| data Nat = Zero
594 data T = MkT (Proxy 'Zero) |] )
595 After splicing, but before renaming we get this:
596 data Nat_77{tc} = Zero_78{d}
597 data T_79{tc} = MkT_80{d} (Proxy 'Zero_78{tc}) |] )
598 The occurrence of 'Zero in the data type for T has the right unique,
599 but it has a TcClsName name-space in its OccName. (This is set by
600 the ctxt_ns argument of Convert.thRdrName.) When we check that is
601 in scope in the GlobalRdrEnv, we need to look up the DataName namespace
602 too. (An alternative would be to make the GlobalRdrEnv also have
603 a Name -> GRE mapping.)
604
605 Note [Template Haskell ambiguity]
606 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
607 The GlobalRdrEnv invariant says that if
608 occ -> [gre1, ..., gren]
609 then the gres have distinct Names (INVARIANT 1 of GlobalRdrEnv).
610 This is guaranteed by extendGlobalRdrEnvRn (the dups check in add_gre).
611
612 So how can we get multiple gres in lookupExactOcc_maybe? Because in
613 TH we might use the same TH NameU in two different name spaces.
614 eg (Trac #7241):
615 $(newName "Foo" >>= \o -> return [DataD [] o [] [RecC o []] [''Show]])
616 Here we generate a type constructor and data constructor with the same
617 unique, but differnt name spaces.
618
619 It'd be nicer to rule this out in extendGlobalRdrEnvRn, but that would
620 mean looking up the OccName in every name-space, just in case, and that
621 seems a bit brutal. So it's just done here on lookup. But we might
622 need to revisit that choice.
623
624 Note [Usage for sub-bndrs]
625 ~~~~~~~~~~~~~~~~~~~~~~~~~~
626 If you have this
627 import qualified M( C( f ) )
628 instance M.C T where
629 f x = x
630 then is the qualified import M.f used? Obviously yes.
631 But the RdrName used in the instance decl is unqualified. In effect,
632 we fill in the qualification by looking for f's whose class is M.C
633 But when adding to the UsedRdrNames we must make that qualification
634 explicit (saying "used M.f"), otherwise we get "Redundant import of M.f".
635
636 So we make up a suitable (fake) RdrName. But be careful
637 import qualifed M
638 import M( C(f) )
639 instance C T where
640 f x = x
641 Here we want to record a use of 'f', not of 'M.f', otherwise
642 we'll miss the fact that the qualified import is redundant.
643
644 --------------------------------------------------
645 -- Occurrences
646 --------------------------------------------------
647 -}
648
649 getLookupOccRn :: RnM (Name -> Maybe Name)
650 getLookupOccRn
651 = do local_env <- getLocalRdrEnv
652 return (lookupLocalRdrOcc local_env . nameOccName)
653
654 lookupLocatedOccRn :: Located RdrName -> RnM (Located Name)
655 lookupLocatedOccRn = wrapLocM lookupOccRn
656
657 lookupLocalOccRn_maybe :: RdrName -> RnM (Maybe Name)
658 -- Just look in the local environment
659 lookupLocalOccRn_maybe rdr_name
660 = do { local_env <- getLocalRdrEnv
661 ; return (lookupLocalRdrEnv local_env rdr_name) }
662
663 lookupLocalOccThLvl_maybe :: Name -> RnM (Maybe (TopLevelFlag, ThLevel))
664 -- Just look in the local environment
665 lookupLocalOccThLvl_maybe name
666 = do { lcl_env <- getLclEnv
667 ; return (lookupNameEnv (tcl_th_bndrs lcl_env) name) }
668
669 -- lookupOccRn looks up an occurrence of a RdrName
670 lookupOccRn :: RdrName -> RnM Name
671 lookupOccRn rdr_name
672 = do { mb_name <- lookupOccRn_maybe rdr_name
673 ; case mb_name of
674 Just name -> return name
675 Nothing -> reportUnboundName rdr_name }
676
677 lookupKindOccRn :: RdrName -> RnM Name
678 -- Looking up a name occurring in a kind
679 lookupKindOccRn rdr_name
680 = do { mb_name <- lookupOccRn_maybe rdr_name
681 ; case mb_name of
682 Just name -> return name
683 Nothing -> reportUnboundName rdr_name }
684
685 -- lookupPromotedOccRn looks up an optionally promoted RdrName.
686 lookupTypeOccRn :: RdrName -> RnM Name
687 -- see Note [Demotion]
688 lookupTypeOccRn rdr_name
689 = do { mb_name <- lookupOccRn_maybe rdr_name
690 ; case mb_name of {
691 Just name -> return name ;
692 Nothing -> lookup_demoted rdr_name } }
693
694 lookup_demoted :: RdrName -> RnM Name
695 lookup_demoted rdr_name
696 | Just demoted_rdr <- demoteRdrName rdr_name
697 -- Maybe it's the name of a *data* constructor
698 = do { data_kinds <- xoptM Opt_DataKinds
699 ; mb_demoted_name <- lookupOccRn_maybe demoted_rdr
700 ; case mb_demoted_name of
701 Nothing -> reportUnboundName rdr_name
702 Just demoted_name
703 | data_kinds ->
704 do { whenWOptM Opt_WarnUntickedPromotedConstructors $
705 addWarn (untickedPromConstrWarn demoted_name)
706 ; return demoted_name }
707 | otherwise -> unboundNameX WL_Any rdr_name suggest_dk }
708
709 | otherwise
710 = reportUnboundName rdr_name
711
712 where
713 suggest_dk = ptext (sLit "A data constructor of that name is in scope; did you mean DataKinds?")
714 untickedPromConstrWarn name =
715 text "Unticked promoted constructor" <> colon <+> quotes (ppr name) <> dot
716 $$
717 hsep [ text "Use"
718 , quotes (char '\'' <> ppr name)
719 , text "instead of"
720 , quotes (ppr name) <> dot ]
721
722 {-
723 Note [Demotion]
724 ~~~~~~~~~~~~~~~
725 When the user writes:
726 data Nat = Zero | Succ Nat
727 foo :: f Zero -> Int
728
729 'Zero' in the type signature of 'foo' is parsed as:
730 HsTyVar ("Zero", TcClsName)
731
732 When the renamer hits this occurrence of 'Zero' it's going to realise
733 that it's not in scope. But because it is renaming a type, it knows
734 that 'Zero' might be a promoted data constructor, so it will demote
735 its namespace to DataName and do a second lookup.
736
737 The final result (after the renamer) will be:
738 HsTyVar ("Zero", DataName)
739 -}
740
741 -- Use this version to get tracing
742 --
743 -- lookupOccRn_maybe, lookupOccRn_maybe' :: RdrName -> RnM (Maybe Name)
744 -- lookupOccRn_maybe rdr_name
745 -- = do { mb_res <- lookupOccRn_maybe' rdr_name
746 -- ; gbl_rdr_env <- getGlobalRdrEnv
747 -- ; local_rdr_env <- getLocalRdrEnv
748 -- ; traceRn $ text "lookupOccRn_maybe" <+>
749 -- vcat [ ppr rdr_name <+> ppr (getUnique (rdrNameOcc rdr_name))
750 -- , ppr mb_res
751 -- , text "Lcl env" <+> ppr local_rdr_env
752 -- , text "Gbl env" <+> ppr [ (getUnique (nameOccName (gre_name (head gres'))),gres') | gres <- occEnvElts gbl_rdr_env
753 -- , let gres' = filter isLocalGRE gres, not (null gres') ] ]
754 -- ; return mb_res }
755
756 lookupOccRn_maybe :: RdrName -> RnM (Maybe Name)
757 -- lookupOccRn looks up an occurrence of a RdrName
758 lookupOccRn_maybe rdr_name
759 = do { local_env <- getLocalRdrEnv
760 ; case lookupLocalRdrEnv local_env rdr_name of {
761 Just name -> return (Just name) ;
762 Nothing -> do
763 { mb_name <- lookupGlobalOccRn_maybe rdr_name
764 ; case mb_name of {
765 Just name -> return (Just name) ;
766 Nothing -> do
767 { ns <- lookupQualifiedNameGHCi rdr_name
768 -- This test is not expensive,
769 -- and only happens for failed lookups
770 ; case ns of
771 (n:_) -> return (Just n) -- Unlikely to be more than one...?
772 [] -> return Nothing } } } } }
773
774 lookupGlobalOccRn :: RdrName -> RnM Name
775 -- lookupGlobalOccRn is like lookupOccRn, except that it looks in the global
776 -- environment. Adds an error message if the RdrName is not in scope.
777 lookupGlobalOccRn rdr_name
778 = do { mb_name <- lookupGlobalOccRn_maybe rdr_name
779 ; case mb_name of
780 Just n -> return n
781 Nothing -> do { traceRn (text "lookupGlobalOccRn" <+> ppr rdr_name)
782 ; unboundName WL_Global rdr_name } }
783
784 lookupInfoOccRn :: RdrName -> RnM [Name]
785 -- lookupInfoOccRn is intended for use in GHCi's ":info" command
786 -- It finds all the GREs that RdrName could mean, not complaining
787 -- about ambiguity, but rather returning them all
788 -- C.f. Trac #9881
789 lookupInfoOccRn rdr_name
790 | Just n <- isExact_maybe rdr_name -- e.g. (->)
791 = return [n]
792
793 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
794 = do { n <- lookupOrig rdr_mod rdr_occ
795 ; return [n] }
796
797 | otherwise
798 = do { rdr_env <- getGlobalRdrEnv
799 ; let ns = map gre_name (lookupGRE_RdrName rdr_name rdr_env)
800 ; qual_ns <- lookupQualifiedNameGHCi rdr_name
801 ; return (ns ++ (qual_ns `minusList` ns)) }
802
803 lookupGlobalOccRn_maybe :: RdrName -> RnM (Maybe Name)
804 -- No filter function; does not report an error on failure
805
806 lookupGlobalOccRn_maybe rdr_name
807 | Just n <- isExact_maybe rdr_name -- This happens in derived code
808 = do { n' <- lookupExactOcc n; return (Just n') }
809
810 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
811 = do { n <- lookupOrig rdr_mod rdr_occ
812 ; return (Just n) }
813
814 | otherwise
815 = do { mb_gre <- lookupGreRn_maybe rdr_name
816 ; case mb_gre of
817 Nothing -> return Nothing
818 Just gre -> return (Just (gre_name gre)) }
819
820
821 --------------------------------------------------
822 -- Lookup in the Global RdrEnv of the module
823 --------------------------------------------------
824
825 lookupGreRn_maybe :: RdrName -> RnM (Maybe GlobalRdrElt)
826 -- Look up the RdrName in the GlobalRdrEnv
827 -- Exactly one binding: records it as "used", return (Just gre)
828 -- No bindings: return Nothing
829 -- Many bindings: report "ambiguous", return an arbitrary (Just gre)
830 -- (This API is a bit strange; lookupGRERn2_maybe is simpler.
831 -- But it works and I don't want to fiddle too much.)
832 lookupGreRn_maybe rdr_name
833 = do { env <- getGlobalRdrEnv
834 ; case lookupGRE_RdrName rdr_name env of
835 [] -> return Nothing
836 [gre] -> do { addUsedRdrName True gre rdr_name
837 ; return (Just gre) }
838 gres -> do { addNameClashErrRn rdr_name gres
839 ; traceRn (text "name clash" <+> (ppr rdr_name $$ ppr gres $$ ppr env))
840 ; return (Just (head gres)) } }
841
842 lookupGreRn2_maybe :: RdrName -> RnM (Maybe GlobalRdrElt)
843 -- Look up the RdrName in the GlobalRdrEnv
844 -- Exactly one binding: record it as "used", return (Just gre)
845 -- No bindings: report "not in scope", return Nothing
846 -- Many bindings: report "ambiguous", return Nothing
847 lookupGreRn2_maybe rdr_name
848 = do { env <- getGlobalRdrEnv
849 ; case lookupGRE_RdrName rdr_name env of
850 [] -> do { _ <- unboundName WL_Global rdr_name
851 ; return Nothing }
852 [gre] -> do { addUsedRdrName True gre rdr_name
853 ; return (Just gre) }
854 gres -> do { addNameClashErrRn rdr_name gres
855 ; traceRn (text "name clash" <+> (ppr rdr_name $$ ppr gres $$ ppr env))
856 ; return Nothing } }
857
858 lookupGreAvailRn :: RdrName -> RnM (Name, AvailInfo)
859 -- Used in export lists
860 -- If not found or ambiguous, add error message, and fake with UnboundName
861 lookupGreAvailRn rdr_name
862 = do { mb_gre <- lookupGreRn2_maybe rdr_name
863 ; case mb_gre of {
864 Just gre -> return (gre_name gre, availFromGRE gre) ;
865 Nothing ->
866 do { traceRn (text "lookupGreRn" <+> ppr rdr_name)
867 ; let name = mkUnboundName rdr_name
868 ; return (name, Avail name) } } }
869
870 {-
871 *********************************************************
872 * *
873 Deprecations
874 * *
875 *********************************************************
876
877 Note [Handling of deprecations]
878 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
879 * We report deprecations at each *occurrence* of the deprecated thing
880 (see Trac #5867)
881
882 * We do not report deprecations for locally-defined names. For a
883 start, we may be exporting a deprecated thing. Also we may use a
884 deprecated thing in the defn of another deprecated things. We may
885 even use a deprecated thing in the defn of a non-deprecated thing,
886 when changing a module's interface.
887
888 * addUsedRdrNames: we do not report deprecations for sub-binders:
889 - the ".." completion for records
890 - the ".." in an export item 'T(..)'
891 - the things exported by a module export 'module M'
892 -}
893
894 addUsedRdrName :: Bool -> GlobalRdrElt -> RdrName -> RnM ()
895 -- Record usage of imported RdrNames
896 addUsedRdrName warn_if_deprec gre rdr
897 = do { unless (isLocalGRE gre) $
898 do { env <- getGblEnv
899 ; updMutVar (tcg_used_rdrnames env)
900 (\s -> Set.insert rdr s) }
901
902 ; when warn_if_deprec $
903 warnIfDeprecated gre }
904
905 addUsedRdrNames :: [RdrName] -> RnM ()
906 -- Record used sub-binders
907 -- We don't check for imported-ness here, because it's inconvenient
908 -- and not stritly necessary.
909 -- NB: no call to warnIfDeprecated; see Note [Handling of deprecations]
910 addUsedRdrNames rdrs
911 = do { env <- getGblEnv
912 ; updMutVar (tcg_used_rdrnames env)
913 (\s -> foldr Set.insert s rdrs) }
914
915 warnIfDeprecated :: GlobalRdrElt -> RnM ()
916 warnIfDeprecated gre@(GRE { gre_name = name, gre_imp = iss })
917 | (imp_spec : _) <- iss
918 = do { dflags <- getDynFlags
919 ; this_mod <- getModule
920 ; when (wopt Opt_WarnWarningsDeprecations dflags &&
921 not (nameIsLocalOrFrom this_mod name)) $
922 -- See Note [Handling of deprecations]
923 do { iface <- loadInterfaceForName doc name
924 ; case lookupImpDeprec iface gre of
925 Just txt -> addWarn (mk_msg imp_spec txt)
926 Nothing -> return () } }
927 | otherwise
928 = return ()
929 where
930 name_mod = ASSERT2( isExternalName name, ppr name ) nameModule name
931 doc = ptext (sLit "The name") <+> quotes (ppr name) <+> ptext (sLit "is mentioned explicitly")
932
933 mk_msg imp_spec txt
934 = sep [ sep [ ptext (sLit "In the use of")
935 <+> pprNonVarNameSpace (occNameSpace (nameOccName name))
936 <+> quotes (ppr name)
937 , parens imp_msg <> colon ]
938 , ppr txt ]
939 where
940 imp_mod = importSpecModule imp_spec
941 imp_msg = ptext (sLit "imported from") <+> ppr imp_mod <> extra
942 extra | imp_mod == moduleName name_mod = Outputable.empty
943 | otherwise = ptext (sLit ", but defined in") <+> ppr name_mod
944
945 lookupImpDeprec :: ModIface -> GlobalRdrElt -> Maybe WarningTxt
946 lookupImpDeprec iface gre
947 = mi_warn_fn iface (gre_name gre) `mplus` -- Bleat if the thing,
948 case gre_par gre of -- or its parent, is warn'd
949 ParentIs p -> mi_warn_fn iface p
950 NoParent -> Nothing
951
952 {-
953 Note [Used names with interface not loaded]
954 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
955 It's (just) possible to find a used
956 Name whose interface hasn't been loaded:
957
958 a) It might be a WiredInName; in that case we may not load
959 its interface (although we could).
960
961 b) It might be GHC.Real.fromRational, or GHC.Num.fromInteger
962 These are seen as "used" by the renamer (if -XRebindableSyntax)
963 is on), but the typechecker may discard their uses
964 if in fact the in-scope fromRational is GHC.Read.fromRational,
965 (see tcPat.tcOverloadedLit), and the typechecker sees that the type
966 is fixed, say, to GHC.Base.Float (see Inst.lookupSimpleInst).
967 In that obscure case it won't force the interface in.
968
969 In both cases we simply don't permit deprecations;
970 this is, after all, wired-in stuff.
971
972
973 *********************************************************
974 * *
975 GHCi support
976 * *
977 *********************************************************
978
979 A qualified name on the command line can refer to any module at
980 all: we try to load the interface if we don't already have it, just
981 as if there was an "import qualified M" declaration for every
982 module.
983
984 If we fail we just return Nothing, rather than bleating
985 about "attempting to use module ā€˜Dā€™ (./D.hs) which is not loaded"
986 which is what loadSrcInterface does.
987
988 Note [Safe Haskell and GHCi]
989 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
990 We DONT do this Safe Haskell as we need to check imports. We can
991 and should instead check the qualified import but at the moment
992 this requires some refactoring so leave as a TODO
993 -}
994
995 lookupQualifiedNameGHCi :: RdrName -> RnM [Name]
996 lookupQualifiedNameGHCi rdr_name
997 = -- We want to behave as we would for a source file import here,
998 -- and respect hiddenness of modules/packages, hence loadSrcInterface.
999 do { dflags <- getDynFlags
1000 ; is_ghci <- getIsGHCi
1001 ; go_for_it dflags is_ghci }
1002
1003 where
1004 go_for_it dflags is_ghci
1005 | Just (mod,occ) <- isQual_maybe rdr_name
1006 , is_ghci
1007 , gopt Opt_ImplicitImportQualified dflags -- Enables this GHCi behaviour
1008 , not (safeDirectImpsReq dflags) -- See Note [Safe Haskell and GHCi]
1009 = do { res <- loadSrcInterface_maybe doc mod False Nothing
1010 ; case res of
1011 Succeeded iface
1012 -> return [ name
1013 | avail <- mi_exports iface
1014 , name <- availNames avail
1015 , nameOccName name == occ ]
1016
1017 _ -> -- Either we couldn't load the interface, or
1018 -- we could but we didn't find the name in it
1019 do { traceRn (text "lookupQualifiedNameGHCi" <+> ppr rdr_name)
1020 ; return [] } }
1021
1022 | otherwise
1023 = return []
1024
1025 doc = ptext (sLit "Need to find") <+> ppr rdr_name
1026
1027 {-
1028 Note [Looking up signature names]
1029 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1030 lookupSigOccRn is used for type signatures and pragmas
1031 Is this valid?
1032 module A
1033 import M( f )
1034 f :: Int -> Int
1035 f x = x
1036 It's clear that the 'f' in the signature must refer to A.f
1037 The Haskell98 report does not stipulate this, but it will!
1038 So we must treat the 'f' in the signature in the same way
1039 as the binding occurrence of 'f', using lookupBndrRn
1040
1041 However, consider this case:
1042 import M( f )
1043 f :: Int -> Int
1044 g x = x
1045 We don't want to say 'f' is out of scope; instead, we want to
1046 return the imported 'f', so that later on the reanamer will
1047 correctly report "misplaced type sig".
1048
1049 Note [Signatures for top level things]
1050 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1051 data HsSigCtxt = ... | TopSigCtxt NameSet | ....
1052
1053 * The NameSet says what is bound in this group of bindings.
1054 We can't use isLocalGRE from the GlobalRdrEnv, because of this:
1055 f x = x
1056 $( ...some TH splice... )
1057 f :: Int -> Int
1058 When we encounter the signature for 'f', the binding for 'f'
1059 will be in the GlobalRdrEnv, and will be a LocalDef. Yet the
1060 signature is mis-placed
1061
1062 * For type signatures the NameSet should be the names bound by the
1063 value bindings; for fixity declarations, the NameSet should also
1064 include class sigs and record selectors
1065
1066 infix 3 `f` -- Yes, ok
1067 f :: C a => a -> a -- No, not ok
1068 class C a where
1069 f :: a -> a
1070 -}
1071
1072 data HsSigCtxt
1073 = TopSigCtxt NameSet -- At top level, binding these names
1074 -- See Note [Signatures for top level things]
1075 | LocalBindCtxt NameSet -- In a local binding, binding these names
1076 | ClsDeclCtxt Name -- Class decl for this class
1077 | InstDeclCtxt Name -- Intsance decl for this class
1078 | HsBootCtxt -- Top level of a hs-boot file
1079 | RoleAnnotCtxt NameSet -- A role annotation, with the names of all types
1080 -- in the group
1081
1082 lookupSigOccRn :: HsSigCtxt
1083 -> Sig RdrName
1084 -> Located RdrName -> RnM (Located Name)
1085 lookupSigOccRn ctxt sig = lookupSigCtxtOccRn ctxt (hsSigDoc sig)
1086
1087 -- | Lookup a name in relation to the names in a 'HsSigCtxt'
1088 lookupSigCtxtOccRn :: HsSigCtxt
1089 -> SDoc -- ^ description of thing we're looking up,
1090 -- like "type family"
1091 -> Located RdrName -> RnM (Located Name)
1092 lookupSigCtxtOccRn ctxt what
1093 = wrapLocM $ \ rdr_name ->
1094 do { mb_name <- lookupBindGroupOcc ctxt what rdr_name
1095 ; case mb_name of
1096 Left err -> do { addErr err; return (mkUnboundName rdr_name) }
1097 Right name -> return name }
1098
1099 lookupBindGroupOcc :: HsSigCtxt
1100 -> SDoc
1101 -> RdrName -> RnM (Either MsgDoc Name)
1102 -- Looks up the RdrName, expecting it to resolve to one of the
1103 -- bound names passed in. If not, return an appropriate error message
1104 --
1105 -- See Note [Looking up signature names]
1106 lookupBindGroupOcc ctxt what rdr_name
1107 | Just n <- isExact_maybe rdr_name
1108 = lookupExactOcc_either n -- allow for the possibility of missing Exacts;
1109 -- see Note [dataTcOccs and Exact Names]
1110 -- Maybe we should check the side conditions
1111 -- but it's a pain, and Exact things only show
1112 -- up when you know what you are doing
1113
1114 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
1115 = do { n' <- lookupOrig rdr_mod rdr_occ
1116 ; return (Right n') }
1117
1118 | otherwise
1119 = case ctxt of
1120 HsBootCtxt -> lookup_top (const True)
1121 TopSigCtxt ns -> lookup_top (`elemNameSet` ns)
1122 RoleAnnotCtxt ns -> lookup_top (`elemNameSet` ns)
1123 LocalBindCtxt ns -> lookup_group ns
1124 ClsDeclCtxt cls -> lookup_cls_op cls
1125 InstDeclCtxt cls -> lookup_cls_op cls
1126 where
1127 lookup_cls_op cls
1128 = do { env <- getGlobalRdrEnv
1129 ; let gres = lookupSubBndrGREs env (ParentIs cls) rdr_name
1130 ; case gres of
1131 [] -> return (Left (unknownSubordinateErr doc rdr_name))
1132 (gre:_) -> return (Right (gre_name gre)) }
1133 -- If there is more than one local GRE for the
1134 -- same OccName 'f', that will be reported separately
1135 -- as a duplicate top-level binding for 'f'
1136 where
1137 doc = ptext (sLit "method of class") <+> quotes (ppr cls)
1138
1139 lookup_top keep_me
1140 = do { env <- getGlobalRdrEnv
1141 ; let all_gres = lookupGlobalRdrEnv env (rdrNameOcc rdr_name)
1142 ; case filter (keep_me . gre_name) all_gres of
1143 [] | null all_gres -> bale_out_with Outputable.empty
1144 | otherwise -> bale_out_with local_msg
1145 (gre:_) -> return (Right (gre_name gre)) }
1146
1147 lookup_group bound_names -- Look in the local envt (not top level)
1148 = do { local_env <- getLocalRdrEnv
1149 ; case lookupLocalRdrEnv local_env rdr_name of
1150 Just n
1151 | n `elemNameSet` bound_names -> return (Right n)
1152 | otherwise -> bale_out_with local_msg
1153 Nothing -> bale_out_with Outputable.empty }
1154
1155 bale_out_with msg
1156 = return (Left (sep [ ptext (sLit "The") <+> what
1157 <+> ptext (sLit "for") <+> quotes (ppr rdr_name)
1158 , nest 2 $ ptext (sLit "lacks an accompanying binding")]
1159 $$ nest 2 msg))
1160
1161 local_msg = parens $ ptext (sLit "The") <+> what <+> ptext (sLit "must be given where")
1162 <+> quotes (ppr rdr_name) <+> ptext (sLit "is declared")
1163
1164
1165 ---------------
1166 lookupLocalTcNames :: HsSigCtxt -> SDoc -> RdrName -> RnM [Name]
1167 -- GHC extension: look up both the tycon and data con or variable.
1168 -- Used for top-level fixity signatures and deprecations.
1169 -- Complain if neither is in scope.
1170 -- See Note [Fixity signature lookup]
1171 lookupLocalTcNames ctxt what rdr_name
1172 = do { mb_gres <- mapM lookup (dataTcOccs rdr_name)
1173 ; let (errs, names) = splitEithers mb_gres
1174 ; when (null names) $ addErr (head errs) -- Bleat about one only
1175 ; return names }
1176 where
1177 lookup = lookupBindGroupOcc ctxt what
1178
1179 dataTcOccs :: RdrName -> [RdrName]
1180 -- Return both the given name and the same name promoted to the TcClsName
1181 -- namespace. This is useful when we aren't sure which we are looking at.
1182 -- See also Note [dataTcOccs and Exact Names]
1183 dataTcOccs rdr_name
1184 | isDataOcc occ || isVarOcc occ
1185 = [rdr_name, rdr_name_tc]
1186 | otherwise
1187 = [rdr_name]
1188 where
1189 occ = rdrNameOcc rdr_name
1190 rdr_name_tc = setRdrNameSpace rdr_name tcName
1191
1192 {-
1193 Note [dataTcOccs and Exact Names]
1194 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1195 Exact RdrNames can occur in code generated by Template Haskell, and generally
1196 those references are, well, exact. However, the TH `Name` type isn't expressive
1197 enough to always track the correct namespace information, so we sometimes get
1198 the right Unique but wrong namespace. Thus, we still have to do the double-lookup
1199 for Exact RdrNames.
1200
1201 There is also an awkward situation for built-in syntax. Example in GHCi
1202 :info []
1203 This parses as the Exact RdrName for nilDataCon, but we also want
1204 the list type constructor.
1205
1206 Note that setRdrNameSpace on an Exact name requires the Name to be External,
1207 which it always is for built in syntax.
1208
1209 *********************************************************
1210 * *
1211 Fixities
1212 * *
1213 *********************************************************
1214
1215 Note [Fixity signature lookup]
1216 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1217 A fixity declaration like
1218
1219 infixr 2 ?
1220
1221 can refer to a value-level operator, e.g.:
1222
1223 (?) :: String -> String -> String
1224
1225 or a type-level operator, like:
1226
1227 data (?) a b = A a | B b
1228
1229 so we extend the lookup of the reader name '?' to the TcClsName namespace, as
1230 well as the original namespace.
1231
1232 The extended lookup is also used in other places, like resolution of
1233 deprecation declarations, and lookup of names in GHCi.
1234 -}
1235
1236 --------------------------------
1237 type MiniFixityEnv = FastStringEnv (Located Fixity)
1238 -- Mini fixity env for the names we're about
1239 -- to bind, in a single binding group
1240 --
1241 -- It is keyed by the *FastString*, not the *OccName*, because
1242 -- the single fixity decl infix 3 T
1243 -- affects both the data constructor T and the type constrctor T
1244 --
1245 -- We keep the location so that if we find
1246 -- a duplicate, we can report it sensibly
1247
1248 --------------------------------
1249 -- Used for nested fixity decls to bind names along with their fixities.
1250 -- the fixities are given as a UFM from an OccName's FastString to a fixity decl
1251
1252 addLocalFixities :: MiniFixityEnv -> [Name] -> RnM a -> RnM a
1253 addLocalFixities mini_fix_env names thing_inside
1254 = extendFixityEnv (mapMaybe find_fixity names) thing_inside
1255 where
1256 find_fixity name
1257 = case lookupFsEnv mini_fix_env (occNameFS occ) of
1258 Just (L _ fix) -> Just (name, FixItem occ fix)
1259 Nothing -> Nothing
1260 where
1261 occ = nameOccName name
1262
1263 {-
1264 --------------------------------
1265 lookupFixity is a bit strange.
1266
1267 * Nested local fixity decls are put in the local fixity env, which we
1268 find with getFixtyEnv
1269
1270 * Imported fixities are found in the HIT or PIT
1271
1272 * Top-level fixity decls in this module may be for Names that are
1273 either Global (constructors, class operations)
1274 or Local/Exported (everything else)
1275 (See notes with RnNames.getLocalDeclBinders for why we have this split.)
1276 We put them all in the local fixity environment
1277 -}
1278
1279 lookupFixityRn :: Name -> RnM Fixity
1280 lookupFixityRn name
1281 | isUnboundName name
1282 = return (Fixity minPrecedence InfixL)
1283 -- Minimise errors from ubound names; eg
1284 -- a>0 `foo` b>0
1285 -- where 'foo' is not in scope, should not give an error (Trac #7937)
1286
1287 | otherwise
1288 = do { local_fix_env <- getFixityEnv
1289 ; case lookupNameEnv local_fix_env name of {
1290 Just (FixItem _ fix) -> return fix ;
1291 Nothing ->
1292
1293 do { this_mod <- getModule
1294 ; if nameIsLocalOrFrom this_mod name
1295 -- Local (and interactive) names are all in the
1296 -- fixity env, and don't have entries in the HPT
1297 then return defaultFixity
1298 else lookup_imported } } }
1299 where
1300 lookup_imported
1301 -- For imported names, we have to get their fixities by doing a
1302 -- loadInterfaceForName, and consulting the Ifaces that comes back
1303 -- from that, because the interface file for the Name might not
1304 -- have been loaded yet. Why not? Suppose you import module A,
1305 -- which exports a function 'f', thus;
1306 -- module CurrentModule where
1307 -- import A( f )
1308 -- module A( f ) where
1309 -- import B( f )
1310 -- Then B isn't loaded right away (after all, it's possible that
1311 -- nothing from B will be used). When we come across a use of
1312 -- 'f', we need to know its fixity, and it's then, and only
1313 -- then, that we load B.hi. That is what's happening here.
1314 --
1315 -- loadInterfaceForName will find B.hi even if B is a hidden module,
1316 -- and that's what we want.
1317 = do { iface <- loadInterfaceForName doc name
1318 ; traceRn (text "lookupFixityRn: looking up name in iface cache and found:" <+>
1319 vcat [ppr name, ppr $ mi_fix_fn iface (nameOccName name)])
1320 ; return (mi_fix_fn iface (nameOccName name)) }
1321
1322 doc = ptext (sLit "Checking fixity for") <+> ppr name
1323
1324 ---------------
1325 lookupTyFixityRn :: Located Name -> RnM Fixity
1326 lookupTyFixityRn (L _ n) = lookupFixityRn n
1327
1328 {-
1329 ************************************************************************
1330 * *
1331 Rebindable names
1332 Dealing with rebindable syntax is driven by the
1333 Opt_RebindableSyntax dynamic flag.
1334
1335 In "deriving" code we don't want to use rebindable syntax
1336 so we switch off the flag locally
1337
1338 * *
1339 ************************************************************************
1340
1341 Haskell 98 says that when you say "3" you get the "fromInteger" from the
1342 Standard Prelude, regardless of what is in scope. However, to experiment
1343 with having a language that is less coupled to the standard prelude, we're
1344 trying a non-standard extension that instead gives you whatever "Prelude.fromInteger"
1345 happens to be in scope. Then you can
1346 import Prelude ()
1347 import MyPrelude as Prelude
1348 to get the desired effect.
1349
1350 At the moment this just happens for
1351 * fromInteger, fromRational on literals (in expressions and patterns)
1352 * negate (in expressions)
1353 * minus (arising from n+k patterns)
1354 * "do" notation
1355
1356 We store the relevant Name in the HsSyn tree, in
1357 * HsIntegral/HsFractional/HsIsString
1358 * NegApp
1359 * NPlusKPat
1360 * HsDo
1361 respectively. Initially, we just store the "standard" name (PrelNames.fromIntegralName,
1362 fromRationalName etc), but the renamer changes this to the appropriate user
1363 name if Opt_NoImplicitPrelude is on. That is what lookupSyntaxName does.
1364
1365 We treat the orignal (standard) names as free-vars too, because the type checker
1366 checks the type of the user thing against the type of the standard thing.
1367 -}
1368
1369 lookupIfThenElse :: RnM (Maybe (SyntaxExpr Name), FreeVars)
1370 -- Different to lookupSyntaxName because in the non-rebindable
1371 -- case we desugar directly rather than calling an existing function
1372 -- Hence the (Maybe (SyntaxExpr Name)) return type
1373 lookupIfThenElse
1374 = do { rebind <- xoptM Opt_RebindableSyntax
1375 ; if not rebind
1376 then return (Nothing, emptyFVs)
1377 else do { ite <- lookupOccRn (mkVarUnqual (fsLit "ifThenElse"))
1378 ; return (Just (HsVar ite), unitFV ite) } }
1379
1380 lookupSyntaxName :: Name -- The standard name
1381 -> RnM (SyntaxExpr Name, FreeVars) -- Possibly a non-standard name
1382 lookupSyntaxName std_name
1383 = do { rebindable_on <- xoptM Opt_RebindableSyntax
1384 ; if not rebindable_on then
1385 return (HsVar std_name, emptyFVs)
1386 else
1387 -- Get the similarly named thing from the local environment
1388 do { usr_name <- lookupOccRn (mkRdrUnqual (nameOccName std_name))
1389 ; return (HsVar usr_name, unitFV usr_name) } }
1390
1391 lookupSyntaxNames :: [Name] -- Standard names
1392 -> RnM ([HsExpr Name], FreeVars) -- See comments with HsExpr.ReboundNames
1393 lookupSyntaxNames std_names
1394 = do { rebindable_on <- xoptM Opt_RebindableSyntax
1395 ; if not rebindable_on then
1396 return (map HsVar std_names, emptyFVs)
1397 else
1398 do { usr_names <- mapM (lookupOccRn . mkRdrUnqual . nameOccName) std_names
1399 ; return (map HsVar usr_names, mkFVs usr_names) } }
1400
1401 {-
1402 *********************************************************
1403 * *
1404 \subsection{Binding}
1405 * *
1406 *********************************************************
1407 -}
1408
1409 newLocalBndrRn :: Located RdrName -> RnM Name
1410 -- Used for non-top-level binders. These should
1411 -- never be qualified.
1412 newLocalBndrRn (L loc rdr_name)
1413 | Just name <- isExact_maybe rdr_name
1414 = return name -- This happens in code generated by Template Haskell
1415 -- See Note [Binders in Template Haskell] in Convert.hs
1416 | otherwise
1417 = do { unless (isUnqual rdr_name)
1418 (addErrAt loc (badQualBndrErr rdr_name))
1419 ; uniq <- newUnique
1420 ; return (mkInternalName uniq (rdrNameOcc rdr_name) loc) }
1421
1422 newLocalBndrsRn :: [Located RdrName] -> RnM [Name]
1423 newLocalBndrsRn = mapM newLocalBndrRn
1424
1425 ---------------------
1426 bindLocatedLocalsRn :: [Located RdrName]
1427 -> ([Name] -> RnM a)
1428 -> RnM a
1429 bindLocatedLocalsRn rdr_names_w_loc enclosed_scope
1430 = do { checkDupRdrNames rdr_names_w_loc
1431 ; checkShadowedRdrNames rdr_names_w_loc
1432
1433 -- Make fresh Names and extend the environment
1434 ; names <- newLocalBndrsRn rdr_names_w_loc
1435 ; bindLocalNames names (enclosed_scope names) }
1436
1437 bindLocalNames :: [Name] -> RnM a -> RnM a
1438 bindLocalNames names enclosed_scope
1439 = do { lcl_env <- getLclEnv
1440 ; let th_level = thLevel (tcl_th_ctxt lcl_env)
1441 th_bndrs' = extendNameEnvList (tcl_th_bndrs lcl_env)
1442 [ (n, (NotTopLevel, th_level)) | n <- names ]
1443 rdr_env' = extendLocalRdrEnvList (tcl_rdr lcl_env) names
1444 ; setLclEnv (lcl_env { tcl_th_bndrs = th_bndrs'
1445 , tcl_rdr = rdr_env' })
1446 enclosed_scope }
1447
1448 bindLocalNamesFV :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
1449 bindLocalNamesFV names enclosed_scope
1450 = do { (result, fvs) <- bindLocalNames names enclosed_scope
1451 ; return (result, delFVs names fvs) }
1452
1453
1454 -------------------------------------
1455 -- binLocalsFVRn is the same as bindLocalsRn
1456 -- except that it deals with free vars
1457 bindLocatedLocalsFV :: [Located RdrName]
1458 -> ([Name] -> RnM (a,FreeVars)) -> RnM (a, FreeVars)
1459 bindLocatedLocalsFV rdr_names enclosed_scope
1460 = bindLocatedLocalsRn rdr_names $ \ names ->
1461 do (thing, fvs) <- enclosed_scope names
1462 return (thing, delFVs names fvs)
1463
1464 -------------------------------------
1465
1466 extendTyVarEnvFVRn :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
1467 -- This function is used only in rnSourceDecl on InstDecl
1468 extendTyVarEnvFVRn tyvars thing_inside = bindLocalNamesFV tyvars thing_inside
1469
1470 -------------------------------------
1471 checkDupRdrNames :: [Located RdrName] -> RnM ()
1472 -- Check for duplicated names in a binding group
1473 checkDupRdrNames rdr_names_w_loc
1474 = mapM_ (dupNamesErr getLoc) dups
1475 where
1476 (_, dups) = removeDups (\n1 n2 -> unLoc n1 `compare` unLoc n2) rdr_names_w_loc
1477
1478 checkDupNames :: [Name] -> RnM ()
1479 -- Check for duplicated names in a binding group
1480 checkDupNames names = check_dup_names (filterOut isSystemName names)
1481 -- See Note [Binders in Template Haskell] in Convert
1482
1483 check_dup_names :: [Name] -> RnM ()
1484 check_dup_names names
1485 = mapM_ (dupNamesErr nameSrcSpan) dups
1486 where
1487 (_, dups) = removeDups (\n1 n2 -> nameOccName n1 `compare` nameOccName n2) names
1488
1489 ---------------------
1490 checkShadowedRdrNames :: [Located RdrName] -> RnM ()
1491 checkShadowedRdrNames loc_rdr_names
1492 = do { envs <- getRdrEnvs
1493 ; checkShadowedOccs envs get_loc_occ filtered_rdrs }
1494 where
1495 filtered_rdrs = filterOut (isExact . unLoc) loc_rdr_names
1496 -- See Note [Binders in Template Haskell] in Convert
1497 get_loc_occ (L loc rdr) = (loc,rdrNameOcc rdr)
1498
1499 checkDupAndShadowedNames :: (GlobalRdrEnv, LocalRdrEnv) -> [Name] -> RnM ()
1500 checkDupAndShadowedNames envs names
1501 = do { check_dup_names filtered_names
1502 ; checkShadowedOccs envs get_loc_occ filtered_names }
1503 where
1504 filtered_names = filterOut isSystemName names
1505 -- See Note [Binders in Template Haskell] in Convert
1506 get_loc_occ name = (nameSrcSpan name, nameOccName name)
1507
1508 -------------------------------------
1509 checkShadowedOccs :: (GlobalRdrEnv, LocalRdrEnv)
1510 -> (a -> (SrcSpan, OccName))
1511 -> [a] -> RnM ()
1512 checkShadowedOccs (global_env,local_env) get_loc_occ ns
1513 = whenWOptM Opt_WarnNameShadowing $
1514 do { traceRn (text "shadow" <+> ppr (map get_loc_occ ns))
1515 ; mapM_ check_shadow ns }
1516 where
1517 check_shadow n
1518 | startsWithUnderscore occ = return () -- Do not report shadowing for "_x"
1519 -- See Trac #3262
1520 | Just n <- mb_local = complain [ptext (sLit "bound at") <+> ppr (nameSrcLoc n)]
1521 | otherwise = do { gres' <- filterM is_shadowed_gre gres
1522 ; complain (map pprNameProvenance gres') }
1523 where
1524 (loc,occ) = get_loc_occ n
1525 mb_local = lookupLocalRdrOcc local_env occ
1526 gres = lookupGRE_RdrName (mkRdrUnqual occ) global_env
1527 -- Make an Unqualified RdrName and look that up, so that
1528 -- we don't find any GREs that are in scope qualified-only
1529
1530 complain [] = return ()
1531 complain pp_locs = addWarnAt loc (shadowedNameWarn occ pp_locs)
1532
1533 is_shadowed_gre :: GlobalRdrElt -> RnM Bool
1534 -- Returns False for record selectors that are shadowed, when
1535 -- punning or wild-cards are on (cf Trac #2723)
1536 is_shadowed_gre gre@(GRE { gre_par = ParentIs _ })
1537 = do { dflags <- getDynFlags
1538 ; if (xopt Opt_RecordPuns dflags || xopt Opt_RecordWildCards dflags)
1539 then do { is_fld <- is_rec_fld gre; return (not is_fld) }
1540 else return True }
1541 is_shadowed_gre _other = return True
1542
1543 is_rec_fld gre -- Return True for record selector ids
1544 | isLocalGRE gre = do { RecFields _ fld_set <- getRecFieldEnv
1545 ; return (gre_name gre `elemNameSet` fld_set) }
1546 | otherwise = do { sel_id <- tcLookupField (gre_name gre)
1547 ; return (isRecordSelector sel_id) }
1548
1549 {-
1550 ************************************************************************
1551 * *
1552 What to do when a lookup fails
1553 * *
1554 ************************************************************************
1555 -}
1556
1557 data WhereLooking = WL_Any -- Any binding
1558 | WL_Global -- Any top-level binding (local or imported)
1559 | WL_LocalTop -- Any top-level binding in this module
1560
1561 reportUnboundName :: RdrName -> RnM Name
1562 reportUnboundName rdr = unboundName WL_Any rdr
1563
1564 unboundName :: WhereLooking -> RdrName -> RnM Name
1565 unboundName wl rdr = unboundNameX wl rdr Outputable.empty
1566
1567 unboundNameX :: WhereLooking -> RdrName -> SDoc -> RnM Name
1568 unboundNameX where_look rdr_name extra
1569 = do { show_helpful_errors <- goptM Opt_HelpfulErrors
1570 ; let what = pprNonVarNameSpace (occNameSpace (rdrNameOcc rdr_name))
1571 err = unknownNameErr what rdr_name $$ extra
1572 ; if not show_helpful_errors
1573 then addErr err
1574 else do { suggestions <- unknownNameSuggestErr where_look rdr_name
1575 ; addErr (err $$ suggestions) }
1576 ; return (mkUnboundName rdr_name) }
1577
1578 unknownNameErr :: SDoc -> RdrName -> SDoc
1579 unknownNameErr what rdr_name
1580 = vcat [ hang (ptext (sLit "Not in scope:"))
1581 2 (what <+> quotes (ppr rdr_name))
1582 , extra ]
1583 where
1584 extra | rdr_name == forall_tv_RDR = perhapsForallMsg
1585 | otherwise = Outputable.empty
1586
1587 type HowInScope = Either SrcSpan ImpDeclSpec
1588 -- Left loc => locally bound at loc
1589 -- Right ispec => imported as specified by ispec
1590
1591 unknownNameSuggestErr :: WhereLooking -> RdrName -> RnM SDoc
1592 unknownNameSuggestErr where_look tried_rdr_name
1593 = do { local_env <- getLocalRdrEnv
1594 ; global_env <- getGlobalRdrEnv
1595 ; dflags <- getDynFlags
1596
1597 ; let all_possibilities :: [(String, (RdrName, HowInScope))]
1598 all_possibilities
1599 = [ (showPpr dflags r, (r, Left loc))
1600 | (r,loc) <- local_possibilities local_env ]
1601 ++ [ (showPpr dflags r, rp) | (r, rp) <- global_possibilities global_env ]
1602
1603 suggest = fuzzyLookup (showPpr dflags tried_rdr_name) all_possibilities
1604 perhaps = ptext (sLit "Perhaps you meant")
1605 extra_err = case suggest of
1606 [] -> Outputable.empty
1607 [p] -> perhaps <+> pp_item p
1608 ps -> sep [ perhaps <+> ptext (sLit "one of these:")
1609 , nest 2 (pprWithCommas pp_item ps) ]
1610 ; return extra_err }
1611 where
1612 pp_item :: (RdrName, HowInScope) -> SDoc
1613 pp_item (rdr, Left loc) = pp_ns rdr <+> quotes (ppr rdr) <+> loc' -- Locally defined
1614 where loc' = case loc of
1615 UnhelpfulSpan l -> parens (ppr l)
1616 RealSrcSpan l -> parens (ptext (sLit "line") <+> int (srcSpanStartLine l))
1617 pp_item (rdr, Right is) = pp_ns rdr <+> quotes (ppr rdr) <+> -- Imported
1618 parens (ptext (sLit "imported from") <+> ppr (is_mod is))
1619
1620 pp_ns :: RdrName -> SDoc
1621 pp_ns rdr | ns /= tried_ns = pprNameSpace ns
1622 | otherwise = Outputable.empty
1623 where ns = rdrNameSpace rdr
1624
1625 tried_occ = rdrNameOcc tried_rdr_name
1626 tried_is_sym = isSymOcc tried_occ
1627 tried_ns = occNameSpace tried_occ
1628 tried_is_qual = isQual tried_rdr_name
1629
1630 correct_name_space occ = nameSpacesRelated (occNameSpace occ) tried_ns
1631 && isSymOcc occ == tried_is_sym
1632 -- Treat operator and non-operators as non-matching
1633 -- This heuristic avoids things like
1634 -- Not in scope 'f'; perhaps you meant '+' (from Prelude)
1635
1636 local_ok = case where_look of { WL_Any -> True; _ -> False }
1637 local_possibilities :: LocalRdrEnv -> [(RdrName, SrcSpan)]
1638 local_possibilities env
1639 | tried_is_qual = []
1640 | not local_ok = []
1641 | otherwise = [ (mkRdrUnqual occ, nameSrcSpan name)
1642 | name <- localRdrEnvElts env
1643 , let occ = nameOccName name
1644 , correct_name_space occ]
1645
1646 gre_ok :: GlobalRdrElt -> Bool
1647 gre_ok = case where_look of
1648 WL_LocalTop -> isLocalGRE
1649 _ -> \_ -> True
1650
1651 global_possibilities :: GlobalRdrEnv -> [(RdrName, (RdrName, HowInScope))]
1652 global_possibilities global_env
1653 | tried_is_qual = [ (rdr_qual, (rdr_qual, how))
1654 | gre <- globalRdrEnvElts global_env
1655 , gre_ok gre
1656 , let name = gre_name gre
1657 occ = nameOccName name
1658 , correct_name_space occ
1659 , (mod, how) <- quals_in_scope gre
1660 , let rdr_qual = mkRdrQual mod occ ]
1661
1662 | otherwise = [ (rdr_unqual, pair)
1663 | gre <- globalRdrEnvElts global_env
1664 , gre_ok gre
1665 , let name = gre_name gre
1666 occ = nameOccName name
1667 rdr_unqual = mkRdrUnqual occ
1668 , correct_name_space occ
1669 , pair <- case (unquals_in_scope gre, quals_only gre) of
1670 (how:_, _) -> [ (rdr_unqual, how) ]
1671 ([], pr:_) -> [ pr ] -- See Note [Only-quals]
1672 ([], []) -> [] ]
1673
1674 -- Note [Only-quals]
1675 -- The second alternative returns those names with the same
1676 -- OccName as the one we tried, but live in *qualified* imports
1677 -- e.g. if you have:
1678 --
1679 -- > import qualified Data.Map as Map
1680 -- > foo :: Map
1681 --
1682 -- then we suggest @Map.Map@.
1683
1684 --------------------
1685 unquals_in_scope :: GlobalRdrElt -> [HowInScope]
1686 unquals_in_scope (GRE { gre_name = n, gre_lcl = lcl, gre_imp = is })
1687 | lcl = [ Left (nameSrcSpan n) ]
1688 | otherwise = [ Right ispec
1689 | i <- is, let ispec = is_decl i
1690 , not (is_qual ispec) ]
1691
1692 --------------------
1693 quals_in_scope :: GlobalRdrElt -> [(ModuleName, HowInScope)]
1694 -- Ones for which the qualified version is in scope
1695 quals_in_scope (GRE { gre_name = n, gre_lcl = lcl, gre_imp = is })
1696 | lcl = case nameModule_maybe n of
1697 Nothing -> []
1698 Just m -> [(moduleName m, Left (nameSrcSpan n))]
1699 | otherwise = [ (is_as ispec, Right ispec)
1700 | i <- is, let ispec = is_decl i ]
1701
1702 --------------------
1703 quals_only :: GlobalRdrElt -> [(RdrName, HowInScope)]
1704 -- Ones for which *only* the qualified version is in scope
1705 quals_only (GRE { gre_name = n, gre_imp = is })
1706 = [ (mkRdrQual (is_as ispec) (nameOccName n), Right ispec)
1707 | i <- is, let ispec = is_decl i, is_qual ispec ]
1708
1709 {-
1710 ************************************************************************
1711 * *
1712 \subsection{Free variable manipulation}
1713 * *
1714 ************************************************************************
1715 -}
1716
1717 -- A useful utility
1718 addFvRn :: FreeVars -> RnM (thing, FreeVars) -> RnM (thing, FreeVars)
1719 addFvRn fvs1 thing_inside = do { (res, fvs2) <- thing_inside
1720 ; return (res, fvs1 `plusFV` fvs2) }
1721
1722 mapFvRn :: (a -> RnM (b, FreeVars)) -> [a] -> RnM ([b], FreeVars)
1723 mapFvRn f xs = do stuff <- mapM f xs
1724 case unzip stuff of
1725 (ys, fvs_s) -> return (ys, plusFVs fvs_s)
1726
1727 mapMaybeFvRn :: (a -> RnM (b, FreeVars)) -> Maybe a -> RnM (Maybe b, FreeVars)
1728 mapMaybeFvRn _ Nothing = return (Nothing, emptyFVs)
1729 mapMaybeFvRn f (Just x) = do { (y, fvs) <- f x; return (Just y, fvs) }
1730
1731 -- because some of the rename functions are CPSed:
1732 -- maps the function across the list from left to right;
1733 -- collects all the free vars into one set
1734 mapFvRnCPS :: (a -> (b -> RnM c) -> RnM c)
1735 -> [a] -> ([b] -> RnM c) -> RnM c
1736
1737 mapFvRnCPS _ [] cont = cont []
1738 mapFvRnCPS f (x:xs) cont = f x $ \ x' ->
1739 mapFvRnCPS f xs $ \ xs' ->
1740 cont (x':xs')
1741
1742 {-
1743 ************************************************************************
1744 * *
1745 \subsection{Envt utility functions}
1746 * *
1747 ************************************************************************
1748 -}
1749
1750 warnUnusedTopBinds :: [GlobalRdrElt] -> RnM ()
1751 warnUnusedTopBinds gres
1752 = whenWOptM Opt_WarnUnusedTopBinds
1753 $ do env <- getGblEnv
1754 let isBoot = tcg_src env == HsBootFile
1755 let noParent gre = case gre_par gre of
1756 NoParent -> True
1757 ParentIs _ -> False
1758 -- Don't warn about unused bindings with parents in
1759 -- .hs-boot files, as you are sometimes required to give
1760 -- unused bindings (trac #3449).
1761 -- HOWEVER, in a signature file, you are never obligated to put a
1762 -- definition in the main text. Thus, if you define something
1763 -- and forget to export it, we really DO want to warn.
1764 gres' = if isBoot then filter noParent gres
1765 else gres
1766 warnUnusedGREs gres'
1767
1768 warnUnusedLocalBinds, warnUnusedMatches :: [Name] -> FreeVars -> RnM ()
1769 warnUnusedLocalBinds = check_unused Opt_WarnUnusedLocalBinds
1770 warnUnusedMatches = check_unused Opt_WarnUnusedMatches
1771
1772 check_unused :: WarningFlag -> [Name] -> FreeVars -> RnM ()
1773 check_unused flag bound_names used_names
1774 = whenWOptM flag (warnUnusedLocals (filterOut (`elemNameSet` used_names) bound_names))
1775
1776 -------------------------
1777 -- Helpers
1778 warnUnusedGREs :: [GlobalRdrElt] -> RnM ()
1779 warnUnusedGREs gres = mapM_ warnUnusedGRE gres
1780
1781 warnUnusedLocals :: [Name] -> RnM ()
1782 warnUnusedLocals names = mapM_ warnUnusedLocal names
1783
1784 warnUnusedLocal :: Name -> RnM ()
1785 warnUnusedLocal name
1786 = when (reportable name) $
1787 addUnusedWarning name (nameSrcSpan name)
1788 (ptext (sLit "Defined but not used"))
1789
1790 warnUnusedGRE :: GlobalRdrElt -> RnM ()
1791 warnUnusedGRE (GRE { gre_name = name, gre_lcl = lcl, gre_imp = is })
1792 | lcl = warnUnusedLocal name
1793 | otherwise = when (reportable name) (mapM_ warn is)
1794 where
1795 warn spec = addUnusedWarning name span msg
1796 where
1797 span = importSpecLoc spec
1798 pp_mod = quotes (ppr (importSpecModule spec))
1799 msg = ptext (sLit "Imported from") <+> pp_mod <+> ptext (sLit "but not used")
1800
1801 reportable :: Name -> Bool
1802 reportable name
1803 | isWiredInName name = False -- Don't report unused wired-in names
1804 -- Otherwise we get a zillion warnings
1805 -- from Data.Tuple
1806 | otherwise = not (startsWithUnderscore (nameOccName name))
1807
1808 addUnusedWarning :: Name -> SrcSpan -> SDoc -> RnM ()
1809 addUnusedWarning name span msg
1810 = addWarnAt span $
1811 sep [msg <> colon,
1812 nest 2 $ pprNonVarNameSpace (occNameSpace (nameOccName name))
1813 <+> quotes (ppr name)]
1814
1815 addNameClashErrRn :: RdrName -> [GlobalRdrElt] -> RnM ()
1816 addNameClashErrRn rdr_name gres
1817 | all isLocalGRE gres -- If there are two or more *local* defns, we'll have reported
1818 = return () -- that already, and we don't want an error cascade
1819 | otherwise
1820 = addErr (vcat [ptext (sLit "Ambiguous occurrence") <+> quotes (ppr rdr_name),
1821 ptext (sLit "It could refer to") <+> vcat (msg1 : msgs)])
1822 where
1823 (np1:nps) = gres
1824 msg1 = ptext (sLit "either") <+> mk_ref np1
1825 msgs = [ptext (sLit " or") <+> mk_ref np | np <- nps]
1826 mk_ref gre = sep [quotes (ppr (gre_name gre)) <> comma, pprNameProvenance gre]
1827
1828 shadowedNameWarn :: OccName -> [SDoc] -> SDoc
1829 shadowedNameWarn occ shadowed_locs
1830 = sep [ptext (sLit "This binding for") <+> quotes (ppr occ)
1831 <+> ptext (sLit "shadows the existing binding") <> plural shadowed_locs,
1832 nest 2 (vcat shadowed_locs)]
1833
1834 perhapsForallMsg :: SDoc
1835 perhapsForallMsg
1836 = vcat [ ptext (sLit "Perhaps you intended to use ExplicitForAll or similar flag")
1837 , ptext (sLit "to enable explicit-forall syntax: forall <tvs>. <type>")]
1838
1839 unknownSubordinateErr :: SDoc -> RdrName -> SDoc
1840 unknownSubordinateErr doc op -- Doc is "method of class" or
1841 -- "field of constructor"
1842 = quotes (ppr op) <+> ptext (sLit "is not a (visible)") <+> doc
1843
1844 badOrigBinding :: RdrName -> SDoc
1845 badOrigBinding name
1846 = ptext (sLit "Illegal binding of built-in syntax:") <+> ppr (rdrNameOcc name)
1847 -- The rdrNameOcc is because we don't want to print Prelude.(,)
1848
1849 dupNamesErr :: Outputable n => (n -> SrcSpan) -> [n] -> RnM ()
1850 dupNamesErr get_loc names
1851 = addErrAt big_loc $
1852 vcat [ptext (sLit "Conflicting definitions for") <+> quotes (ppr (head names)),
1853 locations]
1854 where
1855 locs = map get_loc names
1856 big_loc = foldr1 combineSrcSpans locs
1857 locations = ptext (sLit "Bound at:") <+> vcat (map ppr (sort locs))
1858
1859 kindSigErr :: Outputable a => a -> SDoc
1860 kindSigErr thing
1861 = hang (ptext (sLit "Illegal kind signature for") <+> quotes (ppr thing))
1862 2 (ptext (sLit "Perhaps you intended to use KindSignatures"))
1863
1864 badQualBndrErr :: RdrName -> SDoc
1865 badQualBndrErr rdr_name
1866 = ptext (sLit "Qualified name in binding position:") <+> ppr rdr_name
1867
1868 opDeclErr :: RdrName -> SDoc
1869 opDeclErr n
1870 = hang (ptext (sLit "Illegal declaration of a type or class operator") <+> quotes (ppr n))
1871 2 (ptext (sLit "Use TypeOperators to declare operators in type and declarations"))
1872
1873 checkTupSize :: Int -> RnM ()
1874 checkTupSize tup_size
1875 | tup_size <= mAX_TUPLE_SIZE
1876 = return ()
1877 | otherwise
1878 = addErr (sep [ptext (sLit "A") <+> int tup_size <> ptext (sLit "-tuple is too large for GHC"),
1879 nest 2 (parens (ptext (sLit "max size is") <+> int mAX_TUPLE_SIZE)),
1880 nest 2 (ptext (sLit "Workaround: use nested tuples or define a data type"))])
1881
1882 {-
1883 ************************************************************************
1884 * *
1885 \subsection{Contexts for renaming errors}
1886 * *
1887 ************************************************************************
1888 -}
1889
1890 data HsDocContext
1891 = TypeSigCtx SDoc
1892 | PatCtx
1893 | SpecInstSigCtx
1894 | DefaultDeclCtx
1895 | ForeignDeclCtx (Located RdrName)
1896 | DerivDeclCtx
1897 | RuleCtx FastString
1898 | TyDataCtx (Located RdrName)
1899 | TySynCtx (Located RdrName)
1900 | TyFamilyCtx (Located RdrName)
1901 | ConDeclCtx [Located RdrName]
1902 | ClassDeclCtx (Located RdrName)
1903 | ExprWithTySigCtx
1904 | TypBrCtx
1905 | HsTypeCtx
1906 | GHCiCtx
1907 | SpliceTypeCtx (LHsType RdrName)
1908 | ClassInstanceCtx
1909 | VectDeclCtx (Located RdrName)
1910 | GenericCtx SDoc -- Maybe we want to use this more!
1911
1912 docOfHsDocContext :: HsDocContext -> SDoc
1913 docOfHsDocContext (GenericCtx doc) = doc
1914 docOfHsDocContext (TypeSigCtx doc) = text "In the type signature for" <+> doc
1915 docOfHsDocContext PatCtx = text "In a pattern type-signature"
1916 docOfHsDocContext SpecInstSigCtx = text "In a SPECIALISE instance pragma"
1917 docOfHsDocContext DefaultDeclCtx = text "In a `default' declaration"
1918 docOfHsDocContext (ForeignDeclCtx name) = ptext (sLit "In the foreign declaration for") <+> ppr name
1919 docOfHsDocContext DerivDeclCtx = text "In a deriving declaration"
1920 docOfHsDocContext (RuleCtx name) = text "In the transformation rule" <+> ftext name
1921 docOfHsDocContext (TyDataCtx tycon) = text "In the data type declaration for" <+> quotes (ppr tycon)
1922 docOfHsDocContext (TySynCtx name) = text "In the declaration for type synonym" <+> quotes (ppr name)
1923 docOfHsDocContext (TyFamilyCtx name) = text "In the declaration for type family" <+> quotes (ppr name)
1924
1925 docOfHsDocContext (ConDeclCtx [name])
1926 = text "In the definition of data constructor" <+> quotes (ppr name)
1927 docOfHsDocContext (ConDeclCtx names)
1928 = text "In the definition of data constructors" <+> interpp'SP names
1929
1930 docOfHsDocContext (ClassDeclCtx name) = text "In the declaration for class" <+> ppr name
1931 docOfHsDocContext ExprWithTySigCtx = text "In an expression type signature"
1932 docOfHsDocContext TypBrCtx = ptext (sLit "In a Template-Haskell quoted type")
1933 docOfHsDocContext HsTypeCtx = text "In a type argument"
1934 docOfHsDocContext GHCiCtx = ptext (sLit "In GHCi input")
1935 docOfHsDocContext (SpliceTypeCtx hs_ty) = ptext (sLit "In the spliced type") <+> ppr hs_ty
1936 docOfHsDocContext ClassInstanceCtx = ptext (sLit "TcSplice.reifyInstances")
1937 docOfHsDocContext (VectDeclCtx tycon) = ptext (sLit "In the VECTORISE pragma for type constructor") <+> quotes (ppr tycon)