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