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