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