Remove splitEithers, use partitionEithers from base
[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 {} -> return $ Left (unknownSubordinateErr doc rdr_name)
655
656
657 {-
658 Note [Family instance binders]
659 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
660 Consider
661 data family F a
662 data instance F T = X1 | X2
663
664 The 'data instance' decl has an *occurrence* of F (and T), and *binds*
665 X1 and X2. (This is unlike a normal data type declaration which would
666 bind F too.) So we want an AvailTC F [X1,X2].
667
668 Now consider a similar pair:
669 class C a where
670 data G a
671 instance C S where
672 data G S = Y1 | Y2
673
674 The 'data G S' *binds* Y1 and Y2, and has an *occurrence* of G.
675
676 But there is a small complication: in an instance decl, we don't use
677 qualified names on the LHS; instead we use the class to disambiguate.
678 Thus:
679 module M where
680 import Blib( G )
681 class C a where
682 data G a
683 instance C S where
684 data G S = Y1 | Y2
685 Even though there are two G's in scope (M.G and Blib.G), the occurrence
686 of 'G' in the 'instance C S' decl is unambiguous, because C has only
687 one associated type called G. This is exactly what happens for methods,
688 and it is only consistent to do the same thing for types. That's the
689 role of the function lookupTcdName; the (Maybe Name) give the class of
690 the encloseing instance decl, if any.
691
692 Note [Looking up Exact RdrNames]
693 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
694 Exact RdrNames are generated by Template Haskell. See Note [Binders
695 in Template Haskell] in Convert.
696
697 For data types and classes have Exact system Names in the binding
698 positions for constructors, TyCons etc. For example
699 [d| data T = MkT Int |]
700 when we splice in and Convert to HsSyn RdrName, we'll get
701 data (Exact (system Name "T")) = (Exact (system Name "MkT")) ...
702 These System names are generated by Convert.thRdrName
703
704 But, constructors and the like need External Names, not System Names!
705 So we do the following
706
707 * In RnEnv.newTopSrcBinder we spot Exact RdrNames that wrap a
708 non-External Name, and make an External name for it. This is
709 the name that goes in the GlobalRdrEnv
710
711 * When looking up an occurrence of an Exact name, done in
712 RnEnv.lookupExactOcc, we find the Name with the right unique in the
713 GlobalRdrEnv, and use the one from the envt -- it will be an
714 External Name in the case of the data type/constructor above.
715
716 * Exact names are also use for purely local binders generated
717 by TH, such as \x_33. x_33
718 Both binder and occurrence are Exact RdrNames. The occurrence
719 gets looked up in the LocalRdrEnv by RnEnv.lookupOccRn, and
720 misses, because lookupLocalRdrEnv always returns Nothing for
721 an Exact Name. Now we fall through to lookupExactOcc, which
722 will find the Name is not in the GlobalRdrEnv, so we just use
723 the Exact supplied Name.
724
725 Note [Splicing Exact names]
726 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
727 Consider the splice $(do { x <- newName "x"; return (VarE x) })
728 This will generate a (HsExpr RdrName) term that mentions the
729 Exact RdrName "x_56" (or whatever), but does not bind it. So
730 when looking such Exact names we want to check that it's in scope,
731 otherwise the type checker will get confused. To do this we need to
732 keep track of all the Names in scope, and the LocalRdrEnv does just that;
733 we consult it with RdrName.inLocalRdrEnvScope.
734
735 There is another wrinkle. With TH and -XDataKinds, consider
736 $( [d| data Nat = Zero
737 data T = MkT (Proxy 'Zero) |] )
738 After splicing, but before renaming we get this:
739 data Nat_77{tc} = Zero_78{d}
740 data T_79{tc} = MkT_80{d} (Proxy 'Zero_78{tc}) |] )
741 The occurrence of 'Zero in the data type for T has the right unique,
742 but it has a TcClsName name-space in its OccName. (This is set by
743 the ctxt_ns argument of Convert.thRdrName.) When we check that is
744 in scope in the GlobalRdrEnv, we need to look up the DataName namespace
745 too. (An alternative would be to make the GlobalRdrEnv also have
746 a Name -> GRE mapping.)
747
748 Note [Template Haskell ambiguity]
749 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
750 The GlobalRdrEnv invariant says that if
751 occ -> [gre1, ..., gren]
752 then the gres have distinct Names (INVARIANT 1 of GlobalRdrEnv).
753 This is guaranteed by extendGlobalRdrEnvRn (the dups check in add_gre).
754
755 So how can we get multiple gres in lookupExactOcc_maybe? Because in
756 TH we might use the same TH NameU in two different name spaces.
757 eg (Trac #7241):
758 $(newName "Foo" >>= \o -> return [DataD [] o [] [RecC o []] [''Show]])
759 Here we generate a type constructor and data constructor with the same
760 unique, but different name spaces.
761
762 It'd be nicer to rule this out in extendGlobalRdrEnvRn, but that would
763 mean looking up the OccName in every name-space, just in case, and that
764 seems a bit brutal. So it's just done here on lookup. But we might
765 need to revisit that choice.
766
767 Note [Usage for sub-bndrs]
768 ~~~~~~~~~~~~~~~~~~~~~~~~~~
769 If you have this
770 import qualified M( C( f ) )
771 instance M.C T where
772 f x = x
773 then is the qualified import M.f used? Obviously yes.
774 But the RdrName used in the instance decl is unqualified. In effect,
775 we fill in the qualification by looking for f's whose class is M.C
776 But when adding to the UsedRdrNames we must make that qualification
777 explicit (saying "used M.f"), otherwise we get "Redundant import of M.f".
778
779 So we make up a suitable (fake) RdrName. But be careful
780 import qualified M
781 import M( C(f) )
782 instance C T where
783 f x = x
784 Here we want to record a use of 'f', not of 'M.f', otherwise
785 we'll miss the fact that the qualified import is redundant.
786
787 --------------------------------------------------
788 -- Occurrences
789 --------------------------------------------------
790 -}
791
792
793 lookupLocatedOccRn :: Located RdrName -> RnM (Located Name)
794 lookupLocatedOccRn = wrapLocM lookupOccRn
795
796 lookupLocalOccRn_maybe :: RdrName -> RnM (Maybe Name)
797 -- Just look in the local environment
798 lookupLocalOccRn_maybe rdr_name
799 = do { local_env <- getLocalRdrEnv
800 ; return (lookupLocalRdrEnv local_env rdr_name) }
801
802 lookupLocalOccThLvl_maybe :: Name -> RnM (Maybe (TopLevelFlag, ThLevel))
803 -- Just look in the local environment
804 lookupLocalOccThLvl_maybe name
805 = do { lcl_env <- getLclEnv
806 ; return (lookupNameEnv (tcl_th_bndrs lcl_env) name) }
807
808 -- lookupOccRn looks up an occurrence of a RdrName
809 lookupOccRn :: RdrName -> RnM Name
810 lookupOccRn rdr_name
811 = do { mb_name <- lookupOccRn_maybe rdr_name
812 ; case mb_name of
813 Just name -> return name
814 Nothing -> reportUnboundName rdr_name }
815
816 -- Only used in one place, to rename pattern synonym binders.
817 -- See Note [Renaming pattern synonym variables] in RnBinds
818 lookupLocalOccRn :: RdrName -> RnM Name
819 lookupLocalOccRn rdr_name
820 = do { mb_name <- lookupLocalOccRn_maybe rdr_name
821 ; case mb_name of
822 Just name -> return name
823 Nothing -> unboundName WL_LocalOnly rdr_name }
824
825 lookupKindOccRn :: RdrName -> RnM Name
826 -- Looking up a name occurring in a kind
827 lookupKindOccRn rdr_name
828 | isVarOcc (rdrNameOcc rdr_name) -- See Note [Promoted variables in types]
829 = badVarInType rdr_name
830 | otherwise
831 = do { typeintype <- xoptM LangExt.TypeInType
832 ; if | typeintype -> lookupTypeOccRn rdr_name
833 -- With -XNoTypeInType, treat any usage of * in kinds as in scope
834 -- this is a dirty hack, but then again so was the old * kind.
835 | isStar rdr_name -> return starKindTyConName
836 | isUniStar rdr_name -> return unicodeStarKindTyConName
837 | otherwise -> lookupOccRn rdr_name }
838
839 -- lookupPromotedOccRn looks up an optionally promoted RdrName.
840 lookupTypeOccRn :: RdrName -> RnM Name
841 -- see Note [Demotion]
842 lookupTypeOccRn rdr_name
843 | isVarOcc (rdrNameOcc rdr_name) -- See Note [Promoted variables in types]
844 = badVarInType rdr_name
845 | otherwise
846 = do { mb_name <- lookupOccRn_maybe rdr_name
847 ; case mb_name of {
848 Just name -> return name ;
849 Nothing -> do { dflags <- getDynFlags
850 ; lookup_demoted rdr_name dflags } } }
851
852 lookup_demoted :: RdrName -> DynFlags -> RnM Name
853 lookup_demoted rdr_name dflags
854 | Just demoted_rdr <- demoteRdrName rdr_name
855 -- Maybe it's the name of a *data* constructor
856 = do { data_kinds <- xoptM LangExt.DataKinds
857 ; if data_kinds
858 then do { mb_demoted_name <- lookupOccRn_maybe demoted_rdr
859 ; case mb_demoted_name of
860 Nothing -> unboundNameX WL_Any rdr_name star_info
861 Just demoted_name ->
862 do { whenWOptM Opt_WarnUntickedPromotedConstructors $
863 addWarn
864 (Reason Opt_WarnUntickedPromotedConstructors)
865 (untickedPromConstrWarn demoted_name)
866 ; return demoted_name } }
867 else do { -- We need to check if a data constructor of this name is
868 -- in scope to give good error messages. However, we do
869 -- not want to give an additional error if the data
870 -- constructor happens to be out of scope! See #13947.
871 mb_demoted_name <- discardErrs $
872 lookupOccRn_maybe demoted_rdr
873 ; let suggestion | isJust mb_demoted_name = suggest_dk
874 | otherwise = star_info
875 ; unboundNameX WL_Any rdr_name suggestion } }
876
877 | otherwise
878 = reportUnboundName rdr_name
879
880 where
881 suggest_dk = text "A data constructor of that name is in scope; did you mean DataKinds?"
882 untickedPromConstrWarn name =
883 text "Unticked promoted constructor" <> colon <+> quotes (ppr name) <> dot
884 $$
885 hsep [ text "Use"
886 , quotes (char '\'' <> ppr name)
887 , text "instead of"
888 , quotes (ppr name) <> dot ]
889
890 star_info
891 | isStar rdr_name || isUniStar rdr_name
892 = if xopt LangExt.TypeInType dflags
893 then text "NB: With TypeInType, you must import" <+>
894 ppr rdr_name <+> text "from Data.Kind"
895 else empty
896
897 | otherwise
898 = empty
899
900
901 badVarInType :: RdrName -> RnM Name
902 badVarInType rdr_name
903 = do { addErr (text "Illegal promoted term variable in a type:"
904 <+> ppr rdr_name)
905 ; return (mkUnboundNameRdr rdr_name) }
906
907 {- Note [Promoted variables in types]
908 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
909 Consider this (Trac #12686):
910 x = True
911 data Bad = Bad 'x
912
913 The parser treats the quote in 'x as saying "use the term
914 namespace", so we'll get (Bad x{v}), with 'x' in the
915 VarName namespace. If we don't test for this, the renamer
916 will happily rename it to the x bound at top level, and then
917 the typecheck falls over because it doesn't have 'x' in scope
918 when kind-checking.
919
920 Note [Demotion]
921 ~~~~~~~~~~~~~~~
922 When the user writes:
923 data Nat = Zero | Succ Nat
924 foo :: f Zero -> Int
925
926 'Zero' in the type signature of 'foo' is parsed as:
927 HsTyVar ("Zero", TcClsName)
928
929 When the renamer hits this occurrence of 'Zero' it's going to realise
930 that it's not in scope. But because it is renaming a type, it knows
931 that 'Zero' might be a promoted data constructor, so it will demote
932 its namespace to DataName and do a second lookup.
933
934 The final result (after the renamer) will be:
935 HsTyVar ("Zero", DataName)
936 -}
937
938 lookupOccRnX_maybe :: (RdrName -> RnM (Maybe r)) -> (Name -> r) -> RdrName
939 -> RnM (Maybe r)
940 lookupOccRnX_maybe globalLookup wrapper rdr_name
941 = runMaybeT . msum . map MaybeT $
942 [ fmap wrapper <$> lookupLocalOccRn_maybe rdr_name
943 , globalLookup rdr_name ]
944
945 lookupOccRn_maybe :: RdrName -> RnM (Maybe Name)
946 lookupOccRn_maybe = lookupOccRnX_maybe lookupGlobalOccRn_maybe id
947
948 lookupOccRn_overloaded :: Bool -> RdrName
949 -> RnM (Maybe (Either Name [Name]))
950 lookupOccRn_overloaded overload_ok
951 = lookupOccRnX_maybe global_lookup Left
952 where
953 global_lookup :: RdrName -> RnM (Maybe (Either Name [Name]))
954 global_lookup n =
955 runMaybeT . msum . map MaybeT $
956 [ lookupGlobalOccRn_overloaded overload_ok n
957 , fmap Left . listToMaybe <$> lookupQualifiedNameGHCi n ]
958
959
960
961 lookupGlobalOccRn_maybe :: RdrName -> RnM (Maybe Name)
962 -- Looks up a RdrName occurrence in the top-level
963 -- environment, including using lookupQualifiedNameGHCi
964 -- for the GHCi case
965 -- No filter function; does not report an error on failure
966 -- Uses addUsedRdrName to record use and deprecations
967 lookupGlobalOccRn_maybe rdr_name =
968 lookupExactOrOrig rdr_name Just $
969 runMaybeT . msum . map MaybeT $
970 [ fmap gre_name <$> lookupGreRn_maybe rdr_name
971 , listToMaybe <$> lookupQualifiedNameGHCi rdr_name ]
972 -- This test is not expensive,
973 -- and only happens for failed lookups
974
975 lookupGlobalOccRn :: RdrName -> RnM Name
976 -- lookupGlobalOccRn is like lookupOccRn, except that it looks in the global
977 -- environment. Adds an error message if the RdrName is not in scope.
978 -- You usually want to use "lookupOccRn" which also looks in the local
979 -- environment.
980 lookupGlobalOccRn rdr_name
981 = do { mb_name <- lookupGlobalOccRn_maybe rdr_name
982 ; case mb_name of
983 Just n -> return n
984 Nothing -> do { traceRn "lookupGlobalOccRn" (ppr rdr_name)
985 ; unboundName WL_Global rdr_name } }
986
987 lookupInfoOccRn :: RdrName -> RnM [Name]
988 -- lookupInfoOccRn is intended for use in GHCi's ":info" command
989 -- It finds all the GREs that RdrName could mean, not complaining
990 -- about ambiguity, but rather returning them all
991 -- C.f. Trac #9881
992 lookupInfoOccRn rdr_name =
993 lookupExactOrOrig rdr_name (:[]) $
994 do { rdr_env <- getGlobalRdrEnv
995 ; let ns = map gre_name (lookupGRE_RdrName rdr_name rdr_env)
996 ; qual_ns <- lookupQualifiedNameGHCi rdr_name
997 ; return (ns ++ (qual_ns `minusList` ns)) }
998
999 -- | Like 'lookupOccRn_maybe', but with a more informative result if
1000 -- the 'RdrName' happens to be a record selector:
1001 --
1002 -- * Nothing -> name not in scope (no error reported)
1003 -- * Just (Left x) -> name uniquely refers to x,
1004 -- or there is a name clash (reported)
1005 -- * Just (Right xs) -> name refers to one or more record selectors;
1006 -- if overload_ok was False, this list will be
1007 -- a singleton.
1008
1009 lookupGlobalOccRn_overloaded :: Bool -> RdrName
1010 -> RnM (Maybe (Either Name [Name]))
1011 lookupGlobalOccRn_overloaded overload_ok rdr_name =
1012 lookupExactOrOrig rdr_name (Just . Left) $
1013 do { res <- lookupGreRn_helper rdr_name
1014 ; case res of
1015 GreNotFound -> return Nothing
1016 OneNameMatch gre -> do
1017 let wrapper = if isRecFldGRE gre then Right . (:[]) else Left
1018 return $ Just (wrapper (gre_name gre))
1019 MultipleNames gres | all isRecFldGRE gres && overload_ok ->
1020 -- Don't record usage for ambiguous selectors
1021 -- until we know which is meant
1022 return $ Just (Right (map gre_name gres))
1023 MultipleNames gres -> do
1024 addNameClashErrRn rdr_name gres
1025 return (Just (Left (gre_name (head gres)))) }
1026
1027
1028 --------------------------------------------------
1029 -- Lookup in the Global RdrEnv of the module
1030 --------------------------------------------------
1031
1032 data GreLookupResult = GreNotFound
1033 | OneNameMatch GlobalRdrElt
1034 | MultipleNames [GlobalRdrElt]
1035
1036 lookupGreRn_maybe :: RdrName -> RnM (Maybe GlobalRdrElt)
1037 -- Look up the RdrName in the GlobalRdrEnv
1038 -- Exactly one binding: records it as "used", return (Just gre)
1039 -- No bindings: return Nothing
1040 -- Many bindings: report "ambiguous", return an arbitrary (Just gre)
1041 -- Uses addUsedRdrName to record use and deprecations
1042 lookupGreRn_maybe rdr_name
1043 = do
1044 res <- lookupGreRn_helper rdr_name
1045 case res of
1046 OneNameMatch gre -> return $ Just gre
1047 MultipleNames gres -> do
1048 traceRn "lookupGreRn_maybe:NameClash" (ppr gres)
1049 addNameClashErrRn rdr_name gres
1050 return $ Just (head gres)
1051 GreNotFound -> return Nothing
1052
1053 {-
1054
1055 Note [ Unbound vs Ambiguous Names ]
1056
1057 lookupGreRn_maybe deals with failures in two different ways. If a name
1058 is unbound then we return a `Nothing` but if the name is ambiguous
1059 then we raise an error and return a dummy name.
1060
1061 The reason for this is that when we call `lookupGreRn_maybe` we are
1062 speculatively looking for whatever we are looking up. If we don't find it,
1063 then we might have been looking for the wrong thing and can keep trying.
1064 On the other hand, if we find a clash then there is no way to recover as
1065 we found the thing we were looking for but can no longer resolve which
1066 the correct one is.
1067
1068 One example of this is in `lookupTypeOccRn` which first looks in the type
1069 constructor namespace before looking in the data constructor namespace to
1070 deal with `DataKinds`.
1071
1072 There is however, as always, one exception to this scheme. If we find
1073 an ambiguous occurence of a record selector and DuplicateRecordFields
1074 is enabled then we defer the selection until the typechecker.
1075
1076 -}
1077
1078
1079
1080
1081 -- Internal Function
1082 lookupGreRn_helper :: RdrName -> RnM GreLookupResult
1083 lookupGreRn_helper rdr_name
1084 = do { env <- getGlobalRdrEnv
1085 ; case lookupGRE_RdrName rdr_name env of
1086 [] -> return GreNotFound
1087 [gre] -> do { addUsedGRE True gre
1088 ; return (OneNameMatch gre) }
1089 gres -> return (MultipleNames gres) }
1090
1091 lookupGreAvailRn :: RdrName -> RnM (Name, AvailInfo)
1092 -- Used in export lists
1093 -- If not found or ambiguous, add error message, and fake with UnboundName
1094 -- Uses addUsedRdrName to record use and deprecations
1095 lookupGreAvailRn rdr_name
1096 = do
1097 mb_gre <- lookupGreRn_helper rdr_name
1098 case mb_gre of
1099 GreNotFound ->
1100 do
1101 traceRn "lookupGreAvailRn" (ppr rdr_name)
1102 name <- unboundName WL_Global rdr_name
1103 return (name, avail name)
1104 MultipleNames gres ->
1105 do
1106 addNameClashErrRn rdr_name gres
1107 let unbound_name = mkUnboundNameRdr rdr_name
1108 return (unbound_name, avail unbound_name)
1109 -- Returning an unbound name here prevents an error
1110 -- cascade
1111 OneNameMatch gre ->
1112 return (gre_name gre, availFromGRE gre)
1113
1114
1115 {-
1116 *********************************************************
1117 * *
1118 Deprecations
1119 * *
1120 *********************************************************
1121
1122 Note [Handling of deprecations]
1123 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1124 * We report deprecations at each *occurrence* of the deprecated thing
1125 (see Trac #5867)
1126
1127 * We do not report deprecations for locally-defined names. For a
1128 start, we may be exporting a deprecated thing. Also we may use a
1129 deprecated thing in the defn of another deprecated things. We may
1130 even use a deprecated thing in the defn of a non-deprecated thing,
1131 when changing a module's interface.
1132
1133 * addUsedGREs: we do not report deprecations for sub-binders:
1134 - the ".." completion for records
1135 - the ".." in an export item 'T(..)'
1136 - the things exported by a module export 'module M'
1137 -}
1138
1139 addUsedDataCons :: GlobalRdrEnv -> TyCon -> RnM ()
1140 -- Remember use of in-scope data constructors (Trac #7969)
1141 addUsedDataCons rdr_env tycon
1142 = addUsedGREs [ gre
1143 | dc <- tyConDataCons tycon
1144 , Just gre <- [lookupGRE_Name rdr_env (dataConName dc)] ]
1145
1146 addUsedGRE :: Bool -> GlobalRdrElt -> RnM ()
1147 -- Called for both local and imported things
1148 -- Add usage *and* warn if deprecated
1149 addUsedGRE warn_if_deprec gre
1150 = do { when warn_if_deprec (warnIfDeprecated gre)
1151 ; unless (isLocalGRE gre) $
1152 do { env <- getGblEnv
1153 ; traceRn "addUsedGRE" (ppr gre)
1154 ; updMutVar (tcg_used_gres env) (gre :) } }
1155
1156 addUsedGREs :: [GlobalRdrElt] -> RnM ()
1157 -- Record uses of any *imported* GREs
1158 -- Used for recording used sub-bndrs
1159 -- NB: no call to warnIfDeprecated; see Note [Handling of deprecations]
1160 addUsedGREs gres
1161 | null imp_gres = return ()
1162 | otherwise = do { env <- getGblEnv
1163 ; traceRn "addUsedGREs" (ppr imp_gres)
1164 ; updMutVar (tcg_used_gres env) (imp_gres ++) }
1165 where
1166 imp_gres = filterOut isLocalGRE gres
1167
1168 warnIfDeprecated :: GlobalRdrElt -> RnM ()
1169 warnIfDeprecated gre@(GRE { gre_name = name, gre_imp = iss })
1170 | (imp_spec : _) <- iss
1171 = do { dflags <- getDynFlags
1172 ; this_mod <- getModule
1173 ; when (wopt Opt_WarnWarningsDeprecations dflags &&
1174 not (nameIsLocalOrFrom this_mod name)) $
1175 -- See Note [Handling of deprecations]
1176 do { iface <- loadInterfaceForName doc name
1177 ; case lookupImpDeprec iface gre of
1178 Just txt -> addWarn (Reason Opt_WarnWarningsDeprecations)
1179 (mk_msg imp_spec txt)
1180 Nothing -> return () } }
1181 | otherwise
1182 = return ()
1183 where
1184 occ = greOccName gre
1185 name_mod = ASSERT2( isExternalName name, ppr name ) nameModule name
1186 doc = text "The name" <+> quotes (ppr occ) <+> ptext (sLit "is mentioned explicitly")
1187
1188 mk_msg imp_spec txt
1189 = sep [ sep [ text "In the use of"
1190 <+> pprNonVarNameSpace (occNameSpace occ)
1191 <+> quotes (ppr occ)
1192 , parens imp_msg <> colon ]
1193 , pprWarningTxtForMsg txt ]
1194 where
1195 imp_mod = importSpecModule imp_spec
1196 imp_msg = text "imported from" <+> ppr imp_mod <> extra
1197 extra | imp_mod == moduleName name_mod = Outputable.empty
1198 | otherwise = text ", but defined in" <+> ppr name_mod
1199
1200 lookupImpDeprec :: ModIface -> GlobalRdrElt -> Maybe WarningTxt
1201 lookupImpDeprec iface gre
1202 = mi_warn_fn iface (greOccName gre) `mplus` -- Bleat if the thing,
1203 case gre_par gre of -- or its parent, is warn'd
1204 ParentIs p -> mi_warn_fn iface (nameOccName p)
1205 FldParent { par_is = p } -> mi_warn_fn iface (nameOccName p)
1206 NoParent -> Nothing
1207
1208 {-
1209 Note [Used names with interface not loaded]
1210 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1211 It's (just) possible to find a used
1212 Name whose interface hasn't been loaded:
1213
1214 a) It might be a WiredInName; in that case we may not load
1215 its interface (although we could).
1216
1217 b) It might be GHC.Real.fromRational, or GHC.Num.fromInteger
1218 These are seen as "used" by the renamer (if -XRebindableSyntax)
1219 is on), but the typechecker may discard their uses
1220 if in fact the in-scope fromRational is GHC.Read.fromRational,
1221 (see tcPat.tcOverloadedLit), and the typechecker sees that the type
1222 is fixed, say, to GHC.Base.Float (see Inst.lookupSimpleInst).
1223 In that obscure case it won't force the interface in.
1224
1225 In both cases we simply don't permit deprecations;
1226 this is, after all, wired-in stuff.
1227
1228
1229 *********************************************************
1230 * *
1231 GHCi support
1232 * *
1233 *********************************************************
1234
1235 A qualified name on the command line can refer to any module at
1236 all: we try to load the interface if we don't already have it, just
1237 as if there was an "import qualified M" declaration for every
1238 module.
1239
1240 For example, writing `Data.List.sort` will load the interface file for
1241 `Data.List` as if the user had written `import qualified Data.List`.
1242
1243 If we fail we just return Nothing, rather than bleating
1244 about "attempting to use module ā€˜Dā€™ (./D.hs) which is not loaded"
1245 which is what loadSrcInterface does.
1246
1247 It is enabled by default and disabled by the flag
1248 `-fno-implicit-import-qualified`.
1249
1250 Note [Safe Haskell and GHCi]
1251 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1252 We DON'T do this Safe Haskell as we need to check imports. We can
1253 and should instead check the qualified import but at the moment
1254 this requires some refactoring so leave as a TODO
1255 -}
1256
1257
1258
1259 lookupQualifiedNameGHCi :: RdrName -> RnM [Name]
1260 lookupQualifiedNameGHCi rdr_name
1261 = -- We want to behave as we would for a source file import here,
1262 -- and respect hiddenness of modules/packages, hence loadSrcInterface.
1263 do { dflags <- getDynFlags
1264 ; is_ghci <- getIsGHCi
1265 ; go_for_it dflags is_ghci }
1266
1267 where
1268 go_for_it dflags is_ghci
1269 | Just (mod,occ) <- isQual_maybe rdr_name
1270 , is_ghci
1271 , gopt Opt_ImplicitImportQualified dflags -- Enables this GHCi behaviour
1272 , not (safeDirectImpsReq dflags) -- See Note [Safe Haskell and GHCi]
1273 = do { res <- loadSrcInterface_maybe doc mod False Nothing
1274 ; case res of
1275 Succeeded iface
1276 -> return [ name
1277 | avail <- mi_exports iface
1278 , name <- availNames avail
1279 , nameOccName name == occ ]
1280
1281 _ -> -- Either we couldn't load the interface, or
1282 -- we could but we didn't find the name in it
1283 do { traceRn "lookupQualifiedNameGHCi" (ppr rdr_name)
1284 ; return [] } }
1285
1286 | otherwise
1287 = do { traceRn "lookupQualifiedNameGHCi: off" (ppr rdr_name)
1288 ; return [] }
1289
1290 doc = text "Need to find" <+> ppr rdr_name
1291
1292 {-
1293 Note [Looking up signature names]
1294 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1295 lookupSigOccRn is used for type signatures and pragmas
1296 Is this valid?
1297 module A
1298 import M( f )
1299 f :: Int -> Int
1300 f x = x
1301 It's clear that the 'f' in the signature must refer to A.f
1302 The Haskell98 report does not stipulate this, but it will!
1303 So we must treat the 'f' in the signature in the same way
1304 as the binding occurrence of 'f', using lookupBndrRn
1305
1306 However, consider this case:
1307 import M( f )
1308 f :: Int -> Int
1309 g x = x
1310 We don't want to say 'f' is out of scope; instead, we want to
1311 return the imported 'f', so that later on the reanamer will
1312 correctly report "misplaced type sig".
1313
1314 Note [Signatures for top level things]
1315 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1316 data HsSigCtxt = ... | TopSigCtxt NameSet | ....
1317
1318 * The NameSet says what is bound in this group of bindings.
1319 We can't use isLocalGRE from the GlobalRdrEnv, because of this:
1320 f x = x
1321 $( ...some TH splice... )
1322 f :: Int -> Int
1323 When we encounter the signature for 'f', the binding for 'f'
1324 will be in the GlobalRdrEnv, and will be a LocalDef. Yet the
1325 signature is mis-placed
1326
1327 * For type signatures the NameSet should be the names bound by the
1328 value bindings; for fixity declarations, the NameSet should also
1329 include class sigs and record selectors
1330
1331 infix 3 `f` -- Yes, ok
1332 f :: C a => a -> a -- No, not ok
1333 class C a where
1334 f :: a -> a
1335 -}
1336
1337 data HsSigCtxt
1338 = TopSigCtxt NameSet -- At top level, binding these names
1339 -- See Note [Signatures for top level things]
1340 | LocalBindCtxt NameSet -- In a local binding, binding these names
1341 | ClsDeclCtxt Name -- Class decl for this class
1342 | InstDeclCtxt NameSet -- Instance decl whose user-written method
1343 -- bindings are for these methods
1344 | HsBootCtxt NameSet -- Top level of a hs-boot file, binding these names
1345 | RoleAnnotCtxt NameSet -- A role annotation, with the names of all types
1346 -- in the group
1347
1348 instance Outputable HsSigCtxt where
1349 ppr (TopSigCtxt ns) = text "TopSigCtxt" <+> ppr ns
1350 ppr (LocalBindCtxt ns) = text "LocalBindCtxt" <+> ppr ns
1351 ppr (ClsDeclCtxt n) = text "ClsDeclCtxt" <+> ppr n
1352 ppr (InstDeclCtxt ns) = text "InstDeclCtxt" <+> ppr ns
1353 ppr (HsBootCtxt ns) = text "HsBootCtxt" <+> ppr ns
1354 ppr (RoleAnnotCtxt ns) = text "RoleAnnotCtxt" <+> ppr ns
1355
1356 lookupSigOccRn :: HsSigCtxt
1357 -> Sig GhcPs
1358 -> Located RdrName -> RnM (Located Name)
1359 lookupSigOccRn ctxt sig = lookupSigCtxtOccRn ctxt (hsSigDoc sig)
1360
1361 -- | Lookup a name in relation to the names in a 'HsSigCtxt'
1362 lookupSigCtxtOccRn :: HsSigCtxt
1363 -> SDoc -- ^ description of thing we're looking up,
1364 -- like "type family"
1365 -> Located RdrName -> RnM (Located Name)
1366 lookupSigCtxtOccRn ctxt what
1367 = wrapLocM $ \ rdr_name ->
1368 do { mb_name <- lookupBindGroupOcc ctxt what rdr_name
1369 ; case mb_name of
1370 Left err -> do { addErr err; return (mkUnboundNameRdr rdr_name) }
1371 Right name -> return name }
1372
1373 lookupBindGroupOcc :: HsSigCtxt
1374 -> SDoc
1375 -> RdrName -> RnM (Either MsgDoc Name)
1376 -- Looks up the RdrName, expecting it to resolve to one of the
1377 -- bound names passed in. If not, return an appropriate error message
1378 --
1379 -- See Note [Looking up signature names]
1380 lookupBindGroupOcc ctxt what rdr_name
1381 | Just n <- isExact_maybe rdr_name
1382 = lookupExactOcc_either n -- allow for the possibility of missing Exacts;
1383 -- see Note [dataTcOccs and Exact Names]
1384 -- Maybe we should check the side conditions
1385 -- but it's a pain, and Exact things only show
1386 -- up when you know what you are doing
1387
1388 | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
1389 = do { n' <- lookupOrig rdr_mod rdr_occ
1390 ; return (Right n') }
1391
1392 | otherwise
1393 = case ctxt of
1394 HsBootCtxt ns -> lookup_top (`elemNameSet` ns)
1395 TopSigCtxt ns -> lookup_top (`elemNameSet` ns)
1396 RoleAnnotCtxt ns -> lookup_top (`elemNameSet` ns)
1397 LocalBindCtxt ns -> lookup_group ns
1398 ClsDeclCtxt cls -> lookup_cls_op cls
1399 InstDeclCtxt ns -> lookup_top (`elemNameSet` ns)
1400 where
1401 lookup_cls_op cls
1402 = lookupSubBndrOcc True cls doc rdr_name
1403 where
1404 doc = text "method of class" <+> quotes (ppr cls)
1405
1406 lookup_top keep_me
1407 = do { env <- getGlobalRdrEnv
1408 ; let all_gres = lookupGlobalRdrEnv env (rdrNameOcc rdr_name)
1409 ; case filter (keep_me . gre_name) all_gres of
1410 [] | null all_gres -> bale_out_with Outputable.empty
1411 | otherwise -> bale_out_with local_msg
1412 (gre:_) -> return (Right (gre_name gre)) }
1413
1414 lookup_group bound_names -- Look in the local envt (not top level)
1415 = do { mname <- lookupLocalOccRn_maybe rdr_name
1416 ; case mname of
1417 Just n
1418 | n `elemNameSet` bound_names -> return (Right n)
1419 | otherwise -> bale_out_with local_msg
1420 Nothing -> bale_out_with Outputable.empty }
1421
1422 bale_out_with msg
1423 = return (Left (sep [ text "The" <+> what
1424 <+> text "for" <+> quotes (ppr rdr_name)
1425 , nest 2 $ text "lacks an accompanying binding"]
1426 $$ nest 2 msg))
1427
1428 local_msg = parens $ text "The" <+> what <+> ptext (sLit "must be given where")
1429 <+> quotes (ppr rdr_name) <+> text "is declared"
1430
1431
1432 ---------------
1433 lookupLocalTcNames :: HsSigCtxt -> SDoc -> RdrName -> RnM [(RdrName, Name)]
1434 -- GHC extension: look up both the tycon and data con or variable.
1435 -- Used for top-level fixity signatures and deprecations.
1436 -- Complain if neither is in scope.
1437 -- See Note [Fixity signature lookup]
1438 lookupLocalTcNames ctxt what rdr_name
1439 = do { mb_gres <- mapM lookup (dataTcOccs rdr_name)
1440 ; let (errs, names) = partitionEithers mb_gres
1441 ; when (null names) $ addErr (head errs) -- Bleat about one only
1442 ; return names }
1443 where
1444 lookup rdr = do { name <- lookupBindGroupOcc ctxt what rdr
1445 ; return (fmap ((,) rdr) name) }
1446
1447 dataTcOccs :: RdrName -> [RdrName]
1448 -- Return both the given name and the same name promoted to the TcClsName
1449 -- namespace. This is useful when we aren't sure which we are looking at.
1450 -- See also Note [dataTcOccs and Exact Names]
1451 dataTcOccs rdr_name
1452 | isDataOcc occ || isVarOcc occ
1453 = [rdr_name, rdr_name_tc]
1454 | otherwise
1455 = [rdr_name]
1456 where
1457 occ = rdrNameOcc rdr_name
1458 rdr_name_tc = setRdrNameSpace rdr_name tcName
1459
1460 {-
1461 Note [dataTcOccs and Exact Names]
1462 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1463 Exact RdrNames can occur in code generated by Template Haskell, and generally
1464 those references are, well, exact. However, the TH `Name` type isn't expressive
1465 enough to always track the correct namespace information, so we sometimes get
1466 the right Unique but wrong namespace. Thus, we still have to do the double-lookup
1467 for Exact RdrNames.
1468
1469 There is also an awkward situation for built-in syntax. Example in GHCi
1470 :info []
1471 This parses as the Exact RdrName for nilDataCon, but we also want
1472 the list type constructor.
1473
1474 Note that setRdrNameSpace on an Exact name requires the Name to be External,
1475 which it always is for built in syntax.
1476 -}
1477
1478
1479
1480 {-
1481 ************************************************************************
1482 * *
1483 Rebindable names
1484 Dealing with rebindable syntax is driven by the
1485 Opt_RebindableSyntax dynamic flag.
1486
1487 In "deriving" code we don't want to use rebindable syntax
1488 so we switch off the flag locally
1489
1490 * *
1491 ************************************************************************
1492
1493 Haskell 98 says that when you say "3" you get the "fromInteger" from the
1494 Standard Prelude, regardless of what is in scope. However, to experiment
1495 with having a language that is less coupled to the standard prelude, we're
1496 trying a non-standard extension that instead gives you whatever "Prelude.fromInteger"
1497 happens to be in scope. Then you can
1498 import Prelude ()
1499 import MyPrelude as Prelude
1500 to get the desired effect.
1501
1502 At the moment this just happens for
1503 * fromInteger, fromRational on literals (in expressions and patterns)
1504 * negate (in expressions)
1505 * minus (arising from n+k patterns)
1506 * "do" notation
1507
1508 We store the relevant Name in the HsSyn tree, in
1509 * HsIntegral/HsFractional/HsIsString
1510 * NegApp
1511 * NPlusKPat
1512 * HsDo
1513 respectively. Initially, we just store the "standard" name (PrelNames.fromIntegralName,
1514 fromRationalName etc), but the renamer changes this to the appropriate user
1515 name if Opt_NoImplicitPrelude is on. That is what lookupSyntaxName does.
1516
1517 We treat the original (standard) names as free-vars too, because the type checker
1518 checks the type of the user thing against the type of the standard thing.
1519 -}
1520
1521 lookupIfThenElse :: RnM (Maybe (SyntaxExpr GhcRn), FreeVars)
1522 -- Different to lookupSyntaxName because in the non-rebindable
1523 -- case we desugar directly rather than calling an existing function
1524 -- Hence the (Maybe (SyntaxExpr GhcRn)) return type
1525 lookupIfThenElse
1526 = do { rebindable_on <- xoptM LangExt.RebindableSyntax
1527 ; if not rebindable_on
1528 then return (Nothing, emptyFVs)
1529 else do { ite <- lookupOccRn (mkVarUnqual (fsLit "ifThenElse"))
1530 ; return ( Just (mkRnSyntaxExpr ite)
1531 , unitFV ite ) } }
1532
1533 lookupSyntaxName' :: Name -- ^ The standard name
1534 -> RnM Name -- ^ Possibly a non-standard name
1535 lookupSyntaxName' std_name
1536 = do { rebindable_on <- xoptM LangExt.RebindableSyntax
1537 ; if not rebindable_on then
1538 return std_name
1539 else
1540 -- Get the similarly named thing from the local environment
1541 lookupOccRn (mkRdrUnqual (nameOccName std_name)) }
1542
1543 lookupSyntaxName :: Name -- The standard name
1544 -> RnM (SyntaxExpr GhcRn, FreeVars) -- Possibly a non-standard
1545 -- name
1546 lookupSyntaxName std_name
1547 = do { rebindable_on <- xoptM LangExt.RebindableSyntax
1548 ; if not rebindable_on then
1549 return (mkRnSyntaxExpr std_name, emptyFVs)
1550 else
1551 -- Get the similarly named thing from the local environment
1552 do { usr_name <- lookupOccRn (mkRdrUnqual (nameOccName std_name))
1553 ; return (mkRnSyntaxExpr usr_name, unitFV usr_name) } }
1554
1555 lookupSyntaxNames :: [Name] -- Standard names
1556 -> RnM ([HsExpr GhcRn], FreeVars) -- See comments with HsExpr.ReboundNames
1557 -- this works with CmdTop, which wants HsExprs, not SyntaxExprs
1558 lookupSyntaxNames std_names
1559 = do { rebindable_on <- xoptM LangExt.RebindableSyntax
1560 ; if not rebindable_on then
1561 return (map (HsVar . noLoc) std_names, emptyFVs)
1562 else
1563 do { usr_names <- mapM (lookupOccRn . mkRdrUnqual . nameOccName) std_names
1564 ; return (map (HsVar . noLoc) usr_names, mkFVs usr_names) } }
1565
1566 -- Error messages
1567
1568
1569 opDeclErr :: RdrName -> SDoc
1570 opDeclErr n
1571 = hang (text "Illegal declaration of a type or class operator" <+> quotes (ppr n))
1572 2 (text "Use TypeOperators to declare operators in type and declarations")
1573
1574 badOrigBinding :: RdrName -> SDoc
1575 badOrigBinding name
1576 | Just _ <- isBuiltInOcc_maybe occ
1577 = text "Illegal binding of built-in syntax:" <+> ppr occ
1578 -- Use an OccName here because we don't want to print Prelude.(,)
1579 | otherwise
1580 = text "Cannot redefine a Name retrieved by a Template Haskell quote:"
1581 <+> ppr name
1582 -- This can happen when one tries to use a Template Haskell splice to
1583 -- define a top-level identifier with an already existing name, e.g.,
1584 --
1585 -- $(pure [ValD (VarP 'succ) (NormalB (ConE 'True)) []])
1586 --
1587 -- (See Trac #13968.)
1588 where
1589 occ = rdrNameOcc name