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