Import/export of data constructors in family instances
[ghc-hetmet.git] / compiler / rename / RnEnv.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[RnEnv]{Environment manipulation for the renamer monad}
5
6 \begin{code}
7 module RnEnv ( 
8         newTopSrcBinder, lookupFamInstDeclBndr,
9         lookupLocatedBndrRn, lookupBndrRn, 
10         lookupLocatedTopBndrRn, lookupTopBndrRn,
11         lookupLocatedOccRn, lookupOccRn, 
12         lookupLocatedGlobalOccRn, lookupGlobalOccRn,
13         lookupLocalDataTcNames, lookupSrcOcc_maybe,
14         lookupFixityRn, lookupTyFixityRn, lookupLocatedSigOccRn, 
15         lookupLocatedInstDeclBndr,
16         lookupSyntaxName, lookupSyntaxTable, lookupImportedName,
17
18         newLocalsRn, newIPNameRn,
19         bindLocalNames, bindLocalNamesFV,
20         bindLocatedLocalsFV, bindLocatedLocalsRn,
21         bindSigTyVarsFV, bindPatSigTyVars, bindPatSigTyVarsFV,
22         bindTyVarsRn, extendTyVarEnvFVRn,
23         bindLocalFixities,
24
25         checkDupNames, mapFvRn,
26         warnUnusedMatches, warnUnusedModules, warnUnusedImports, 
27         warnUnusedTopBinds, warnUnusedLocalBinds,
28         dataTcOccs, unknownNameErr,
29     ) where
30
31 #include "HsVersions.h"
32
33 import LoadIface        ( loadInterfaceForName, loadSrcInterface )
34 import IfaceEnv         ( lookupOrig, newGlobalBinder, newIPName )
35 import HsSyn            ( FixitySig(..), HsExpr(..), SyntaxExpr, SyntaxTable,
36                           LHsTyVarBndr, LHsType, 
37                           Fixity, hsLTyVarLocNames, replaceTyVarName )
38 import RdrHsSyn         ( extractHsTyRdrTyVars )
39 import RdrName          ( RdrName, isQual, isUnqual, isOrig_maybe,
40                           isQual_maybe,
41                           mkRdrUnqual, setRdrNameSpace, rdrNameOcc,
42                           pprGlobalRdrEnv, lookupGRE_RdrName, 
43                           isExact_maybe, isSrcRdrName,
44                           GlobalRdrElt(..), GlobalRdrEnv, lookupGlobalRdrEnv, 
45                           isLocalGRE, extendLocalRdrEnv, elemLocalRdrEnv, lookupLocalRdrEnv,
46                           Provenance(..), pprNameProvenance,
47                           importSpecLoc, importSpecModule
48                         )
49 import HscTypes         ( availNames, ModIface(..), FixItem(..), lookupFixity )
50 import TcRnMonad
51 import Name             ( Name, nameIsLocalOrFrom, mkInternalName, isWiredInName,
52                           nameSrcLoc, nameOccName, nameModule, nameParent, isExternalName )
53 import NameSet
54 import OccName          ( tcName, isDataOcc, pprNonVarNameSpace, occNameSpace,
55                           reportIfUnused )
56 import Module           ( Module, ModuleName )
57 import PrelNames        ( mkUnboundName, rOOT_MAIN, iNTERACTIVE, consDataConKey, hasKey )
58 import UniqSupply
59 import BasicTypes       ( IPName, mapIPName )
60 import SrcLoc           ( SrcSpan, srcSpanStart, Located(..), eqLocated, unLoc,
61                           srcLocSpan, getLoc, combineSrcSpans, isOneLineSpan )
62 import Outputable
63 import Util             ( sortLe )
64 import ListSetOps       ( removeDups )
65 import List             ( nubBy )
66 import Monad            ( when )
67 import DynFlags
68 \end{code}
69
70 %*********************************************************
71 %*                                                      *
72                 Source-code binders
73 %*                                                      *
74 %*********************************************************
75
76 \begin{code}
77 newTopSrcBinder :: Module -> Maybe Name -> Located RdrName -> RnM Name
78 newTopSrcBinder this_mod mb_parent (L loc rdr_name)
79   | Just name <- isExact_maybe rdr_name
80   =     -- This is here to catch 
81         --   (a) Exact-name binders created by Template Haskell
82         --   (b) The PrelBase defn of (say) [] and similar, for which
83         --       the parser reads the special syntax and returns an Exact RdrName
84         -- We are at a binding site for the name, so check first that it 
85         -- the current module is the correct one; otherwise GHC can get
86         -- very confused indeed. This test rejects code like
87         --      data T = (,) Int Int
88         -- unless we are in GHC.Tup
89     ASSERT2( isExternalName name,  ppr name )
90     do  { checkM (this_mod == nameModule name)
91                  (addErrAt loc (badOrigBinding rdr_name))
92         ; return name }
93
94
95   | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
96   = do  { checkM (rdr_mod == this_mod || rdr_mod == rOOT_MAIN)
97                  (addErrAt loc (badOrigBinding rdr_name))
98         -- When reading External Core we get Orig names as binders, 
99         -- but they should agree with the module gotten from the monad
100         --
101         -- We can get built-in syntax showing up here too, sadly.  If you type
102         --      data T = (,,,)
103         -- the constructor is parsed as a type, and then RdrHsSyn.tyConToDataCon 
104         -- uses setRdrNameSpace to make it into a data constructors.  At that point
105         -- the nice Exact name for the TyCon gets swizzled to an Orig name.
106         -- Hence the badOrigBinding error message.
107         --
108         -- Except for the ":Main.main = ..." definition inserted into 
109         -- the Main module; ugh!
110
111         -- Because of this latter case, we call newGlobalBinder with a module from 
112         -- the RdrName, not from the environment.  In principle, it'd be fine to 
113         -- have an arbitrary mixture of external core definitions in a single module,
114         -- (apart from module-initialisation issues, perhaps).
115         ; newGlobalBinder rdr_mod rdr_occ mb_parent (srcSpanStart loc) }
116                 --TODO, should pass the whole span
117
118   | otherwise
119   = do  { checkM (not (isQual rdr_name))
120                  (addErrAt loc (badQualBndrErr rdr_name))
121                 -- Binders should not be qualified; if they are, and with a different
122                 -- module name, we we get a confusing "M.T is not in scope" error later
123         ; newGlobalBinder this_mod (rdrNameOcc rdr_name) mb_parent (srcSpanStart loc) }
124 \end{code}
125
126 %*********************************************************
127 %*                                                      *
128         Source code occurrences
129 %*                                                      *
130 %*********************************************************
131
132 Looking up a name in the RnEnv.
133
134 \begin{code}
135 lookupLocatedBndrRn :: Located RdrName -> RnM (Located Name)
136 lookupLocatedBndrRn = wrapLocM lookupBndrRn
137
138 lookupBndrRn :: RdrName -> RnM Name
139 -- NOTE: assumes that the SrcSpan of the binder has already been setSrcSpan'd
140 lookupBndrRn rdr_name
141   = getLocalRdrEnv              `thenM` \ local_env ->
142     case lookupLocalRdrEnv local_env rdr_name of 
143           Just name -> returnM name
144           Nothing   -> lookupTopBndrRn rdr_name
145
146 lookupLocatedTopBndrRn :: Located RdrName -> RnM (Located Name)
147 lookupLocatedTopBndrRn = wrapLocM lookupTopBndrRn
148
149 lookupTopBndrRn :: RdrName -> RnM Name
150 -- Look up a top-level source-code binder.   We may be looking up an unqualified 'f',
151 -- and there may be several imported 'f's too, which must not confuse us.
152 -- For example, this is OK:
153 --      import Foo( f )
154 --      infix 9 f       -- The 'f' here does not need to be qualified
155 --      f x = x         -- Nor here, of course
156 -- So we have to filter out the non-local ones.
157 --
158 -- A separate function (importsFromLocalDecls) reports duplicate top level
159 -- decls, so here it's safe just to choose an arbitrary one.
160 --
161 -- There should never be a qualified name in a binding position in Haskell,
162 -- but there can be if we have read in an external-Core file.
163 -- The Haskell parser checks for the illegal qualified name in Haskell 
164 -- source files, so we don't need to do so here.
165
166 lookupTopBndrRn rdr_name
167   | Just name <- isExact_maybe rdr_name
168   = returnM name
169
170   | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name    
171         -- This deals with the case of derived bindings, where
172         -- we don't bother to call newTopSrcBinder first
173         -- We assume there is no "parent" name
174   = do  { loc <- getSrcSpanM
175         ; newGlobalBinder rdr_mod rdr_occ Nothing (srcSpanStart loc) }
176
177   | otherwise
178   = do  { mb_gre <- lookupGreLocalRn rdr_name
179         ; case mb_gre of
180                 Nothing  -> unboundName rdr_name
181                 Just gre -> returnM (gre_name gre) }
182               
183 -- lookupLocatedSigOccRn is used for type signatures and pragmas
184 -- Is this valid?
185 --   module A
186 --      import M( f )
187 --      f :: Int -> Int
188 --      f x = x
189 -- It's clear that the 'f' in the signature must refer to A.f
190 -- The Haskell98 report does not stipulate this, but it will!
191 -- So we must treat the 'f' in the signature in the same way
192 -- as the binding occurrence of 'f', using lookupBndrRn
193 lookupLocatedSigOccRn :: Located RdrName -> RnM (Located Name)
194 lookupLocatedSigOccRn = lookupLocatedBndrRn
195
196 -- lookupInstDeclBndr is used for the binders in an 
197 -- instance declaration.   Here we use the class name to
198 -- disambiguate.  
199
200 lookupLocatedInstDeclBndr :: Name -> Located RdrName -> RnM (Located Name)
201 lookupLocatedInstDeclBndr cls = wrapLocM (lookupInstDeclBndr cls)
202
203 lookupInstDeclBndr :: Name -> RdrName -> RnM Name
204 lookupInstDeclBndr cls_name rdr_name
205   | isUnqual rdr_name   -- Find all the things the rdr-name maps to
206   = do  {               -- and pick the one with the right parent name
207           let { is_op gre     = cls_name == nameParent (gre_name gre)
208               ; occ           = rdrNameOcc rdr_name
209               ; lookup_fn env = filter is_op (lookupGlobalRdrEnv env occ) }
210         ; mb_gre <- lookupGreRn_help rdr_name lookup_fn
211         ; case mb_gre of
212             Just gre -> return (gre_name gre)
213             Nothing  -> do { addErr (unknownInstBndrErr cls_name rdr_name)
214                            ; return (mkUnboundName rdr_name) } }
215
216   | otherwise   -- Occurs in derived instances, where we just
217                 -- refer directly to the right method
218   = ASSERT2( not (isQual rdr_name), ppr rdr_name )
219           -- NB: qualified names are rejected by the parser
220     lookupImportedName rdr_name
221
222 newIPNameRn :: IPName RdrName -> TcRnIf m n (IPName Name)
223 newIPNameRn ip_rdr = newIPName (mapIPName rdrNameOcc ip_rdr)
224
225 -- Looking up family names in type instances is a subtle affair.  The family
226 -- may be imported, in which case we need to lookup the occurence of a global
227 -- name.  Alternatively, the family may be in the same binding group (and in
228 -- fact in a declaration processed later), and we need to create a new top
229 -- source binder.
230 --
231 -- So, also this is strictly speaking an occurence, we cannot raise an error
232 -- message yet for instances without a family declaration.  This will happen
233 -- during renaming the type instance declaration in RnSource.rnTyClDecl.
234 --
235 lookupFamInstDeclBndr :: Module -> Located RdrName -> RnM Name
236 lookupFamInstDeclBndr mod lrdr_name@(L _ rdr_name)
237   | not (isSrcRdrName rdr_name)
238   = lookupImportedName rdr_name 
239
240   | otherwise
241   =     -- First look up the name in the normal environment.
242    lookupGreRn rdr_name                 `thenM` \ mb_gre ->
243    case mb_gre of {
244         Just gre -> returnM (gre_name gre) ;
245         Nothing  -> newTopSrcBinder mod Nothing lrdr_name }
246
247 --------------------------------------------------
248 --              Occurrences
249 --------------------------------------------------
250
251 lookupLocatedOccRn :: Located RdrName -> RnM (Located Name)
252 lookupLocatedOccRn = wrapLocM lookupOccRn
253
254 -- lookupOccRn looks up an occurrence of a RdrName
255 lookupOccRn :: RdrName -> RnM Name
256 lookupOccRn rdr_name
257   = getLocalRdrEnv                      `thenM` \ local_env ->
258     case lookupLocalRdrEnv local_env rdr_name of
259           Just name -> returnM name
260           Nothing   -> lookupGlobalOccRn rdr_name
261
262 lookupLocatedGlobalOccRn :: Located RdrName -> RnM (Located Name)
263 lookupLocatedGlobalOccRn = wrapLocM lookupGlobalOccRn
264
265 lookupGlobalOccRn :: RdrName -> RnM Name
266 -- lookupGlobalOccRn is like lookupOccRn, except that it looks in the global 
267 -- environment.  It's used only for
268 --      record field names
269 --      class op names in class and instance decls
270
271 lookupGlobalOccRn rdr_name
272   | not (isSrcRdrName rdr_name)
273   = lookupImportedName rdr_name 
274
275   | otherwise
276   =     -- First look up the name in the normal environment.
277    lookupGreRn rdr_name                 `thenM` \ mb_gre ->
278    case mb_gre of {
279         Just gre -> returnM (gre_name gre) ;
280         Nothing   -> 
281
282         -- We allow qualified names on the command line to refer to 
283         --  *any* name exported by any module in scope, just as if 
284         -- there was an "import qualified M" declaration for every 
285         -- module.
286    getModule            `thenM` \ mod ->
287    if isQual rdr_name && mod == iNTERACTIVE then        
288                                         -- This test is not expensive,
289         lookupQualifiedName rdr_name    -- and only happens for failed lookups
290    else 
291         unboundName rdr_name }
292
293 lookupImportedName :: RdrName -> TcRnIf m n Name
294 -- Lookup the occurrence of an imported name
295 -- The RdrName is *always* qualified or Exact
296 -- Treat it as an original name, and conjure up the Name
297 -- Usually it's Exact or Orig, but it can be Qual if it
298 --      comes from an hi-boot file.  (This minor infelicity is 
299 --      just to reduce duplication in the parser.)
300 lookupImportedName rdr_name
301   | Just n <- isExact_maybe rdr_name 
302         -- This happens in derived code
303   = returnM n
304
305         -- Always Orig, even when reading a .hi-boot file
306   | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
307   = lookupOrig rdr_mod rdr_occ
308
309   | otherwise
310   = pprPanic "RnEnv.lookupImportedName" (ppr rdr_name)
311
312 unboundName :: RdrName -> RnM Name
313 unboundName rdr_name 
314   = do  { addErr (unknownNameErr rdr_name)
315         ; env <- getGlobalRdrEnv;
316         ; traceRn (vcat [unknownNameErr rdr_name, 
317                          ptext SLIT("Global envt is:"),
318                          nest 3 (pprGlobalRdrEnv env)])
319         ; returnM (mkUnboundName rdr_name) }
320
321 --------------------------------------------------
322 --      Lookup in the Global RdrEnv of the module
323 --------------------------------------------------
324
325 lookupSrcOcc_maybe :: RdrName -> RnM (Maybe Name)
326 -- No filter function; does not report an error on failure
327 lookupSrcOcc_maybe rdr_name
328   = do  { mb_gre <- lookupGreRn rdr_name
329         ; case mb_gre of
330                 Nothing  -> returnM Nothing
331                 Just gre -> returnM (Just (gre_name gre)) }
332         
333 -------------------------
334 lookupGreRn :: RdrName -> RnM (Maybe GlobalRdrElt)
335 -- Just look up the RdrName in the GlobalRdrEnv
336 lookupGreRn rdr_name 
337   = lookupGreRn_help rdr_name (lookupGRE_RdrName rdr_name)
338
339 lookupGreLocalRn :: RdrName -> RnM (Maybe GlobalRdrElt)
340 -- Similar, but restricted to locally-defined things
341 lookupGreLocalRn rdr_name 
342   = lookupGreRn_help rdr_name lookup_fn
343   where
344     lookup_fn env = filter isLocalGRE (lookupGRE_RdrName rdr_name env)
345
346 lookupGreRn_help :: RdrName                     -- Only used in error message
347                  -> (GlobalRdrEnv -> [GlobalRdrElt])    -- Lookup function
348                  -> RnM (Maybe GlobalRdrElt)
349 -- Checks for exactly one match; reports deprecations
350 -- Returns Nothing, without error, if too few
351 lookupGreRn_help rdr_name lookup 
352   = do  { env <- getGlobalRdrEnv
353         ; case lookup env of
354             []    -> returnM Nothing
355             [gre] -> returnM (Just gre)
356             gres  -> do { addNameClashErrRn rdr_name gres
357                         ; returnM (Just (head gres)) } }
358
359 ------------------------------
360 --      GHCi support
361 ------------------------------
362
363 -- A qualified name on the command line can refer to any module at all: we
364 -- try to load the interface if we don't already have it.
365 lookupQualifiedName :: RdrName -> RnM Name
366 lookupQualifiedName rdr_name
367   | Just (mod,occ) <- isQual_maybe rdr_name
368    -- Note: we want to behave as we would for a source file import here,
369    -- and respect hiddenness of modules/packages, hence loadSrcInterface.
370    = loadSrcInterface doc mod False     `thenM` \ iface ->
371
372    case  [ (mod,occ) | 
373            (mod,avails) <- mi_exports iface,
374            avail        <- avails,
375            name         <- availNames avail,
376            name == occ ] of
377       ((mod,occ):ns) -> ASSERT (null ns) 
378                         lookupOrig mod occ
379       _ -> unboundName rdr_name
380
381   | otherwise
382   = pprPanic "RnEnv.lookupQualifiedName" (ppr rdr_name)
383   where
384     doc = ptext SLIT("Need to find") <+> ppr rdr_name
385 \end{code}
386
387 %*********************************************************
388 %*                                                      *
389                 Fixities
390 %*                                                      *
391 %*********************************************************
392
393 \begin{code}
394 lookupLocalDataTcNames :: RdrName -> RnM [Name]
395 -- GHC extension: look up both the tycon and data con 
396 -- for con-like things
397 -- Complain if neither is in scope
398 lookupLocalDataTcNames rdr_name
399   | Just n <- isExact_maybe rdr_name    
400         -- Special case for (:), which doesn't get into the GlobalRdrEnv
401   = return [n]  -- For this we don't need to try the tycon too
402   | otherwise
403   = do  { mb_gres <- mapM lookupGreLocalRn (dataTcOccs rdr_name)
404         ; case [gre_name gre | Just gre <- mb_gres] of
405             [] -> do { addErr (unknownNameErr rdr_name)
406                      ; return [] }
407             names -> return names
408     }
409
410 --------------------------------
411 bindLocalFixities :: [FixitySig RdrName] -> RnM a -> RnM a
412 -- Used for nested fixity decls
413 -- No need to worry about type constructors here,
414 -- Should check for duplicates but we don't
415 bindLocalFixities fixes thing_inside
416   | null fixes = thing_inside
417   | otherwise  = mappM rn_sig fixes     `thenM` \ new_bit ->
418                  extendFixityEnv new_bit thing_inside
419   where
420     rn_sig (FixitySig lv@(L loc v) fix)
421         = addLocM lookupBndrRn lv       `thenM` \ new_v ->
422           returnM (new_v, (FixItem (rdrNameOcc v) fix loc))
423 \end{code}
424
425 --------------------------------
426 lookupFixity is a bit strange.  
427
428 * Nested local fixity decls are put in the local fixity env, which we
429   find with getFixtyEnv
430
431 * Imported fixities are found in the HIT or PIT
432
433 * Top-level fixity decls in this module may be for Names that are
434     either  Global         (constructors, class operations)
435     or      Local/Exported (everything else)
436   (See notes with RnNames.getLocalDeclBinders for why we have this split.)
437   We put them all in the local fixity environment
438
439 \begin{code}
440 lookupFixityRn :: Name -> RnM Fixity
441 lookupFixityRn name
442   = getModule                           `thenM` \ this_mod ->
443     if nameIsLocalOrFrom this_mod name
444     then        -- It's defined in this module
445         getFixityEnv            `thenM` \ local_fix_env ->
446         traceRn (text "lookupFixityRn" <+> (ppr name $$ ppr local_fix_env)) `thenM_`
447         returnM (lookupFixity local_fix_env name)
448
449     else        -- It's imported
450       -- For imported names, we have to get their fixities by doing a
451       -- loadInterfaceForName, and consulting the Ifaces that comes back
452       -- from that, because the interface file for the Name might not
453       -- have been loaded yet.  Why not?  Suppose you import module A,
454       -- which exports a function 'f', thus;
455       --        module CurrentModule where
456       --          import A( f )
457       --        module A( f ) where
458       --          import B( f )
459       -- Then B isn't loaded right away (after all, it's possible that
460       -- nothing from B will be used).  When we come across a use of
461       -- 'f', we need to know its fixity, and it's then, and only
462       -- then, that we load B.hi.  That is what's happening here.
463       --
464       -- loadInterfaceForName will find B.hi even if B is a hidden module,
465       -- and that's what we want.
466         loadInterfaceForName doc name   `thenM` \ iface ->
467         returnM (mi_fix_fn iface (nameOccName name))
468   where
469     doc = ptext SLIT("Checking fixity for") <+> ppr name
470
471 ---------------
472 lookupTyFixityRn :: Located Name -> RnM Fixity
473 lookupTyFixityRn (L loc n)
474   = do  { glaExts <- doptM Opt_GlasgowExts
475         ; when (not glaExts) (addWarnAt loc (infixTyConWarn n))
476         ; lookupFixityRn n }
477
478 ---------------
479 dataTcOccs :: RdrName -> [RdrName]
480 -- If the input is a data constructor, return both it and a type
481 -- constructor.  This is useful when we aren't sure which we are
482 -- looking at.
483 dataTcOccs rdr_name
484   | Just n <- isExact_maybe rdr_name            -- Ghastly special case
485   , n `hasKey` consDataConKey = [rdr_name]      -- see note below
486   | isDataOcc occ             = [rdr_name_tc, rdr_name]
487   | otherwise                 = [rdr_name]
488   where    
489     occ         = rdrNameOcc rdr_name
490     rdr_name_tc = setRdrNameSpace rdr_name tcName
491
492 -- If the user typed "[]" or "(,,)", we'll generate an Exact RdrName,
493 -- and setRdrNameSpace generates an Orig, which is fine
494 -- But it's not fine for (:), because there *is* no corresponding type
495 -- constructor.  If we generate an Orig tycon for GHC.Base.(:), it'll
496 -- appear to be in scope (because Orig's simply allocate a new name-cache
497 -- entry) and then we get an error when we use dataTcOccs in 
498 -- TcRnDriver.tcRnGetInfo.  Large sigh.
499 \end{code}
500
501 %************************************************************************
502 %*                                                                      *
503                         Rebindable names
504         Dealing with rebindable syntax is driven by the 
505         Opt_NoImplicitPrelude dynamic flag.
506
507         In "deriving" code we don't want to use rebindable syntax
508         so we switch off the flag locally
509
510 %*                                                                      *
511 %************************************************************************
512
513 Haskell 98 says that when you say "3" you get the "fromInteger" from the
514 Standard Prelude, regardless of what is in scope.   However, to experiment
515 with having a language that is less coupled to the standard prelude, we're
516 trying a non-standard extension that instead gives you whatever "Prelude.fromInteger"
517 happens to be in scope.  Then you can
518         import Prelude ()
519         import MyPrelude as Prelude
520 to get the desired effect.
521
522 At the moment this just happens for
523   * fromInteger, fromRational on literals (in expressions and patterns)
524   * negate (in expressions)
525   * minus  (arising from n+k patterns)
526   * "do" notation
527
528 We store the relevant Name in the HsSyn tree, in 
529   * HsIntegral/HsFractional     
530   * NegApp
531   * NPlusKPat
532   * HsDo
533 respectively.  Initially, we just store the "standard" name (PrelNames.fromIntegralName,
534 fromRationalName etc), but the renamer changes this to the appropriate user
535 name if Opt_NoImplicitPrelude is on.  That is what lookupSyntaxName does.
536
537 We treat the orignal (standard) names as free-vars too, because the type checker
538 checks the type of the user thing against the type of the standard thing.
539
540 \begin{code}
541 lookupSyntaxName :: Name                                -- The standard name
542                  -> RnM (SyntaxExpr Name, FreeVars)     -- Possibly a non-standard name
543 lookupSyntaxName std_name
544   = doptM Opt_ImplicitPrelude           `thenM` \ implicit_prelude -> 
545     if implicit_prelude then normal_case
546     else
547         -- Get the similarly named thing from the local environment
548     lookupOccRn (mkRdrUnqual (nameOccName std_name)) `thenM` \ usr_name ->
549     returnM (HsVar usr_name, unitFV usr_name)
550   where
551     normal_case = returnM (HsVar std_name, emptyFVs)
552
553 lookupSyntaxTable :: [Name]                             -- Standard names
554                   -> RnM (SyntaxTable Name, FreeVars)   -- See comments with HsExpr.ReboundNames
555 lookupSyntaxTable std_names
556   = doptM Opt_ImplicitPrelude           `thenM` \ implicit_prelude -> 
557     if implicit_prelude then normal_case 
558     else
559         -- Get the similarly named thing from the local environment
560     mappM (lookupOccRn . mkRdrUnqual . nameOccName) std_names   `thenM` \ usr_names ->
561
562     returnM (std_names `zip` map HsVar usr_names, mkFVs usr_names)
563   where
564     normal_case = returnM (std_names `zip` map HsVar std_names, emptyFVs)
565 \end{code}
566
567
568 %*********************************************************
569 %*                                                      *
570 \subsection{Binding}
571 %*                                                      *
572 %*********************************************************
573
574 \begin{code}
575 newLocalsRn :: [Located RdrName] -> RnM [Name]
576 newLocalsRn rdr_names_w_loc
577   = newUniqueSupply             `thenM` \ us ->
578     returnM (zipWith mk rdr_names_w_loc (uniqsFromSupply us))
579   where
580     mk (L loc rdr_name) uniq
581         | Just name <- isExact_maybe rdr_name = name
582                 -- This happens in code generated by Template Haskell 
583         | otherwise = ASSERT2( isUnqual rdr_name, ppr rdr_name )
584                         -- We only bind unqualified names here
585                         -- lookupRdrEnv doesn't even attempt to look up a qualified RdrName
586                       mkInternalName uniq (rdrNameOcc rdr_name) (srcSpanStart loc)
587
588 bindLocatedLocalsRn :: SDoc     -- Documentation string for error message
589                     -> [Located RdrName]
590                     -> ([Name] -> RnM a)
591                     -> RnM a
592 bindLocatedLocalsRn doc_str rdr_names_w_loc enclosed_scope
593   =     -- Check for duplicate names
594     checkDupNames doc_str rdr_names_w_loc       `thenM_`
595
596         -- Warn about shadowing, but only in source modules
597     ifOptM Opt_WarnNameShadowing 
598       (checkShadowing doc_str rdr_names_w_loc)  `thenM_`
599
600         -- Make fresh Names and extend the environment
601     newLocalsRn rdr_names_w_loc         `thenM` \ names ->
602     getLocalRdrEnv                      `thenM` \ local_env ->
603     setLocalRdrEnv (extendLocalRdrEnv local_env names)
604                    (enclosed_scope names)
605
606
607 bindLocalNames :: [Name] -> RnM a -> RnM a
608 bindLocalNames names enclosed_scope
609   = getLocalRdrEnv              `thenM` \ name_env ->
610     setLocalRdrEnv (extendLocalRdrEnv name_env names)
611                     enclosed_scope
612
613 bindLocalNamesFV :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
614 bindLocalNamesFV names enclosed_scope
615   = do  { (result, fvs) <- bindLocalNames names enclosed_scope
616         ; returnM (result, delListFromNameSet fvs names) }
617
618
619 -------------------------------------
620         -- binLocalsFVRn is the same as bindLocalsRn
621         -- except that it deals with free vars
622 bindLocatedLocalsFV :: SDoc -> [Located RdrName] -> ([Name] -> RnM (a,FreeVars))
623   -> RnM (a, FreeVars)
624 bindLocatedLocalsFV doc rdr_names enclosed_scope
625   = bindLocatedLocalsRn doc rdr_names   $ \ names ->
626     enclosed_scope names                `thenM` \ (thing, fvs) ->
627     returnM (thing, delListFromNameSet fvs names)
628
629 -------------------------------------
630 bindTyVarsRn :: SDoc -> [LHsTyVarBndr RdrName]
631               -> ([LHsTyVarBndr Name] -> RnM a)
632               -> RnM a
633 -- Haskell-98 binding of type variables; e.g. within a data type decl
634 bindTyVarsRn doc_str tyvar_names enclosed_scope
635   = let
636         located_tyvars = hsLTyVarLocNames tyvar_names
637     in
638     bindLocatedLocalsRn doc_str located_tyvars  $ \ names ->
639     enclosed_scope (zipWith replace tyvar_names names)
640     where 
641         replace (L loc n1) n2 = L loc (replaceTyVarName n1 n2)
642
643 bindPatSigTyVars :: [LHsType RdrName] -> ([Name] -> RnM a) -> RnM a
644   -- Find the type variables in the pattern type 
645   -- signatures that must be brought into scope
646 bindPatSigTyVars tys thing_inside
647   = do  { scoped_tyvars <- doptM Opt_ScopedTypeVariables
648         ; if not scoped_tyvars then 
649                 thing_inside []
650           else 
651     do  { name_env <- getLocalRdrEnv
652         ; let locd_tvs  = [ tv | ty <- tys
653                                , tv <- extractHsTyRdrTyVars ty
654                                , not (unLoc tv `elemLocalRdrEnv` name_env) ]
655               nubbed_tvs = nubBy eqLocated locd_tvs
656                 -- The 'nub' is important.  For example:
657                 --      f (x :: t) (y :: t) = ....
658                 -- We don't want to complain about binding t twice!
659
660         ; bindLocatedLocalsRn doc_sig nubbed_tvs thing_inside }}
661   where
662     doc_sig = text "In a pattern type-signature"
663
664 bindPatSigTyVarsFV :: [LHsType RdrName]
665                    -> RnM (a, FreeVars)
666                    -> RnM (a, FreeVars)
667 bindPatSigTyVarsFV tys thing_inside
668   = bindPatSigTyVars tys        $ \ tvs ->
669     thing_inside                `thenM` \ (result,fvs) ->
670     returnM (result, fvs `delListFromNameSet` tvs)
671
672 bindSigTyVarsFV :: [Name]
673                 -> RnM (a, FreeVars)
674                 -> RnM (a, FreeVars)
675 bindSigTyVarsFV tvs thing_inside
676   = do  { scoped_tyvars <- doptM Opt_ScopedTypeVariables
677         ; if not scoped_tyvars then 
678                 thing_inside 
679           else
680                 bindLocalNamesFV tvs thing_inside }
681
682 extendTyVarEnvFVRn :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
683         -- This function is used only in rnSourceDecl on InstDecl
684 extendTyVarEnvFVRn tyvars thing_inside = bindLocalNamesFV tyvars thing_inside
685
686 -------------------------------------
687 checkDupNames :: SDoc
688               -> [Located RdrName]
689               -> RnM ()
690 checkDupNames doc_str rdr_names_w_loc
691   =     -- Check for duplicated names in a binding group
692     mappM_ (dupNamesErr doc_str) dups
693   where
694     (_, dups) = removeDups (\n1 n2 -> unLoc n1 `compare` unLoc n2) rdr_names_w_loc
695
696 -------------------------------------
697 checkShadowing doc_str loc_rdr_names
698   = getLocalRdrEnv              `thenM` \ local_env ->
699     getGlobalRdrEnv             `thenM` \ global_env ->
700     let
701       check_shadow (L loc rdr_name)
702         |  rdr_name `elemLocalRdrEnv` local_env 
703         || not (null (lookupGRE_RdrName rdr_name global_env ))
704         = addWarnAt loc (shadowedNameWarn doc_str rdr_name)
705         | otherwise = returnM ()
706     in
707     mappM_ check_shadow loc_rdr_names
708 \end{code}
709
710
711 %************************************************************************
712 %*                                                                      *
713 \subsection{Free variable manipulation}
714 %*                                                                      *
715 %************************************************************************
716
717 \begin{code}
718 -- A useful utility
719 mapFvRn f xs = mappM f xs       `thenM` \ stuff ->
720                let
721                   (ys, fvs_s) = unzip stuff
722                in
723                returnM (ys, plusFVs fvs_s)
724 \end{code}
725
726
727 %************************************************************************
728 %*                                                                      *
729 \subsection{Envt utility functions}
730 %*                                                                      *
731 %************************************************************************
732
733 \begin{code}
734 warnUnusedModules :: [(ModuleName,SrcSpan)] -> RnM ()
735 warnUnusedModules mods
736   = ifOptM Opt_WarnUnusedImports (mappM_ bleat mods)
737   where
738     bleat (mod,loc) = addWarnAt loc (mk_warn mod)
739     mk_warn m = vcat [ptext SLIT("Module") <+> quotes (ppr m)
740                         <+> text "is imported, but nothing from it is used,",
741                       nest 2 (ptext SLIT("except perhaps instances visible in") 
742                         <+> quotes (ppr m)),
743                       ptext SLIT("To suppress this warning, use:") 
744                         <+> ptext SLIT("import") <+> ppr m <> parens empty ]
745
746
747 warnUnusedImports, warnUnusedTopBinds :: [GlobalRdrElt] -> RnM ()
748 warnUnusedImports gres  = ifOptM Opt_WarnUnusedImports (warnUnusedGREs gres)
749 warnUnusedTopBinds gres = ifOptM Opt_WarnUnusedBinds   (warnUnusedGREs gres)
750
751 warnUnusedLocalBinds, warnUnusedMatches :: [Name] -> RnM ()
752 warnUnusedLocalBinds names = ifOptM Opt_WarnUnusedBinds   (warnUnusedLocals names)
753 warnUnusedMatches    names = ifOptM Opt_WarnUnusedMatches (warnUnusedLocals names)
754
755 -------------------------
756 --      Helpers
757 warnUnusedGREs gres 
758  = warnUnusedBinds [(n,Just p) | GRE {gre_name = n, gre_prov = p} <- gres]
759
760 warnUnusedLocals names
761  = warnUnusedBinds [(n,Nothing) | n<-names]
762
763 warnUnusedBinds :: [(Name,Maybe Provenance)] -> RnM ()
764 warnUnusedBinds names  = mappM_ warnUnusedName (filter reportable names)
765  where reportable (name,_) 
766         | isWiredInName name = False    -- Don't report unused wired-in names
767                                         -- Otherwise we get a zillion warnings
768                                         -- from Data.Tuple
769         | otherwise = reportIfUnused (nameOccName name)
770
771 -------------------------
772
773 warnUnusedName :: (Name, Maybe Provenance) -> RnM ()
774 warnUnusedName (name, prov)
775   = addWarnAt loc $
776     sep [msg <> colon, 
777          nest 2 $ pprNonVarNameSpace (occNameSpace (nameOccName name))
778                         <+> quotes (ppr name)]
779         -- TODO should be a proper span
780   where
781     (loc,msg) = case prov of
782                   Just (Imported is)
783                         -> (importSpecLoc imp_spec, imp_from (importSpecModule imp_spec))
784                         where
785                           imp_spec = head is
786                   other -> (srcLocSpan (nameSrcLoc name), unused_msg)
787
788     unused_msg   = text "Defined but not used"
789     imp_from mod = text "Imported from" <+> quotes (ppr mod) <+> text "but not used"
790 \end{code}
791
792 \begin{code}
793 addNameClashErrRn rdr_name names
794   = addErr (vcat [ptext SLIT("Ambiguous occurrence") <+> quotes (ppr rdr_name),
795                   ptext SLIT("It could refer to") <+> vcat (msg1 : msgs)])
796   where
797     (np1:nps) = names
798     msg1 = ptext  SLIT("either") <+> mk_ref np1
799     msgs = [ptext SLIT("    or") <+> mk_ref np | np <- nps]
800     mk_ref gre = quotes (ppr (gre_name gre)) <> comma <+> pprNameProvenance gre
801
802 shadowedNameWarn doc shadow
803   = hsep [ptext SLIT("This binding for"), 
804                quotes (ppr shadow),
805                ptext SLIT("shadows an existing binding")]
806     $$ doc
807
808 unknownNameErr rdr_name
809   = sep [ptext SLIT("Not in scope:"), 
810          nest 2 $ pprNonVarNameSpace (occNameSpace (rdrNameOcc rdr_name))
811                   <+> quotes (ppr rdr_name)]
812
813 unknownInstBndrErr cls op
814   = quotes (ppr op) <+> ptext SLIT("is not a (visible) method of class") <+> quotes (ppr cls)
815
816 badOrigBinding name
817   = ptext SLIT("Illegal binding of built-in syntax:") <+> ppr (rdrNameOcc name)
818         -- The rdrNameOcc is because we don't want to print Prelude.(,)
819
820 dupNamesErr :: SDoc -> [Located RdrName] -> RnM ()
821 dupNamesErr descriptor located_names
822   = addErrAt big_loc $
823     vcat [ptext SLIT("Conflicting definitions for") <+> quotes (ppr name1),
824           locations, descriptor]
825   where
826     L _ name1 = head located_names
827     locs      = map getLoc located_names
828     big_loc   = foldr1 combineSrcSpans locs
829     one_line  = isOneLineSpan big_loc
830     locations | one_line  = empty 
831               | otherwise = ptext SLIT("Bound at:") <+> 
832                             vcat (map ppr (sortLe (<=) locs))
833
834 badQualBndrErr rdr_name
835   = ptext SLIT("Qualified name in binding position:") <+> ppr rdr_name
836
837 infixTyConWarn op
838   = vcat [ftext FSLIT("Accepting non-standard infix type constructor") <+> quotes (ppr op),
839           ftext FSLIT("Use -fglasgow-exts to avoid this warning")]
840 \end{code}