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