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