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