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