2 (c) The GRASP/AQUA Project, Glasgow University, 1992-2006
4 \section[RnEnv]{Environment manipulation for the renamer monad}
11 lookupLocatedTopBndrRn
, lookupTopBndrRn
,
12 lookupLocatedOccRn
, lookupOccRn
, lookupOccRn_maybe
,
13 lookupLocalOccRn_maybe
, lookupInfoOccRn
,
14 lookupLocalOccThLvl_maybe
,
15 lookupTypeOccRn
, lookupKindOccRn
,
16 lookupGlobalOccRn
, lookupGlobalOccRn_maybe
,
17 lookupOccRn_overloaded
, lookupGlobalOccRn_overloaded
,
18 reportUnboundName
, unknownNameSuggestions
,
21 HsSigCtxt
(..), lookupLocalTcNames
, lookupSigOccRn
,
24 lookupFixityRn
, lookupTyFixityRn
,
25 lookupInstDeclBndr
, lookupSubBndrOcc
, lookupFamInstName
,
26 lookupSubBndrGREs
, lookupConstructorFields
,
27 lookupSyntaxName
, lookupSyntaxNames
, lookupIfThenElse
,
30 addUsedGRE
, addUsedGREs
, addUsedDataCons
,
32 newLocalBndrRn
, newLocalBndrsRn
,
33 bindLocalNames
, bindLocalNamesFV
,
36 bindLocatedLocalsFV
, bindLocatedLocalsRn
,
39 checkDupRdrNames
, checkShadowedRdrNames
,
40 checkDupNames
, checkDupAndShadowedNames
, checkTupSize
,
41 addFvRn
, mapFvRn
, mapMaybeFvRn
, mapFvRnCPS
,
43 warnUnusedTopBinds
, warnUnusedLocalBinds
,
45 dataTcOccs
, kindSigErr
, perhapsForallMsg
, unknownSubordinateErr
,
46 HsDocContext
(..), docOfHsDocContext
49 #include
"HsVersions.h"
51 import LoadIface
( loadInterfaceForName
, loadSrcInterface_maybe
)
58 import RdrHsSyn
( setRdrNameSpace
)
67 import PrelNames
( mkUnboundName
, isUnboundName
, rOOT_MAIN
, forall_tv_RDR
)
68 import ErrUtils
( MsgDoc
)
69 import BasicTypes
( Fixity
(..), FixityDirection
(..), minPrecedence
, defaultFixity
)
74 import BasicTypes
( TopLevelFlag
(..) )
75 import ListSetOps
( removeDups
)
80 import Data
.Function
( on
)
81 import ListSetOps
( minusList
)
82 import Constants
( mAX_TUPLE_SIZE
)
85 *********************************************************
89 *********************************************************
91 Note [Signature lazy interface loading]
92 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
94 GHC's lazy interface loading can be a bit confusing, so this Note is an
95 empirical description of what happens in one interesting case. When
96 compiling a signature module against an its implementation, we do NOT
97 load interface files associated with its names until after the type
98 checking phase. For example:
104 Suppose we compile this with -sig-of "A is ASig":
110 module A(module B) where
113 During type checking, we'll load A.hi because we need to know what the
114 RdrEnv for the module is, but we DO NOT load the interface for B.hi!
115 It's wholly unnecessary: our local definition 'data T' in ASig is all
116 the information we need to finish type checking. This is contrast to
117 type checking of ordinary Haskell files, in which we would not have the
118 local definition "data T" and would need to consult B.hi immediately.
119 (Also, this situation never occurs for hs-boot files, since you're not
120 allowed to reexport from another module.)
122 After type checking, we then check that the types we provided are
123 consistent with the backing implementation (in checkHiBootOrHsigIface).
124 At this point, B.hi is loaded, because we need something to compare
127 I discovered this behavior when trying to figure out why type class
128 instances for Data.Map weren't in the EPS when I was type checking a
129 test very much like ASig (sigof02dm): the associated interface hadn't
130 been loaded yet! (The larger issue is a moot point, since an instance
131 declared in a signature can never be a duplicate.)
133 This behavior might change in the future. Consider this
137 {-# DEPRECATED T, f "Don't use" #-}
141 One might conceivably want to report deprecation warnings
when compiling
142 ASig with
-sig
-of B
, in which
case we need to look at B
.hi to
find the
143 deprecation warnings during renaming
. At the moment
, you don
't get
any
144 warning
until you use the identifier further downstream
. This would
145 require adjusting addUsedGRE so that during signature compilation
,
146 we
do not report deprecation warnings for LocalDef
. See also
147 Note
[Handling
of deprecations
]
150 newTopSrcBinder
:: Located RdrName
-> RnM Name
151 newTopSrcBinder
(L loc rdr_name
)
152 | Just name
<- isExact_maybe rdr_name
153 = -- This is here to catch
154 -- (a) Exact-name binders created by Template Haskell
155 -- (b) The PrelBase defn of (say) [] and similar, for which
156 -- the parser reads the special syntax and returns an Exact RdrName
157 -- We are at a binding site for the name, so check first that it
158 -- the current module is the correct one; otherwise GHC can get
159 -- very confused indeed. This test rejects code like
160 -- data T = (,) Int Int
161 -- unless we are in GHC.Tup
162 if isExternalName name
then
163 do { this_mod
<- getModule
164 ; unless (this_mod
== nameModule name
)
165 (addErrAt loc
(badOrigBinding rdr_name
))
167 else -- See Note [Binders in Template Haskell] in Convert.hs
168 do { this_mod
<- getModule
169 ; externaliseName this_mod name
}
171 | Just
(rdr_mod
, rdr_occ
) <- isOrig_maybe rdr_name
172 = do { this_mod
<- getModule
173 ; unless (rdr_mod
== this_mod || rdr_mod
== rOOT_MAIN
)
174 (addErrAt loc
(badOrigBinding rdr_name
))
175 -- When reading External Core we get Orig names as binders,
176 -- but they should agree with the module gotten from the monad
178 -- We can get built-in syntax showing up here too, sadly. If you type
180 -- the constructor is parsed as a type, and then RdrHsSyn.tyConToDataCon
181 -- uses setRdrNameSpace to make it into a data constructors. At that point
182 -- the nice Exact name for the TyCon gets swizzled to an Orig name.
183 -- Hence the badOrigBinding error message.
185 -- Except for the ":Main.main = ..." definition inserted into
186 -- the Main module; ugh!
188 -- Because of this latter case, we call newGlobalBinder with a module from
189 -- the RdrName, not from the environment. In principle, it'd be fine to
190 -- have an arbitrary mixture of external core definitions in a single module,
191 -- (apart from module-initialisation issues, perhaps).
192 ; newGlobalBinder rdr_mod rdr_occ loc
}
195 = do { unless (not (isQual rdr_name
))
196 (addErrAt loc
(badQualBndrErr rdr_name
))
197 -- Binders should not be qualified; if they are, and with a different
198 -- module name, we we get a confusing "M.T is not in scope" error later
202 ; if isBrackStage stage
then
203 -- We are inside a TH bracket, so make an *Internal* name
204 -- See Note [Top-level Names in Template Haskell decl quotes] in RnNames
205 do { uniq
<- newUnique
206 ; return (mkInternalName uniq
(rdrNameOcc rdr_name
) loc
) }
207 else case tcg_impl_rdr_env env
of
209 -- We're compiling --sig-of, so resolve with respect to this
211 -- See Note [Signature parameters in TcGblEnv and DynFlags]
212 do { case lookupGlobalRdrEnv gr
(rdrNameOcc rdr_name
) of
213 -- Be sure to override the loc so that we get accurate
215 [GRE
{ gre_name
= n
}] -> do
216 -- NB: Just adding this line will not work:
217 -- addUsedGRE True gre
218 -- see Note [Signature lazy interface loading] for
220 return (setNameLoc n loc
)
222 { -- NB: cannot use reportUnboundName rdr_name
223 -- because it looks up in the wrong RdrEnv
224 -- ToDo: more helpful error messages
225 ; addErr
(unknownNameErr
(pprNonVarNameSpace
226 (occNameSpace
(rdrNameOcc rdr_name
))) rdr_name
)
227 ; return (mkUnboundName rdr_name
)
232 do { this_mod
<- getModule
233 ; traceRn
(text
"newTopSrcBinder" <+> (ppr this_mod
$$ ppr rdr_name
$$ ppr loc
))
234 ; newGlobalBinder this_mod
(rdrNameOcc rdr_name
) loc
} }
237 *********************************************************
239 Source code occurrences
241 *********************************************************
243 Looking up a name in the RnEnv.
245 Note [Type and class operator definitions]
246 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
247 We want to reject all of these unless we have -XTypeOperators (Trac #3265)
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.
258 lookupTopBndrRn
:: RdrName
-> RnM Name
259 lookupTopBndrRn n
= do nopt
<- lookupTopBndrRn_maybe n
262 Nothing
-> do traceRn
$ (text
"lookupTopBndrRn fail" <+> ppr n
)
263 unboundName WL_LocalTop n
265 lookupLocatedTopBndrRn
:: Located RdrName
-> RnM
(Located Name
)
266 lookupLocatedTopBndrRn
= wrapLocM lookupTopBndrRn
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:
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.
277 -- A separate function (importsFromLocalDecls) reports duplicate top level
278 -- decls, so here it's safe just to choose an arbitrary one.
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.
285 lookupTopBndrRn_maybe rdr_name
286 | Just name
<- isExact_maybe rdr_name
287 = do { name
' <- lookupExactOcc name
; return (Just name
') }
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
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
)) })
305 ; env
<- getGlobalRdrEnv
306 ; case filter isLocalGRE
(lookupGRE_RdrName rdr_name env
) of
307 [gre
] -> return (Just
(gre_name gre
))
308 _
-> return Nothing
-- Ambiguous (can't happen) or unbound
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
316 = do { result
<- lookupExactOcc_either name
318 Left err
-> do { addErr err
320 Right name
' -> return name
' }
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
330 AConLike
(RealDataCon dc
) -> Just
(dataConTyCon dc
)
333 = do { checkTupSize
(tyConArity tycon
)
334 ; return (Right name
) }
336 | isExternalName name
337 = return (Right name
)
340 = do { env
<- getGlobalRdrEnv
341 ; let -- See Note [Splicing Exact names]
342 main_occ
= nameOccName name
343 demoted_occs
= case demoteOccName main_occ
of
346 gres
= [ gre | occ
<- main_occ
: demoted_occs
347 , gre
<- lookupGlobalRdrEnv env occ
348 , gre_name gre
== name
]
350 [gre
] -> return (Right
(gre_name gre
))
352 [] -> -- See Note [Splicing Exact names]
353 do { lcl_env
<- getLocalRdrEnv
354 ; if name `inLocalRdrEnvScope` lcl_env
355 then return (Right name
)
358 do { th_topnames_var
<- fmap tcg_th_topnames getGblEnv
359 ; th_topnames
<- readTcRef th_topnames_var
360 ; if name `elemNameSet` th_topnames
361 then return (Right name
)
362 else return (Left exact_nm_err
)
365 return (Left exact_nm_err
)
368 gres
-> return (Left
(sameNameErr gres
)) -- Ugh! See Note [Template Haskell ambiguity]
371 exact_nm_err
= hang
(ptext
(sLit
"The exact Name") <+> quotes
(ppr name
) <+> ptext
(sLit
"is not in scope"))
372 2 (vcat
[ ptext
(sLit
"Probable cause: you used a unique Template Haskell name (NameU), ")
373 , ptext
(sLit
"perhaps via newName, but did not bind it")
374 , ptext
(sLit
"If that's it, then -ddump-splices might be useful") ])
376 sameNameErr
:: [GlobalRdrElt
] -> MsgDoc
377 sameNameErr
[] = panic
"addSameNameErr: empty list"
378 sameNameErr gres
@(_
: _
)
379 = hang
(ptext
(sLit
"Same exact name in multiple name-spaces:"))
380 2 (vcat
(map pp_one sorted_names
) $$ th_hint
)
382 sorted_names
= sortWith nameSrcLoc
(map gre_name gres
)
384 = hang
(pprNameSpace
(occNameSpace
(getOccName name
))
385 <+> quotes
(ppr name
) <> comma
)
386 2 (ptext
(sLit
"declared at:") <+> ppr
(nameSrcLoc name
))
388 th_hint
= vcat
[ ptext
(sLit
"Probable cause: you bound a unique Template Haskell name (NameU),")
389 , ptext
(sLit
"perhaps via newName, in different name-spaces.")
390 , ptext
(sLit
"If that's it, then -ddump-splices might be useful") ]
393 -----------------------------------------------
394 lookupInstDeclBndr
:: Name
-> SDoc
-> RdrName
-> RnM Name
395 -- This is called on the method name on the left-hand side of an
396 -- instance declaration binding. eg. instance Functor T where
398 -- ^^^^ called on this
399 -- Regardless of how many unqualified fmaps are in scope, we want
400 -- the one that comes from the Functor class.
402 -- Furthermore, note that we take no account of whether the
403 -- name is only in scope qualified. I.e. even if method op is
404 -- in scope as M.op, we still allow plain 'op' on the LHS of
407 -- The "what" parameter says "method" or "associated type",
408 -- depending on what we are looking up
409 lookupInstDeclBndr cls what rdr
410 = do { when (isQual rdr
)
411 (addErr
(badQualBndrErr rdr
))
412 -- In an instance decl you aren't allowed
413 -- to use a qualified name for the method
414 -- (Although it'd make perfect sense.)
415 ; lookupSubBndrOcc
False -- False => we don't give deprecated
416 -- warnings when a deprecated class
417 -- method is defined. We only warn
421 doc
= what
<+> ptext
(sLit
"of class") <+> quotes
(ppr cls
)
424 -----------------------------------------------
425 lookupFamInstName
:: Maybe Name
-> Located RdrName
-> RnM
(Located Name
)
426 -- Used for TyData and TySynonym family instances only,
427 -- See Note [Family instance binders]
428 lookupFamInstName
(Just cls
) tc_rdr
-- Associated type; c.f RnBinds.rnMethodBind
429 = wrapLocM
(lookupInstDeclBndr cls
(ptext
(sLit
"associated type"))) tc_rdr
430 lookupFamInstName Nothing tc_rdr
-- Family instance; tc_rdr is an *occurrence*
431 = lookupLocatedOccRn tc_rdr
433 -----------------------------------------------
434 lookupConstructorFields
:: Name
-> RnM
[FieldLabel
]
435 -- Look up the fields of a given constructor
436 -- * For constructors from this module, use the record field env,
437 -- which is itself gathered from the (as yet un-typechecked)
440 -- * For constructors from imported modules, use the *type* environment
441 -- since imported modles are already compiled, the info is conveniently
444 lookupConstructorFields con_name
445 = do { this_mod
<- getModule
446 ; if nameIsLocalOrFrom this_mod con_name
then
447 do { field_env
<- getRecFieldEnv
448 ; return (lookupNameEnv field_env con_name `orElse`
[]) }
450 do { con
<- tcLookupDataCon con_name
451 ; return (dataConFieldLabels con
) } }
453 -----------------------------------------------
454 -- Used for record construction and pattern matching
455 -- When the -XDisambiguateRecordFields flag is on, take account of the
456 -- constructor name to disambiguate which field to use; it's just the
457 -- same as for instance decls
459 -- NB: Consider this:
460 -- module Foo where { data R = R { fld :: Int } }
461 -- module Odd where { import Foo; fld x = x { fld = 3 } }
462 -- Arguably this should work, because the reference to 'fld' is
463 -- unambiguous because there is only one field id 'fld' in scope.
464 -- But currently it's rejected.
465 lookupSubBndrOcc
:: Bool
466 -> Maybe Name
-- Nothing => just look it up as usual
467 -- Just p => use parent p to disambiguate
470 lookupSubBndrOcc warnIfDeprec parent doc rdr_name
471 | Just n
<- isExact_maybe rdr_name
-- This happens in derived code
474 | Just
(rdr_mod
, rdr_occ
) <- isOrig_maybe rdr_name
475 = lookupOrig rdr_mod rdr_occ
477 |
otherwise -- Find all the things the rdr-name maps to
478 = do { -- and pick the one with the right parent namep
479 env
<- getGlobalRdrEnv
480 ; case lookupSubBndrGREs env parent rdr_name
of
481 -- NB: lookupGlobalRdrEnv, not lookupGRE_RdrName!
482 -- The latter does pickGREs, but we want to allow 'x'
483 -- even if only 'M.x' is in scope
484 [gre
] -> do { addUsedGRE warnIfDeprec gre
485 -- Add a usage; this is an *occurrence* site
486 -- Note [Usage for sub-bndrs]
487 ; return (gre_name gre
) }
488 [] -> do { ns
<- lookupQualifiedNameGHCi rdr_name
491 -- Unlikely to be more than one...?
493 { addErr
(unknownSubordinateErr doc rdr_name
)
494 ; return (mkUnboundName rdr_name
) } } }
495 gres
-> do { addNameClashErrRn rdr_name gres
496 ; return (gre_name
(head gres
)) } }
498 lookupSubBndrGREs
:: GlobalRdrEnv
-> Maybe Name
-> RdrName
-> [GlobalRdrElt
]
499 -- If parent = Nothing, just do a normal lookup
500 -- If parent = Just p then find all GREs that
502 -- (b) for Unqual, are in scope qualified or unqualified
503 -- for Qual, are in scope with that qualification
504 lookupSubBndrGREs env parent rdr_name
506 Nothing
-> pickGREs rdr_name gres
508 | isUnqual rdr_name
-> filter (parent_is p
) gres
509 |
otherwise -> filter (parent_is p
) (pickGREs rdr_name gres
)
512 gres
= lookupGlobalRdrEnv env
(rdrNameOcc rdr_name
)
514 parent_is p
(GRE
{ gre_par
= ParentIs p
' }) = p
== p
'
515 parent_is p
(GRE
{ gre_par
= FldParent
{ par_is
= p
'}}) = p
== p
'
516 parent_is _ _
= False
519 Note [Family instance binders]
520 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
523 data instance F T = X1 | X2
525 The 'data instance' decl has an *occurrence* of F (and T), and *binds*
526 X1 and X2. (This is unlike a normal data type declaration which would
527 bind F too.) So we want an AvailTC F [X1,X2].
529 Now consider a similar pair:
535 The 'data G S' *binds* Y1 and Y2, and has an *occurrence* of G.
537 But there is a small complication: in an instance decl, we don't use
538 qualified names on the LHS; instead we use the class to disambiguate.
546 Even though there are two G's in scope (M.G and Blib.G), the occurrence
547 of 'G' in the 'instance C S' decl is unambiguous, because C has only
548 one associated type called G. This is exactly what happens for methods,
549 and it is only consistent to do the same thing for types. That's the
550 role of the function lookupTcdName; the (Maybe Name) give the class of
551 the encloseing instance decl, if any.
553 Note [Looking up Exact RdrNames]
554 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
555 Exact RdrNames are generated by Template Haskell. See Note [Binders
556 in Template Haskell] in Convert.
558 For data types and classes have Exact system Names in the binding
559 positions for constructors, TyCons etc. For example
560 [d| data T = MkT Int |]
561 when we splice in and Convert to HsSyn RdrName, we'll get
562 data (Exact (system Name "T")) = (Exact (system Name "MkT")) ...
563 These System names are generated by Convert.thRdrName
565 But, constructors and the like need External Names, not System Names!
566 So we do the following
568 * In RnEnv.newTopSrcBinder we spot Exact RdrNames that wrap a
569 non-External Name, and make an External name for it. This is
570 the name that goes in the GlobalRdrEnv
572 * When looking up an occurrence of an Exact name, done in
573 RnEnv.lookupExactOcc, we find the Name with the right unique in the
574 GlobalRdrEnv, and use the one from the envt -- it will be an
575 External Name in the case of the data type/constructor above.
577 * Exact names are also use for purely local binders generated
578 by TH, such as \x_33. x_33
579 Both binder and occurrence are Exact RdrNames. The occurrence
580 gets looked up in the LocalRdrEnv by RnEnv.lookupOccRn, and
581 misses, because lookupLocalRdrEnv always returns Nothing for
582 an Exact Name. Now we fall through to lookupExactOcc, which
583 will find the Name is not in the GlobalRdrEnv, so we just use
584 the Exact supplied Name.
586 Note [Splicing Exact names]
587 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
588 Consider the splice $(do { x <- newName "x"; return (VarE x) })
589 This will generate a (HsExpr RdrName) term that mentions the
590 Exact RdrName "x_56" (or whatever), but does not bind it. So
591 when looking such Exact names we want to check that it's in scope,
592 otherwise the type checker will get confused. To do this we need to
593 keep track of all the Names in scope, and the LocalRdrEnv does just that;
594 we consult it with RdrName.inLocalRdrEnvScope.
596 There is another wrinkle. With TH and -XDataKinds, consider
597 $( [d| data Nat = Zero
598 data T = MkT (Proxy 'Zero) |] )
599 After splicing, but before renaming we get this:
600 data Nat_77{tc} = Zero_78{d}
601 data T_79{tc} = MkT_80{d} (Proxy 'Zero_78{tc}) |] )
602 The occurrence of 'Zero in the data type for T has the right unique,
603 but it has a TcClsName name-space in its OccName. (This is set by
604 the ctxt_ns argument of Convert.thRdrName.) When we check that is
605 in scope in the GlobalRdrEnv, we need to look up the DataName namespace
606 too. (An alternative would be to make the GlobalRdrEnv also have
607 a Name -> GRE mapping.)
609 Note [Template Haskell ambiguity]
610 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
611 The GlobalRdrEnv invariant says that if
612 occ -> [gre1, ..., gren]
613 then the gres have distinct Names (INVARIANT 1 of GlobalRdrEnv).
614 This is guaranteed by extendGlobalRdrEnvRn (the dups check in add_gre).
616 So how can we get multiple gres in lookupExactOcc_maybe? Because in
617 TH we might use the same TH NameU in two different name spaces.
619 $(newName "Foo" >>= \o -> return [DataD [] o [] [RecC o []] [''Show]])
620 Here we generate a type constructor and data constructor with the same
621 unique, but differnt name spaces.
623 It'd be nicer to rule this out in extendGlobalRdrEnvRn, but that would
624 mean looking up the OccName in every name-space, just in case, and that
625 seems a bit brutal. So it's just done here on lookup. But we might
626 need to revisit that choice.
628 Note [Usage for sub-bndrs]
629 ~~~~~~~~~~~~~~~~~~~~~~~~~~
631 import qualified M( C( f ) )
634 then is the qualified import M.f used? Obviously yes.
635 But the RdrName used in the instance decl is unqualified. In effect,
636 we fill in the qualification by looking for f's whose class is M.C
637 But when adding to the UsedRdrNames we must make that qualification
638 explicit (saying "used M.f"), otherwise we get "Redundant import of M.f".
640 So we make up a suitable (fake) RdrName. But be careful
645 Here we want to record a use of 'f', not of 'M.f', otherwise
646 we'll miss the fact that the qualified import is redundant.
648 --------------------------------------------------
650 --------------------------------------------------
653 getLookupOccRn
:: RnM
(Name
-> Maybe Name
)
655 = do local_env
<- getLocalRdrEnv
656 return (lookupLocalRdrOcc local_env
. nameOccName
)
658 lookupLocatedOccRn
:: Located RdrName
-> RnM
(Located Name
)
659 lookupLocatedOccRn
= wrapLocM lookupOccRn
661 lookupLocalOccRn_maybe
:: RdrName
-> RnM
(Maybe Name
)
662 -- Just look in the local environment
663 lookupLocalOccRn_maybe rdr_name
664 = do { local_env
<- getLocalRdrEnv
665 ; return (lookupLocalRdrEnv local_env rdr_name
) }
667 lookupLocalOccThLvl_maybe
:: Name
-> RnM
(Maybe (TopLevelFlag
, ThLevel
))
668 -- Just look in the local environment
669 lookupLocalOccThLvl_maybe name
670 = do { lcl_env
<- getLclEnv
671 ; return (lookupNameEnv
(tcl_th_bndrs lcl_env
) name
) }
673 -- lookupOccRn looks up an occurrence of a RdrName
674 lookupOccRn
:: RdrName
-> RnM Name
676 = do { mb_name
<- lookupOccRn_maybe rdr_name
678 Just name
-> return name
679 Nothing
-> reportUnboundName rdr_name
}
681 lookupKindOccRn
:: RdrName
-> RnM Name
682 -- Looking up a name occurring in a kind
683 lookupKindOccRn rdr_name
684 = do { mb_name
<- lookupOccRn_maybe rdr_name
686 Just name
-> return name
687 Nothing
-> reportUnboundName rdr_name
}
689 -- lookupPromotedOccRn looks up an optionally promoted RdrName.
690 lookupTypeOccRn
:: RdrName
-> RnM Name
691 -- see Note [Demotion]
692 lookupTypeOccRn rdr_name
693 = do { mb_name
<- lookupOccRn_maybe rdr_name
695 Just name
-> return name
;
696 Nothing
-> lookup_demoted rdr_name
} }
698 lookup_demoted
:: RdrName
-> RnM Name
699 lookup_demoted rdr_name
700 | Just demoted_rdr
<- demoteRdrName rdr_name
701 -- Maybe it's the name of a *data* constructor
702 = do { data_kinds
<- xoptM Opt_DataKinds
703 ; mb_demoted_name
<- lookupOccRn_maybe demoted_rdr
704 ; case mb_demoted_name
of
705 Nothing
-> reportUnboundName rdr_name
708 do { whenWOptM Opt_WarnUntickedPromotedConstructors
$
709 addWarn
(untickedPromConstrWarn demoted_name
)
710 ; return demoted_name
}
711 |
otherwise -> unboundNameX WL_Any rdr_name suggest_dk
}
714 = reportUnboundName rdr_name
717 suggest_dk
= ptext
(sLit
"A data constructor of that name is in scope; did you mean DataKinds?")
718 untickedPromConstrWarn name
=
719 text
"Unticked promoted constructor" <> colon
<+> quotes
(ppr name
) <> dot
722 , quotes
(char
'\'' <> ppr name
)
724 , quotes
(ppr name
) <> dot
]
729 When the user writes:
730 data Nat = Zero | Succ Nat
733 'Zero' in the type signature of 'foo' is parsed as:
734 HsTyVar ("Zero", TcClsName)
736 When the renamer hits this occurrence of 'Zero' it's going to realise
737 that it's not in scope. But because it is renaming a type, it knows
738 that 'Zero' might be a promoted data constructor, so it will demote
739 its namespace to DataName and do a second lookup.
741 The final result (after the renamer) will be:
742 HsTyVar ("Zero", DataName)
745 -- Use this version to get tracing
747 -- lookupOccRn_maybe, lookupOccRn_maybe' :: RdrName -> RnM (Maybe Name)
748 -- lookupOccRn_maybe rdr_name
749 -- = do { mb_res <- lookupOccRn_maybe' rdr_name
750 -- ; gbl_rdr_env <- getGlobalRdrEnv
751 -- ; local_rdr_env <- getLocalRdrEnv
752 -- ; traceRn $ text "lookupOccRn_maybe" <+>
753 -- vcat [ ppr rdr_name <+> ppr (getUnique (rdrNameOcc rdr_name))
755 -- , text "Lcl env" <+> ppr local_rdr_env
756 -- , text "Gbl env" <+> ppr [ (getUnique (nameOccName (gre_name (head gres'))),gres') | gres <- occEnvElts gbl_rdr_env
757 -- , let gres' = filter isLocalGRE gres, not (null gres') ] ]
760 lookupOccRn_maybe
:: RdrName
-> RnM
(Maybe Name
)
761 -- lookupOccRn looks up an occurrence of a RdrName
762 lookupOccRn_maybe rdr_name
763 = do { local_env
<- getLocalRdrEnv
764 ; case lookupLocalRdrEnv local_env rdr_name
of {
765 Just name
-> return (Just name
) ;
767 { mb_name
<- lookupGlobalOccRn_maybe rdr_name
769 Just name
-> return (Just name
) ;
771 { ns
<- lookupQualifiedNameGHCi rdr_name
772 -- This test is not expensive,
773 -- and only happens for failed lookups
775 (n
:_
) -> return (Just n
) -- Unlikely to be more than one...?
776 [] -> return Nothing
} } } } }
778 lookupGlobalOccRn
:: RdrName
-> RnM Name
779 -- lookupGlobalOccRn is like lookupOccRn, except that it looks in the global
780 -- environment. Adds an error message if the RdrName is not in scope.
781 lookupGlobalOccRn rdr_name
782 = do { mb_name
<- lookupGlobalOccRn_maybe rdr_name
785 Nothing
-> do { traceRn
(text
"lookupGlobalOccRn" <+> ppr rdr_name
)
786 ; unboundName WL_Global rdr_name
} }
788 lookupInfoOccRn
:: RdrName
-> RnM
[Name
]
789 -- lookupInfoOccRn is intended for use in GHCi's ":info" command
790 -- It finds all the GREs that RdrName could mean, not complaining
791 -- about ambiguity, but rather returning them all
793 lookupInfoOccRn rdr_name
794 | Just n
<- isExact_maybe rdr_name
-- e.g. (->)
797 | Just
(rdr_mod
, rdr_occ
) <- isOrig_maybe rdr_name
798 = do { n
<- lookupOrig rdr_mod rdr_occ
802 = do { rdr_env
<- getGlobalRdrEnv
803 ; let ns
= map gre_name
(lookupGRE_RdrName rdr_name rdr_env
)
804 ; qual_ns
<- lookupQualifiedNameGHCi rdr_name
805 ; return (ns
++ (qual_ns `minusList` ns
)) }
807 lookupGlobalOccRn_maybe
:: RdrName
-> RnM
(Maybe Name
)
808 -- No filter function; does not report an error on failure
810 lookupGlobalOccRn_maybe rdr_name
811 | Just n
<- isExact_maybe rdr_name
-- This happens in derived code
812 = do { n
' <- lookupExactOcc n
; return (Just n
') }
814 | Just
(rdr_mod
, rdr_occ
) <- isOrig_maybe rdr_name
815 = do { n
<- lookupOrig rdr_mod rdr_occ
819 = do { mb_gre
<- lookupGreRn_maybe rdr_name
821 Nothing
-> return Nothing
822 Just gre
-> return (Just
(gre_name gre
)) }
825 -- | Like 'lookupOccRn_maybe', but with a more informative result if
826 -- the 'RdrName' happens to be a record selector:
828 -- * Nothing -> name not in scope (no error reported)
829 -- * Just (Left x) -> name uniquely refers to x,
830 -- or there is a name clash (reported)
831 -- * Just (Right xs) -> name refers to one or more record selectors;
832 -- if overload_ok was False, this list will be
834 lookupOccRn_overloaded
:: Bool -> RdrName
-> RnM
(Maybe (Either Name
[FieldOcc Name
]))
835 lookupOccRn_overloaded overload_ok rdr_name
836 = do { local_env
<- getLocalRdrEnv
837 ; case lookupLocalRdrEnv local_env rdr_name
of {
838 Just name
-> return (Just
(Left name
)) ;
840 { mb_name
<- lookupGlobalOccRn_overloaded overload_ok rdr_name
842 Just name
-> return (Just name
) ;
844 { ns
<- lookupQualifiedNameGHCi rdr_name
845 -- This test is not expensive,
846 -- and only happens for failed lookups
848 (n
:_
) -> return $ Just
$ Left n
-- Unlikely to be more than one...?
849 [] -> return Nothing
} } } } }
851 lookupGlobalOccRn_overloaded
:: Bool -> RdrName
-> RnM
(Maybe (Either Name
[FieldOcc Name
]))
852 lookupGlobalOccRn_overloaded overload_ok rdr_name
853 | Just n
<- isExact_maybe rdr_name
-- This happens in derived code
854 = do { n
' <- lookupExactOcc n
; return (Just
(Left n
')) }
856 | Just
(rdr_mod
, rdr_occ
) <- isOrig_maybe rdr_name
857 = do { n
<- lookupOrig rdr_mod rdr_occ
858 ; return (Just
(Left n
)) }
861 = do { env
<- getGlobalRdrEnv
862 ; case lookupGRE_RdrName rdr_name env
of
864 [gre
] | isRecFldGRE gre
865 -> do { addUsedGRE
True gre
866 ; let fld_occ
= FieldOcc rdr_name
(gre_name gre
)
867 ; return (Just
(Right
[fld_occ
])) }
869 -> do { addUsedGRE
True gre
870 ; return (Just
(Left
(gre_name gre
))) }
871 gres |
all isRecFldGRE gres
&& overload_ok
872 -- Don't record usage for ambiguous selectors
873 -- until we know which is meant
874 -> return (Just
(Right
(map (FieldOcc rdr_name
. gre_name
) gres
)))
875 gres
-> do { addNameClashErrRn rdr_name gres
876 ; return (Just
(Left
(gre_name
(head gres
)))) } }
879 --------------------------------------------------
880 -- Lookup in the Global RdrEnv of the module
881 --------------------------------------------------
883 lookupGreRn_maybe
:: RdrName
-> RnM
(Maybe GlobalRdrElt
)
884 -- Look up the RdrName in the GlobalRdrEnv
885 -- Exactly one binding: records it as "used", return (Just gre)
886 -- No bindings: return Nothing
887 -- Many bindings: report "ambiguous", return an arbitrary (Just gre)
888 -- (This API is a bit strange; lookupGRERn2_maybe is simpler.
889 -- But it works and I don't want to fiddle too much.)
890 lookupGreRn_maybe rdr_name
891 = do { env
<- getGlobalRdrEnv
892 ; case lookupGRE_RdrName rdr_name env
of
894 [gre
] -> do { addUsedGRE
True gre
895 ; return (Just gre
) }
896 gres
-> do { addNameClashErrRn rdr_name gres
897 ; traceRn
(text
"name clash" <+> (ppr rdr_name
$$ ppr gres
$$ ppr env
))
898 ; return (Just
(head gres
)) } }
900 lookupGreRn2_maybe
:: RdrName
-> RnM
(Maybe GlobalRdrElt
)
901 -- Look up the RdrName in the GlobalRdrEnv
902 -- Exactly one binding: record it as "used", return (Just gre)
903 -- No bindings: report "not in scope", return Nothing
904 -- Many bindings: report "ambiguous", return Nothing
905 lookupGreRn2_maybe rdr_name
906 = do { env
<- getGlobalRdrEnv
907 ; case lookupGRE_RdrName rdr_name env
of
908 [] -> do { _
<- unboundName WL_Global rdr_name
910 [gre
] -> do { addUsedGRE
True gre
911 ; return (Just gre
) }
912 gres
-> do { addNameClashErrRn rdr_name gres
913 ; traceRn
(text
"name clash" <+> (ppr rdr_name
$$ ppr gres
$$ ppr env
))
916 lookupGreAvailRn
:: RdrName
-> RnM
(Name
, AvailInfo
)
917 -- Used in export lists
918 -- If not found or ambiguous, add error message, and fake with UnboundName
919 lookupGreAvailRn rdr_name
920 = do { mb_gre
<- lookupGreRn2_maybe rdr_name
922 Just gre
-> return (gre_name gre
, availFromGRE gre
) ;
924 do { traceRn
(text
"lookupGreRn" <+> ppr rdr_name
)
925 ; let name
= mkUnboundName rdr_name
926 ; return (name
, avail name
) } } }
929 *********************************************************
933 *********************************************************
935 Note [Handling of deprecations]
936 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
937 * We report deprecations at each *occurrence* of the deprecated thing
940 * We do not report deprecations for locally-defined names. For a
941 start, we may be exporting a deprecated thing. Also we may use a
942 deprecated thing in the defn of another deprecated things. We may
943 even use a deprecated thing in the defn of a non-deprecated thing,
944 when changing a module's interface.
946 * addUsedGREs: we do not report deprecations for sub-binders:
947 - the ".." completion for records
948 - the ".." in an export item 'T(..)'
949 - the things exported by a module export 'module M'
952 addUsedDataCons
:: GlobalRdrEnv
-> TyCon
-> RnM
()
953 -- Remember use of in-scope data constructors (Trac #7969)
954 addUsedDataCons rdr_env tycon
956 | dc
<- tyConDataCons tycon
957 , gre
: _
<- [lookupGRE_Name rdr_env
(dataConName dc
) ] ]
959 addUsedGRE
:: Bool -> GlobalRdrElt
-> RnM
()
960 -- Called for both local and imported things
961 -- Add usage *and* warn if deprecated
962 addUsedGRE warn_if_deprec gre
963 = do { when warn_if_deprec
(warnIfDeprecated gre
)
964 ; unless (isLocalGRE gre
) $
965 do { env
<- getGblEnv
966 ; traceRn
(text
"addUsedGRE" <+> ppr gre
)
967 ; updMutVar
(tcg_used_gres env
) (gre
:) } }
969 addUsedGREs
:: [GlobalRdrElt
] -> RnM
()
970 -- Record uses of any *imported* GREs
971 -- Used for recording used sub-bndrs
972 -- NB: no call to warnIfDeprecated; see Note [Handling of deprecations]
974 |
null imp_gres
= return ()
975 |
otherwise = do { env
<- getGblEnv
976 ; traceRn
(text
"addUsedGREs" <+> ppr imp_gres
)
977 ; updMutVar
(tcg_used_gres env
) (imp_gres
++) }
979 imp_gres
= filterOut isLocalGRE gres
981 warnIfDeprecated
:: GlobalRdrElt
-> RnM
()
982 warnIfDeprecated gre
@(GRE
{ gre_name
= name
, gre_imp
= iss
})
983 |
(imp_spec
: _
) <- iss
984 = do { dflags
<- getDynFlags
985 ; this_mod
<- getModule
986 ; when (wopt Opt_WarnWarningsDeprecations dflags
&&
987 not (nameIsLocalOrFrom this_mod name
)) $
988 -- See Note [Handling of deprecations]
989 do { iface
<- loadInterfaceForName doc name
990 ; case lookupImpDeprec iface gre
of
991 Just txt
-> addWarn
(mk_msg imp_spec txt
)
992 Nothing
-> return () } }
997 name_mod
= ASSERT2
( isExternalName name
, ppr name
) nameModule name
998 doc
= ptext
(sLit
"The name") <+> quotes
(ppr occ
) <+> ptext
(sLit
"is mentioned explicitly")
1001 = sep
[ sep
[ ptext
(sLit
"In the use of")
1002 <+> pprNonVarNameSpace
(occNameSpace occ
)
1003 <+> quotes
(ppr occ
)
1004 , parens imp_msg
<> colon
]
1007 imp_mod
= importSpecModule imp_spec
1008 imp_msg
= ptext
(sLit
"imported from") <+> ppr imp_mod
<> extra
1009 extra | imp_mod
== moduleName name_mod
= Outputable
.empty
1010 |
otherwise = ptext
(sLit
", but defined in") <+> ppr name_mod
1012 lookupImpDeprec
:: ModIface
-> GlobalRdrElt
-> Maybe WarningTxt
1013 lookupImpDeprec iface gre
1014 = mi_warn_fn iface
(gre_name gre
) `mplus`
-- Bleat if the thing,
1015 case gre_par gre
of -- or its parent, is warn'd
1016 ParentIs p
-> mi_warn_fn iface p
1017 FldParent
{ par_is
= p
} -> mi_warn_fn iface p
1019 PatternSynonym
-> Nothing
1022 Note [Used names with interface not loaded]
1023 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1024 It's (just) possible to find a used
1025 Name whose interface hasn't been loaded:
1027 a) It might be a WiredInName; in that case we may not load
1028 its interface (although we could).
1030 b) It might be GHC.Real.fromRational, or GHC.Num.fromInteger
1031 These are seen as "used" by the renamer (if -XRebindableSyntax)
1032 is on), but the typechecker may discard their uses
1033 if in fact the in-scope fromRational is GHC.Read.fromRational,
1034 (see tcPat.tcOverloadedLit), and the typechecker sees that the type
1035 is fixed, say, to GHC.Base.Float (see Inst.lookupSimpleInst).
1036 In that obscure case it won't force the interface in.
1038 In both cases we simply don't permit deprecations;
1039 this is, after all, wired-in stuff.
1042 *********************************************************
1046 *********************************************************
1048 A qualified name on the command line can refer to any module at
1049 all: we try to load the interface if we don't already have it, just
1050 as if there was an "import qualified M" declaration for every
1053 If we fail we just return Nothing, rather than bleating
1054 about "attempting to use module ‘D’ (./D.hs) which is not loaded"
1055 which is what loadSrcInterface does.
1057 Note [Safe Haskell and GHCi]
1058 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1059 We DONT do this Safe Haskell as we need to check imports. We can
1060 and should instead check the qualified import but at the moment
1061 this requires some refactoring so leave as a TODO
1064 lookupQualifiedNameGHCi
:: RdrName
-> RnM
[Name
]
1065 lookupQualifiedNameGHCi rdr_name
1066 = -- We want to behave as we would for a source file import here,
1067 -- and respect hiddenness of modules/packages, hence loadSrcInterface.
1068 do { dflags
<- getDynFlags
1069 ; is_ghci
<- getIsGHCi
1070 ; go_for_it dflags is_ghci
}
1073 go_for_it dflags is_ghci
1074 | Just
(mod,occ
) <- isQual_maybe rdr_name
1076 , gopt Opt_ImplicitImportQualified dflags
-- Enables this GHCi behaviour
1077 , not (safeDirectImpsReq dflags
) -- See Note [Safe Haskell and GHCi]
1078 = do { res
<- loadSrcInterface_maybe doc
mod False Nothing
1082 | avail
<- mi_exports iface
1083 , name
<- availNames avail
1084 , nameOccName name
== occ
]
1086 _
-> -- Either we couldn't load the interface, or
1087 -- we could but we didn't find the name in it
1088 do { traceRn
(text
"lookupQualifiedNameGHCi" <+> ppr rdr_name
)
1094 doc
= ptext
(sLit
"Need to find") <+> ppr rdr_name
1097 Note [Looking up signature names]
1098 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1099 lookupSigOccRn is used for type signatures and pragmas
1105 It's clear that the 'f' in the signature must refer to A.f
1106 The Haskell98 report does not stipulate this, but it will!
1107 So we must treat the 'f' in the signature in the same way
1108 as the binding occurrence of 'f', using lookupBndrRn
1110 However, consider this case:
1114 We don't want to say 'f' is out of scope; instead, we want to
1115 return the imported 'f', so that later on the reanamer will
1116 correctly report "misplaced type sig".
1118 Note [Signatures for top level things]
1119 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1120 data HsSigCtxt = ... | TopSigCtxt NameSet | ....
1122 * The NameSet says what is bound in this group of bindings.
1123 We can't use isLocalGRE from the GlobalRdrEnv, because of this:
1125 $( ...some TH splice... )
1127 When we encounter the signature for 'f', the binding for 'f'
1128 will be in the GlobalRdrEnv, and will be a LocalDef. Yet the
1129 signature is mis-placed
1131 * For type signatures the NameSet should be the names bound by the
1132 value bindings; for fixity declarations, the NameSet should also
1133 include class sigs and record selectors
1135 infix 3 `f` -- Yes, ok
1136 f :: C a => a -> a -- No, not ok
1142 = TopSigCtxt NameSet
-- At top level, binding these names
1143 -- See Note [Signatures for top level things]
1144 | LocalBindCtxt NameSet
-- In a local binding, binding these names
1145 | ClsDeclCtxt Name
-- Class decl for this class
1146 | InstDeclCtxt NameSet
-- Instance decl whose user-written method
1147 -- bindings are for these methods
1148 | HsBootCtxt
-- Top level of a hs-boot file
1149 | RoleAnnotCtxt NameSet
-- A role annotation, with the names of all types
1152 lookupSigOccRn
:: HsSigCtxt
1154 -> Located RdrName
-> RnM
(Located Name
)
1155 lookupSigOccRn ctxt sig
= lookupSigCtxtOccRn ctxt
(hsSigDoc sig
)
1157 -- | Lookup a name in relation to the names in a 'HsSigCtxt'
1158 lookupSigCtxtOccRn
:: HsSigCtxt
1159 -> SDoc
-- ^ description of thing we're looking up,
1160 -- like "type family"
1161 -> Located RdrName
-> RnM
(Located Name
)
1162 lookupSigCtxtOccRn ctxt what
1163 = wrapLocM
$ \ rdr_name
->
1164 do { mb_name
<- lookupBindGroupOcc ctxt what rdr_name
1166 Left err
-> do { addErr err
; return (mkUnboundName rdr_name
) }
1167 Right name
-> return name
}
1169 lookupBindGroupOcc
:: HsSigCtxt
1171 -> RdrName
-> RnM
(Either MsgDoc Name
)
1172 -- Looks up the RdrName, expecting it to resolve to one of the
1173 -- bound names passed in. If not, return an appropriate error message
1175 -- See Note [Looking up signature names]
1176 lookupBindGroupOcc ctxt what rdr_name
1177 | Just n
<- isExact_maybe rdr_name
1178 = lookupExactOcc_either n
-- allow for the possibility of missing Exacts;
1179 -- see Note [dataTcOccs and Exact Names]
1180 -- Maybe we should check the side conditions
1181 -- but it's a pain, and Exact things only show
1182 -- up when you know what you are doing
1184 | Just
(rdr_mod
, rdr_occ
) <- isOrig_maybe rdr_name
1185 = do { n
' <- lookupOrig rdr_mod rdr_occ
1186 ; return (Right n
') }
1190 HsBootCtxt
-> lookup_top
(const True)
1191 TopSigCtxt ns
-> lookup_top
(`elemNameSet` ns
)
1192 RoleAnnotCtxt ns
-> lookup_top
(`elemNameSet` ns
)
1193 LocalBindCtxt ns
-> lookup_group ns
1194 ClsDeclCtxt cls
-> lookup_cls_op cls
1195 InstDeclCtxt ns
-> lookup_top
(`elemNameSet` ns
)
1198 = do { env
<- getGlobalRdrEnv
1199 ; let gres
= lookupSubBndrGREs env
(Just cls
) rdr_name
1201 [] -> return (Left
(unknownSubordinateErr doc rdr_name
))
1202 (gre
:_
) -> return (Right
(gre_name gre
)) }
1203 -- If there is more than one local GRE for the
1204 -- same OccName 'f', that will be reported separately
1205 -- as a duplicate top-level binding for 'f'
1207 doc
= ptext
(sLit
"method of class") <+> quotes
(ppr cls
)
1210 = do { env
<- getGlobalRdrEnv
1211 ; let all_gres
= lookupGlobalRdrEnv env
(rdrNameOcc rdr_name
)
1212 ; case filter (keep_me
. gre_name
) all_gres
of
1213 [] |
null all_gres
-> bale_out_with Outputable
.empty
1214 |
otherwise -> bale_out_with local_msg
1215 (gre
:_
) -> return (Right
(gre_name gre
)) }
1217 lookup_group bound_names
-- Look in the local envt (not top level)
1218 = do { local_env
<- getLocalRdrEnv
1219 ; case lookupLocalRdrEnv local_env rdr_name
of
1221 | n `elemNameSet` bound_names
-> return (Right n
)
1222 |
otherwise -> bale_out_with local_msg
1223 Nothing
-> bale_out_with Outputable
.empty }
1226 = return (Left
(sep
[ ptext
(sLit
"The") <+> what
1227 <+> ptext
(sLit
"for") <+> quotes
(ppr rdr_name
)
1228 , nest
2 $ ptext
(sLit
"lacks an accompanying binding")]
1231 local_msg
= parens
$ ptext
(sLit
"The") <+> what
<+> ptext
(sLit
"must be given where")
1232 <+> quotes
(ppr rdr_name
) <+> ptext
(sLit
"is declared")
1236 lookupLocalTcNames
:: HsSigCtxt
-> SDoc
-> RdrName
-> RnM
[Name
]
1237 -- GHC extension: look up both the tycon and data con or variable.
1238 -- Used for top-level fixity signatures and deprecations.
1239 -- Complain if neither is in scope.
1240 -- See Note [Fixity signature lookup]
1241 lookupLocalTcNames ctxt what rdr_name
1242 = do { mb_gres
<- mapM lookup (dataTcOccs rdr_name
)
1243 ; let (errs
, names
) = splitEithers mb_gres
1244 ; when (null names
) $ addErr
(head errs
) -- Bleat about one only
1247 lookup = lookupBindGroupOcc ctxt what
1249 dataTcOccs
:: RdrName
-> [RdrName
]
1250 -- Return both the given name and the same name promoted to the TcClsName
1251 -- namespace. This is useful when we aren't sure which we are looking at.
1252 -- See also Note [dataTcOccs and Exact Names]
1254 | isDataOcc occ || isVarOcc occ
1255 = [rdr_name
, rdr_name_tc
]
1259 occ
= rdrNameOcc rdr_name
1260 rdr_name_tc
= setRdrNameSpace rdr_name tcName
1263 Note [dataTcOccs and Exact Names]
1264 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1265 Exact RdrNames can occur in code generated by Template Haskell, and generally
1266 those references are, well, exact. However, the TH `Name` type isn't expressive
1267 enough to always track the correct namespace information, so we sometimes get
1268 the right Unique but wrong namespace. Thus, we still have to do the double-lookup
1271 There is also an awkward situation for built-in syntax. Example in GHCi
1273 This parses as the Exact RdrName for nilDataCon, but we also want
1274 the list type constructor.
1276 Note that setRdrNameSpace on an Exact name requires the Name to be External,
1277 which it always is for built in syntax.
1279 *********************************************************
1283 *********************************************************
1285 Note [Fixity signature lookup]
1286 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1287 A fixity declaration like
1291 can refer to a value-level operator, e.g.:
1293 (?) :: String -> String -> String
1295 or a type-level operator, like:
1297 data (?) a b = A a | B b
1299 so we extend the lookup of the reader name '?' to the TcClsName namespace, as
1300 well as the original namespace.
1302 The extended lookup is also used in other places, like resolution of
1303 deprecation declarations, and lookup of names in GHCi.
1306 --------------------------------
1307 type MiniFixityEnv
= FastStringEnv
(Located Fixity
)
1308 -- Mini fixity env for the names we're about
1309 -- to bind, in a single binding group
1311 -- It is keyed by the *FastString*, not the *OccName*, because
1312 -- the single fixity decl infix 3 T
1313 -- affects both the data constructor T and the type constrctor T
1315 -- We keep the location so that if we find
1316 -- a duplicate, we can report it sensibly
1318 --------------------------------
1319 -- Used for nested fixity decls to bind names along with their fixities.
1320 -- the fixities are given as a UFM from an OccName's FastString to a fixity decl
1322 addLocalFixities
:: MiniFixityEnv
-> [Name
] -> RnM a
-> RnM a
1323 addLocalFixities mini_fix_env names thing_inside
1324 = extendFixityEnv
(mapMaybe find_fixity names
) thing_inside
1327 = case lookupFsEnv mini_fix_env
(occNameFS occ
) of
1328 Just
(L _ fix
) -> Just
(name
, FixItem occ fix
)
1331 occ
= nameOccName name
1334 --------------------------------
1335 lookupFixity is a bit strange.
1337 * Nested local fixity decls are put in the local fixity env, which we
1338 find with getFixtyEnv
1340 * Imported fixities are found in the HIT or PIT
1342 * Top-level fixity decls in this module may be for Names that are
1343 either Global (constructors, class operations)
1344 or Local/Exported (everything else)
1345 (See notes with RnNames.getLocalDeclBinders for why we have this split.)
1346 We put them all in the local fixity environment
1349 lookupFixityRn
:: Name
-> RnM Fixity
1351 | isUnboundName name
1352 = return (Fixity minPrecedence InfixL
)
1353 -- Minimise errors from ubound names; eg
1355 -- where 'foo' is not in scope, should not give an error (Trac #7937)
1358 = do { local_fix_env
<- getFixityEnv
1359 ; case lookupNameEnv local_fix_env name
of {
1360 Just
(FixItem _ fix
) -> return fix
;
1363 do { this_mod
<- getModule
1364 ; if nameIsLocalOrFrom this_mod name
1365 -- Local (and interactive) names are all in the
1366 -- fixity env, and don't have entries in the HPT
1367 then return defaultFixity
1368 else lookup_imported
} } }
1371 -- For imported names, we have to get their fixities by doing a
1372 -- loadInterfaceForName, and consulting the Ifaces that comes back
1373 -- from that, because the interface file for the Name might not
1374 -- have been loaded yet. Why not? Suppose you import module A,
1375 -- which exports a function 'f', thus;
1376 -- module CurrentModule where
1378 -- module A( f ) where
1380 -- Then B isn't loaded right away (after all, it's possible that
1381 -- nothing from B will be used). When we come across a use of
1382 -- 'f', we need to know its fixity, and it's then, and only
1383 -- then, that we load B.hi. That is what's happening here.
1385 -- loadInterfaceForName will find B.hi even if B is a hidden module,
1386 -- and that's what we want.
1387 = do { iface
<- loadInterfaceForName doc name
1388 ; traceRn
(text
"lookupFixityRn: looking up name in iface cache and found:" <+>
1389 vcat
[ppr name
, ppr
$ mi_fix_fn iface
(nameOccName name
)])
1390 ; return (mi_fix_fn iface
(nameOccName name
)) }
1392 doc
= ptext
(sLit
"Checking fixity for") <+> ppr name
1395 lookupTyFixityRn
:: Located Name
-> RnM Fixity
1396 lookupTyFixityRn
(L _ n
) = lookupFixityRn n
1399 ************************************************************************
1402 Dealing with rebindable syntax is driven by the
1403 Opt_RebindableSyntax dynamic flag.
1405 In "deriving" code we don't want to use rebindable syntax
1406 so we switch off the flag locally
1409 ************************************************************************
1411 Haskell 98 says that when you say "3" you get the "fromInteger" from the
1412 Standard Prelude, regardless of what is in scope. However, to experiment
1413 with having a language that is less coupled to the standard prelude, we're
1414 trying a non-standard extension that instead gives you whatever "Prelude.fromInteger"
1415 happens to be in scope. Then you can
1417 import MyPrelude as Prelude
1418 to get the desired effect.
1420 At the moment this just happens for
1421 * fromInteger, fromRational on literals (in expressions and patterns)
1422 * negate (in expressions)
1423 * minus (arising from n+k patterns)
1426 We store the relevant Name in the HsSyn tree, in
1427 * HsIntegral/HsFractional/HsIsString
1431 respectively. Initially, we just store the "standard" name (PrelNames.fromIntegralName,
1432 fromRationalName etc), but the renamer changes this to the appropriate user
1433 name if Opt_NoImplicitPrelude is on. That is what lookupSyntaxName does.
1435 We treat the orignal (standard) names as free-vars too, because the type checker
1436 checks the type of the user thing against the type of the standard thing.
1439 lookupIfThenElse
:: RnM
(Maybe (SyntaxExpr Name
), FreeVars
)
1440 -- Different to lookupSyntaxName because in the non-rebindable
1441 -- case we desugar directly rather than calling an existing function
1442 -- Hence the (Maybe (SyntaxExpr Name)) return type
1444 = do { rebindable_on
<- xoptM Opt_RebindableSyntax
1445 ; if not rebindable_on
1446 then return (Nothing
, emptyFVs
)
1447 else do { ite
<- lookupOccRn
(mkVarUnqual
(fsLit
"ifThenElse"))
1448 ; return (Just
(HsVar
(noLoc ite
)), unitFV ite
) } }
1450 lookupSyntaxName
:: Name
-- The standard name
1451 -> RnM
(SyntaxExpr Name
, FreeVars
) -- Possibly a non-standard name
1452 lookupSyntaxName std_name
1453 = do { rebindable_on
<- xoptM Opt_RebindableSyntax
1454 ; if not rebindable_on
then
1455 return (HsVar
(noLoc std_name
), emptyFVs
)
1457 -- Get the similarly named thing from the local environment
1458 do { usr_name
<- lookupOccRn
(mkRdrUnqual
(nameOccName std_name
))
1459 ; return (HsVar
(noLoc usr_name
), unitFV usr_name
) } }
1461 lookupSyntaxNames
:: [Name
] -- Standard names
1462 -> RnM
([HsExpr Name
], FreeVars
) -- See comments with HsExpr.ReboundNames
1463 lookupSyntaxNames std_names
1464 = do { rebindable_on
<- xoptM Opt_RebindableSyntax
1465 ; if not rebindable_on
then
1466 return (map (HsVar
. noLoc
) std_names
, emptyFVs
)
1468 do { usr_names
<- mapM (lookupOccRn
. mkRdrUnqual
. nameOccName
) std_names
1469 ; return (map (HsVar
. noLoc
) usr_names
, mkFVs usr_names
) } }
1472 *********************************************************
1474 \subsection{Binding}
1476 *********************************************************
1479 newLocalBndrRn
:: Located RdrName
-> RnM Name
1480 -- Used for non-top-level binders. These should
1481 -- never be qualified.
1482 newLocalBndrRn
(L loc rdr_name
)
1483 | Just name
<- isExact_maybe rdr_name
1484 = return name
-- This happens in code generated by Template Haskell
1485 -- See Note [Binders in Template Haskell] in Convert.hs
1487 = do { unless (isUnqual rdr_name
)
1488 (addErrAt loc
(badQualBndrErr rdr_name
))
1490 ; return (mkInternalName uniq
(rdrNameOcc rdr_name
) loc
) }
1492 newLocalBndrsRn
:: [Located RdrName
] -> RnM
[Name
]
1493 newLocalBndrsRn
= mapM newLocalBndrRn
1495 ---------------------
1496 bindLocatedLocalsRn
:: [Located RdrName
]
1497 -> ([Name
] -> RnM a
)
1499 bindLocatedLocalsRn rdr_names_w_loc enclosed_scope
1500 = do { checkDupRdrNames rdr_names_w_loc
1501 ; checkShadowedRdrNames rdr_names_w_loc
1503 -- Make fresh Names and extend the environment
1504 ; names
<- newLocalBndrsRn rdr_names_w_loc
1505 ; bindLocalNames names
(enclosed_scope names
) }
1507 bindLocalNames
:: [Name
] -> RnM a
-> RnM a
1508 bindLocalNames names enclosed_scope
1509 = do { lcl_env
<- getLclEnv
1510 ; let th_level
= thLevel
(tcl_th_ctxt lcl_env
)
1511 th_bndrs
' = extendNameEnvList
(tcl_th_bndrs lcl_env
)
1512 [ (n
, (NotTopLevel
, th_level
)) | n
<- names
]
1513 rdr_env
' = extendLocalRdrEnvList
(tcl_rdr lcl_env
) names
1514 ; setLclEnv
(lcl_env
{ tcl_th_bndrs
= th_bndrs
'
1515 , tcl_rdr
= rdr_env
' })
1518 bindLocalNamesFV
:: [Name
] -> RnM
(a
, FreeVars
) -> RnM
(a
, FreeVars
)
1519 bindLocalNamesFV names enclosed_scope
1520 = do { (result
, fvs
) <- bindLocalNames names enclosed_scope
1521 ; return (result
, delFVs names fvs
) }
1524 -------------------------------------
1525 -- binLocalsFVRn is the same as bindLocalsRn
1526 -- except that it deals with free vars
1527 bindLocatedLocalsFV
:: [Located RdrName
]
1528 -> ([Name
] -> RnM
(a
,FreeVars
)) -> RnM
(a
, FreeVars
)
1529 bindLocatedLocalsFV rdr_names enclosed_scope
1530 = bindLocatedLocalsRn rdr_names
$ \ names
->
1531 do (thing
, fvs
) <- enclosed_scope names
1532 return (thing
, delFVs names fvs
)
1534 -------------------------------------
1536 extendTyVarEnvFVRn
:: [Name
] -> RnM
(a
, FreeVars
) -> RnM
(a
, FreeVars
)
1537 -- This function is used only in rnSourceDecl on InstDecl
1538 extendTyVarEnvFVRn tyvars thing_inside
= bindLocalNamesFV tyvars thing_inside
1540 -------------------------------------
1541 checkDupRdrNames
:: [Located RdrName
] -> RnM
()
1542 -- Check for duplicated names in a binding group
1543 checkDupRdrNames rdr_names_w_loc
1544 = mapM_ (dupNamesErr getLoc
) dups
1546 (_
, dups
) = removeDups
(\n1 n2
-> unLoc n1 `
compare` unLoc n2
) rdr_names_w_loc
1548 checkDupNames
:: [Name
] -> RnM
()
1549 -- Check for duplicated names in a binding group
1550 checkDupNames names
= check_dup_names
(filterOut isSystemName names
)
1551 -- See Note [Binders in Template Haskell] in Convert
1553 check_dup_names
:: [Name
] -> RnM
()
1554 check_dup_names names
1555 = mapM_ (dupNamesErr nameSrcSpan
) dups
1557 (_
, dups
) = removeDups
(\n1 n2
-> nameOccName n1 `
compare` nameOccName n2
) names
1559 ---------------------
1560 checkShadowedRdrNames
:: [Located RdrName
] -> RnM
()
1561 checkShadowedRdrNames loc_rdr_names
1562 = do { envs
<- getRdrEnvs
1563 ; checkShadowedOccs envs get_loc_occ filtered_rdrs
}
1565 filtered_rdrs
= filterOut
(isExact
. unLoc
) loc_rdr_names
1566 -- See Note [Binders in Template Haskell] in Convert
1567 get_loc_occ
(L loc rdr
) = (loc
,rdrNameOcc rdr
)
1569 checkDupAndShadowedNames
:: (GlobalRdrEnv
, LocalRdrEnv
) -> [Name
] -> RnM
()
1570 checkDupAndShadowedNames envs names
1571 = do { check_dup_names filtered_names
1572 ; checkShadowedOccs envs get_loc_occ filtered_names
}
1574 filtered_names
= filterOut isSystemName names
1575 -- See Note [Binders in Template Haskell] in Convert
1576 get_loc_occ name
= (nameSrcSpan name
, nameOccName name
)
1578 -------------------------------------
1579 checkShadowedOccs
:: (GlobalRdrEnv
, LocalRdrEnv
)
1580 -> (a
-> (SrcSpan
, OccName
))
1582 checkShadowedOccs
(global_env
,local_env
) get_loc_occ ns
1583 = whenWOptM Opt_WarnNameShadowing
$
1584 do { traceRn
(text
"shadow" <+> ppr
(map get_loc_occ ns
))
1585 ; mapM_ check_shadow ns
}
1588 | startsWithUnderscore occ
= return () -- Do not report shadowing for "_x"
1590 | Just n
<- mb_local
= complain
[ptext
(sLit
"bound at") <+> ppr
(nameSrcLoc n
)]
1591 |
otherwise = do { gres
' <- filterM is_shadowed_gre gres
1592 ; complain
(map pprNameProvenance gres
') }
1594 (loc
,occ
) = get_loc_occ n
1595 mb_local
= lookupLocalRdrOcc local_env occ
1596 gres
= lookupGRE_RdrName
(mkRdrUnqual occ
) global_env
1597 -- Make an Unqualified RdrName and look that up, so that
1598 -- we don't find any GREs that are in scope qualified-only
1600 complain
[] = return ()
1601 complain pp_locs
= addWarnAt loc
(shadowedNameWarn occ pp_locs
)
1603 is_shadowed_gre
:: GlobalRdrElt
-> RnM
Bool
1604 -- Returns False for record selectors that are shadowed, when
1605 -- punning or wild-cards are on (cf Trac #2723)
1606 is_shadowed_gre gre | isRecFldGRE gre
1607 = do { dflags
<- getDynFlags
1608 ; return $ not (xopt Opt_RecordPuns dflags || xopt Opt_RecordWildCards dflags
) }
1609 is_shadowed_gre _other
= return True
1612 ************************************************************************
1614 What to do when a lookup fails
1616 ************************************************************************
1619 data WhereLooking
= WL_Any
-- Any binding
1620 | WL_Global
-- Any top-level binding (local or imported)
1621 | WL_LocalTop
-- Any top-level binding in this module
1623 reportUnboundName
:: RdrName
-> RnM Name
1624 reportUnboundName rdr
= unboundName WL_Any rdr
1626 unboundName
:: WhereLooking
-> RdrName
-> RnM Name
1627 unboundName wl rdr
= unboundNameX wl rdr Outputable
.empty
1629 unboundNameX
:: WhereLooking
-> RdrName
-> SDoc
-> RnM Name
1630 unboundNameX where_look rdr_name extra
1631 = do { dflags
<- getDynFlags
1632 ; let show_helpful_errors
= gopt Opt_HelpfulErrors dflags
1633 what
= pprNonVarNameSpace
(occNameSpace
(rdrNameOcc rdr_name
))
1634 err
= unknownNameErr what rdr_name
$$ extra
1635 ; if not show_helpful_errors
1637 else do { local_env
<- getLocalRdrEnv
1638 ; global_env
<- getGlobalRdrEnv
1639 ; impInfo
<- getImports
1640 ; let suggestions
= unknownNameSuggestions_ where_look
1641 dflags global_env local_env impInfo rdr_name
1642 ; addErr
(err
$$ suggestions
) }
1643 ; return (mkUnboundName rdr_name
) }
1645 unknownNameErr
:: SDoc
-> RdrName
-> SDoc
1646 unknownNameErr what rdr_name
1647 = vcat
[ hang
(ptext
(sLit
"Not in scope:"))
1648 2 (what
<+> quotes
(ppr rdr_name
))
1651 extra | rdr_name
== forall_tv_RDR
= perhapsForallMsg
1652 |
otherwise = Outputable
.empty
1654 type HowInScope
= Either SrcSpan ImpDeclSpec
1655 -- Left loc => locally bound at loc
1656 -- Right ispec => imported as specified by ispec
1659 -- | Called from the typechecker (TcErrors) when we find an unbound variable
1660 unknownNameSuggestions
:: DynFlags
1661 -> GlobalRdrEnv
-> LocalRdrEnv
-> ImportAvails
1663 unknownNameSuggestions
= unknownNameSuggestions_ WL_Any
1665 unknownNameSuggestions_
:: WhereLooking
-> DynFlags
1666 -> GlobalRdrEnv
-> LocalRdrEnv
-> ImportAvails
1668 unknownNameSuggestions_ where_look dflags global_env local_env imports tried_rdr_name
=
1669 similarNameSuggestions where_look dflags global_env local_env tried_rdr_name
$$
1670 importSuggestions dflags imports tried_rdr_name
1673 similarNameSuggestions
:: WhereLooking
-> DynFlags
1674 -> GlobalRdrEnv
-> LocalRdrEnv
1676 similarNameSuggestions where_look dflags global_env
1677 local_env tried_rdr_name
1679 [] -> Outputable
.empty
1680 [p
] -> perhaps
<+> pp_item p
1681 ps
-> sep
[ perhaps
<+> ptext
(sLit
"one of these:")
1682 , nest
2 (pprWithCommas pp_item ps
) ]
1684 all_possibilities
:: [(String, (RdrName
, HowInScope
))]
1686 = [ (showPpr dflags r
, (r
, Left loc
))
1687 |
(r
,loc
) <- local_possibilities local_env
]
1688 ++ [ (showPpr dflags r
, rp
) |
(r
, rp
) <- global_possibilities global_env
]
1690 suggest
= fuzzyLookup
(showPpr dflags tried_rdr_name
) all_possibilities
1691 perhaps
= ptext
(sLit
"Perhaps you meant")
1693 pp_item
:: (RdrName
, HowInScope
) -> SDoc
1694 pp_item
(rdr
, Left loc
) = pp_ns rdr
<+> quotes
(ppr rdr
) <+> loc
' -- Locally defined
1695 where loc
' = case loc
of
1696 UnhelpfulSpan l
-> parens
(ppr l
)
1697 RealSrcSpan l
-> parens
(ptext
(sLit
"line") <+> int
(srcSpanStartLine l
))
1698 pp_item
(rdr
, Right is
) = pp_ns rdr
<+> quotes
(ppr rdr
) <+> -- Imported
1699 parens
(ptext
(sLit
"imported from") <+> ppr
(is_mod is
))
1701 pp_ns
:: RdrName
-> SDoc
1702 pp_ns rdr | ns
/= tried_ns
= pprNameSpace ns
1703 |
otherwise = Outputable
.empty
1704 where ns
= rdrNameSpace rdr
1706 tried_occ
= rdrNameOcc tried_rdr_name
1707 tried_is_sym
= isSymOcc tried_occ
1708 tried_ns
= occNameSpace tried_occ
1709 tried_is_qual
= isQual tried_rdr_name
1711 correct_name_space occ
= nameSpacesRelated
(occNameSpace occ
) tried_ns
1712 && isSymOcc occ
== tried_is_sym
1713 -- Treat operator and non-operators as non-matching
1714 -- This heuristic avoids things like
1715 -- Not in scope 'f'; perhaps you meant '+' (from Prelude)
1717 local_ok
= case where_look
of { WL_Any
-> True; _
-> False }
1718 local_possibilities
:: LocalRdrEnv
-> [(RdrName
, SrcSpan
)]
1719 local_possibilities env
1720 | tried_is_qual
= []
1722 |
otherwise = [ (mkRdrUnqual occ
, nameSrcSpan name
)
1723 | name
<- localRdrEnvElts env
1724 , let occ
= nameOccName name
1725 , correct_name_space occ
]
1727 gre_ok
:: GlobalRdrElt
-> Bool
1728 gre_ok
= case where_look
of
1729 WL_LocalTop
-> isLocalGRE
1732 global_possibilities
:: GlobalRdrEnv
-> [(RdrName
, (RdrName
, HowInScope
))]
1733 global_possibilities global_env
1734 | tried_is_qual
= [ (rdr_qual
, (rdr_qual
, how
))
1735 | gre
<- globalRdrEnvElts global_env
1737 , let name
= gre_name gre
1738 occ
= nameOccName name
1739 , correct_name_space occ
1740 , (mod, how
) <- quals_in_scope gre
1741 , let rdr_qual
= mkRdrQual
mod occ
]
1743 |
otherwise = [ (rdr_unqual
, pair
)
1744 | gre
<- globalRdrEnvElts global_env
1746 , let name
= gre_name gre
1747 occ
= nameOccName name
1748 rdr_unqual
= mkRdrUnqual occ
1749 , correct_name_space occ
1750 , pair
<- case (unquals_in_scope gre
, quals_only gre
) of
1751 (how
:_
, _
) -> [ (rdr_unqual
, how
) ]
1752 ([], pr
:_
) -> [ pr
] -- See Note [Only-quals]
1755 -- Note [Only-quals]
1756 -- The second alternative returns those names with the same
1757 -- OccName as the one we tried, but live in *qualified* imports
1758 -- e.g. if you have:
1760 -- > import qualified Data.Map as Map
1763 -- then we suggest @Map.Map@.
1765 --------------------
1766 unquals_in_scope
:: GlobalRdrElt
-> [HowInScope
]
1767 unquals_in_scope
(GRE
{ gre_name
= n
, gre_lcl
= lcl
, gre_imp
= is
})
1768 | lcl
= [ Left
(nameSrcSpan n
) ]
1769 |
otherwise = [ Right ispec
1770 | i
<- is
, let ispec
= is_decl i
1771 , not (is_qual ispec
) ]
1773 --------------------
1774 quals_in_scope
:: GlobalRdrElt
-> [(ModuleName
, HowInScope
)]
1775 -- Ones for which the qualified version is in scope
1776 quals_in_scope
(GRE
{ gre_name
= n
, gre_lcl
= lcl
, gre_imp
= is
})
1777 | lcl
= case nameModule_maybe n
of
1779 Just m
-> [(moduleName m
, Left
(nameSrcSpan n
))]
1780 |
otherwise = [ (is_as ispec
, Right ispec
)
1781 | i
<- is
, let ispec
= is_decl i
]
1783 --------------------
1784 quals_only
:: GlobalRdrElt
-> [(RdrName
, HowInScope
)]
1785 -- Ones for which *only* the qualified version is in scope
1786 quals_only
(GRE
{ gre_name
= n
, gre_imp
= is
})
1787 = [ (mkRdrQual
(is_as ispec
) (nameOccName n
), Right ispec
)
1788 | i
<- is
, let ispec
= is_decl i
, is_qual ispec
]
1790 -- | Generate helpful suggestions if a qualified name Mod.foo is not in scope.
1791 importSuggestions
:: DynFlags
-> ImportAvails
-> RdrName
-> SDoc
1792 importSuggestions _dflags imports rdr_name
1793 |
not (isQual rdr_name || isUnqual rdr_name
) = Outputable
.empty
1794 |
null interesting_imports
1795 , Just name
<- mod_name
1797 [ ptext
(sLit
"No module named")
1799 , ptext
(sLit
"is imported.")
1802 , null helpful_imports
1803 , [(mod,_
)] <- interesting_imports
1805 [ ptext
(sLit
"Module")
1807 , ptext
(sLit
"does not export")
1808 , quotes
(ppr occ_name
) <> dot
1811 , null helpful_imports
1812 , mods
<- map fst interesting_imports
1814 [ ptext
(sLit
"Neither")
1815 , quotedListWithNor
(map ppr mods
)
1816 , ptext
(sLit
"exports")
1817 , quotes
(ppr occ_name
) <> dot
1819 |
[(mod,imv
)] <- helpful_imports_non_hiding
1821 [ ptext
(sLit
"Perhaps you want to add")
1822 , quotes
(ppr occ_name
)
1823 , ptext
(sLit
"to the import list")
1824 , ptext
(sLit
"in the import of")
1826 , parens
(ppr
(imv_span imv
)) <> dot
1828 |
not (null helpful_imports_non_hiding
)
1830 [ ptext
(sLit
"Perhaps you want to add")
1831 , quotes
(ppr occ_name
)
1832 , ptext
(sLit
"to one of these import lists:")
1836 [ quotes
(ppr
mod) <+> parens
(ppr
(imv_span imv
))
1837 |
(mod,imv
) <- helpful_imports_non_hiding
1839 |
[(mod,imv
)] <- helpful_imports_hiding
1841 [ ptext
(sLit
"Perhaps you want to remove")
1842 , quotes
(ppr occ_name
)
1843 , ptext
(sLit
"from the explicit hiding list")
1844 , ptext
(sLit
"in the import of")
1846 , parens
(ppr
(imv_span imv
)) <> dot
1848 |
not (null helpful_imports_hiding
)
1850 [ ptext
(sLit
"Perhaps you want to remove")
1851 , quotes
(ppr occ_name
)
1852 , ptext
(sLit
"from the hiding clauses")
1853 , ptext
(sLit
"in one of these imports:")
1857 [ quotes
(ppr
mod) <+> parens
(ppr
(imv_span imv
))
1858 |
(mod,imv
) <- helpful_imports_hiding
1863 is_qualified
= isQual rdr_name
1864 (mod_name
, occ_name
) = case rdr_name
of
1865 Unqual occ_name
-> (Nothing
, occ_name
)
1866 Qual mod_name occ_name
-> (Just mod_name
, occ_name
)
1867 _
-> error "importSuggestions: dead code"
1870 -- What import statements provide "Mod" at all
1871 -- or, if this is an unqualified name, are not qualified imports
1872 interesting_imports
= [ (mod, imp
)
1873 |
(mod, mod_imports
) <- moduleEnvToList
(imp_mods imports
)
1874 , Just imp
<- return $ pick mod_imports
1877 -- We want to keep only one for each original module; preferably one with an
1878 -- explicit import list (for no particularly good reason)
1879 pick
:: [ImportedModsVal
] -> Maybe ImportedModsVal
1880 pick
= listToMaybe . sortBy (compare `on` prefer
) . filter select
1881 where select imv
= case mod_name
of Just name
-> imv_name imv
== name
1882 Nothing
-> not (imv_qualified imv
)
1883 prefer imv
= (imv_is_hiding imv
, imv_span imv
)
1885 -- Which of these would export a 'foo'
1886 -- (all of these are restricted imports, because if they were not, we
1887 -- wouldn't have an out-of-scope error in the first place)
1888 helpful_imports
= filter helpful interesting_imports
1889 where helpful
(_
,imv
)
1890 = not . null $ lookupGlobalRdrEnv
(imv_all_exports imv
) occ_name
1892 -- Which of these do that because of an explicit hiding list resp. an
1893 -- explicit import list
1894 (helpful_imports_hiding
, helpful_imports_non_hiding
)
1895 = partition (imv_is_hiding
. snd) helpful_imports
1898 ************************************************************************
1900 \subsection{Free variable manipulation}
1902 ************************************************************************
1906 addFvRn
:: FreeVars
-> RnM
(thing
, FreeVars
) -> RnM
(thing
, FreeVars
)
1907 addFvRn fvs1 thing_inside
= do { (res
, fvs2
) <- thing_inside
1908 ; return (res
, fvs1 `plusFV` fvs2
) }
1910 mapFvRn
:: (a
-> RnM
(b
, FreeVars
)) -> [a
] -> RnM
([b
], FreeVars
)
1911 mapFvRn f xs
= do stuff
<- mapM f xs
1913 (ys
, fvs_s
) -> return (ys
, plusFVs fvs_s
)
1915 mapMaybeFvRn
:: (a
-> RnM
(b
, FreeVars
)) -> Maybe a
-> RnM
(Maybe b
, FreeVars
)
1916 mapMaybeFvRn _ Nothing
= return (Nothing
, emptyFVs
)
1917 mapMaybeFvRn f
(Just x
) = do { (y
, fvs
) <- f x
; return (Just y
, fvs
) }
1919 -- because some of the rename functions are CPSed:
1920 -- maps the function across the list from left to right;
1921 -- collects all the free vars into one set
1922 mapFvRnCPS
:: (a
-> (b
-> RnM c
) -> RnM c
)
1923 -> [a
] -> ([b
] -> RnM c
) -> RnM c
1925 mapFvRnCPS _
[] cont
= cont
[]
1926 mapFvRnCPS f
(x
:xs
) cont
= f x
$ \ x
' ->
1927 mapFvRnCPS f xs
$ \ xs
' ->
1931 ************************************************************************
1933 \subsection{Envt utility functions}
1935 ************************************************************************
1938 warnUnusedTopBinds
:: [GlobalRdrElt
] -> RnM
()
1939 warnUnusedTopBinds gres
1940 = whenWOptM Opt_WarnUnusedTopBinds
1941 $ do env
<- getGblEnv
1942 let isBoot
= tcg_src env
== HsBootFile
1943 let noParent gre
= case gre_par gre
of
1945 PatternSynonym
-> True
1947 -- Don't warn about unused bindings with parents in
1948 -- .hs-boot files, as you are sometimes required to give
1949 -- unused bindings (trac #3449).
1950 -- HOWEVER, in a signature file, you are never obligated to put a
1951 -- definition in the main text. Thus, if you define something
1952 -- and forget to export it, we really DO want to warn.
1953 gres
' = if isBoot
then filter noParent gres
1955 warnUnusedGREs gres
'
1957 warnUnusedLocalBinds
, warnUnusedMatches
:: [Name
] -> FreeVars
-> RnM
()
1958 warnUnusedLocalBinds
= check_unused Opt_WarnUnusedLocalBinds
1959 warnUnusedMatches
= check_unused Opt_WarnUnusedMatches
1961 check_unused
:: WarningFlag
-> [Name
] -> FreeVars
-> RnM
()
1962 check_unused flag bound_names used_names
1963 = whenWOptM flag
(warnUnusedLocals
(filterOut
(`elemNameSet` used_names
) bound_names
))
1965 -------------------------
1967 warnUnusedGREs
:: [GlobalRdrElt
] -> RnM
()
1968 warnUnusedGREs gres
= mapM_ warnUnusedGRE gres
1970 warnUnusedLocals
:: [Name
] -> RnM
()
1971 warnUnusedLocals names
= do
1972 fld_env
<- mkFieldEnv
<$> getGlobalRdrEnv
1973 mapM_ (warnUnusedLocal fld_env
) names
1975 warnUnusedLocal
:: NameEnv
(FieldLabelString
, Name
) -> Name
-> RnM
()
1976 warnUnusedLocal fld_env name
1977 = when (reportable name
) $
1978 addUnusedWarning occ
(nameSrcSpan name
)
1979 (ptext
(sLit
"Defined but not used"))
1981 occ
= case lookupNameEnv fld_env name
of
1982 Just
(fl
, _
) -> mkVarOccFS fl
1983 Nothing
-> nameOccName name
1985 warnUnusedGRE
:: GlobalRdrElt
-> RnM
()
1986 warnUnusedGRE gre
@(GRE
{ gre_name
= name
, gre_lcl
= lcl
, gre_imp
= is
})
1987 | lcl
= do fld_env
<- mkFieldEnv
<$> getGlobalRdrEnv
1988 warnUnusedLocal fld_env name
1989 |
otherwise = when (reportable name
) (mapM_ warn is
)
1991 occ
= greOccName gre
1992 warn spec
= addUnusedWarning occ span msg
1994 span
= importSpecLoc spec
1995 pp_mod
= quotes
(ppr
(importSpecModule spec
))
1996 msg
= ptext
(sLit
"Imported from") <+> pp_mod
<+> ptext
(sLit
"but not used")
1998 -- | Make a map from selector names to field labels and parent tycon
1999 -- names, to be used when reporting unused record fields.
2000 mkFieldEnv
:: GlobalRdrEnv
-> NameEnv
(FieldLabelString
, Name
)
2001 mkFieldEnv rdr_env
= mkNameEnv
[ (gre_name gre
, (lbl
, par_is
(gre_par gre
)))
2002 | gres
<- occEnvElts rdr_env
2004 , Just lbl
<- [greLabel gre
]
2007 reportable
:: Name
-> Bool
2009 | isWiredInName name
= False -- Don't report unused wired-in names
2010 -- Otherwise we get a zillion warnings
2012 |
otherwise = not (startsWithUnderscore
(nameOccName name
))
2014 addUnusedWarning
:: OccName
-> SrcSpan
-> SDoc
-> RnM
()
2015 addUnusedWarning occ span msg
2018 nest
2 $ pprNonVarNameSpace
(occNameSpace occ
)
2019 <+> quotes
(ppr occ
)]
2021 addNameClashErrRn
:: RdrName
-> [GlobalRdrElt
] -> RnM
()
2022 addNameClashErrRn rdr_name gres
2023 |
all isLocalGRE gres
&& not (all isRecFldGRE gres
)
2024 -- If there are two or more *local* defns, we'll have reported
2025 = return () -- that already, and we don't want an error cascade
2027 = addErr
(vcat
[ptext
(sLit
"Ambiguous occurrence") <+> quotes
(ppr rdr_name
),
2028 ptext
(sLit
"It could refer to") <+> vcat
(msg1
: msgs
)])
2031 msg1
= ptext
(sLit
"either") <+> mk_ref np1
2032 msgs
= [ptext
(sLit
" or") <+> mk_ref np | np
<- nps
]
2033 mk_ref gre
= sep
[nom
<> comma
, pprNameProvenance gre
]
2034 where nom
= case gre_par gre
of
2035 FldParent
{ par_lbl
= Just lbl
} -> text
"the field" <+> quotes
(ppr lbl
)
2036 _
-> quotes
(ppr
(gre_name gre
))
2038 shadowedNameWarn
:: OccName
-> [SDoc
] -> SDoc
2039 shadowedNameWarn occ shadowed_locs
2040 = sep
[ptext
(sLit
"This binding for") <+> quotes
(ppr occ
)
2041 <+> ptext
(sLit
"shadows the existing binding") <> plural shadowed_locs
,
2042 nest
2 (vcat shadowed_locs
)]
2044 perhapsForallMsg
:: SDoc
2046 = vcat
[ ptext
(sLit
"Perhaps you intended to use ExplicitForAll or similar flag")
2047 , ptext
(sLit
"to enable explicit-forall syntax: forall <tvs>. <type>")]
2049 unknownSubordinateErr
:: SDoc
-> RdrName
-> SDoc
2050 unknownSubordinateErr doc op
-- Doc is "method of class" or
2051 -- "field of constructor"
2052 = quotes
(ppr op
) <+> ptext
(sLit
"is not a (visible)") <+> doc
2054 badOrigBinding
:: RdrName
-> SDoc
2056 = ptext
(sLit
"Illegal binding of built-in syntax:") <+> ppr
(rdrNameOcc name
)
2057 -- The rdrNameOcc is because we don't want to print Prelude.(,)
2059 dupNamesErr
:: Outputable n
=> (n
-> SrcSpan
) -> [n
] -> RnM
()
2060 dupNamesErr get_loc names
2061 = addErrAt big_loc
$
2062 vcat
[ptext
(sLit
"Conflicting definitions for") <+> quotes
(ppr
(head names
)),
2065 locs
= map get_loc names
2066 big_loc
= foldr1 combineSrcSpans locs
2067 locations
= ptext
(sLit
"Bound at:") <+> vcat
(map ppr
(sort locs
))
2069 kindSigErr
:: Outputable a
=> a
-> SDoc
2071 = hang
(ptext
(sLit
"Illegal kind signature for") <+> quotes
(ppr thing
))
2072 2 (ptext
(sLit
"Perhaps you intended to use KindSignatures"))
2074 badQualBndrErr
:: RdrName
-> SDoc
2075 badQualBndrErr rdr_name
2076 = ptext
(sLit
"Qualified name in binding position:") <+> ppr rdr_name
2078 opDeclErr
:: RdrName
-> SDoc
2080 = hang
(ptext
(sLit
"Illegal declaration of a type or class operator") <+> quotes
(ppr n
))
2081 2 (ptext
(sLit
"Use TypeOperators to declare operators in type and declarations"))
2083 checkTupSize
:: Int -> RnM
()
2084 checkTupSize tup_size
2085 | tup_size
<= mAX_TUPLE_SIZE
2088 = addErr
(sep
[ptext
(sLit
"A") <+> int tup_size
<> ptext
(sLit
"-tuple is too large for GHC"),
2089 nest
2 (parens
(ptext
(sLit
"max size is") <+> int mAX_TUPLE_SIZE
)),
2090 nest
2 (ptext
(sLit
"Workaround: use nested tuples or define a data type"))])
2093 ************************************************************************
2095 \subsection{Contexts for renaming errors}
2097 ************************************************************************
2105 | ForeignDeclCtx
(Located RdrName
)
2107 | RuleCtx FastString
2108 | TyDataCtx
(Located RdrName
)
2109 | TySynCtx
(Located RdrName
)
2110 | TyFamilyCtx
(Located RdrName
)
2111 | ConDeclCtx
[Located RdrName
]
2112 | ClassDeclCtx
(Located RdrName
)
2117 | SpliceTypeCtx
(LHsType RdrName
)
2119 | VectDeclCtx
(Located RdrName
)
2120 | GenericCtx SDoc
-- Maybe we want to use this more!
2122 docOfHsDocContext
:: HsDocContext
-> SDoc
2123 docOfHsDocContext
(GenericCtx doc
) = doc
2124 docOfHsDocContext
(TypeSigCtx doc
) = text
"In the type signature for" <+> doc
2125 docOfHsDocContext PatCtx
= text
"In a pattern type-signature"
2126 docOfHsDocContext SpecInstSigCtx
= text
"In a SPECIALISE instance pragma"
2127 docOfHsDocContext DefaultDeclCtx
= text
"In a `default' declaration"
2128 docOfHsDocContext
(ForeignDeclCtx name
) = ptext
(sLit
"In the foreign declaration for") <+> ppr name
2129 docOfHsDocContext DerivDeclCtx
= text
"In a deriving declaration"
2130 docOfHsDocContext
(RuleCtx name
) = text
"In the transformation rule" <+> ftext name
2131 docOfHsDocContext
(TyDataCtx tycon
) = text
"In the data type declaration for" <+> quotes
(ppr tycon
)
2132 docOfHsDocContext
(TySynCtx name
) = text
"In the declaration for type synonym" <+> quotes
(ppr name
)
2133 docOfHsDocContext
(TyFamilyCtx name
) = text
"In the declaration for type family" <+> quotes
(ppr name
)
2135 docOfHsDocContext
(ConDeclCtx
[name
])
2136 = text
"In the definition of data constructor" <+> quotes
(ppr name
)
2137 docOfHsDocContext
(ConDeclCtx names
)
2138 = text
"In the definition of data constructors" <+> interpp
'SP names
2140 docOfHsDocContext
(ClassDeclCtx name
) = text
"In the declaration for class" <+> ppr name
2141 docOfHsDocContext ExprWithTySigCtx
= text
"In an expression type signature"
2142 docOfHsDocContext TypBrCtx
= ptext
(sLit
"In a Template-Haskell quoted type")
2143 docOfHsDocContext HsTypeCtx
= text
"In a type argument"
2144 docOfHsDocContext GHCiCtx
= ptext
(sLit
"In GHCi input")
2145 docOfHsDocContext
(SpliceTypeCtx hs_ty
) = ptext
(sLit
"In the spliced type") <+> ppr hs_ty
2146 docOfHsDocContext ClassInstanceCtx
= ptext
(sLit
"TcSplice.reifyInstances")
2147 docOfHsDocContext
(VectDeclCtx tycon
) = ptext
(sLit
"In the VECTORISE pragma for type constructor") <+> quotes
(ppr tycon
)