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