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