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