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