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