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