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