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