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