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