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