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