Add kind equalities to GHC.
[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 | is_star -> return starKindTyConName
718 | is_uni_star -> return unicodeStarKindTyConName
719 | otherwise -> lookupOccRn rdr_name }
720 where
721 -- With -XNoTypeInType, treat any usage of * in kinds as in scope
722 -- this is a dirty hack, but then again so was the old * kind.
723 fs_name = occNameFS $ rdrNameOcc rdr_name
724 is_star = fs_name == fsLit "*"
725 is_uni_star = fs_name == fsLit "ā˜…"
726
727 -- lookupPromotedOccRn looks up an optionally promoted RdrName.
728 lookupTypeOccRn :: RdrName -> RnM Name
729 -- see Note [Demotion]
730 lookupTypeOccRn rdr_name
731 = do { mb_name <- lookupOccRn_maybe rdr_name
732 ; case mb_name of {
733 Just name -> return name ;
734 Nothing -> lookup_demoted rdr_name } }
735
736 lookup_demoted :: RdrName -> RnM Name
737 lookup_demoted rdr_name
738 | Just demoted_rdr <- demoteRdrName rdr_name
739 -- Maybe it's the name of a *data* constructor
740 = do { data_kinds <- xoptM Opt_DataKinds
741 ; mb_demoted_name <- lookupOccRn_maybe demoted_rdr
742 ; case mb_demoted_name of
743 Nothing -> reportUnboundName rdr_name
744 Just demoted_name
745 | data_kinds ->
746 do { whenWOptM Opt_WarnUntickedPromotedConstructors $
747 addWarn (untickedPromConstrWarn demoted_name)
748 ; return demoted_name }
749 | otherwise -> unboundNameX WL_Any rdr_name suggest_dk }
750
751 | otherwise
752 = reportUnboundName rdr_name
753
754 where
755 suggest_dk = ptext (sLit "A data constructor of that name is in scope; did you mean DataKinds?")
756 untickedPromConstrWarn name =
757 text "Unticked promoted constructor" <> colon <+> quotes (ppr name) <> dot
758 $$
759 hsep [ text "Use"
760 , quotes (char '\'' <> ppr name)
761 , text "instead of"
762 , quotes (ppr name) <> dot ]
763
764 {-
765 Note [Demotion]
766 ~~~~~~~~~~~~~~~
767 When the user writes:
768 data Nat = Zero | Succ Nat
769 foo :: f Zero -> Int
770
771 'Zero' in the type signature of 'foo' is parsed as:
772 HsTyVar ("Zero", TcClsName)
773
774 When the renamer hits this occurrence of 'Zero' it's going to realise
775 that it's not in scope. But because it is renaming a type, it knows
776 that 'Zero' might be a promoted data constructor, so it will demote
777 its namespace to DataName and do a second lookup.
778
779 The final result (after the renamer) will be:
780 HsTyVar ("Zero", DataName)
781 -}
782
783 -- Use this version to get tracing
784 --
785 -- lookupOccRn_maybe, lookupOccRn_maybe' :: RdrName -> RnM (Maybe Name)
786 -- lookupOccRn_maybe rdr_name
787 -- = do { mb_res <- lookupOccRn_maybe' rdr_name
788 -- ; gbl_rdr_env <- getGlobalRdrEnv
789 -- ; local_rdr_env <- getLocalRdrEnv
790 -- ; traceRn $ text "lookupOccRn_maybe" <+>
791 -- vcat [ ppr rdr_name <+> ppr (getUnique (rdrNameOcc rdr_name))
792 -- , ppr mb_res
793 -- , text "Lcl env" <+> ppr local_rdr_env
794 -- , text "Gbl env" <+> ppr [ (getUnique (nameOccName (gre_name (head gres'))),gres') | gres <- occEnvElts gbl_rdr_env
795 -- , let gres' = filter isLocalGRE gres, not (null gres') ] ]
796 -- ; return mb_res }
797
798 lookupOccRn_maybe :: RdrName -> RnM (Maybe Name)
799 -- lookupOccRn looks up an occurrence of a RdrName
800 lookupOccRn_maybe rdr_name
801 = do { local_env <- getLocalRdrEnv
802 ; case lookupLocalRdrEnv local_env rdr_name of {
803 Just name -> return (Just name) ;
804 Nothing -> do
805 ; lookupGlobalOccRn_maybe rdr_name } }
806
807 lookupGlobalOccRn_maybe :: RdrName -> RnM (Maybe Name)
808 -- Looks up a RdrName occurrence in the top-level
809 -- environment, including using lookupQualifiedNameGHCi
810 -- for the GHCi case
811 -- No filter function; does not report an error on failure
812 -- Uses addUsedRdrName to record use and deprecations
813 lookupGlobalOccRn_maybe rdr_name
814 | Just n <- isExact_maybe rdr_name -- This happens in derived code
815 = do { n' <- lookupExactOcc n; return (Just n') }
816
817 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
818 = do { n <- lookupOrig rdr_mod rdr_occ
819 ; return (Just n) }
820
821 | otherwise
822 = do { mb_gre <- lookupGreRn_maybe rdr_name
823 ; case mb_gre of {
824 Just gre -> return (Just (gre_name gre)) ;
825 Nothing ->
826 do { ns <- lookupQualifiedNameGHCi rdr_name
827 -- This test is not expensive,
828 -- and only happens for failed lookups
829 ; case ns of
830 (n:_) -> return (Just n) -- Unlikely to be more than one...?
831 [] -> return Nothing } } }
832
833 lookupGlobalOccRn :: RdrName -> RnM Name
834 -- lookupGlobalOccRn is like lookupOccRn, except that it looks in the global
835 -- environment. Adds an error message if the RdrName is not in scope.
836 lookupGlobalOccRn rdr_name
837 = do { mb_name <- lookupGlobalOccRn_maybe rdr_name
838 ; case mb_name of
839 Just n -> return n
840 Nothing -> do { traceRn (text "lookupGlobalOccRn" <+> ppr rdr_name)
841 ; unboundName WL_Global rdr_name } }
842
843 lookupInfoOccRn :: RdrName -> RnM [Name]
844 -- lookupInfoOccRn is intended for use in GHCi's ":info" command
845 -- It finds all the GREs that RdrName could mean, not complaining
846 -- about ambiguity, but rather returning them all
847 -- C.f. Trac #9881
848 lookupInfoOccRn rdr_name
849 | Just n <- isExact_maybe rdr_name -- e.g. (->)
850 = return [n]
851
852 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
853 = do { n <- lookupOrig rdr_mod rdr_occ
854 ; return [n] }
855
856 | otherwise
857 = do { rdr_env <- getGlobalRdrEnv
858 ; let ns = map gre_name (lookupGRE_RdrName rdr_name rdr_env)
859 ; qual_ns <- lookupQualifiedNameGHCi rdr_name
860 ; return (ns ++ (qual_ns `minusList` ns)) }
861
862 -- | Like 'lookupOccRn_maybe', but with a more informative result if
863 -- the 'RdrName' happens to be a record selector:
864 --
865 -- * Nothing -> name not in scope (no error reported)
866 -- * Just (Left x) -> name uniquely refers to x,
867 -- or there is a name clash (reported)
868 -- * Just (Right xs) -> name refers to one or more record selectors;
869 -- if overload_ok was False, this list will be
870 -- a singleton.
871 lookupOccRn_overloaded :: Bool -> RdrName -> RnM (Maybe (Either Name [FieldOcc Name]))
872 lookupOccRn_overloaded overload_ok rdr_name
873 = do { local_env <- getLocalRdrEnv
874 ; case lookupLocalRdrEnv local_env rdr_name of {
875 Just name -> return (Just (Left name)) ;
876 Nothing -> do
877 { mb_name <- lookupGlobalOccRn_overloaded overload_ok rdr_name
878 ; case mb_name of {
879 Just name -> return (Just name) ;
880 Nothing -> do
881 { ns <- lookupQualifiedNameGHCi rdr_name
882 -- This test is not expensive,
883 -- and only happens for failed lookups
884 ; case ns of
885 (n:_) -> return $ Just $ Left n -- Unlikely to be more than one...?
886 [] -> return Nothing } } } } }
887
888 lookupGlobalOccRn_overloaded :: Bool -> RdrName -> RnM (Maybe (Either Name [FieldOcc Name]))
889 lookupGlobalOccRn_overloaded overload_ok rdr_name
890 | Just n <- isExact_maybe rdr_name -- This happens in derived code
891 = do { n' <- lookupExactOcc n; return (Just (Left n')) }
892
893 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
894 = do { n <- lookupOrig rdr_mod rdr_occ
895 ; return (Just (Left n)) }
896
897 | otherwise
898 = do { env <- getGlobalRdrEnv
899 ; case lookupGRE_RdrName rdr_name env of
900 [] -> return Nothing
901 [gre] | isRecFldGRE gre
902 -> do { addUsedGRE True gre
903 ; let fld_occ :: FieldOcc Name
904 fld_occ = FieldOcc rdr_name (gre_name gre)
905 ; return (Just (Right [fld_occ])) }
906 | otherwise
907 -> do { addUsedGRE True gre
908 ; return (Just (Left (gre_name gre))) }
909 gres | all isRecFldGRE gres && overload_ok
910 -- Don't record usage for ambiguous selectors
911 -- until we know which is meant
912 -> return (Just (Right (map (FieldOcc rdr_name . gre_name) gres)))
913 gres -> do { addNameClashErrRn rdr_name gres
914 ; return (Just (Left (gre_name (head gres)))) } }
915
916
917 --------------------------------------------------
918 -- Lookup in the Global RdrEnv of the module
919 --------------------------------------------------
920
921 lookupGreRn_maybe :: RdrName -> RnM (Maybe GlobalRdrElt)
922 -- Look up the RdrName in the GlobalRdrEnv
923 -- Exactly one binding: records it as "used", return (Just gre)
924 -- No bindings: return Nothing
925 -- Many bindings: report "ambiguous", return an arbitrary (Just gre)
926 -- (This API is a bit strange; lookupGRERn2_maybe is simpler.
927 -- But it works and I don't want to fiddle too much.)
928 -- Uses addUsedRdrName to record use and deprecations
929 lookupGreRn_maybe rdr_name
930 = do { env <- getGlobalRdrEnv
931 ; case lookupGRE_RdrName rdr_name env of
932 [] -> return Nothing
933 [gre] -> do { addUsedGRE True gre
934 ; return (Just gre) }
935 gres -> do { addNameClashErrRn rdr_name gres
936 ; traceRn (text "name clash" <+> (ppr rdr_name $$ ppr gres $$ ppr env))
937 ; return (Just (head gres)) } }
938
939 lookupGreRn2_maybe :: RdrName -> RnM (Maybe GlobalRdrElt)
940 -- Look up the RdrName in the GlobalRdrEnv
941 -- Exactly one binding: record it as "used", return (Just gre)
942 -- No bindings: report "not in scope", return Nothing
943 -- Many bindings: report "ambiguous", return Nothing
944 -- Uses addUsedRdrName to record use and deprecations
945 lookupGreRn2_maybe rdr_name
946 = do { env <- getGlobalRdrEnv
947 ; case lookupGRE_RdrName rdr_name env of
948 [] -> do { _ <- unboundName WL_Global rdr_name
949 ; return Nothing }
950 [gre] -> do { addUsedGRE True gre
951 ; return (Just gre) }
952 gres -> do { addNameClashErrRn rdr_name gres
953 ; traceRn (text "name clash" <+> (ppr rdr_name $$ ppr gres $$ ppr env))
954 ; return Nothing } }
955
956 lookupGreAvailRn :: RdrName -> RnM (Name, AvailInfo)
957 -- Used in export lists
958 -- If not found or ambiguous, add error message, and fake with UnboundName
959 -- Uses addUsedRdrName to record use and deprecations
960 lookupGreAvailRn rdr_name
961 = do { mb_gre <- lookupGreRn2_maybe rdr_name
962 ; case mb_gre of {
963 Just gre -> return (gre_name gre, availFromGRE gre) ;
964 Nothing ->
965 do { traceRn (text "lookupGreRn" <+> ppr rdr_name)
966 ; let name = mkUnboundNameRdr rdr_name
967 ; return (name, avail name) } } }
968
969 {-
970 *********************************************************
971 * *
972 Deprecations
973 * *
974 *********************************************************
975
976 Note [Handling of deprecations]
977 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
978 * We report deprecations at each *occurrence* of the deprecated thing
979 (see Trac #5867)
980
981 * We do not report deprecations for locally-defined names. For a
982 start, we may be exporting a deprecated thing. Also we may use a
983 deprecated thing in the defn of another deprecated things. We may
984 even use a deprecated thing in the defn of a non-deprecated thing,
985 when changing a module's interface.
986
987 * addUsedGREs: we do not report deprecations for sub-binders:
988 - the ".." completion for records
989 - the ".." in an export item 'T(..)'
990 - the things exported by a module export 'module M'
991 -}
992
993 addUsedDataCons :: GlobalRdrEnv -> TyCon -> RnM ()
994 -- Remember use of in-scope data constructors (Trac #7969)
995 addUsedDataCons rdr_env tycon
996 = addUsedGREs [ gre
997 | dc <- tyConDataCons tycon
998 , gre : _ <- [lookupGRE_Name rdr_env (dataConName dc) ] ]
999
1000 addUsedGRE :: Bool -> GlobalRdrElt -> RnM ()
1001 -- Called for both local and imported things
1002 -- Add usage *and* warn if deprecated
1003 addUsedGRE warn_if_deprec gre
1004 = do { when warn_if_deprec (warnIfDeprecated gre)
1005 ; unless (isLocalGRE gre) $
1006 do { env <- getGblEnv
1007 ; traceRn (text "addUsedGRE" <+> ppr gre)
1008 ; updMutVar (tcg_used_gres env) (gre :) } }
1009
1010 addUsedGREs :: [GlobalRdrElt] -> RnM ()
1011 -- Record uses of any *imported* GREs
1012 -- Used for recording used sub-bndrs
1013 -- NB: no call to warnIfDeprecated; see Note [Handling of deprecations]
1014 addUsedGREs gres
1015 | null imp_gres = return ()
1016 | otherwise = do { env <- getGblEnv
1017 ; traceRn (text "addUsedGREs" <+> ppr imp_gres)
1018 ; updMutVar (tcg_used_gres env) (imp_gres ++) }
1019 where
1020 imp_gres = filterOut isLocalGRE gres
1021
1022 warnIfDeprecated :: GlobalRdrElt -> RnM ()
1023 warnIfDeprecated gre@(GRE { gre_name = name, gre_imp = iss })
1024 | (imp_spec : _) <- iss
1025 = do { dflags <- getDynFlags
1026 ; this_mod <- getModule
1027 ; when (wopt Opt_WarnWarningsDeprecations dflags &&
1028 not (nameIsLocalOrFrom this_mod name)) $
1029 -- See Note [Handling of deprecations]
1030 do { iface <- loadInterfaceForName doc name
1031 ; case lookupImpDeprec iface gre of
1032 Just txt -> addWarn (mk_msg imp_spec txt)
1033 Nothing -> return () } }
1034 | otherwise
1035 = return ()
1036 where
1037 occ = greOccName gre
1038 name_mod = ASSERT2( isExternalName name, ppr name ) nameModule name
1039 doc = ptext (sLit "The name") <+> quotes (ppr occ) <+> ptext (sLit "is mentioned explicitly")
1040
1041 mk_msg imp_spec txt
1042 = sep [ sep [ ptext (sLit "In the use of")
1043 <+> pprNonVarNameSpace (occNameSpace occ)
1044 <+> quotes (ppr occ)
1045 , parens imp_msg <> colon ]
1046 , ppr txt ]
1047 where
1048 imp_mod = importSpecModule imp_spec
1049 imp_msg = ptext (sLit "imported from") <+> ppr imp_mod <> extra
1050 extra | imp_mod == moduleName name_mod = Outputable.empty
1051 | otherwise = ptext (sLit ", but defined in") <+> ppr name_mod
1052
1053 lookupImpDeprec :: ModIface -> GlobalRdrElt -> Maybe WarningTxt
1054 lookupImpDeprec iface gre
1055 = mi_warn_fn iface (greOccName gre) `mplus` -- Bleat if the thing,
1056 case gre_par gre of -- or its parent, is warn'd
1057 ParentIs p -> mi_warn_fn iface (nameOccName p)
1058 FldParent { par_is = p } -> mi_warn_fn iface (nameOccName p)
1059 NoParent -> Nothing
1060 PatternSynonym -> Nothing
1061
1062 {-
1063 Note [Used names with interface not loaded]
1064 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1065 It's (just) possible to find a used
1066 Name whose interface hasn't been loaded:
1067
1068 a) It might be a WiredInName; in that case we may not load
1069 its interface (although we could).
1070
1071 b) It might be GHC.Real.fromRational, or GHC.Num.fromInteger
1072 These are seen as "used" by the renamer (if -XRebindableSyntax)
1073 is on), but the typechecker may discard their uses
1074 if in fact the in-scope fromRational is GHC.Read.fromRational,
1075 (see tcPat.tcOverloadedLit), and the typechecker sees that the type
1076 is fixed, say, to GHC.Base.Float (see Inst.lookupSimpleInst).
1077 In that obscure case it won't force the interface in.
1078
1079 In both cases we simply don't permit deprecations;
1080 this is, after all, wired-in stuff.
1081
1082
1083 *********************************************************
1084 * *
1085 GHCi support
1086 * *
1087 *********************************************************
1088
1089 A qualified name on the command line can refer to any module at
1090 all: we try to load the interface if we don't already have it, just
1091 as if there was an "import qualified M" declaration for every
1092 module.
1093
1094 If we fail we just return Nothing, rather than bleating
1095 about "attempting to use module ā€˜Dā€™ (./D.hs) which is not loaded"
1096 which is what loadSrcInterface does.
1097
1098 Note [Safe Haskell and GHCi]
1099 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1100 We DONT do this Safe Haskell as we need to check imports. We can
1101 and should instead check the qualified import but at the moment
1102 this requires some refactoring so leave as a TODO
1103 -}
1104
1105 lookupQualifiedNameGHCi :: RdrName -> RnM [Name]
1106 lookupQualifiedNameGHCi rdr_name
1107 = -- We want to behave as we would for a source file import here,
1108 -- and respect hiddenness of modules/packages, hence loadSrcInterface.
1109 do { dflags <- getDynFlags
1110 ; is_ghci <- getIsGHCi
1111 ; go_for_it dflags is_ghci }
1112
1113 where
1114 go_for_it dflags is_ghci
1115 | Just (mod,occ) <- isQual_maybe rdr_name
1116 , is_ghci
1117 , gopt Opt_ImplicitImportQualified dflags -- Enables this GHCi behaviour
1118 , not (safeDirectImpsReq dflags) -- See Note [Safe Haskell and GHCi]
1119 = do { res <- loadSrcInterface_maybe doc mod False Nothing
1120 ; case res of
1121 Succeeded iface
1122 -> return [ name
1123 | avail <- mi_exports iface
1124 , name <- availNames avail
1125 , nameOccName name == occ ]
1126
1127 _ -> -- Either we couldn't load the interface, or
1128 -- we could but we didn't find the name in it
1129 do { traceRn (text "lookupQualifiedNameGHCi" <+> ppr rdr_name)
1130 ; return [] } }
1131
1132 | otherwise
1133 = do { traceRn (text "lookupQualifedNameGHCi: off" <+> ppr rdr_name)
1134 ; return [] }
1135
1136 doc = ptext (sLit "Need to find") <+> ppr rdr_name
1137
1138 {-
1139 Note [Looking up signature names]
1140 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1141 lookupSigOccRn is used for type signatures and pragmas
1142 Is this valid?
1143 module A
1144 import M( f )
1145 f :: Int -> Int
1146 f x = x
1147 It's clear that the 'f' in the signature must refer to A.f
1148 The Haskell98 report does not stipulate this, but it will!
1149 So we must treat the 'f' in the signature in the same way
1150 as the binding occurrence of 'f', using lookupBndrRn
1151
1152 However, consider this case:
1153 import M( f )
1154 f :: Int -> Int
1155 g x = x
1156 We don't want to say 'f' is out of scope; instead, we want to
1157 return the imported 'f', so that later on the reanamer will
1158 correctly report "misplaced type sig".
1159
1160 Note [Signatures for top level things]
1161 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1162 data HsSigCtxt = ... | TopSigCtxt NameSet | ....
1163
1164 * The NameSet says what is bound in this group of bindings.
1165 We can't use isLocalGRE from the GlobalRdrEnv, because of this:
1166 f x = x
1167 $( ...some TH splice... )
1168 f :: Int -> Int
1169 When we encounter the signature for 'f', the binding for 'f'
1170 will be in the GlobalRdrEnv, and will be a LocalDef. Yet the
1171 signature is mis-placed
1172
1173 * For type signatures the NameSet should be the names bound by the
1174 value bindings; for fixity declarations, the NameSet should also
1175 include class sigs and record selectors
1176
1177 infix 3 `f` -- Yes, ok
1178 f :: C a => a -> a -- No, not ok
1179 class C a where
1180 f :: a -> a
1181 -}
1182
1183 data HsSigCtxt
1184 = TopSigCtxt NameSet -- At top level, binding these names
1185 -- See Note [Signatures for top level things]
1186 | LocalBindCtxt NameSet -- In a local binding, binding these names
1187 | ClsDeclCtxt Name -- Class decl for this class
1188 | InstDeclCtxt NameSet -- Instance decl whose user-written method
1189 -- bindings are for these methods
1190 | HsBootCtxt -- Top level of a hs-boot file
1191 | RoleAnnotCtxt NameSet -- A role annotation, with the names of all types
1192 -- in the group
1193
1194 lookupSigOccRn :: HsSigCtxt
1195 -> Sig RdrName
1196 -> Located RdrName -> RnM (Located Name)
1197 lookupSigOccRn ctxt sig = lookupSigCtxtOccRn ctxt (hsSigDoc sig)
1198
1199 -- | Lookup a name in relation to the names in a 'HsSigCtxt'
1200 lookupSigCtxtOccRn :: HsSigCtxt
1201 -> SDoc -- ^ description of thing we're looking up,
1202 -- like "type family"
1203 -> Located RdrName -> RnM (Located Name)
1204 lookupSigCtxtOccRn ctxt what
1205 = wrapLocM $ \ rdr_name ->
1206 do { mb_name <- lookupBindGroupOcc ctxt what rdr_name
1207 ; case mb_name of
1208 Left err -> do { addErr err; return (mkUnboundNameRdr rdr_name) }
1209 Right name -> return name }
1210
1211 lookupBindGroupOcc :: HsSigCtxt
1212 -> SDoc
1213 -> RdrName -> RnM (Either MsgDoc Name)
1214 -- Looks up the RdrName, expecting it to resolve to one of the
1215 -- bound names passed in. If not, return an appropriate error message
1216 --
1217 -- See Note [Looking up signature names]
1218 lookupBindGroupOcc ctxt what rdr_name
1219 | Just n <- isExact_maybe rdr_name
1220 = lookupExactOcc_either n -- allow for the possibility of missing Exacts;
1221 -- see Note [dataTcOccs and Exact Names]
1222 -- Maybe we should check the side conditions
1223 -- but it's a pain, and Exact things only show
1224 -- up when you know what you are doing
1225
1226 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
1227 = do { n' <- lookupOrig rdr_mod rdr_occ
1228 ; return (Right n') }
1229
1230 | otherwise
1231 = case ctxt of
1232 HsBootCtxt -> lookup_top (const True)
1233 TopSigCtxt ns -> lookup_top (`elemNameSet` ns)
1234 RoleAnnotCtxt ns -> lookup_top (`elemNameSet` ns)
1235 LocalBindCtxt ns -> lookup_group ns
1236 ClsDeclCtxt cls -> lookup_cls_op cls
1237 InstDeclCtxt ns -> lookup_top (`elemNameSet` ns)
1238 where
1239 lookup_cls_op cls
1240 = lookupSubBndrOcc True cls doc rdr_name
1241 where
1242 doc = ptext (sLit "method of class") <+> quotes (ppr cls)
1243
1244 lookup_top keep_me
1245 = do { env <- getGlobalRdrEnv
1246 ; let all_gres = lookupGlobalRdrEnv env (rdrNameOcc rdr_name)
1247 ; case filter (keep_me . gre_name) all_gres of
1248 [] | null all_gres -> bale_out_with Outputable.empty
1249 | otherwise -> bale_out_with local_msg
1250 (gre:_) -> return (Right (gre_name gre)) }
1251
1252 lookup_group bound_names -- Look in the local envt (not top level)
1253 = do { local_env <- getLocalRdrEnv
1254 ; case lookupLocalRdrEnv local_env rdr_name of
1255 Just n
1256 | n `elemNameSet` bound_names -> return (Right n)
1257 | otherwise -> bale_out_with local_msg
1258 Nothing -> bale_out_with Outputable.empty }
1259
1260 bale_out_with msg
1261 = return (Left (sep [ ptext (sLit "The") <+> what
1262 <+> ptext (sLit "for") <+> quotes (ppr rdr_name)
1263 , nest 2 $ ptext (sLit "lacks an accompanying binding")]
1264 $$ nest 2 msg))
1265
1266 local_msg = parens $ ptext (sLit "The") <+> what <+> ptext (sLit "must be given where")
1267 <+> quotes (ppr rdr_name) <+> ptext (sLit "is declared")
1268
1269
1270 ---------------
1271 lookupLocalTcNames :: HsSigCtxt -> SDoc -> RdrName -> RnM [(RdrName, Name)]
1272 -- GHC extension: look up both the tycon and data con or variable.
1273 -- Used for top-level fixity signatures and deprecations.
1274 -- Complain if neither is in scope.
1275 -- See Note [Fixity signature lookup]
1276 lookupLocalTcNames ctxt what rdr_name
1277 = do { mb_gres <- mapM lookup (dataTcOccs rdr_name)
1278 ; let (errs, names) = splitEithers mb_gres
1279 ; when (null names) $ addErr (head errs) -- Bleat about one only
1280 ; return names }
1281 where
1282 lookup rdr = do { name <- lookupBindGroupOcc ctxt what rdr
1283 ; return (fmap ((,) rdr) name) }
1284
1285 dataTcOccs :: RdrName -> [RdrName]
1286 -- Return both the given name and the same name promoted to the TcClsName
1287 -- namespace. This is useful when we aren't sure which we are looking at.
1288 -- See also Note [dataTcOccs and Exact Names]
1289 dataTcOccs rdr_name
1290 | isDataOcc occ || isVarOcc occ
1291 = [rdr_name, rdr_name_tc]
1292 | otherwise
1293 = [rdr_name]
1294 where
1295 occ = rdrNameOcc rdr_name
1296 rdr_name_tc = setRdrNameSpace rdr_name tcName
1297
1298 {-
1299 Note [dataTcOccs and Exact Names]
1300 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1301 Exact RdrNames can occur in code generated by Template Haskell, and generally
1302 those references are, well, exact. However, the TH `Name` type isn't expressive
1303 enough to always track the correct namespace information, so we sometimes get
1304 the right Unique but wrong namespace. Thus, we still have to do the double-lookup
1305 for Exact RdrNames.
1306
1307 There is also an awkward situation for built-in syntax. Example in GHCi
1308 :info []
1309 This parses as the Exact RdrName for nilDataCon, but we also want
1310 the list type constructor.
1311
1312 Note that setRdrNameSpace on an Exact name requires the Name to be External,
1313 which it always is for built in syntax.
1314
1315 *********************************************************
1316 * *
1317 Fixities
1318 * *
1319 *********************************************************
1320
1321 Note [Fixity signature lookup]
1322 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1323 A fixity declaration like
1324
1325 infixr 2 ?
1326
1327 can refer to a value-level operator, e.g.:
1328
1329 (?) :: String -> String -> String
1330
1331 or a type-level operator, like:
1332
1333 data (?) a b = A a | B b
1334
1335 so we extend the lookup of the reader name '?' to the TcClsName namespace, as
1336 well as the original namespace.
1337
1338 The extended lookup is also used in other places, like resolution of
1339 deprecation declarations, and lookup of names in GHCi.
1340 -}
1341
1342 --------------------------------
1343 type MiniFixityEnv = FastStringEnv (Located Fixity)
1344 -- Mini fixity env for the names we're about
1345 -- to bind, in a single binding group
1346 --
1347 -- It is keyed by the *FastString*, not the *OccName*, because
1348 -- the single fixity decl infix 3 T
1349 -- affects both the data constructor T and the type constrctor T
1350 --
1351 -- We keep the location so that if we find
1352 -- a duplicate, we can report it sensibly
1353
1354 --------------------------------
1355 -- Used for nested fixity decls to bind names along with their fixities.
1356 -- the fixities are given as a UFM from an OccName's FastString to a fixity decl
1357
1358 addLocalFixities :: MiniFixityEnv -> [Name] -> RnM a -> RnM a
1359 addLocalFixities mini_fix_env names thing_inside
1360 = extendFixityEnv (mapMaybe find_fixity names) thing_inside
1361 where
1362 find_fixity name
1363 = case lookupFsEnv mini_fix_env (occNameFS occ) of
1364 Just (L _ fix) -> Just (name, FixItem occ fix)
1365 Nothing -> Nothing
1366 where
1367 occ = nameOccName name
1368
1369 {-
1370 --------------------------------
1371 lookupFixity is a bit strange.
1372
1373 * Nested local fixity decls are put in the local fixity env, which we
1374 find with getFixtyEnv
1375
1376 * Imported fixities are found in the HIT or PIT
1377
1378 * Top-level fixity decls in this module may be for Names that are
1379 either Global (constructors, class operations)
1380 or Local/Exported (everything else)
1381 (See notes with RnNames.getLocalDeclBinders for why we have this split.)
1382 We put them all in the local fixity environment
1383 -}
1384
1385 lookupFixityRn :: Name -> RnM Fixity
1386 lookupFixityRn name = lookupFixityRn' name (nameOccName name)
1387
1388 lookupFixityRn' :: Name -> OccName -> RnM Fixity
1389 lookupFixityRn' name occ
1390 | isUnboundName name
1391 = return (Fixity minPrecedence InfixL)
1392 -- Minimise errors from ubound names; eg
1393 -- a>0 `foo` b>0
1394 -- where 'foo' is not in scope, should not give an error (Trac #7937)
1395
1396 | otherwise
1397 = do { local_fix_env <- getFixityEnv
1398 ; case lookupNameEnv local_fix_env name of {
1399 Just (FixItem _ fix) -> return fix ;
1400 Nothing ->
1401
1402 do { this_mod <- getModule
1403 ; if nameIsLocalOrFrom this_mod name
1404 -- Local (and interactive) names are all in the
1405 -- fixity env, and don't have entries in the HPT
1406 then return defaultFixity
1407 else lookup_imported } } }
1408 where
1409 lookup_imported
1410 -- For imported names, we have to get their fixities by doing a
1411 -- loadInterfaceForName, and consulting the Ifaces that comes back
1412 -- from that, because the interface file for the Name might not
1413 -- have been loaded yet. Why not? Suppose you import module A,
1414 -- which exports a function 'f', thus;
1415 -- module CurrentModule where
1416 -- import A( f )
1417 -- module A( f ) where
1418 -- import B( f )
1419 -- Then B isn't loaded right away (after all, it's possible that
1420 -- nothing from B will be used). When we come across a use of
1421 -- 'f', we need to know its fixity, and it's then, and only
1422 -- then, that we load B.hi. That is what's happening here.
1423 --
1424 -- loadInterfaceForName will find B.hi even if B is a hidden module,
1425 -- and that's what we want.
1426 = do { iface <- loadInterfaceForName doc name
1427 ; traceRn (text "lookupFixityRn: looking up name in iface cache and found:" <+>
1428 vcat [ppr name, ppr $ mi_fix_fn iface occ])
1429 ; return (mi_fix_fn iface occ) }
1430
1431 doc = ptext (sLit "Checking fixity for") <+> ppr name
1432
1433 ---------------
1434 lookupTyFixityRn :: Located Name -> RnM Fixity
1435 lookupTyFixityRn (L _ n) = lookupFixityRn n
1436
1437 -- | Look up the fixity of a (possibly ambiguous) occurrence of a record field
1438 -- selector. We use 'lookupFixityRn'' so that we can specifiy the 'OccName' as
1439 -- the field label, which might be different to the 'OccName' of the selector
1440 -- 'Name' if @DuplicateRecordFields@ is in use (Trac #1173). If there are
1441 -- multiple possible selectors with different fixities, generate an error.
1442 lookupFieldFixityRn :: AmbiguousFieldOcc Name -> RnM Fixity
1443 lookupFieldFixityRn (Unambiguous rdr n) = lookupFixityRn' n (rdrNameOcc rdr)
1444 lookupFieldFixityRn (Ambiguous rdr _) = get_ambiguous_fixity rdr
1445 where
1446 get_ambiguous_fixity :: RdrName -> RnM Fixity
1447 get_ambiguous_fixity rdr_name = do
1448 traceRn $ text "get_ambiguous_fixity" <+> ppr rdr_name
1449 rdr_env <- getGlobalRdrEnv
1450 let elts = lookupGRE_RdrName rdr_name rdr_env
1451
1452 fixities <- groupBy ((==) `on` snd) . zip elts
1453 <$> mapM lookup_gre_fixity elts
1454
1455 case fixities of
1456 -- There should always be at least one fixity.
1457 -- Something's very wrong if there are no fixity candidates, so panic
1458 [] -> panic "get_ambiguous_fixity: no candidates for a given RdrName"
1459 [ (_, fix):_ ] -> return fix
1460 ambigs -> addErr (ambiguous_fixity_err rdr_name ambigs)
1461 >> return (Fixity minPrecedence InfixL)
1462
1463 lookup_gre_fixity gre = lookupFixityRn' (gre_name gre) (greOccName gre)
1464
1465 ambiguous_fixity_err rn ambigs
1466 = vcat [ text "Ambiguous fixity for record field" <+> quotes (ppr rn)
1467 , hang (text "Conflicts: ") 2 . vcat .
1468 map format_ambig $ concat ambigs ]
1469
1470 format_ambig (elt, fix) = hang (ppr fix)
1471 2 (pprNameProvenance elt)
1472
1473
1474 {-
1475 ************************************************************************
1476 * *
1477 Rebindable names
1478 Dealing with rebindable syntax is driven by the
1479 Opt_RebindableSyntax dynamic flag.
1480
1481 In "deriving" code we don't want to use rebindable syntax
1482 so we switch off the flag locally
1483
1484 * *
1485 ************************************************************************
1486
1487 Haskell 98 says that when you say "3" you get the "fromInteger" from the
1488 Standard Prelude, regardless of what is in scope. However, to experiment
1489 with having a language that is less coupled to the standard prelude, we're
1490 trying a non-standard extension that instead gives you whatever "Prelude.fromInteger"
1491 happens to be in scope. Then you can
1492 import Prelude ()
1493 import MyPrelude as Prelude
1494 to get the desired effect.
1495
1496 At the moment this just happens for
1497 * fromInteger, fromRational on literals (in expressions and patterns)
1498 * negate (in expressions)
1499 * minus (arising from n+k patterns)
1500 * "do" notation
1501
1502 We store the relevant Name in the HsSyn tree, in
1503 * HsIntegral/HsFractional/HsIsString
1504 * NegApp
1505 * NPlusKPat
1506 * HsDo
1507 respectively. Initially, we just store the "standard" name (PrelNames.fromIntegralName,
1508 fromRationalName etc), but the renamer changes this to the appropriate user
1509 name if Opt_NoImplicitPrelude is on. That is what lookupSyntaxName does.
1510
1511 We treat the orignal (standard) names as free-vars too, because the type checker
1512 checks the type of the user thing against the type of the standard thing.
1513 -}
1514
1515 lookupIfThenElse :: RnM (Maybe (SyntaxExpr Name), FreeVars)
1516 -- Different to lookupSyntaxName because in the non-rebindable
1517 -- case we desugar directly rather than calling an existing function
1518 -- Hence the (Maybe (SyntaxExpr Name)) return type
1519 lookupIfThenElse
1520 = do { rebindable_on <- xoptM Opt_RebindableSyntax
1521 ; if not rebindable_on
1522 then return (Nothing, emptyFVs)
1523 else do { ite <- lookupOccRn (mkVarUnqual (fsLit "ifThenElse"))
1524 ; return (Just (HsVar (noLoc ite)), unitFV ite) } }
1525
1526 lookupSyntaxName :: Name -- The standard name
1527 -> RnM (SyntaxExpr Name, FreeVars) -- Possibly a non-standard name
1528 lookupSyntaxName std_name
1529 = do { rebindable_on <- xoptM Opt_RebindableSyntax
1530 ; if not rebindable_on then
1531 return (HsVar (noLoc std_name), emptyFVs)
1532 else
1533 -- Get the similarly named thing from the local environment
1534 do { usr_name <- lookupOccRn (mkRdrUnqual (nameOccName std_name))
1535 ; return (HsVar (noLoc usr_name), unitFV usr_name) } }
1536
1537 lookupSyntaxNames :: [Name] -- Standard names
1538 -> RnM ([HsExpr Name], FreeVars) -- See comments with HsExpr.ReboundNames
1539 lookupSyntaxNames std_names
1540 = do { rebindable_on <- xoptM Opt_RebindableSyntax
1541 ; if not rebindable_on then
1542 return (map (HsVar . noLoc) std_names, emptyFVs)
1543 else
1544 do { usr_names <- mapM (lookupOccRn . mkRdrUnqual . nameOccName) std_names
1545 ; return (map (HsVar . noLoc) usr_names, mkFVs usr_names) } }
1546
1547 {-
1548 *********************************************************
1549 * *
1550 \subsection{Binding}
1551 * *
1552 *********************************************************
1553 -}
1554
1555 newLocalBndrRn :: Located RdrName -> RnM Name
1556 -- Used for non-top-level binders. These should
1557 -- never be qualified.
1558 newLocalBndrRn (L loc rdr_name)
1559 | Just name <- isExact_maybe rdr_name
1560 = return name -- This happens in code generated by Template Haskell
1561 -- See Note [Binders in Template Haskell] in Convert.hs
1562 | otherwise
1563 = do { unless (isUnqual rdr_name)
1564 (addErrAt loc (badQualBndrErr rdr_name))
1565 ; uniq <- newUnique
1566 ; return (mkInternalName uniq (rdrNameOcc rdr_name) loc) }
1567
1568 newLocalBndrsRn :: [Located RdrName] -> RnM [Name]
1569 newLocalBndrsRn = mapM newLocalBndrRn
1570
1571 ---------------------
1572 bindLocatedLocalsRn :: [Located RdrName]
1573 -> ([Name] -> RnM a)
1574 -> RnM a
1575 bindLocatedLocalsRn rdr_names_w_loc enclosed_scope
1576 = do { checkDupRdrNames rdr_names_w_loc
1577 ; checkShadowedRdrNames rdr_names_w_loc
1578
1579 -- Make fresh Names and extend the environment
1580 ; names <- newLocalBndrsRn rdr_names_w_loc
1581 ; bindLocalNames names (enclosed_scope names) }
1582
1583 bindLocalNames :: [Name] -> RnM a -> RnM a
1584 bindLocalNames names enclosed_scope
1585 = do { lcl_env <- getLclEnv
1586 ; let th_level = thLevel (tcl_th_ctxt lcl_env)
1587 th_bndrs' = extendNameEnvList (tcl_th_bndrs lcl_env)
1588 [ (n, (NotTopLevel, th_level)) | n <- names ]
1589 rdr_env' = extendLocalRdrEnvList (tcl_rdr lcl_env) names
1590 ; setLclEnv (lcl_env { tcl_th_bndrs = th_bndrs'
1591 , tcl_rdr = rdr_env' })
1592 enclosed_scope }
1593
1594 bindLocalNamesFV :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
1595 bindLocalNamesFV names enclosed_scope
1596 = do { (result, fvs) <- bindLocalNames names enclosed_scope
1597 ; return (result, delFVs names fvs) }
1598
1599
1600 -------------------------------------
1601 -- binLocalsFVRn is the same as bindLocalsRn
1602 -- except that it deals with free vars
1603 bindLocatedLocalsFV :: [Located RdrName]
1604 -> ([Name] -> RnM (a,FreeVars)) -> RnM (a, FreeVars)
1605 bindLocatedLocalsFV rdr_names enclosed_scope
1606 = bindLocatedLocalsRn rdr_names $ \ names ->
1607 do (thing, fvs) <- enclosed_scope names
1608 return (thing, delFVs names fvs)
1609
1610 -------------------------------------
1611
1612 extendTyVarEnvFVRn :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
1613 -- This function is used only in rnSourceDecl on InstDecl
1614 extendTyVarEnvFVRn tyvars thing_inside = bindLocalNamesFV tyvars thing_inside
1615
1616 -------------------------------------
1617 checkDupRdrNames :: [Located RdrName] -> RnM ()
1618 -- Check for duplicated names in a binding group
1619 checkDupRdrNames rdr_names_w_loc
1620 = mapM_ (dupNamesErr getLoc) dups
1621 where
1622 (_, dups) = removeDups (\n1 n2 -> unLoc n1 `compare` unLoc n2) rdr_names_w_loc
1623
1624 checkDupNames :: [Name] -> RnM ()
1625 -- Check for duplicated names in a binding group
1626 checkDupNames names = check_dup_names (filterOut isSystemName names)
1627 -- See Note [Binders in Template Haskell] in Convert
1628
1629 check_dup_names :: [Name] -> RnM ()
1630 check_dup_names names
1631 = mapM_ (dupNamesErr nameSrcSpan) dups
1632 where
1633 (_, dups) = removeDups (\n1 n2 -> nameOccName n1 `compare` nameOccName n2) names
1634
1635 ---------------------
1636 checkShadowedRdrNames :: [Located RdrName] -> RnM ()
1637 checkShadowedRdrNames loc_rdr_names
1638 = do { envs <- getRdrEnvs
1639 ; checkShadowedOccs envs get_loc_occ filtered_rdrs }
1640 where
1641 filtered_rdrs = filterOut (isExact . unLoc) loc_rdr_names
1642 -- See Note [Binders in Template Haskell] in Convert
1643 get_loc_occ (L loc rdr) = (loc,rdrNameOcc rdr)
1644
1645 checkDupAndShadowedNames :: (GlobalRdrEnv, LocalRdrEnv) -> [Name] -> RnM ()
1646 checkDupAndShadowedNames envs names
1647 = do { check_dup_names filtered_names
1648 ; checkShadowedOccs envs get_loc_occ filtered_names }
1649 where
1650 filtered_names = filterOut isSystemName names
1651 -- See Note [Binders in Template Haskell] in Convert
1652 get_loc_occ name = (nameSrcSpan name, nameOccName name)
1653
1654 -------------------------------------
1655 checkShadowedOccs :: (GlobalRdrEnv, LocalRdrEnv)
1656 -> (a -> (SrcSpan, OccName))
1657 -> [a] -> RnM ()
1658 checkShadowedOccs (global_env,local_env) get_loc_occ ns
1659 = whenWOptM Opt_WarnNameShadowing $
1660 do { traceRn (text "shadow" <+> ppr (map get_loc_occ ns))
1661 ; mapM_ check_shadow ns }
1662 where
1663 check_shadow n
1664 | startsWithUnderscore occ = return () -- Do not report shadowing for "_x"
1665 -- See Trac #3262
1666 | Just n <- mb_local = complain [ptext (sLit "bound at") <+> ppr (nameSrcLoc n)]
1667 | otherwise = do { gres' <- filterM is_shadowed_gre gres
1668 ; complain (map pprNameProvenance gres') }
1669 where
1670 (loc,occ) = get_loc_occ n
1671 mb_local = lookupLocalRdrOcc local_env occ
1672 gres = lookupGRE_RdrName (mkRdrUnqual occ) global_env
1673 -- Make an Unqualified RdrName and look that up, so that
1674 -- we don't find any GREs that are in scope qualified-only
1675
1676 complain [] = return ()
1677 complain pp_locs = addWarnAt loc (shadowedNameWarn occ pp_locs)
1678
1679 is_shadowed_gre :: GlobalRdrElt -> RnM Bool
1680 -- Returns False for record selectors that are shadowed, when
1681 -- punning or wild-cards are on (cf Trac #2723)
1682 is_shadowed_gre gre | isRecFldGRE gre
1683 = do { dflags <- getDynFlags
1684 ; return $ not (xopt Opt_RecordPuns dflags || xopt Opt_RecordWildCards dflags) }
1685 is_shadowed_gre _other = return True
1686
1687 {-
1688 ************************************************************************
1689 * *
1690 What to do when a lookup fails
1691 * *
1692 ************************************************************************
1693 -}
1694
1695 data WhereLooking = WL_Any -- Any binding
1696 | WL_Global -- Any top-level binding (local or imported)
1697 | WL_LocalTop -- Any top-level binding in this module
1698
1699 reportUnboundName :: RdrName -> RnM Name
1700 reportUnboundName rdr = unboundName WL_Any rdr
1701
1702 unboundName :: WhereLooking -> RdrName -> RnM Name
1703 unboundName wl rdr = unboundNameX wl rdr Outputable.empty
1704
1705 unboundNameX :: WhereLooking -> RdrName -> SDoc -> RnM Name
1706 unboundNameX where_look rdr_name extra
1707 = do { dflags <- getDynFlags
1708 ; let show_helpful_errors = gopt Opt_HelpfulErrors dflags
1709 what = pprNonVarNameSpace (occNameSpace (rdrNameOcc rdr_name))
1710 err = unknownNameErr what rdr_name $$ extra
1711 ; if not show_helpful_errors
1712 then addErr err
1713 else do { local_env <- getLocalRdrEnv
1714 ; global_env <- getGlobalRdrEnv
1715 ; impInfo <- getImports
1716 ; let suggestions = unknownNameSuggestions_ where_look
1717 dflags global_env local_env impInfo rdr_name
1718 ; addErr (err $$ suggestions) }
1719 ; return (mkUnboundNameRdr rdr_name) }
1720
1721 unknownNameErr :: SDoc -> RdrName -> SDoc
1722 unknownNameErr what rdr_name
1723 = vcat [ hang (ptext (sLit "Not in scope:"))
1724 2 (what <+> quotes (ppr rdr_name))
1725 , extra ]
1726 where
1727 extra | rdr_name == forall_tv_RDR = perhapsForallMsg
1728 | otherwise = Outputable.empty
1729
1730 type HowInScope = Either SrcSpan ImpDeclSpec
1731 -- Left loc => locally bound at loc
1732 -- Right ispec => imported as specified by ispec
1733
1734
1735 -- | Called from the typechecker (TcErrors) when we find an unbound variable
1736 unknownNameSuggestions :: DynFlags
1737 -> GlobalRdrEnv -> LocalRdrEnv -> ImportAvails
1738 -> RdrName -> SDoc
1739 unknownNameSuggestions = unknownNameSuggestions_ WL_Any
1740
1741 unknownNameSuggestions_ :: WhereLooking -> DynFlags
1742 -> GlobalRdrEnv -> LocalRdrEnv -> ImportAvails
1743 -> RdrName -> SDoc
1744 unknownNameSuggestions_ where_look dflags global_env local_env imports tried_rdr_name =
1745 similarNameSuggestions where_look dflags global_env local_env tried_rdr_name $$
1746 importSuggestions dflags imports tried_rdr_name
1747
1748
1749 similarNameSuggestions :: WhereLooking -> DynFlags
1750 -> GlobalRdrEnv -> LocalRdrEnv
1751 -> RdrName -> SDoc
1752 similarNameSuggestions where_look dflags global_env
1753 local_env tried_rdr_name
1754 = case suggest of
1755 [] -> Outputable.empty
1756 [p] -> perhaps <+> pp_item p
1757 ps -> sep [ perhaps <+> ptext (sLit "one of these:")
1758 , nest 2 (pprWithCommas pp_item ps) ]
1759 where
1760 all_possibilities :: [(String, (RdrName, HowInScope))]
1761 all_possibilities
1762 = [ (showPpr dflags r, (r, Left loc))
1763 | (r,loc) <- local_possibilities local_env ]
1764 ++ [ (showPpr dflags r, rp) | (r, rp) <- global_possibilities global_env ]
1765
1766 suggest = fuzzyLookup (showPpr dflags tried_rdr_name) all_possibilities
1767 perhaps = ptext (sLit "Perhaps you meant")
1768
1769 pp_item :: (RdrName, HowInScope) -> SDoc
1770 pp_item (rdr, Left loc) = pp_ns rdr <+> quotes (ppr rdr) <+> loc' -- Locally defined
1771 where loc' = case loc of
1772 UnhelpfulSpan l -> parens (ppr l)
1773 RealSrcSpan l -> parens (ptext (sLit "line") <+> int (srcSpanStartLine l))
1774 pp_item (rdr, Right is) = pp_ns rdr <+> quotes (ppr rdr) <+> -- Imported
1775 parens (ptext (sLit "imported from") <+> ppr (is_mod is))
1776
1777 pp_ns :: RdrName -> SDoc
1778 pp_ns rdr | ns /= tried_ns = pprNameSpace ns
1779 | otherwise = Outputable.empty
1780 where ns = rdrNameSpace rdr
1781
1782 tried_occ = rdrNameOcc tried_rdr_name
1783 tried_is_sym = isSymOcc tried_occ
1784 tried_ns = occNameSpace tried_occ
1785 tried_is_qual = isQual tried_rdr_name
1786
1787 correct_name_space occ = nameSpacesRelated (occNameSpace occ) tried_ns
1788 && isSymOcc occ == tried_is_sym
1789 -- Treat operator and non-operators as non-matching
1790 -- This heuristic avoids things like
1791 -- Not in scope 'f'; perhaps you meant '+' (from Prelude)
1792
1793 local_ok = case where_look of { WL_Any -> True; _ -> False }
1794 local_possibilities :: LocalRdrEnv -> [(RdrName, SrcSpan)]
1795 local_possibilities env
1796 | tried_is_qual = []
1797 | not local_ok = []
1798 | otherwise = [ (mkRdrUnqual occ, nameSrcSpan name)
1799 | name <- localRdrEnvElts env
1800 , let occ = nameOccName name
1801 , correct_name_space occ]
1802
1803 gre_ok :: GlobalRdrElt -> Bool
1804 gre_ok = case where_look of
1805 WL_LocalTop -> isLocalGRE
1806 _ -> \_ -> True
1807
1808 global_possibilities :: GlobalRdrEnv -> [(RdrName, (RdrName, HowInScope))]
1809 global_possibilities global_env
1810 | tried_is_qual = [ (rdr_qual, (rdr_qual, how))
1811 | gre <- globalRdrEnvElts global_env
1812 , gre_ok gre
1813 , let name = gre_name gre
1814 occ = nameOccName name
1815 , correct_name_space occ
1816 , (mod, how) <- quals_in_scope gre
1817 , let rdr_qual = mkRdrQual mod occ ]
1818
1819 | otherwise = [ (rdr_unqual, pair)
1820 | gre <- globalRdrEnvElts global_env
1821 , gre_ok gre
1822 , let name = gre_name gre
1823 occ = nameOccName name
1824 rdr_unqual = mkRdrUnqual occ
1825 , correct_name_space occ
1826 , pair <- case (unquals_in_scope gre, quals_only gre) of
1827 (how:_, _) -> [ (rdr_unqual, how) ]
1828 ([], pr:_) -> [ pr ] -- See Note [Only-quals]
1829 ([], []) -> [] ]
1830
1831 -- Note [Only-quals]
1832 -- The second alternative returns those names with the same
1833 -- OccName as the one we tried, but live in *qualified* imports
1834 -- e.g. if you have:
1835 --
1836 -- > import qualified Data.Map as Map
1837 -- > foo :: Map
1838 --
1839 -- then we suggest @Map.Map@.
1840
1841 --------------------
1842 unquals_in_scope :: GlobalRdrElt -> [HowInScope]
1843 unquals_in_scope (GRE { gre_name = n, gre_lcl = lcl, gre_imp = is })
1844 | lcl = [ Left (nameSrcSpan n) ]
1845 | otherwise = [ Right ispec
1846 | i <- is, let ispec = is_decl i
1847 , not (is_qual ispec) ]
1848
1849 --------------------
1850 quals_in_scope :: GlobalRdrElt -> [(ModuleName, HowInScope)]
1851 -- Ones for which the qualified version is in scope
1852 quals_in_scope (GRE { gre_name = n, gre_lcl = lcl, gre_imp = is })
1853 | lcl = case nameModule_maybe n of
1854 Nothing -> []
1855 Just m -> [(moduleName m, Left (nameSrcSpan n))]
1856 | otherwise = [ (is_as ispec, Right ispec)
1857 | i <- is, let ispec = is_decl i ]
1858
1859 --------------------
1860 quals_only :: GlobalRdrElt -> [(RdrName, HowInScope)]
1861 -- Ones for which *only* the qualified version is in scope
1862 quals_only (GRE { gre_name = n, gre_imp = is })
1863 = [ (mkRdrQual (is_as ispec) (nameOccName n), Right ispec)
1864 | i <- is, let ispec = is_decl i, is_qual ispec ]
1865
1866 -- | Generate helpful suggestions if a qualified name Mod.foo is not in scope.
1867 importSuggestions :: DynFlags -> ImportAvails -> RdrName -> SDoc
1868 importSuggestions _dflags imports rdr_name
1869 | not (isQual rdr_name || isUnqual rdr_name) = Outputable.empty
1870 | null interesting_imports
1871 , Just name <- mod_name
1872 = hsep
1873 [ ptext (sLit "No module named")
1874 , quotes (ppr name)
1875 , ptext (sLit "is imported.")
1876 ]
1877 | is_qualified
1878 , null helpful_imports
1879 , [(mod,_)] <- interesting_imports
1880 = hsep
1881 [ ptext (sLit "Module")
1882 , quotes (ppr mod)
1883 , ptext (sLit "does not export")
1884 , quotes (ppr occ_name) <> dot
1885 ]
1886 | is_qualified
1887 , null helpful_imports
1888 , mods <- map fst interesting_imports
1889 = hsep
1890 [ ptext (sLit "Neither")
1891 , quotedListWithNor (map ppr mods)
1892 , ptext (sLit "exports")
1893 , quotes (ppr occ_name) <> dot
1894 ]
1895 | [(mod,imv)] <- helpful_imports_non_hiding
1896 = fsep
1897 [ ptext (sLit "Perhaps you want to add")
1898 , quotes (ppr occ_name)
1899 , ptext (sLit "to the import list")
1900 , ptext (sLit "in the import of")
1901 , quotes (ppr mod)
1902 , parens (ppr (imv_span imv)) <> dot
1903 ]
1904 | not (null helpful_imports_non_hiding)
1905 = fsep
1906 [ ptext (sLit "Perhaps you want to add")
1907 , quotes (ppr occ_name)
1908 , ptext (sLit "to one of these import lists:")
1909 ]
1910 $$
1911 nest 2 (vcat
1912 [ quotes (ppr mod) <+> parens (ppr (imv_span imv))
1913 | (mod,imv) <- helpful_imports_non_hiding
1914 ])
1915 | [(mod,imv)] <- helpful_imports_hiding
1916 = fsep
1917 [ ptext (sLit "Perhaps you want to remove")
1918 , quotes (ppr occ_name)
1919 , ptext (sLit "from the explicit hiding list")
1920 , ptext (sLit "in the import of")
1921 , quotes (ppr mod)
1922 , parens (ppr (imv_span imv)) <> dot
1923 ]
1924 | not (null helpful_imports_hiding)
1925 = fsep
1926 [ ptext (sLit "Perhaps you want to remove")
1927 , quotes (ppr occ_name)
1928 , ptext (sLit "from the hiding clauses")
1929 , ptext (sLit "in one of these imports:")
1930 ]
1931 $$
1932 nest 2 (vcat
1933 [ quotes (ppr mod) <+> parens (ppr (imv_span imv))
1934 | (mod,imv) <- helpful_imports_hiding
1935 ])
1936 | otherwise
1937 = Outputable.empty
1938 where
1939 is_qualified = isQual rdr_name
1940 (mod_name, occ_name) = case rdr_name of
1941 Unqual occ_name -> (Nothing, occ_name)
1942 Qual mod_name occ_name -> (Just mod_name, occ_name)
1943 _ -> error "importSuggestions: dead code"
1944
1945
1946 -- What import statements provide "Mod" at all
1947 -- or, if this is an unqualified name, are not qualified imports
1948 interesting_imports = [ (mod, imp)
1949 | (mod, mod_imports) <- moduleEnvToList (imp_mods imports)
1950 , Just imp <- return $ pick mod_imports
1951 ]
1952
1953 -- We want to keep only one for each original module; preferably one with an
1954 -- explicit import list (for no particularly good reason)
1955 pick :: [ImportedModsVal] -> Maybe ImportedModsVal
1956 pick = listToMaybe . sortBy (compare `on` prefer) . filter select
1957 where select imv = case mod_name of Just name -> imv_name imv == name
1958 Nothing -> not (imv_qualified imv)
1959 prefer imv = (imv_is_hiding imv, imv_span imv)
1960
1961 -- Which of these would export a 'foo'
1962 -- (all of these are restricted imports, because if they were not, we
1963 -- wouldn't have an out-of-scope error in the first place)
1964 helpful_imports = filter helpful interesting_imports
1965 where helpful (_,imv)
1966 = not . null $ lookupGlobalRdrEnv (imv_all_exports imv) occ_name
1967
1968 -- Which of these do that because of an explicit hiding list resp. an
1969 -- explicit import list
1970 (helpful_imports_hiding, helpful_imports_non_hiding)
1971 = partition (imv_is_hiding . snd) helpful_imports
1972
1973 {-
1974 ************************************************************************
1975 * *
1976 \subsection{Free variable manipulation}
1977 * *
1978 ************************************************************************
1979 -}
1980
1981 -- A useful utility
1982 addFvRn :: FreeVars -> RnM (thing, FreeVars) -> RnM (thing, FreeVars)
1983 addFvRn fvs1 thing_inside = do { (res, fvs2) <- thing_inside
1984 ; return (res, fvs1 `plusFV` fvs2) }
1985
1986 mapFvRn :: (a -> RnM (b, FreeVars)) -> [a] -> RnM ([b], FreeVars)
1987 mapFvRn f xs = do stuff <- mapM f xs
1988 case unzip stuff of
1989 (ys, fvs_s) -> return (ys, plusFVs fvs_s)
1990
1991 mapMaybeFvRn :: (a -> RnM (b, FreeVars)) -> Maybe a -> RnM (Maybe b, FreeVars)
1992 mapMaybeFvRn _ Nothing = return (Nothing, emptyFVs)
1993 mapMaybeFvRn f (Just x) = do { (y, fvs) <- f x; return (Just y, fvs) }
1994
1995 -- because some of the rename functions are CPSed:
1996 -- maps the function across the list from left to right;
1997 -- collects all the free vars into one set
1998 mapFvRnCPS :: (a -> (b -> RnM c) -> RnM c)
1999 -> [a] -> ([b] -> RnM c) -> RnM c
2000
2001 mapFvRnCPS _ [] cont = cont []
2002 mapFvRnCPS f (x:xs) cont = f x $ \ x' ->
2003 mapFvRnCPS f xs $ \ xs' ->
2004 cont (x':xs')
2005
2006 {-
2007 ************************************************************************
2008 * *
2009 \subsection{Envt utility functions}
2010 * *
2011 ************************************************************************
2012 -}
2013
2014 warnUnusedTopBinds :: [GlobalRdrElt] -> RnM ()
2015 warnUnusedTopBinds gres
2016 = whenWOptM Opt_WarnUnusedTopBinds
2017 $ do env <- getGblEnv
2018 let isBoot = tcg_src env == HsBootFile
2019 let noParent gre = case gre_par gre of
2020 NoParent -> True
2021 PatternSynonym -> True
2022 _ -> False
2023 -- Don't warn about unused bindings with parents in
2024 -- .hs-boot files, as you are sometimes required to give
2025 -- unused bindings (trac #3449).
2026 -- HOWEVER, in a signature file, you are never obligated to put a
2027 -- definition in the main text. Thus, if you define something
2028 -- and forget to export it, we really DO want to warn.
2029 gres' = if isBoot then filter noParent gres
2030 else gres
2031 warnUnusedGREs gres'
2032
2033 warnUnusedLocalBinds, warnUnusedMatches :: [Name] -> FreeVars -> RnM ()
2034 warnUnusedLocalBinds = check_unused Opt_WarnUnusedLocalBinds
2035 warnUnusedMatches = check_unused Opt_WarnUnusedMatches
2036
2037 check_unused :: WarningFlag -> [Name] -> FreeVars -> RnM ()
2038 check_unused flag bound_names used_names
2039 = whenWOptM flag (warnUnusedLocals (filterOut (`elemNameSet` used_names) bound_names))
2040
2041 -------------------------
2042 -- Helpers
2043 warnUnusedGREs :: [GlobalRdrElt] -> RnM ()
2044 warnUnusedGREs gres = mapM_ warnUnusedGRE gres
2045
2046 warnUnusedLocals :: [Name] -> RnM ()
2047 warnUnusedLocals names = do
2048 fld_env <- mkFieldEnv <$> getGlobalRdrEnv
2049 mapM_ (warnUnusedLocal fld_env) names
2050
2051 warnUnusedLocal :: NameEnv (FieldLabelString, Name) -> Name -> RnM ()
2052 warnUnusedLocal fld_env name
2053 = when (reportable name) $
2054 addUnusedWarning occ (nameSrcSpan name)
2055 (ptext (sLit "Defined but not used"))
2056 where
2057 occ = case lookupNameEnv fld_env name of
2058 Just (fl, _) -> mkVarOccFS fl
2059 Nothing -> nameOccName name
2060
2061 warnUnusedGRE :: GlobalRdrElt -> RnM ()
2062 warnUnusedGRE gre@(GRE { gre_name = name, gre_lcl = lcl, gre_imp = is })
2063 | lcl = do fld_env <- mkFieldEnv <$> getGlobalRdrEnv
2064 warnUnusedLocal fld_env name
2065 | otherwise = when (reportable name) (mapM_ warn is)
2066 where
2067 occ = greOccName gre
2068 warn spec = addUnusedWarning occ span msg
2069 where
2070 span = importSpecLoc spec
2071 pp_mod = quotes (ppr (importSpecModule spec))
2072 msg = ptext (sLit "Imported from") <+> pp_mod <+> ptext (sLit "but not used")
2073
2074 -- | Make a map from selector names to field labels and parent tycon
2075 -- names, to be used when reporting unused record fields.
2076 mkFieldEnv :: GlobalRdrEnv -> NameEnv (FieldLabelString, Name)
2077 mkFieldEnv rdr_env = mkNameEnv [ (gre_name gre, (lbl, par_is (gre_par gre)))
2078 | gres <- occEnvElts rdr_env
2079 , gre <- gres
2080 , Just lbl <- [greLabel gre]
2081 ]
2082
2083 reportable :: Name -> Bool
2084 reportable name
2085 | isWiredInName name = False -- Don't report unused wired-in names
2086 -- Otherwise we get a zillion warnings
2087 -- from Data.Tuple
2088 | otherwise = not (startsWithUnderscore (nameOccName name))
2089
2090 addUnusedWarning :: OccName -> SrcSpan -> SDoc -> RnM ()
2091 addUnusedWarning occ span msg
2092 = addWarnAt span $
2093 sep [msg <> colon,
2094 nest 2 $ pprNonVarNameSpace (occNameSpace occ)
2095 <+> quotes (ppr occ)]
2096
2097 addNameClashErrRn :: RdrName -> [GlobalRdrElt] -> RnM ()
2098 addNameClashErrRn rdr_name gres
2099 | all isLocalGRE gres && not (all isRecFldGRE gres)
2100 -- If there are two or more *local* defns, we'll have reported
2101 = return () -- that already, and we don't want an error cascade
2102 | otherwise
2103 = addErr (vcat [ptext (sLit "Ambiguous occurrence") <+> quotes (ppr rdr_name),
2104 ptext (sLit "It could refer to") <+> vcat (msg1 : msgs)])
2105 where
2106 (np1:nps) = gres
2107 msg1 = ptext (sLit "either") <+> mk_ref np1
2108 msgs = [ptext (sLit " or") <+> mk_ref np | np <- nps]
2109 mk_ref gre = sep [nom <> comma, pprNameProvenance gre]
2110 where nom = case gre_par gre of
2111 FldParent { par_lbl = Just lbl } -> text "the field" <+> quotes (ppr lbl)
2112 _ -> quotes (ppr (gre_name gre))
2113
2114 shadowedNameWarn :: OccName -> [SDoc] -> SDoc
2115 shadowedNameWarn occ shadowed_locs
2116 = sep [ptext (sLit "This binding for") <+> quotes (ppr occ)
2117 <+> ptext (sLit "shadows the existing binding") <> plural shadowed_locs,
2118 nest 2 (vcat shadowed_locs)]
2119
2120 perhapsForallMsg :: SDoc
2121 perhapsForallMsg
2122 = vcat [ ptext (sLit "Perhaps you intended to use ExplicitForAll or similar flag")
2123 , ptext (sLit "to enable explicit-forall syntax: forall <tvs>. <type>")]
2124
2125 unknownSubordinateErr :: SDoc -> RdrName -> SDoc
2126 unknownSubordinateErr doc op -- Doc is "method of class" or
2127 -- "field of constructor"
2128 = quotes (ppr op) <+> ptext (sLit "is not a (visible)") <+> doc
2129
2130 badOrigBinding :: RdrName -> SDoc
2131 badOrigBinding name
2132 = ptext (sLit "Illegal binding of built-in syntax:") <+> ppr (rdrNameOcc name)
2133 -- The rdrNameOcc is because we don't want to print Prelude.(,)
2134
2135 dupNamesErr :: Outputable n => (n -> SrcSpan) -> [n] -> RnM ()
2136 dupNamesErr get_loc names
2137 = addErrAt big_loc $
2138 vcat [ptext (sLit "Conflicting definitions for") <+> quotes (ppr (head names)),
2139 locations]
2140 where
2141 locs = map get_loc names
2142 big_loc = foldr1 combineSrcSpans locs
2143 locations = ptext (sLit "Bound at:") <+> vcat (map ppr (sort locs))
2144
2145 kindSigErr :: Outputable a => a -> SDoc
2146 kindSigErr thing
2147 = hang (ptext (sLit "Illegal kind signature for") <+> quotes (ppr thing))
2148 2 (ptext (sLit "Perhaps you intended to use KindSignatures"))
2149
2150 badQualBndrErr :: RdrName -> SDoc
2151 badQualBndrErr rdr_name
2152 = ptext (sLit "Qualified name in binding position:") <+> ppr rdr_name
2153
2154 opDeclErr :: RdrName -> SDoc
2155 opDeclErr n
2156 = hang (ptext (sLit "Illegal declaration of a type or class operator") <+> quotes (ppr n))
2157 2 (ptext (sLit "Use TypeOperators to declare operators in type and declarations"))
2158
2159 checkTupSize :: Int -> RnM ()
2160 checkTupSize tup_size
2161 | tup_size <= mAX_TUPLE_SIZE
2162 = return ()
2163 | otherwise
2164 = addErr (sep [ptext (sLit "A") <+> int tup_size <> ptext (sLit "-tuple is too large for GHC"),
2165 nest 2 (parens (ptext (sLit "max size is") <+> int mAX_TUPLE_SIZE)),
2166 nest 2 (ptext (sLit "Workaround: use nested tuples or define a data type"))])
2167
2168 {-
2169 ************************************************************************
2170 * *
2171 \subsection{Contexts for renaming errors}
2172 * *
2173 ************************************************************************
2174 -}
2175
2176 -- AZ:TODO: Change these all to be Name instead of RdrName.
2177 -- Merge TcType.UserTypeContext in to it.
2178 data HsDocContext
2179 = TypeSigCtx SDoc
2180 | PatCtx
2181 | SpecInstSigCtx
2182 | DefaultDeclCtx
2183 | ForeignDeclCtx (Located RdrName)
2184 | DerivDeclCtx
2185 | RuleCtx FastString
2186 | TyDataCtx (Located RdrName)
2187 | TySynCtx (Located RdrName)
2188 | TyFamilyCtx (Located RdrName)
2189 | FamPatCtx (Located RdrName) -- The patterns of a type/data family instance
2190 | ConDeclCtx [Located Name]
2191 | ClassDeclCtx (Located RdrName)
2192 | ExprWithTySigCtx
2193 | TypBrCtx
2194 | HsTypeCtx
2195 | GHCiCtx
2196 | SpliceTypeCtx (LHsType RdrName)
2197 | ClassInstanceCtx
2198 | VectDeclCtx (Located RdrName)
2199 | GenericCtx SDoc -- Maybe we want to use this more!
2200
2201 withHsDocContext :: HsDocContext -> SDoc -> SDoc
2202 withHsDocContext ctxt doc = doc $$ inHsDocContext ctxt
2203
2204 inHsDocContext :: HsDocContext -> SDoc
2205 inHsDocContext ctxt = ptext (sLit "In") <+> pprHsDocContext ctxt
2206
2207 pprHsDocContext :: HsDocContext -> SDoc
2208 pprHsDocContext (GenericCtx doc) = doc
2209 pprHsDocContext (TypeSigCtx doc) = text "the type signature for" <+> doc
2210 pprHsDocContext PatCtx = text "a pattern type-signature"
2211 pprHsDocContext SpecInstSigCtx = text "a SPECIALISE instance pragma"
2212 pprHsDocContext DefaultDeclCtx = text "a `default' declaration"
2213 pprHsDocContext DerivDeclCtx = text "a deriving declaration"
2214 pprHsDocContext (RuleCtx name) = text "the transformation rule" <+> ftext name
2215 pprHsDocContext (TyDataCtx tycon) = text "the data type declaration for" <+> quotes (ppr tycon)
2216 pprHsDocContext (FamPatCtx tycon) = text "a type pattern of family instance for" <+> quotes (ppr tycon)
2217 pprHsDocContext (TySynCtx name) = text "the declaration for type synonym" <+> quotes (ppr name)
2218 pprHsDocContext (TyFamilyCtx name) = text "the declaration for type family" <+> quotes (ppr name)
2219 pprHsDocContext (ClassDeclCtx name) = text "the declaration for class" <+> quotes (ppr name)
2220 pprHsDocContext ExprWithTySigCtx = text "an expression type signature"
2221 pprHsDocContext TypBrCtx = text "a Template-Haskell quoted type"
2222 pprHsDocContext HsTypeCtx = text "a type argument"
2223 pprHsDocContext GHCiCtx = text "GHCi input"
2224 pprHsDocContext (SpliceTypeCtx hs_ty) = text "the spliced type" <+> quotes (ppr hs_ty)
2225 pprHsDocContext ClassInstanceCtx = text "TcSplice.reifyInstances"
2226
2227 pprHsDocContext (ForeignDeclCtx name)
2228 = ptext (sLit "the foreign declaration for") <+> quotes (ppr name)
2229 pprHsDocContext (ConDeclCtx [name])
2230 = text "the definition of data constructor" <+> quotes (ppr name)
2231 pprHsDocContext (ConDeclCtx names)
2232 = text "the definition of data constructors" <+> interpp'SP names
2233 pprHsDocContext (VectDeclCtx tycon)
2234 = ptext (sLit "the VECTORISE pragma for type constructor") <+> quotes (ppr tycon)