6d940299e4d1f2d7e692a21640d18bdd5cd25846
[ghc.git] / compiler / rename / RnEnv.hs
1 {-
2 (c) The GRASP/AQUA Project, Glasgow University, 1992-2006
3
4 RnEnv contains functions which convert RdrNames into Names.
5
6 -}
7
8 {-# LANGUAGE CPP, MultiWayIf, NamedFieldPuns #-}
9
10 module RnEnv (
11 newTopSrcBinder,
12 lookupLocatedTopBndrRn, lookupTopBndrRn,
13 lookupLocatedOccRn, lookupOccRn, lookupOccRn_maybe,
14 lookupLocalOccRn_maybe, lookupInfoOccRn,
15 lookupLocalOccThLvl_maybe, lookupLocalOccRn,
16 lookupTypeOccRn, lookupKindOccRn,
17 lookupGlobalOccRn, lookupGlobalOccRn_maybe,
18 lookupOccRn_overloaded, lookupGlobalOccRn_overloaded, lookupExactOcc,
19
20 ChildLookupResult(..),
21 lookupSubBndrOcc_helper,
22 combineChildLookupResult, -- Called by lookupChildrenExport
23
24 HsSigCtxt(..), lookupLocalTcNames, lookupSigOccRn,
25 lookupSigCtxtOccRn,
26
27 lookupInstDeclBndr, lookupRecFieldOcc, lookupFamInstName,
28 lookupConstructorFields,
29
30 lookupGreAvailRn,
31
32 -- Rebindable Syntax
33 lookupSyntaxName, lookupSyntaxName', lookupSyntaxNames,
34 lookupIfThenElse,
35
36 -- Constructing usage information
37 addUsedGRE, addUsedGREs, addUsedDataCons,
38
39
40
41 dataTcOccs, --TODO: Move this somewhere, into utils?
42
43 ) where
44
45 #include "HsVersions.h"
46
47 import GhcPrelude
48
49 import LoadIface ( loadInterfaceForName, loadSrcInterface_maybe )
50 import IfaceEnv
51 import HsSyn
52 import RdrName
53 import HscTypes
54 import TcEnv
55 import TcRnMonad
56 import RdrHsSyn ( setRdrNameSpace )
57 import TysWiredIn
58 import Name
59 import NameSet
60 import NameEnv
61 import Avail
62 import Module
63 import ConLike
64 import DataCon
65 import TyCon
66 import ErrUtils ( MsgDoc )
67 import PrelNames ( rOOT_MAIN )
68 import BasicTypes ( pprWarningTxtForMsg, TopLevelFlag(..))
69 import SrcLoc
70 import Outputable
71 import Util
72 import Maybes
73 import DynFlags
74 import FastString
75 import Control.Monad
76 import ListSetOps ( minusList )
77 import qualified GHC.LanguageExtensions as LangExt
78 import RnUnbound
79 import RnUtils
80 import Data.Maybe (isJust)
81 import qualified Data.Semigroup as Semi
82 import Data.Either ( partitionEithers )
83
84 {-
85 *********************************************************
86 * *
87 Source-code binders
88 * *
89 *********************************************************
90
91 Note [Signature lazy interface loading]
92 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
93
94 GHC's lazy interface loading can be a bit confusing, so this Note is an
95 empirical description of what happens in one interesting case. When
96 compiling a signature module against an its implementation, we do NOT
97 load interface files associated with its names until after the type
98 checking phase. For example:
99
100 module ASig where
101 data T
102 f :: T -> T
103
104 Suppose we compile this with -sig-of "A is ASig":
105
106 module B where
107 data T = T
108 f T = T
109
110 module A(module B) where
111 import B
112
113 During type checking, we'll load A.hi because we need to know what the
114 RdrEnv for the module is, but we DO NOT load the interface for B.hi!
115 It's wholly unnecessary: our local definition 'data T' in ASig is all
116 the information we need to finish type checking. This is contrast to
117 type checking of ordinary Haskell files, in which we would not have the
118 local definition "data T" and would need to consult B.hi immediately.
119 (Also, this situation never occurs for hs-boot files, since you're not
120 allowed to reexport from another module.)
121
122 After type checking, we then check that the types we provided are
123 consistent with the backing implementation (in checkHiBootOrHsigIface).
124 At this point, B.hi is loaded, because we need something to compare
125 against.
126
127 I discovered this behavior when trying to figure out why type class
128 instances for Data.Map weren't in the EPS when I was type checking a
129 test very much like ASig (sigof02dm): the associated interface hadn't
130 been loaded yet! (The larger issue is a moot point, since an instance
131 declared in a signature can never be a duplicate.)
132
133 This behavior might change in the future. Consider this
134 alternate module B:
135
136 module B where
137 {-# DEPRECATED T, f "Don't use" #-}
138 data T = T
139 f T = T
140
141 One might conceivably want to report deprecation warnings when compiling
142 ASig with -sig-of B, in which case we need to look at B.hi to find the
143 deprecation warnings during renaming. At the moment, you don't get any
144 warning until you use the identifier further downstream. This would
145 require adjusting addUsedGRE so that during signature compilation,
146 we do not report deprecation warnings for LocalDef. See also
147 Note [Handling of deprecations]
148 -}
149
150 newTopSrcBinder :: Located RdrName -> RnM Name
151 newTopSrcBinder (L loc rdr_name)
152 | Just name <- isExact_maybe rdr_name
153 = -- This is here to catch
154 -- (a) Exact-name binders created by Template Haskell
155 -- (b) The PrelBase defn of (say) [] and similar, for which
156 -- the parser reads the special syntax and returns an Exact RdrName
157 -- We are at a binding site for the name, so check first that it
158 -- the current module is the correct one; otherwise GHC can get
159 -- very confused indeed. This test rejects code like
160 -- data T = (,) Int Int
161 -- unless we are in GHC.Tup
162 if isExternalName name then
163 do { this_mod <- getModule
164 ; unless (this_mod == nameModule name)
165 (addErrAt loc (badOrigBinding rdr_name))
166 ; return name }
167 else -- See Note [Binders in Template Haskell] in Convert.hs
168 do { this_mod <- getModule
169 ; externaliseName this_mod name }
170
171 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
172 = do { this_mod <- getModule
173 ; unless (rdr_mod == this_mod || rdr_mod == rOOT_MAIN)
174 (addErrAt loc (badOrigBinding rdr_name))
175 -- When reading External Core we get Orig names as binders,
176 -- but they should agree with the module gotten from the monad
177 --
178 -- We can get built-in syntax showing up here too, sadly. If you type
179 -- data T = (,,,)
180 -- the constructor is parsed as a type, and then RdrHsSyn.tyConToDataCon
181 -- uses setRdrNameSpace to make it into a data constructors. At that point
182 -- the nice Exact name for the TyCon gets swizzled to an Orig name.
183 -- Hence the badOrigBinding error message.
184 --
185 -- Except for the ":Main.main = ..." definition inserted into
186 -- the Main module; ugh!
187
188 -- Because of this latter case, we call newGlobalBinder with a module from
189 -- the RdrName, not from the environment. In principle, it'd be fine to
190 -- have an arbitrary mixture of external core definitions in a single module,
191 -- (apart from module-initialisation issues, perhaps).
192 ; newGlobalBinder rdr_mod rdr_occ loc }
193
194 | otherwise
195 = do { when (isQual rdr_name)
196 (addErrAt loc (badQualBndrErr rdr_name))
197 -- Binders should not be qualified; if they are, and with a different
198 -- module name, we get a confusing "M.T is not in scope" error later
199
200 ; stage <- getStage
201 ; if isBrackStage stage then
202 -- We are inside a TH bracket, so make an *Internal* name
203 -- See Note [Top-level Names in Template Haskell decl quotes] in RnNames
204 do { uniq <- newUnique
205 ; return (mkInternalName uniq (rdrNameOcc rdr_name) loc) }
206 else
207 do { this_mod <- getModule
208 ; traceRn "newTopSrcBinder" (ppr this_mod $$ ppr rdr_name $$ ppr loc)
209 ; newGlobalBinder this_mod (rdrNameOcc rdr_name) loc }
210 }
211
212 {-
213 *********************************************************
214 * *
215 Source code occurrences
216 * *
217 *********************************************************
218
219 Looking up a name in the RnEnv.
220
221 Note [Type and class operator definitions]
222 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
223 We want to reject all of these unless we have -XTypeOperators (Trac #3265)
224 data a :*: b = ...
225 class a :*: b where ...
226 data (:*:) a b = ....
227 class (:*:) a b where ...
228 The latter two mean that we are not just looking for a
229 *syntactically-infix* declaration, but one that uses an operator
230 OccName. We use OccName.isSymOcc to detect that case, which isn't
231 terribly efficient, but there seems to be no better way.
232 -}
233
234 -- Can be made to not be exposed
235 -- Only used unwrapped in rnAnnProvenance
236 lookupTopBndrRn :: RdrName -> RnM Name
237 lookupTopBndrRn n = do nopt <- lookupTopBndrRn_maybe n
238 case nopt of
239 Just n' -> return n'
240 Nothing -> do traceRn "lookupTopBndrRn fail" (ppr n)
241 unboundName WL_LocalTop n
242
243 lookupLocatedTopBndrRn :: Located RdrName -> RnM (Located Name)
244 lookupLocatedTopBndrRn = wrapLocM lookupTopBndrRn
245
246 lookupTopBndrRn_maybe :: RdrName -> RnM (Maybe Name)
247 -- Look up a top-level source-code binder. We may be looking up an unqualified 'f',
248 -- and there may be several imported 'f's too, which must not confuse us.
249 -- For example, this is OK:
250 -- import Foo( f )
251 -- infix 9 f -- The 'f' here does not need to be qualified
252 -- f x = x -- Nor here, of course
253 -- So we have to filter out the non-local ones.
254 --
255 -- A separate function (importsFromLocalDecls) reports duplicate top level
256 -- decls, so here it's safe just to choose an arbitrary one.
257 --
258 -- There should never be a qualified name in a binding position in Haskell,
259 -- but there can be if we have read in an external-Core file.
260 -- The Haskell parser checks for the illegal qualified name in Haskell
261 -- source files, so we don't need to do so here.
262
263 lookupTopBndrRn_maybe rdr_name =
264 lookupExactOrOrig rdr_name Just $
265 do { -- Check for operators in type or class declarations
266 -- See Note [Type and class operator definitions]
267 let occ = rdrNameOcc rdr_name
268 ; when (isTcOcc occ && isSymOcc occ)
269 (do { op_ok <- xoptM LangExt.TypeOperators
270 ; unless op_ok (addErr (opDeclErr rdr_name)) })
271
272 ; env <- getGlobalRdrEnv
273 ; case filter isLocalGRE (lookupGRE_RdrName rdr_name env) of
274 [gre] -> return (Just (gre_name gre))
275 _ -> return Nothing -- Ambiguous (can't happen) or unbound
276 }
277
278 -----------------------------------------------
279 -- | Lookup an @Exact@ @RdrName@. See Note [Looking up Exact RdrNames].
280 -- This adds an error if the name cannot be found.
281 lookupExactOcc :: Name -> RnM Name
282 lookupExactOcc name
283 = do { result <- lookupExactOcc_either name
284 ; case result of
285 Left err -> do { addErr err
286 ; return name }
287 Right name' -> return name' }
288
289 -- | Lookup an @Exact@ @RdrName@. See Note [Looking up Exact RdrNames].
290 -- This never adds an error, but it may return one.
291 lookupExactOcc_either :: Name -> RnM (Either MsgDoc Name)
292 -- See Note [Looking up Exact RdrNames]
293 lookupExactOcc_either name
294 | Just thing <- wiredInNameTyThing_maybe name
295 , Just tycon <- case thing of
296 ATyCon tc -> Just tc
297 AConLike (RealDataCon dc) -> Just (dataConTyCon dc)
298 _ -> Nothing
299 , isTupleTyCon tycon
300 = do { checkTupSize (tyConArity tycon)
301 ; return (Right name) }
302
303 | isExternalName name
304 = return (Right name)
305
306 | otherwise
307 = do { env <- getGlobalRdrEnv
308 ; let -- See Note [Splicing Exact names]
309 main_occ = nameOccName name
310 demoted_occs = case demoteOccName main_occ of
311 Just occ -> [occ]
312 Nothing -> []
313 gres = [ gre | occ <- main_occ : demoted_occs
314 , gre <- lookupGlobalRdrEnv env occ
315 , gre_name gre == name ]
316 ; case gres of
317 [gre] -> return (Right (gre_name gre))
318
319 [] -> -- See Note [Splicing Exact names]
320 do { lcl_env <- getLocalRdrEnv
321 ; if name `inLocalRdrEnvScope` lcl_env
322 then return (Right name)
323 else
324 do { th_topnames_var <- fmap tcg_th_topnames getGblEnv
325 ; th_topnames <- readTcRef th_topnames_var
326 ; if name `elemNameSet` th_topnames
327 then return (Right name)
328 else return (Left exact_nm_err)
329 }
330 }
331 gres -> return (Left (sameNameErr gres)) -- Ugh! See Note [Template Haskell ambiguity]
332 }
333 where
334 exact_nm_err = hang (text "The exact Name" <+> quotes (ppr name) <+> ptext (sLit "is not in scope"))
335 2 (vcat [ text "Probable cause: you used a unique Template Haskell name (NameU), "
336 , text "perhaps via newName, but did not bind it"
337 , text "If that's it, then -ddump-splices might be useful" ])
338
339 sameNameErr :: [GlobalRdrElt] -> MsgDoc
340 sameNameErr [] = panic "addSameNameErr: empty list"
341 sameNameErr gres@(_ : _)
342 = hang (text "Same exact name in multiple name-spaces:")
343 2 (vcat (map pp_one sorted_names) $$ th_hint)
344 where
345 sorted_names = sortWith nameSrcLoc (map gre_name gres)
346 pp_one name
347 = hang (pprNameSpace (occNameSpace (getOccName name))
348 <+> quotes (ppr name) <> comma)
349 2 (text "declared at:" <+> ppr (nameSrcLoc name))
350
351 th_hint = vcat [ text "Probable cause: you bound a unique Template Haskell name (NameU),"
352 , text "perhaps via newName, in different name-spaces."
353 , text "If that's it, then -ddump-splices might be useful" ]
354
355
356 -----------------------------------------------
357 lookupInstDeclBndr :: Name -> SDoc -> RdrName -> RnM Name
358 -- This is called on the method name on the left-hand side of an
359 -- instance declaration binding. eg. instance Functor T where
360 -- fmap = ...
361 -- ^^^^ called on this
362 -- Regardless of how many unqualified fmaps are in scope, we want
363 -- the one that comes from the Functor class.
364 --
365 -- Furthermore, note that we take no account of whether the
366 -- name is only in scope qualified. I.e. even if method op is
367 -- in scope as M.op, we still allow plain 'op' on the LHS of
368 -- an instance decl
369 --
370 -- The "what" parameter says "method" or "associated type",
371 -- depending on what we are looking up
372 lookupInstDeclBndr cls what rdr
373 = do { when (isQual rdr)
374 (addErr (badQualBndrErr rdr))
375 -- In an instance decl you aren't allowed
376 -- to use a qualified name for the method
377 -- (Although it'd make perfect sense.)
378 ; mb_name <- lookupSubBndrOcc
379 False -- False => we don't give deprecated
380 -- warnings when a deprecated class
381 -- method is defined. We only warn
382 -- when it's used
383 cls doc rdr
384 ; case mb_name of
385 Left err -> do { addErr err; return (mkUnboundNameRdr rdr) }
386 Right nm -> return nm }
387 where
388 doc = what <+> text "of class" <+> quotes (ppr cls)
389
390 -----------------------------------------------
391 lookupFamInstName :: Maybe Name -> Located RdrName
392 -> RnM (Located Name)
393 -- Used for TyData and TySynonym family instances only,
394 -- See Note [Family instance binders]
395 lookupFamInstName (Just cls) tc_rdr -- Associated type; c.f RnBinds.rnMethodBind
396 = wrapLocM (lookupInstDeclBndr cls (text "associated type")) tc_rdr
397 lookupFamInstName Nothing tc_rdr -- Family instance; tc_rdr is an *occurrence*
398 = lookupLocatedOccRn tc_rdr
399
400 -----------------------------------------------
401 lookupConstructorFields :: Name -> RnM [FieldLabel]
402 -- Look up the fields of a given constructor
403 -- * For constructors from this module, use the record field env,
404 -- which is itself gathered from the (as yet un-typechecked)
405 -- data type decls
406 --
407 -- * For constructors from imported modules, use the *type* environment
408 -- since imported modles are already compiled, the info is conveniently
409 -- right there
410
411 lookupConstructorFields con_name
412 = do { this_mod <- getModule
413 ; if nameIsLocalOrFrom this_mod con_name then
414 do { field_env <- getRecFieldEnv
415 ; traceTc "lookupCF" (ppr con_name $$ ppr (lookupNameEnv field_env con_name) $$ ppr field_env)
416 ; return (lookupNameEnv field_env con_name `orElse` []) }
417 else
418 do { con <- tcLookupConLike con_name
419 ; traceTc "lookupCF 2" (ppr con)
420 ; return (conLikeFieldLabels con) } }
421
422
423 -- In CPS style as `RnM r` is monadic
424 lookupExactOrOrig :: RdrName -> (Name -> r) -> RnM r -> RnM r
425 lookupExactOrOrig rdr_name res k
426 | Just n <- isExact_maybe rdr_name -- This happens in derived code
427 = res <$> lookupExactOcc n
428 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
429 = res <$> lookupOrig rdr_mod rdr_occ
430 | otherwise = k
431
432
433
434 -----------------------------------------------
435 -- Used for record construction and pattern matching
436 -- When the -XDisambiguateRecordFields flag is on, take account of the
437 -- constructor name to disambiguate which field to use; it's just the
438 -- same as for instance decls
439 --
440 -- NB: Consider this:
441 -- module Foo where { data R = R { fld :: Int } }
442 -- module Odd where { import Foo; fld x = x { fld = 3 } }
443 -- Arguably this should work, because the reference to 'fld' is
444 -- unambiguous because there is only one field id 'fld' in scope.
445 -- But currently it's rejected.
446
447 lookupRecFieldOcc :: Maybe Name -- Nothing => just look it up as usual
448 -- Just tycon => use tycon to disambiguate
449 -> SDoc -> RdrName
450 -> RnM Name
451 lookupRecFieldOcc parent doc rdr_name
452 | Just tc_name <- parent
453 = do { mb_name <- lookupSubBndrOcc True tc_name doc rdr_name
454 ; case mb_name of
455 Left err -> do { addErr err; return (mkUnboundNameRdr rdr_name) }
456 Right n -> return n }
457
458 | otherwise
459 -- This use of Global is right as we are looking up a selector which
460 -- can only be defined at the top level.
461 = lookupGlobalOccRn rdr_name
462
463
464
465 -- | Used in export lists to lookup the children.
466 lookupSubBndrOcc_helper :: Bool -> Bool -> Name -> RdrName
467 -> RnM ChildLookupResult
468 lookupSubBndrOcc_helper must_have_parent warn_if_deprec parent rdr_name
469 | isUnboundName parent
470 -- Avoid an error cascade
471 = return (FoundName NoParent (mkUnboundNameRdr rdr_name))
472
473 | otherwise = do
474 gre_env <- getGlobalRdrEnv
475
476 let original_gres = lookupGlobalRdrEnv gre_env (rdrNameOcc rdr_name)
477 -- Disambiguate the lookup based on the parent information.
478 -- The remaining GREs are things that we *could* export here, note that
479 -- this includes things which have `NoParent`. Those are sorted in
480 -- `checkPatSynParent`.
481 traceRn "parent" (ppr parent)
482 traceRn "lookupExportChild original_gres:" (ppr original_gres)
483 traceRn "lookupExportChild picked_gres:" (ppr $ picked_gres original_gres)
484 case picked_gres original_gres of
485 NoOccurrence ->
486 noMatchingParentErr original_gres
487 UniqueOccurrence g ->
488 if must_have_parent then noMatchingParentErr original_gres
489 else checkFld g
490 DisambiguatedOccurrence g ->
491 checkFld g
492 AmbiguousOccurrence gres ->
493 mkNameClashErr gres
494 where
495 -- Convert into FieldLabel if necessary
496 checkFld :: GlobalRdrElt -> RnM ChildLookupResult
497 checkFld g@GRE{gre_name, gre_par} = do
498 addUsedGRE warn_if_deprec g
499 return $ case gre_par of
500 FldParent _ mfs ->
501 FoundFL (fldParentToFieldLabel gre_name mfs)
502 _ -> FoundName gre_par gre_name
503
504 fldParentToFieldLabel :: Name -> Maybe FastString -> FieldLabel
505 fldParentToFieldLabel name mfs =
506 case mfs of
507 Nothing ->
508 let fs = occNameFS (nameOccName name)
509 in FieldLabel fs False name
510 Just fs -> FieldLabel fs True name
511
512 -- Called when we find no matching GREs after disambiguation but
513 -- there are three situations where this happens.
514 -- 1. There were none to begin with.
515 -- 2. None of the matching ones were the parent but
516 -- a. They were from an overloaded record field so we can report
517 -- a better error
518 -- b. The original lookup was actually ambiguous.
519 -- For example, the case where overloading is off and two
520 -- record fields are in scope from different record
521 -- constructors, neither of which is the parent.
522 noMatchingParentErr :: [GlobalRdrElt] -> RnM ChildLookupResult
523 noMatchingParentErr original_gres = do
524 overload_ok <- xoptM LangExt.DuplicateRecordFields
525 case original_gres of
526 [] -> return NameNotFound
527 [g] -> return $ IncorrectParent parent
528 (gre_name g) (ppr $ gre_name g)
529 [p | Just p <- [getParent g]]
530 gss@(g:_:_) ->
531 if all isRecFldGRE gss && overload_ok
532 then return $
533 IncorrectParent parent
534 (gre_name g)
535 (ppr $ expectJust "noMatchingParentErr" (greLabel g))
536 [p | x <- gss, Just p <- [getParent x]]
537 else mkNameClashErr gss
538
539 mkNameClashErr :: [GlobalRdrElt] -> RnM ChildLookupResult
540 mkNameClashErr gres = do
541 addNameClashErrRn rdr_name gres
542 return (FoundName (gre_par (head gres)) (gre_name (head gres)))
543
544 getParent :: GlobalRdrElt -> Maybe Name
545 getParent (GRE { gre_par = p } ) =
546 case p of
547 ParentIs cur_parent -> Just cur_parent
548 FldParent { par_is = cur_parent } -> Just cur_parent
549 NoParent -> Nothing
550
551 picked_gres :: [GlobalRdrElt] -> DisambigInfo
552 picked_gres gres
553 | isUnqual rdr_name
554 = mconcat (map right_parent gres)
555 | otherwise
556 = mconcat (map right_parent (pickGREs rdr_name gres))
557
558
559 right_parent :: GlobalRdrElt -> DisambigInfo
560 right_parent p
561 | Just cur_parent <- getParent p
562 = if parent == cur_parent
563 then DisambiguatedOccurrence p
564 else NoOccurrence
565 | otherwise
566 = UniqueOccurrence p
567
568
569 -- This domain specific datatype is used to record why we decided it was
570 -- possible that a GRE could be exported with a parent.
571 data DisambigInfo
572 = NoOccurrence
573 -- The GRE could never be exported. It has the wrong parent.
574 | UniqueOccurrence GlobalRdrElt
575 -- The GRE has no parent. It could be a pattern synonym.
576 | DisambiguatedOccurrence GlobalRdrElt
577 -- The parent of the GRE is the correct parent
578 | AmbiguousOccurrence [GlobalRdrElt]
579 -- For example, two normal identifiers with the same name are in
580 -- scope. They will both be resolved to "UniqueOccurrence" and the
581 -- monoid will combine them to this failing case.
582
583 instance Outputable DisambigInfo where
584 ppr NoOccurrence = text "NoOccurence"
585 ppr (UniqueOccurrence gre) = text "UniqueOccurrence:" <+> ppr gre
586 ppr (DisambiguatedOccurrence gre) = text "DiambiguatedOccurrence:" <+> ppr gre
587 ppr (AmbiguousOccurrence gres) = text "Ambiguous:" <+> ppr gres
588
589 instance Semi.Semigroup DisambigInfo where
590 -- This is the key line: We prefer disambiguated occurrences to other
591 -- names.
592 _ <> DisambiguatedOccurrence g' = DisambiguatedOccurrence g'
593 DisambiguatedOccurrence g' <> _ = DisambiguatedOccurrence g'
594
595 NoOccurrence <> m = m
596 m <> NoOccurrence = m
597 UniqueOccurrence g <> UniqueOccurrence g'
598 = AmbiguousOccurrence [g, g']
599 UniqueOccurrence g <> AmbiguousOccurrence gs
600 = AmbiguousOccurrence (g:gs)
601 AmbiguousOccurrence gs <> UniqueOccurrence g'
602 = AmbiguousOccurrence (g':gs)
603 AmbiguousOccurrence gs <> AmbiguousOccurrence gs'
604 = AmbiguousOccurrence (gs ++ gs')
605
606 instance Monoid DisambigInfo where
607 mempty = NoOccurrence
608 mappend = (Semi.<>)
609
610 -- Lookup SubBndrOcc can never be ambiguous
611 --
612 -- Records the result of looking up a child.
613 data ChildLookupResult
614 = NameNotFound -- We couldn't find a suitable name
615 | IncorrectParent Name -- Parent
616 Name -- Name of thing we were looking for
617 SDoc -- How to print the name
618 [Name] -- List of possible parents
619 | FoundName Parent Name -- We resolved to a normal name
620 | FoundFL FieldLabel -- We resolved to a FL
621
622 -- | Specialised version of msum for RnM ChildLookupResult
623 combineChildLookupResult :: [RnM ChildLookupResult] -> RnM ChildLookupResult
624 combineChildLookupResult [] = return NameNotFound
625 combineChildLookupResult (x:xs) = do
626 res <- x
627 case res of
628 NameNotFound -> combineChildLookupResult xs
629 _ -> return res
630
631 instance Outputable ChildLookupResult where
632 ppr NameNotFound = text "NameNotFound"
633 ppr (FoundName p n) = text "Found:" <+> ppr p <+> ppr n
634 ppr (FoundFL fls) = text "FoundFL:" <+> ppr fls
635 ppr (IncorrectParent p n td ns) = text "IncorrectParent"
636 <+> hsep [ppr p, ppr n, td, ppr ns]
637
638 lookupSubBndrOcc :: Bool
639 -> Name -- Parent
640 -> SDoc
641 -> RdrName
642 -> RnM (Either MsgDoc Name)
643 -- Find all the things the rdr-name maps to
644 -- and pick the one with the right parent namep
645 lookupSubBndrOcc warn_if_deprec the_parent doc rdr_name = do
646 res <-
647 lookupExactOrOrig rdr_name (FoundName NoParent) $
648 -- This happens for built-in classes, see mod052 for example
649 lookupSubBndrOcc_helper True warn_if_deprec the_parent rdr_name
650 case res of
651 NameNotFound -> return (Left (unknownSubordinateErr doc rdr_name))
652 FoundName _p n -> return (Right n)
653 FoundFL fl -> return (Right (flSelector fl))
654 IncorrectParent {}
655 -- See [Mismatched class methods and associated type families]
656 -- in TcInstDecls.
657 -> return $ Left (unknownSubordinateErr doc rdr_name)
658
659 {-
660 Note [Family instance binders]
661 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
662 Consider
663 data family F a
664 data instance F T = X1 | X2
665
666 The 'data instance' decl has an *occurrence* of F (and T), and *binds*
667 X1 and X2. (This is unlike a normal data type declaration which would
668 bind F too.) So we want an AvailTC F [X1,X2].
669
670 Now consider a similar pair:
671 class C a where
672 data G a
673 instance C S where
674 data G S = Y1 | Y2
675
676 The 'data G S' *binds* Y1 and Y2, and has an *occurrence* of G.
677
678 But there is a small complication: in an instance decl, we don't use
679 qualified names on the LHS; instead we use the class to disambiguate.
680 Thus:
681 module M where
682 import Blib( G )
683 class C a where
684 data G a
685 instance C S where
686 data G S = Y1 | Y2
687 Even though there are two G's in scope (M.G and Blib.G), the occurrence
688 of 'G' in the 'instance C S' decl is unambiguous, because C has only
689 one associated type called G. This is exactly what happens for methods,
690 and it is only consistent to do the same thing for types. That's the
691 role of the function lookupTcdName; the (Maybe Name) give the class of
692 the encloseing instance decl, if any.
693
694 Note [Looking up Exact RdrNames]
695 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
696 Exact RdrNames are generated by Template Haskell. See Note [Binders
697 in Template Haskell] in Convert.
698
699 For data types and classes have Exact system Names in the binding
700 positions for constructors, TyCons etc. For example
701 [d| data T = MkT Int |]
702 when we splice in and Convert to HsSyn RdrName, we'll get
703 data (Exact (system Name "T")) = (Exact (system Name "MkT")) ...
704 These System names are generated by Convert.thRdrName
705
706 But, constructors and the like need External Names, not System Names!
707 So we do the following
708
709 * In RnEnv.newTopSrcBinder we spot Exact RdrNames that wrap a
710 non-External Name, and make an External name for it. This is
711 the name that goes in the GlobalRdrEnv
712
713 * When looking up an occurrence of an Exact name, done in
714 RnEnv.lookupExactOcc, we find the Name with the right unique in the
715 GlobalRdrEnv, and use the one from the envt -- it will be an
716 External Name in the case of the data type/constructor above.
717
718 * Exact names are also use for purely local binders generated
719 by TH, such as \x_33. x_33
720 Both binder and occurrence are Exact RdrNames. The occurrence
721 gets looked up in the LocalRdrEnv by RnEnv.lookupOccRn, and
722 misses, because lookupLocalRdrEnv always returns Nothing for
723 an Exact Name. Now we fall through to lookupExactOcc, which
724 will find the Name is not in the GlobalRdrEnv, so we just use
725 the Exact supplied Name.
726
727 Note [Splicing Exact names]
728 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
729 Consider the splice $(do { x <- newName "x"; return (VarE x) })
730 This will generate a (HsExpr RdrName) term that mentions the
731 Exact RdrName "x_56" (or whatever), but does not bind it. So
732 when looking such Exact names we want to check that it's in scope,
733 otherwise the type checker will get confused. To do this we need to
734 keep track of all the Names in scope, and the LocalRdrEnv does just that;
735 we consult it with RdrName.inLocalRdrEnvScope.
736
737 There is another wrinkle. With TH and -XDataKinds, consider
738 $( [d| data Nat = Zero
739 data T = MkT (Proxy 'Zero) |] )
740 After splicing, but before renaming we get this:
741 data Nat_77{tc} = Zero_78{d}
742 data T_79{tc} = MkT_80{d} (Proxy 'Zero_78{tc}) |] )
743 The occurrence of 'Zero in the data type for T has the right unique,
744 but it has a TcClsName name-space in its OccName. (This is set by
745 the ctxt_ns argument of Convert.thRdrName.) When we check that is
746 in scope in the GlobalRdrEnv, we need to look up the DataName namespace
747 too. (An alternative would be to make the GlobalRdrEnv also have
748 a Name -> GRE mapping.)
749
750 Note [Template Haskell ambiguity]
751 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
752 The GlobalRdrEnv invariant says that if
753 occ -> [gre1, ..., gren]
754 then the gres have distinct Names (INVARIANT 1 of GlobalRdrEnv).
755 This is guaranteed by extendGlobalRdrEnvRn (the dups check in add_gre).
756
757 So how can we get multiple gres in lookupExactOcc_maybe? Because in
758 TH we might use the same TH NameU in two different name spaces.
759 eg (Trac #7241):
760 $(newName "Foo" >>= \o -> return [DataD [] o [] [RecC o []] [''Show]])
761 Here we generate a type constructor and data constructor with the same
762 unique, but different name spaces.
763
764 It'd be nicer to rule this out in extendGlobalRdrEnvRn, but that would
765 mean looking up the OccName in every name-space, just in case, and that
766 seems a bit brutal. So it's just done here on lookup. But we might
767 need to revisit that choice.
768
769 Note [Usage for sub-bndrs]
770 ~~~~~~~~~~~~~~~~~~~~~~~~~~
771 If you have this
772 import qualified M( C( f ) )
773 instance M.C T where
774 f x = x
775 then is the qualified import M.f used? Obviously yes.
776 But the RdrName used in the instance decl is unqualified. In effect,
777 we fill in the qualification by looking for f's whose class is M.C
778 But when adding to the UsedRdrNames we must make that qualification
779 explicit (saying "used M.f"), otherwise we get "Redundant import of M.f".
780
781 So we make up a suitable (fake) RdrName. But be careful
782 import qualified M
783 import M( C(f) )
784 instance C T where
785 f x = x
786 Here we want to record a use of 'f', not of 'M.f', otherwise
787 we'll miss the fact that the qualified import is redundant.
788
789 --------------------------------------------------
790 -- Occurrences
791 --------------------------------------------------
792 -}
793
794
795 lookupLocatedOccRn :: Located RdrName -> RnM (Located Name)
796 lookupLocatedOccRn = wrapLocM lookupOccRn
797
798 lookupLocalOccRn_maybe :: RdrName -> RnM (Maybe Name)
799 -- Just look in the local environment
800 lookupLocalOccRn_maybe rdr_name
801 = do { local_env <- getLocalRdrEnv
802 ; return (lookupLocalRdrEnv local_env rdr_name) }
803
804 lookupLocalOccThLvl_maybe :: Name -> RnM (Maybe (TopLevelFlag, ThLevel))
805 -- Just look in the local environment
806 lookupLocalOccThLvl_maybe name
807 = do { lcl_env <- getLclEnv
808 ; return (lookupNameEnv (tcl_th_bndrs lcl_env) name) }
809
810 -- lookupOccRn looks up an occurrence of a RdrName
811 lookupOccRn :: RdrName -> RnM Name
812 lookupOccRn rdr_name
813 = do { mb_name <- lookupOccRn_maybe rdr_name
814 ; case mb_name of
815 Just name -> return name
816 Nothing -> reportUnboundName rdr_name }
817
818 -- Only used in one place, to rename pattern synonym binders.
819 -- See Note [Renaming pattern synonym variables] in RnBinds
820 lookupLocalOccRn :: RdrName -> RnM Name
821 lookupLocalOccRn rdr_name
822 = do { mb_name <- lookupLocalOccRn_maybe rdr_name
823 ; case mb_name of
824 Just name -> return name
825 Nothing -> unboundName WL_LocalOnly rdr_name }
826
827 lookupKindOccRn :: RdrName -> RnM Name
828 -- Looking up a name occurring in a kind
829 lookupKindOccRn rdr_name
830 | isVarOcc (rdrNameOcc rdr_name) -- See Note [Promoted variables in types]
831 = badVarInType rdr_name
832 | otherwise
833 = do { typeintype <- xoptM LangExt.TypeInType
834 ; if | typeintype -> lookupTypeOccRn rdr_name
835 -- With -XNoTypeInType, treat any usage of * in kinds as in scope
836 -- this is a dirty hack, but then again so was the old * kind.
837 | isStar rdr_name -> return starKindTyConName
838 | isUniStar rdr_name -> return unicodeStarKindTyConName
839 | otherwise -> lookupOccRn rdr_name }
840
841 -- lookupPromotedOccRn looks up an optionally promoted RdrName.
842 lookupTypeOccRn :: RdrName -> RnM Name
843 -- see Note [Demotion]
844 lookupTypeOccRn rdr_name
845 | isVarOcc (rdrNameOcc rdr_name) -- See Note [Promoted variables in types]
846 = badVarInType rdr_name
847 | otherwise
848 = do { mb_name <- lookupOccRn_maybe rdr_name
849 ; case mb_name of {
850 Just name -> return name ;
851 Nothing -> do { dflags <- getDynFlags
852 ; lookup_demoted rdr_name dflags } } }
853
854 lookup_demoted :: RdrName -> DynFlags -> RnM Name
855 lookup_demoted rdr_name dflags
856 | Just demoted_rdr <- demoteRdrName rdr_name
857 -- Maybe it's the name of a *data* constructor
858 = do { data_kinds <- xoptM LangExt.DataKinds
859 ; if data_kinds
860 then do { mb_demoted_name <- lookupOccRn_maybe demoted_rdr
861 ; case mb_demoted_name of
862 Nothing -> unboundNameX WL_Any rdr_name star_info
863 Just demoted_name ->
864 do { whenWOptM Opt_WarnUntickedPromotedConstructors $
865 addWarn
866 (Reason Opt_WarnUntickedPromotedConstructors)
867 (untickedPromConstrWarn demoted_name)
868 ; return demoted_name } }
869 else do { -- We need to check if a data constructor of this name is
870 -- in scope to give good error messages. However, we do
871 -- not want to give an additional error if the data
872 -- constructor happens to be out of scope! See #13947.
873 mb_demoted_name <- discardErrs $
874 lookupOccRn_maybe demoted_rdr
875 ; let suggestion | isJust mb_demoted_name = suggest_dk
876 | otherwise = star_info
877 ; unboundNameX WL_Any rdr_name suggestion } }
878
879 | otherwise
880 = reportUnboundName rdr_name
881
882 where
883 suggest_dk = text "A data constructor of that name is in scope; did you mean DataKinds?"
884 untickedPromConstrWarn name =
885 text "Unticked promoted constructor" <> colon <+> quotes (ppr name) <> dot
886 $$
887 hsep [ text "Use"
888 , quotes (char '\'' <> ppr name)
889 , text "instead of"
890 , quotes (ppr name) <> dot ]
891
892 star_info
893 | isStar rdr_name || isUniStar rdr_name
894 = if xopt LangExt.TypeInType dflags
895 then text "NB: With TypeInType, you must import" <+>
896 ppr rdr_name <+> text "from Data.Kind"
897 else empty
898
899 | otherwise
900 = empty
901
902
903 badVarInType :: RdrName -> RnM Name
904 badVarInType rdr_name
905 = do { addErr (text "Illegal promoted term variable in a type:"
906 <+> ppr rdr_name)
907 ; return (mkUnboundNameRdr rdr_name) }
908
909 {- Note [Promoted variables in types]
910 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
911 Consider this (Trac #12686):
912 x = True
913 data Bad = Bad 'x
914
915 The parser treats the quote in 'x as saying "use the term
916 namespace", so we'll get (Bad x{v}), with 'x' in the
917 VarName namespace. If we don't test for this, the renamer
918 will happily rename it to the x bound at top level, and then
919 the typecheck falls over because it doesn't have 'x' in scope
920 when kind-checking.
921
922 Note [Demotion]
923 ~~~~~~~~~~~~~~~
924 When the user writes:
925 data Nat = Zero | Succ Nat
926 foo :: f Zero -> Int
927
928 'Zero' in the type signature of 'foo' is parsed as:
929 HsTyVar ("Zero", TcClsName)
930
931 When the renamer hits this occurrence of 'Zero' it's going to realise
932 that it's not in scope. But because it is renaming a type, it knows
933 that 'Zero' might be a promoted data constructor, so it will demote
934 its namespace to DataName and do a second lookup.
935
936 The final result (after the renamer) will be:
937 HsTyVar ("Zero", DataName)
938 -}
939
940 lookupOccRnX_maybe :: (RdrName -> RnM (Maybe r)) -> (Name -> r) -> RdrName
941 -> RnM (Maybe r)
942 lookupOccRnX_maybe globalLookup wrapper rdr_name
943 = runMaybeT . msum . map MaybeT $
944 [ fmap wrapper <$> lookupLocalOccRn_maybe rdr_name
945 , globalLookup rdr_name ]
946
947 lookupOccRn_maybe :: RdrName -> RnM (Maybe Name)
948 lookupOccRn_maybe = lookupOccRnX_maybe lookupGlobalOccRn_maybe id
949
950 lookupOccRn_overloaded :: Bool -> RdrName
951 -> RnM (Maybe (Either Name [Name]))
952 lookupOccRn_overloaded overload_ok
953 = lookupOccRnX_maybe global_lookup Left
954 where
955 global_lookup :: RdrName -> RnM (Maybe (Either Name [Name]))
956 global_lookup n =
957 runMaybeT . msum . map MaybeT $
958 [ lookupGlobalOccRn_overloaded overload_ok n
959 , fmap Left . listToMaybe <$> lookupQualifiedNameGHCi n ]
960
961
962
963 lookupGlobalOccRn_maybe :: RdrName -> RnM (Maybe Name)
964 -- Looks up a RdrName occurrence in the top-level
965 -- environment, including using lookupQualifiedNameGHCi
966 -- for the GHCi case
967 -- No filter function; does not report an error on failure
968 -- Uses addUsedRdrName to record use and deprecations
969 lookupGlobalOccRn_maybe rdr_name =
970 lookupExactOrOrig rdr_name Just $
971 runMaybeT . msum . map MaybeT $
972 [ fmap gre_name <$> lookupGreRn_maybe rdr_name
973 , listToMaybe <$> lookupQualifiedNameGHCi rdr_name ]
974 -- This test is not expensive,
975 -- and only happens for failed lookups
976
977 lookupGlobalOccRn :: RdrName -> RnM Name
978 -- lookupGlobalOccRn is like lookupOccRn, except that it looks in the global
979 -- environment. Adds an error message if the RdrName is not in scope.
980 -- You usually want to use "lookupOccRn" which also looks in the local
981 -- environment.
982 lookupGlobalOccRn rdr_name
983 = do { mb_name <- lookupGlobalOccRn_maybe rdr_name
984 ; case mb_name of
985 Just n -> return n
986 Nothing -> do { traceRn "lookupGlobalOccRn" (ppr rdr_name)
987 ; unboundName WL_Global rdr_name } }
988
989 lookupInfoOccRn :: RdrName -> RnM [Name]
990 -- lookupInfoOccRn is intended for use in GHCi's ":info" command
991 -- It finds all the GREs that RdrName could mean, not complaining
992 -- about ambiguity, but rather returning them all
993 -- C.f. Trac #9881
994 lookupInfoOccRn rdr_name =
995 lookupExactOrOrig rdr_name (:[]) $
996 do { rdr_env <- getGlobalRdrEnv
997 ; let ns = map gre_name (lookupGRE_RdrName rdr_name rdr_env)
998 ; qual_ns <- lookupQualifiedNameGHCi rdr_name
999 ; return (ns ++ (qual_ns `minusList` ns)) }
1000
1001 -- | Like 'lookupOccRn_maybe', but with a more informative result if
1002 -- the 'RdrName' happens to be a record selector:
1003 --
1004 -- * Nothing -> name not in scope (no error reported)
1005 -- * Just (Left x) -> name uniquely refers to x,
1006 -- or there is a name clash (reported)
1007 -- * Just (Right xs) -> name refers to one or more record selectors;
1008 -- if overload_ok was False, this list will be
1009 -- a singleton.
1010
1011 lookupGlobalOccRn_overloaded :: Bool -> RdrName
1012 -> RnM (Maybe (Either Name [Name]))
1013 lookupGlobalOccRn_overloaded overload_ok rdr_name =
1014 lookupExactOrOrig rdr_name (Just . Left) $
1015 do { res <- lookupGreRn_helper rdr_name
1016 ; case res of
1017 GreNotFound -> return Nothing
1018 OneNameMatch gre -> do
1019 let wrapper = if isRecFldGRE gre then Right . (:[]) else Left
1020 return $ Just (wrapper (gre_name gre))
1021 MultipleNames gres | all isRecFldGRE gres && overload_ok ->
1022 -- Don't record usage for ambiguous selectors
1023 -- until we know which is meant
1024 return $ Just (Right (map gre_name gres))
1025 MultipleNames gres -> do
1026 addNameClashErrRn rdr_name gres
1027 return (Just (Left (gre_name (head gres)))) }
1028
1029
1030 --------------------------------------------------
1031 -- Lookup in the Global RdrEnv of the module
1032 --------------------------------------------------
1033
1034 data GreLookupResult = GreNotFound
1035 | OneNameMatch GlobalRdrElt
1036 | MultipleNames [GlobalRdrElt]
1037
1038 lookupGreRn_maybe :: RdrName -> RnM (Maybe GlobalRdrElt)
1039 -- Look up the RdrName in the GlobalRdrEnv
1040 -- Exactly one binding: records it as "used", return (Just gre)
1041 -- No bindings: return Nothing
1042 -- Many bindings: report "ambiguous", return an arbitrary (Just gre)
1043 -- Uses addUsedRdrName to record use and deprecations
1044 lookupGreRn_maybe rdr_name
1045 = do
1046 res <- lookupGreRn_helper rdr_name
1047 case res of
1048 OneNameMatch gre -> return $ Just gre
1049 MultipleNames gres -> do
1050 traceRn "lookupGreRn_maybe:NameClash" (ppr gres)
1051 addNameClashErrRn rdr_name gres
1052 return $ Just (head gres)
1053 GreNotFound -> return Nothing
1054
1055 {-
1056
1057 Note [ Unbound vs Ambiguous Names ]
1058
1059 lookupGreRn_maybe deals with failures in two different ways. If a name
1060 is unbound then we return a `Nothing` but if the name is ambiguous
1061 then we raise an error and return a dummy name.
1062
1063 The reason for this is that when we call `lookupGreRn_maybe` we are
1064 speculatively looking for whatever we are looking up. If we don't find it,
1065 then we might have been looking for the wrong thing and can keep trying.
1066 On the other hand, if we find a clash then there is no way to recover as
1067 we found the thing we were looking for but can no longer resolve which
1068 the correct one is.
1069
1070 One example of this is in `lookupTypeOccRn` which first looks in the type
1071 constructor namespace before looking in the data constructor namespace to
1072 deal with `DataKinds`.
1073
1074 There is however, as always, one exception to this scheme. If we find
1075 an ambiguous occurence of a record selector and DuplicateRecordFields
1076 is enabled then we defer the selection until the typechecker.
1077
1078 -}
1079
1080
1081
1082
1083 -- Internal Function
1084 lookupGreRn_helper :: RdrName -> RnM GreLookupResult
1085 lookupGreRn_helper rdr_name
1086 = do { env <- getGlobalRdrEnv
1087 ; case lookupGRE_RdrName rdr_name env of
1088 [] -> return GreNotFound
1089 [gre] -> do { addUsedGRE True gre
1090 ; return (OneNameMatch gre) }
1091 gres -> return (MultipleNames gres) }
1092
1093 lookupGreAvailRn :: RdrName -> RnM (Name, AvailInfo)
1094 -- Used in export lists
1095 -- If not found or ambiguous, add error message, and fake with UnboundName
1096 -- Uses addUsedRdrName to record use and deprecations
1097 lookupGreAvailRn rdr_name
1098 = do
1099 mb_gre <- lookupGreRn_helper rdr_name
1100 case mb_gre of
1101 GreNotFound ->
1102 do
1103 traceRn "lookupGreAvailRn" (ppr rdr_name)
1104 name <- unboundName WL_Global rdr_name
1105 return (name, avail name)
1106 MultipleNames gres ->
1107 do
1108 addNameClashErrRn rdr_name gres
1109 let unbound_name = mkUnboundNameRdr rdr_name
1110 return (unbound_name, avail unbound_name)
1111 -- Returning an unbound name here prevents an error
1112 -- cascade
1113 OneNameMatch gre ->
1114 return (gre_name gre, availFromGRE gre)
1115
1116
1117 {-
1118 *********************************************************
1119 * *
1120 Deprecations
1121 * *
1122 *********************************************************
1123
1124 Note [Handling of deprecations]
1125 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1126 * We report deprecations at each *occurrence* of the deprecated thing
1127 (see Trac #5867)
1128
1129 * We do not report deprecations for locally-defined names. For a
1130 start, we may be exporting a deprecated thing. Also we may use a
1131 deprecated thing in the defn of another deprecated things. We may
1132 even use a deprecated thing in the defn of a non-deprecated thing,
1133 when changing a module's interface.
1134
1135 * addUsedGREs: we do not report deprecations for sub-binders:
1136 - the ".." completion for records
1137 - the ".." in an export item 'T(..)'
1138 - the things exported by a module export 'module M'
1139 -}
1140
1141 addUsedDataCons :: GlobalRdrEnv -> TyCon -> RnM ()
1142 -- Remember use of in-scope data constructors (Trac #7969)
1143 addUsedDataCons rdr_env tycon
1144 = addUsedGREs [ gre
1145 | dc <- tyConDataCons tycon
1146 , Just gre <- [lookupGRE_Name rdr_env (dataConName dc)] ]
1147
1148 addUsedGRE :: Bool -> GlobalRdrElt -> RnM ()
1149 -- Called for both local and imported things
1150 -- Add usage *and* warn if deprecated
1151 addUsedGRE warn_if_deprec gre
1152 = do { when warn_if_deprec (warnIfDeprecated gre)
1153 ; unless (isLocalGRE gre) $
1154 do { env <- getGblEnv
1155 ; traceRn "addUsedGRE" (ppr gre)
1156 ; updMutVar (tcg_used_gres env) (gre :) } }
1157
1158 addUsedGREs :: [GlobalRdrElt] -> RnM ()
1159 -- Record uses of any *imported* GREs
1160 -- Used for recording used sub-bndrs
1161 -- NB: no call to warnIfDeprecated; see Note [Handling of deprecations]
1162 addUsedGREs gres
1163 | null imp_gres = return ()
1164 | otherwise = do { env <- getGblEnv
1165 ; traceRn "addUsedGREs" (ppr imp_gres)
1166 ; updMutVar (tcg_used_gres env) (imp_gres ++) }
1167 where
1168 imp_gres = filterOut isLocalGRE gres
1169
1170 warnIfDeprecated :: GlobalRdrElt -> RnM ()
1171 warnIfDeprecated gre@(GRE { gre_name = name, gre_imp = iss })
1172 | (imp_spec : _) <- iss
1173 = do { dflags <- getDynFlags
1174 ; this_mod <- getModule
1175 ; when (wopt Opt_WarnWarningsDeprecations dflags &&
1176 not (nameIsLocalOrFrom this_mod name)) $
1177 -- See Note [Handling of deprecations]
1178 do { iface <- loadInterfaceForName doc name
1179 ; case lookupImpDeprec iface gre of
1180 Just txt -> addWarn (Reason Opt_WarnWarningsDeprecations)
1181 (mk_msg imp_spec txt)
1182 Nothing -> return () } }
1183 | otherwise
1184 = return ()
1185 where
1186 occ = greOccName gre
1187 name_mod = ASSERT2( isExternalName name, ppr name ) nameModule name
1188 doc = text "The name" <+> quotes (ppr occ) <+> ptext (sLit "is mentioned explicitly")
1189
1190 mk_msg imp_spec txt
1191 = sep [ sep [ text "In the use of"
1192 <+> pprNonVarNameSpace (occNameSpace occ)
1193 <+> quotes (ppr occ)
1194 , parens imp_msg <> colon ]
1195 , pprWarningTxtForMsg txt ]
1196 where
1197 imp_mod = importSpecModule imp_spec
1198 imp_msg = text "imported from" <+> ppr imp_mod <> extra
1199 extra | imp_mod == moduleName name_mod = Outputable.empty
1200 | otherwise = text ", but defined in" <+> ppr name_mod
1201
1202 lookupImpDeprec :: ModIface -> GlobalRdrElt -> Maybe WarningTxt
1203 lookupImpDeprec iface gre
1204 = mi_warn_fn iface (greOccName gre) `mplus` -- Bleat if the thing,
1205 case gre_par gre of -- or its parent, is warn'd
1206 ParentIs p -> mi_warn_fn iface (nameOccName p)
1207 FldParent { par_is = p } -> mi_warn_fn iface (nameOccName p)
1208 NoParent -> Nothing
1209
1210 {-
1211 Note [Used names with interface not loaded]
1212 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1213 It's (just) possible to find a used
1214 Name whose interface hasn't been loaded:
1215
1216 a) It might be a WiredInName; in that case we may not load
1217 its interface (although we could).
1218
1219 b) It might be GHC.Real.fromRational, or GHC.Num.fromInteger
1220 These are seen as "used" by the renamer (if -XRebindableSyntax)
1221 is on), but the typechecker may discard their uses
1222 if in fact the in-scope fromRational is GHC.Read.fromRational,
1223 (see tcPat.tcOverloadedLit), and the typechecker sees that the type
1224 is fixed, say, to GHC.Base.Float (see Inst.lookupSimpleInst).
1225 In that obscure case it won't force the interface in.
1226
1227 In both cases we simply don't permit deprecations;
1228 this is, after all, wired-in stuff.
1229
1230
1231 *********************************************************
1232 * *
1233 GHCi support
1234 * *
1235 *********************************************************
1236
1237 A qualified name on the command line can refer to any module at
1238 all: we try to load the interface if we don't already have it, just
1239 as if there was an "import qualified M" declaration for every
1240 module.
1241
1242 For example, writing `Data.List.sort` will load the interface file for
1243 `Data.List` as if the user had written `import qualified Data.List`.
1244
1245 If we fail we just return Nothing, rather than bleating
1246 about "attempting to use module ā€˜Dā€™ (./D.hs) which is not loaded"
1247 which is what loadSrcInterface does.
1248
1249 It is enabled by default and disabled by the flag
1250 `-fno-implicit-import-qualified`.
1251
1252 Note [Safe Haskell and GHCi]
1253 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1254 We DON'T do this Safe Haskell as we need to check imports. We can
1255 and should instead check the qualified import but at the moment
1256 this requires some refactoring so leave as a TODO
1257 -}
1258
1259
1260
1261 lookupQualifiedNameGHCi :: RdrName -> RnM [Name]
1262 lookupQualifiedNameGHCi rdr_name
1263 = -- We want to behave as we would for a source file import here,
1264 -- and respect hiddenness of modules/packages, hence loadSrcInterface.
1265 do { dflags <- getDynFlags
1266 ; is_ghci <- getIsGHCi
1267 ; go_for_it dflags is_ghci }
1268
1269 where
1270 go_for_it dflags is_ghci
1271 | Just (mod,occ) <- isQual_maybe rdr_name
1272 , is_ghci
1273 , gopt Opt_ImplicitImportQualified dflags -- Enables this GHCi behaviour
1274 , not (safeDirectImpsReq dflags) -- See Note [Safe Haskell and GHCi]
1275 = do { res <- loadSrcInterface_maybe doc mod False Nothing
1276 ; case res of
1277 Succeeded iface
1278 -> return [ name
1279 | avail <- mi_exports iface
1280 , name <- availNames avail
1281 , nameOccName name == occ ]
1282
1283 _ -> -- Either we couldn't load the interface, or
1284 -- we could but we didn't find the name in it
1285 do { traceRn "lookupQualifiedNameGHCi" (ppr rdr_name)
1286 ; return [] } }
1287
1288 | otherwise
1289 = do { traceRn "lookupQualifiedNameGHCi: off" (ppr rdr_name)
1290 ; return [] }
1291
1292 doc = text "Need to find" <+> ppr rdr_name
1293
1294 {-
1295 Note [Looking up signature names]
1296 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1297 lookupSigOccRn is used for type signatures and pragmas
1298 Is this valid?
1299 module A
1300 import M( f )
1301 f :: Int -> Int
1302 f x = x
1303 It's clear that the 'f' in the signature must refer to A.f
1304 The Haskell98 report does not stipulate this, but it will!
1305 So we must treat the 'f' in the signature in the same way
1306 as the binding occurrence of 'f', using lookupBndrRn
1307
1308 However, consider this case:
1309 import M( f )
1310 f :: Int -> Int
1311 g x = x
1312 We don't want to say 'f' is out of scope; instead, we want to
1313 return the imported 'f', so that later on the reanamer will
1314 correctly report "misplaced type sig".
1315
1316 Note [Signatures for top level things]
1317 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1318 data HsSigCtxt = ... | TopSigCtxt NameSet | ....
1319
1320 * The NameSet says what is bound in this group of bindings.
1321 We can't use isLocalGRE from the GlobalRdrEnv, because of this:
1322 f x = x
1323 $( ...some TH splice... )
1324 f :: Int -> Int
1325 When we encounter the signature for 'f', the binding for 'f'
1326 will be in the GlobalRdrEnv, and will be a LocalDef. Yet the
1327 signature is mis-placed
1328
1329 * For type signatures the NameSet should be the names bound by the
1330 value bindings; for fixity declarations, the NameSet should also
1331 include class sigs and record selectors
1332
1333 infix 3 `f` -- Yes, ok
1334 f :: C a => a -> a -- No, not ok
1335 class C a where
1336 f :: a -> a
1337 -}
1338
1339 data HsSigCtxt
1340 = TopSigCtxt NameSet -- At top level, binding these names
1341 -- See Note [Signatures for top level things]
1342 | LocalBindCtxt NameSet -- In a local binding, binding these names
1343 | ClsDeclCtxt Name -- Class decl for this class
1344 | InstDeclCtxt NameSet -- Instance decl whose user-written method
1345 -- bindings are for these methods
1346 | HsBootCtxt NameSet -- Top level of a hs-boot file, binding these names
1347 | RoleAnnotCtxt NameSet -- A role annotation, with the names of all types
1348 -- in the group
1349
1350 instance Outputable HsSigCtxt where
1351 ppr (TopSigCtxt ns) = text "TopSigCtxt" <+> ppr ns
1352 ppr (LocalBindCtxt ns) = text "LocalBindCtxt" <+> ppr ns
1353 ppr (ClsDeclCtxt n) = text "ClsDeclCtxt" <+> ppr n
1354 ppr (InstDeclCtxt ns) = text "InstDeclCtxt" <+> ppr ns
1355 ppr (HsBootCtxt ns) = text "HsBootCtxt" <+> ppr ns
1356 ppr (RoleAnnotCtxt ns) = text "RoleAnnotCtxt" <+> ppr ns
1357
1358 lookupSigOccRn :: HsSigCtxt
1359 -> Sig GhcPs
1360 -> Located RdrName -> RnM (Located Name)
1361 lookupSigOccRn ctxt sig = lookupSigCtxtOccRn ctxt (hsSigDoc sig)
1362
1363 -- | Lookup a name in relation to the names in a 'HsSigCtxt'
1364 lookupSigCtxtOccRn :: HsSigCtxt
1365 -> SDoc -- ^ description of thing we're looking up,
1366 -- like "type family"
1367 -> Located RdrName -> RnM (Located Name)
1368 lookupSigCtxtOccRn ctxt what
1369 = wrapLocM $ \ rdr_name ->
1370 do { mb_name <- lookupBindGroupOcc ctxt what rdr_name
1371 ; case mb_name of
1372 Left err -> do { addErr err; return (mkUnboundNameRdr rdr_name) }
1373 Right name -> return name }
1374
1375 lookupBindGroupOcc :: HsSigCtxt
1376 -> SDoc
1377 -> RdrName -> RnM (Either MsgDoc Name)
1378 -- Looks up the RdrName, expecting it to resolve to one of the
1379 -- bound names passed in. If not, return an appropriate error message
1380 --
1381 -- See Note [Looking up signature names]
1382 lookupBindGroupOcc ctxt what rdr_name
1383 | Just n <- isExact_maybe rdr_name
1384 = lookupExactOcc_either n -- allow for the possibility of missing Exacts;
1385 -- see Note [dataTcOccs and Exact Names]
1386 -- Maybe we should check the side conditions
1387 -- but it's a pain, and Exact things only show
1388 -- up when you know what you are doing
1389
1390 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
1391 = do { n' <- lookupOrig rdr_mod rdr_occ
1392 ; return (Right n') }
1393
1394 | otherwise
1395 = case ctxt of
1396 HsBootCtxt ns -> lookup_top (`elemNameSet` ns)
1397 TopSigCtxt ns -> lookup_top (`elemNameSet` ns)
1398 RoleAnnotCtxt ns -> lookup_top (`elemNameSet` ns)
1399 LocalBindCtxt ns -> lookup_group ns
1400 ClsDeclCtxt cls -> lookup_cls_op cls
1401 InstDeclCtxt ns -> lookup_top (`elemNameSet` ns)
1402 where
1403 lookup_cls_op cls
1404 = lookupSubBndrOcc True cls doc rdr_name
1405 where
1406 doc = text "method of class" <+> quotes (ppr cls)
1407
1408 lookup_top keep_me
1409 = do { env <- getGlobalRdrEnv
1410 ; let all_gres = lookupGlobalRdrEnv env (rdrNameOcc rdr_name)
1411 ; case filter (keep_me . gre_name) all_gres of
1412 [] | null all_gres -> bale_out_with Outputable.empty
1413 | otherwise -> bale_out_with local_msg
1414 (gre:_) -> return (Right (gre_name gre)) }
1415
1416 lookup_group bound_names -- Look in the local envt (not top level)
1417 = do { mname <- lookupLocalOccRn_maybe rdr_name
1418 ; case mname of
1419 Just n
1420 | n `elemNameSet` bound_names -> return (Right n)
1421 | otherwise -> bale_out_with local_msg
1422 Nothing -> bale_out_with Outputable.empty }
1423
1424 bale_out_with msg
1425 = return (Left (sep [ text "The" <+> what
1426 <+> text "for" <+> quotes (ppr rdr_name)
1427 , nest 2 $ text "lacks an accompanying binding"]
1428 $$ nest 2 msg))
1429
1430 local_msg = parens $ text "The" <+> what <+> ptext (sLit "must be given where")
1431 <+> quotes (ppr rdr_name) <+> text "is declared"
1432
1433
1434 ---------------
1435 lookupLocalTcNames :: HsSigCtxt -> SDoc -> RdrName -> RnM [(RdrName, Name)]
1436 -- GHC extension: look up both the tycon and data con or variable.
1437 -- Used for top-level fixity signatures and deprecations.
1438 -- Complain if neither is in scope.
1439 -- See Note [Fixity signature lookup]
1440 lookupLocalTcNames ctxt what rdr_name
1441 = do { mb_gres <- mapM lookup (dataTcOccs rdr_name)
1442 ; let (errs, names) = partitionEithers mb_gres
1443 ; when (null names) $ addErr (head errs) -- Bleat about one only
1444 ; return names }
1445 where
1446 lookup rdr = do { name <- lookupBindGroupOcc ctxt what rdr
1447 ; return (fmap ((,) rdr) name) }
1448
1449 dataTcOccs :: RdrName -> [RdrName]
1450 -- Return both the given name and the same name promoted to the TcClsName
1451 -- namespace. This is useful when we aren't sure which we are looking at.
1452 -- See also Note [dataTcOccs and Exact Names]
1453 dataTcOccs rdr_name
1454 | isDataOcc occ || isVarOcc occ
1455 = [rdr_name, rdr_name_tc]
1456 | otherwise
1457 = [rdr_name]
1458 where
1459 occ = rdrNameOcc rdr_name
1460 rdr_name_tc = setRdrNameSpace rdr_name tcName
1461
1462 {-
1463 Note [dataTcOccs and Exact Names]
1464 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1465 Exact RdrNames can occur in code generated by Template Haskell, and generally
1466 those references are, well, exact. However, the TH `Name` type isn't expressive
1467 enough to always track the correct namespace information, so we sometimes get
1468 the right Unique but wrong namespace. Thus, we still have to do the double-lookup
1469 for Exact RdrNames.
1470
1471 There is also an awkward situation for built-in syntax. Example in GHCi
1472 :info []
1473 This parses as the Exact RdrName for nilDataCon, but we also want
1474 the list type constructor.
1475
1476 Note that setRdrNameSpace on an Exact name requires the Name to be External,
1477 which it always is for built in syntax.
1478 -}
1479
1480
1481
1482 {-
1483 ************************************************************************
1484 * *
1485 Rebindable names
1486 Dealing with rebindable syntax is driven by the
1487 Opt_RebindableSyntax dynamic flag.
1488
1489 In "deriving" code we don't want to use rebindable syntax
1490 so we switch off the flag locally
1491
1492 * *
1493 ************************************************************************
1494
1495 Haskell 98 says that when you say "3" you get the "fromInteger" from the
1496 Standard Prelude, regardless of what is in scope. However, to experiment
1497 with having a language that is less coupled to the standard prelude, we're
1498 trying a non-standard extension that instead gives you whatever "Prelude.fromInteger"
1499 happens to be in scope. Then you can
1500 import Prelude ()
1501 import MyPrelude as Prelude
1502 to get the desired effect.
1503
1504 At the moment this just happens for
1505 * fromInteger, fromRational on literals (in expressions and patterns)
1506 * negate (in expressions)
1507 * minus (arising from n+k patterns)
1508 * "do" notation
1509
1510 We store the relevant Name in the HsSyn tree, in
1511 * HsIntegral/HsFractional/HsIsString
1512 * NegApp
1513 * NPlusKPat
1514 * HsDo
1515 respectively. Initially, we just store the "standard" name (PrelNames.fromIntegralName,
1516 fromRationalName etc), but the renamer changes this to the appropriate user
1517 name if Opt_NoImplicitPrelude is on. That is what lookupSyntaxName does.
1518
1519 We treat the original (standard) names as free-vars too, because the type checker
1520 checks the type of the user thing against the type of the standard thing.
1521 -}
1522
1523 lookupIfThenElse :: RnM (Maybe (SyntaxExpr GhcRn), FreeVars)
1524 -- Different to lookupSyntaxName because in the non-rebindable
1525 -- case we desugar directly rather than calling an existing function
1526 -- Hence the (Maybe (SyntaxExpr GhcRn)) return type
1527 lookupIfThenElse
1528 = do { rebindable_on <- xoptM LangExt.RebindableSyntax
1529 ; if not rebindable_on
1530 then return (Nothing, emptyFVs)
1531 else do { ite <- lookupOccRn (mkVarUnqual (fsLit "ifThenElse"))
1532 ; return ( Just (mkRnSyntaxExpr ite)
1533 , unitFV ite ) } }
1534
1535 lookupSyntaxName' :: Name -- ^ The standard name
1536 -> RnM Name -- ^ Possibly a non-standard name
1537 lookupSyntaxName' std_name
1538 = do { rebindable_on <- xoptM LangExt.RebindableSyntax
1539 ; if not rebindable_on then
1540 return std_name
1541 else
1542 -- Get the similarly named thing from the local environment
1543 lookupOccRn (mkRdrUnqual (nameOccName std_name)) }
1544
1545 lookupSyntaxName :: Name -- The standard name
1546 -> RnM (SyntaxExpr GhcRn, FreeVars) -- Possibly a non-standard
1547 -- name
1548 lookupSyntaxName std_name
1549 = do { rebindable_on <- xoptM LangExt.RebindableSyntax
1550 ; if not rebindable_on then
1551 return (mkRnSyntaxExpr std_name, emptyFVs)
1552 else
1553 -- Get the similarly named thing from the local environment
1554 do { usr_name <- lookupOccRn (mkRdrUnqual (nameOccName std_name))
1555 ; return (mkRnSyntaxExpr usr_name, unitFV usr_name) } }
1556
1557 lookupSyntaxNames :: [Name] -- Standard names
1558 -> RnM ([HsExpr GhcRn], FreeVars) -- See comments with HsExpr.ReboundNames
1559 -- this works with CmdTop, which wants HsExprs, not SyntaxExprs
1560 lookupSyntaxNames std_names
1561 = do { rebindable_on <- xoptM LangExt.RebindableSyntax
1562 ; if not rebindable_on then
1563 return (map (HsVar noExt . noLoc) std_names, emptyFVs)
1564 else
1565 do { usr_names <- mapM (lookupOccRn . mkRdrUnqual . nameOccName) std_names
1566 ; return (map (HsVar noExt . noLoc) usr_names, mkFVs usr_names) } }
1567
1568 -- Error messages
1569
1570
1571 opDeclErr :: RdrName -> SDoc
1572 opDeclErr n
1573 = hang (text "Illegal declaration of a type or class operator" <+> quotes (ppr n))
1574 2 (text "Use TypeOperators to declare operators in type and declarations")
1575
1576 badOrigBinding :: RdrName -> SDoc
1577 badOrigBinding name
1578 | Just _ <- isBuiltInOcc_maybe occ
1579 = text "Illegal binding of built-in syntax:" <+> ppr occ
1580 -- Use an OccName here because we don't want to print Prelude.(,)
1581 | otherwise
1582 = text "Cannot redefine a Name retrieved by a Template Haskell quote:"
1583 <+> ppr name
1584 -- This can happen when one tries to use a Template Haskell splice to
1585 -- define a top-level identifier with an already existing name, e.g.,
1586 --
1587 -- $(pure [ValD (VarP 'succ) (NormalB (ConE 'True)) []])
1588 --
1589 -- (See Trac #13968.)
1590 where
1591 occ = rdrNameOcc name