Add several new record features
[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
236                                 (ptext SLIT("method of class")) rdr
237   where
238     doc = ptext SLIT("method of class") <+> quotes (ppr cls)
239     is_op gre@(GRE {gre_par = ParentIs n}) = n == cls
240     is_op other                            = False
241
242 -----------------------------------------------
243 lookupRecordBndr :: Maybe (Located Name) -> Located RdrName -> RnM (Located Name)
244 -- Used for record construction and pattern matching
245 -- When the -fdisambiguate-record-fields flag is on, take account of the
246 -- constructor name to disambiguate which field to use; it's just the
247 -- same as for instance decls
248 lookupRecordBndr Nothing rdr_name
249   = lookupLocatedGlobalOccRn rdr_name
250 lookupRecordBndr (Just (L _ data_con)) rdr_name
251   = do  { flag_on <- doptM Opt_DisambiguateRecordFields
252         ; if not flag_on 
253           then lookupLocatedGlobalOccRn rdr_name
254           else do {
255           fields <- lookupConstructorFields data_con
256         ; let is_field gre = gre_name gre `elem` fields
257         ; lookup_located_sub_bndr is_field doc rdr_name
258         }}
259    where
260      doc = ptext SLIT("field of constructor") <+> quotes (ppr data_con)
261
262
263 lookupConstructorFields :: Name -> RnM [Name]
264 -- Look up the fields of a given constructor
265 --   *  For constructors from this module, use the record field env,
266 --      which is itself gathered from the (as yet un-typechecked)
267 --      data type decls
268 -- 
269 --    * For constructors from imported modules, use the *type* environment
270 --      since imported modles are already compiled, the info is conveniently
271 --      right there
272
273 lookupConstructorFields con_name
274   = do  { this_mod <- getModule
275         ; if nameIsLocalOrFrom this_mod con_name then
276           do { field_env <- getRecFieldEnv
277              ; return (lookupNameEnv field_env con_name `orElse` []) }
278           else
279           do { con <- tcLookupDataCon con_name
280              ; return (dataConFieldLabels con) } }
281
282 -----------------------------------------------
283 lookup_located_sub_bndr :: (GlobalRdrElt -> Bool)
284                         -> SDoc -> Located RdrName
285                         -> RnM (Located Name)
286 lookup_located_sub_bndr is_good doc rdr_name
287   = wrapLocM (lookup_sub_bndr is_good doc) rdr_name
288
289 lookup_sub_bndr is_good doc rdr_name
290   | isUnqual rdr_name   -- Find all the things the rdr-name maps to
291   = do  {               -- and pick the one with the right parent name
292         ; env <- getGlobalRdrEnv
293         ; case filter is_good (lookupGlobalRdrEnv env (rdrNameOcc rdr_name)) of
294                 -- NB: lookupGlobalRdrEnv, not lookupGRE_RdrName!
295                 --     The latter does pickGREs, but we want to allow 'x'
296                 --     even if only 'M.x' is in scope
297             [gre] -> return (gre_name gre)
298             []    -> do { addErr (unknownSubordinateErr doc rdr_name)
299                         ; traceRn (text "RnEnv.lookup_sub_bndr" <+> ppr rdr_name)
300                         ; return (mkUnboundName rdr_name) }
301             gres  -> do { addNameClashErrRn rdr_name gres
302                         ; return (gre_name (head gres)) }
303         }
304
305   | otherwise   -- Occurs in derived instances, where we just
306                 -- refer directly to the right method
307   = ASSERT2( not (isQual rdr_name), ppr rdr_name )
308           -- NB: qualified names are rejected by the parser
309     lookupImportedName rdr_name
310
311 newIPNameRn :: IPName RdrName -> TcRnIf m n (IPName Name)
312 newIPNameRn ip_rdr = newIPName (mapIPName rdrNameOcc ip_rdr)
313
314 -- Looking up family names in type instances is a subtle affair.  The family
315 -- may be imported, in which case we need to lookup the occurence of a global
316 -- name.  Alternatively, the family may be in the same binding group (and in
317 -- fact in a declaration processed later), and we need to create a new top
318 -- source binder.
319 --
320 -- So, also this is strictly speaking an occurence, we cannot raise an error
321 -- message yet for instances without a family declaration.  This will happen
322 -- during renaming the type instance declaration in RnSource.rnTyClDecl.
323 --
324 lookupFamInstDeclBndr :: Module -> Located RdrName -> RnM Name
325 lookupFamInstDeclBndr mod lrdr_name@(L _ rdr_name)
326   = do { mb_gre <- lookupGreRn_maybe rdr_name
327        ; case mb_gre of
328            Just gre -> returnM (gre_name gre) ;
329            Nothing  -> newTopSrcBinder mod lrdr_name }
330
331 --------------------------------------------------
332 --              Occurrences
333 --------------------------------------------------
334
335 getLookupOccRn :: RnM (Name -> Maybe Name)
336 getLookupOccRn
337   = getLocalRdrEnv                      `thenM` \ local_env ->
338     return (lookupLocalRdrEnv local_env . mkRdrUnqual . nameOccName)
339
340 lookupLocatedOccRn :: Located RdrName -> RnM (Located Name)
341 lookupLocatedOccRn = wrapLocM lookupOccRn
342
343 -- lookupOccRn looks up an occurrence of a RdrName
344 lookupOccRn :: RdrName -> RnM Name
345 lookupOccRn rdr_name
346   = getLocalRdrEnv                      `thenM` \ local_env ->
347     case lookupLocalRdrEnv local_env rdr_name of
348           Just name -> returnM name
349           Nothing   -> lookupGlobalOccRn rdr_name
350
351 lookupLocatedGlobalOccRn :: Located RdrName -> RnM (Located Name)
352 lookupLocatedGlobalOccRn = wrapLocM lookupGlobalOccRn
353
354 lookupGlobalOccRn :: RdrName -> RnM Name
355 -- lookupGlobalOccRn is like lookupOccRn, except that it looks in the global 
356 -- environment.  It's used only for
357 --      record field names
358 --      class op names in class and instance decls
359
360 lookupGlobalOccRn rdr_name
361   | not (isSrcRdrName rdr_name)
362   = lookupImportedName rdr_name 
363
364   | otherwise
365   =     -- First look up the name in the normal environment.
366    lookupGreRn_maybe rdr_name           `thenM` \ mb_gre ->
367    case mb_gre of {
368         Just gre -> returnM (gre_name gre) ;
369         Nothing   -> 
370
371         -- We allow qualified names on the command line to refer to 
372         --  *any* name exported by any module in scope, just as if 
373         -- there was an "import qualified M" declaration for every 
374         -- module.
375    getModule            `thenM` \ mod ->
376    if isQual rdr_name && mod == iNTERACTIVE then        
377                                         -- This test is not expensive,
378         lookupQualifiedName rdr_name    -- and only happens for failed lookups
379    else do
380         traceRn $ text "lookupGlobalOccRn"
381         unboundName rdr_name }
382
383 lookupImportedName :: RdrName -> TcRnIf m n Name
384 -- Lookup the occurrence of an imported name
385 -- The RdrName is *always* qualified or Exact
386 -- Treat it as an original name, and conjure up the Name
387 -- Usually it's Exact or Orig, but it can be Qual if it
388 --      comes from an hi-boot file.  (This minor infelicity is 
389 --      just to reduce duplication in the parser.)
390 lookupImportedName rdr_name
391   | Just n <- isExact_maybe rdr_name 
392         -- This happens in derived code
393   = returnM n
394
395         -- Always Orig, even when reading a .hi-boot file
396   | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
397   = lookupOrig rdr_mod rdr_occ
398
399   | otherwise
400   = pprPanic "RnEnv.lookupImportedName" (ppr rdr_name)
401
402 unboundName :: RdrName -> RnM Name
403 unboundName rdr_name 
404   = do  { addErr (unknownNameErr rdr_name)
405         ; env <- getGlobalRdrEnv;
406         ; traceRn (vcat [unknownNameErr rdr_name, 
407                          ptext SLIT("Global envt is:"),
408                          nest 3 (pprGlobalRdrEnv env)])
409         ; returnM (mkUnboundName rdr_name) }
410
411 --------------------------------------------------
412 --      Lookup in the Global RdrEnv of the module
413 --------------------------------------------------
414
415 lookupSrcOcc_maybe :: RdrName -> RnM (Maybe Name)
416 -- No filter function; does not report an error on failure
417 lookupSrcOcc_maybe rdr_name
418   = do  { mb_gre <- lookupGreRn_maybe rdr_name
419         ; case mb_gre of
420                 Nothing  -> returnM Nothing
421                 Just gre -> returnM (Just (gre_name gre)) }
422         
423 -------------------------
424 lookupGreRn_maybe :: RdrName -> RnM (Maybe GlobalRdrElt)
425 -- Just look up the RdrName in the GlobalRdrEnv
426 lookupGreRn_maybe rdr_name 
427   = lookupGreRn_help rdr_name (lookupGRE_RdrName rdr_name)
428
429 lookupGreRn :: RdrName -> RnM GlobalRdrElt
430 -- If not found, add error message, and return a fake GRE
431 lookupGreRn rdr_name 
432   = do  { mb_gre <- lookupGreRn_maybe rdr_name
433         ; case mb_gre of {
434             Just gre -> return gre ;
435             Nothing  -> do
436         { traceRn $ text "lookupGreRn"
437         ; name <- unboundName rdr_name
438         ; return (GRE { gre_name = name, gre_par = NoParent,
439                         gre_prov = LocalDef }) }}}
440
441 lookupGreLocalRn :: RdrName -> RnM (Maybe GlobalRdrElt)
442 -- Similar, but restricted to locally-defined things
443 lookupGreLocalRn rdr_name 
444   = lookupGreRn_help rdr_name lookup_fn
445   where
446     lookup_fn env = filter isLocalGRE (lookupGRE_RdrName rdr_name env)
447
448 lookupGreRn_help :: RdrName                     -- Only used in error message
449                  -> (GlobalRdrEnv -> [GlobalRdrElt])    -- Lookup function
450                  -> RnM (Maybe GlobalRdrElt)
451 -- Checks for exactly one match; reports deprecations
452 -- Returns Nothing, without error, if too few
453 lookupGreRn_help rdr_name lookup 
454   = do  { env <- getGlobalRdrEnv
455         ; case lookup env of
456             []    -> returnM Nothing
457             [gre] -> returnM (Just gre)
458             gres  -> do { addNameClashErrRn rdr_name gres
459                         ; returnM (Just (head gres)) } }
460
461 ------------------------------
462 --      GHCi support
463 ------------------------------
464
465 -- A qualified name on the command line can refer to any module at all: we
466 -- try to load the interface if we don't already have it.
467 lookupQualifiedName :: RdrName -> RnM Name
468 lookupQualifiedName rdr_name
469   | Just (mod,occ) <- isQual_maybe rdr_name
470    -- Note: we want to behave as we would for a source file import here,
471    -- and respect hiddenness of modules/packages, hence loadSrcInterface.
472    = loadSrcInterface doc mod False     `thenM` \ iface ->
473
474    case  [ (mod,occ) | 
475            (mod,avails) <- mi_exports iface,
476            avail        <- avails,
477            name         <- availNames avail,
478            name == occ ] of
479       ((mod,occ):ns) -> ASSERT (null ns) 
480                         lookupOrig mod occ
481       _ -> unboundName rdr_name
482
483   | otherwise
484   = pprPanic "RnEnv.lookupQualifiedName" (ppr rdr_name)
485   where
486     doc = ptext SLIT("Need to find") <+> ppr rdr_name
487 \end{code}
488
489 %*********************************************************
490 %*                                                      *
491                 Fixities
492 %*                                                      *
493 %*********************************************************
494
495 \begin{code}
496 lookupLocalDataTcNames :: RdrName -> RnM [Name]
497 -- GHC extension: look up both the tycon and data con 
498 -- for con-like things
499 -- Complain if neither is in scope
500 lookupLocalDataTcNames rdr_name
501   | Just n <- isExact_maybe rdr_name    
502         -- Special case for (:), which doesn't get into the GlobalRdrEnv
503   = return [n]  -- For this we don't need to try the tycon too
504   | otherwise
505   = do  { mb_gres <- mapM lookupGreLocalRn (dataTcOccs rdr_name)
506         ; case [gre_name gre | Just gre <- mb_gres] of
507             [] -> do { addErr (unknownNameErr rdr_name)
508                      ; return [] }
509             names -> return names
510     }
511
512 --------------------------------
513 bindLocalFixities :: [FixitySig RdrName] -> RnM a -> RnM a
514 -- Used for nested fixity decls
515 -- No need to worry about type constructors here,
516 -- Should check for duplicates but we don't
517 bindLocalFixities fixes thing_inside
518   | null fixes = thing_inside
519   | otherwise  = mappM rn_sig fixes     `thenM` \ new_bit ->
520                  extendFixityEnv new_bit thing_inside
521   where
522     rn_sig (FixitySig lv@(L loc v) fix)
523         = addLocM lookupBndrRn lv       `thenM` \ new_v ->
524           returnM (new_v, (FixItem (rdrNameOcc v) fix loc))
525 \end{code}
526
527 --------------------------------
528 lookupFixity is a bit strange.  
529
530 * Nested local fixity decls are put in the local fixity env, which we
531   find with getFixtyEnv
532
533 * Imported fixities are found in the HIT or PIT
534
535 * Top-level fixity decls in this module may be for Names that are
536     either  Global         (constructors, class operations)
537     or      Local/Exported (everything else)
538   (See notes with RnNames.getLocalDeclBinders for why we have this split.)
539   We put them all in the local fixity environment
540
541 \begin{code}
542 lookupFixityRn :: Name -> RnM Fixity
543 lookupFixityRn name
544   = getModule                           `thenM` \ this_mod ->
545     if nameIsLocalOrFrom this_mod name
546     then        -- It's defined in this module
547         getFixityEnv            `thenM` \ local_fix_env ->
548         traceRn (text "lookupFixityRn" <+> (ppr name $$ ppr local_fix_env)) `thenM_`
549         returnM (lookupFixity local_fix_env name)
550
551     else        -- It's imported
552       -- For imported names, we have to get their fixities by doing a
553       -- loadInterfaceForName, and consulting the Ifaces that comes back
554       -- from that, because the interface file for the Name might not
555       -- have been loaded yet.  Why not?  Suppose you import module A,
556       -- which exports a function 'f', thus;
557       --        module CurrentModule where
558       --          import A( f )
559       --        module A( f ) where
560       --          import B( f )
561       -- Then B isn't loaded right away (after all, it's possible that
562       -- nothing from B will be used).  When we come across a use of
563       -- 'f', we need to know its fixity, and it's then, and only
564       -- then, that we load B.hi.  That is what's happening here.
565       --
566       -- loadInterfaceForName will find B.hi even if B is a hidden module,
567       -- and that's what we want.
568         loadInterfaceForName doc name   `thenM` \ iface ->
569         returnM (mi_fix_fn iface (nameOccName name))
570   where
571     doc = ptext SLIT("Checking fixity for") <+> ppr name
572
573 ---------------
574 lookupTyFixityRn :: Located Name -> RnM Fixity
575 lookupTyFixityRn (L loc n)
576   = do  { glaExts <- doptM Opt_GlasgowExts
577         ; when (not glaExts) (addWarnAt loc (infixTyConWarn n))
578         ; lookupFixityRn n }
579
580 ---------------
581 dataTcOccs :: RdrName -> [RdrName]
582 -- If the input is a data constructor, return both it and a type
583 -- constructor.  This is useful when we aren't sure which we are
584 -- looking at.
585 dataTcOccs rdr_name
586   | Just n <- isExact_maybe rdr_name            -- Ghastly special case
587   , n `hasKey` consDataConKey = [rdr_name]      -- see note below
588   | isDataOcc occ             = [rdr_name_tc, rdr_name]
589   | otherwise                 = [rdr_name]
590   where    
591     occ         = rdrNameOcc rdr_name
592     rdr_name_tc = setRdrNameSpace rdr_name tcName
593
594 -- If the user typed "[]" or "(,,)", we'll generate an Exact RdrName,
595 -- and setRdrNameSpace generates an Orig, which is fine
596 -- But it's not fine for (:), because there *is* no corresponding type
597 -- constructor.  If we generate an Orig tycon for GHC.Base.(:), it'll
598 -- appear to be in scope (because Orig's simply allocate a new name-cache
599 -- entry) and then we get an error when we use dataTcOccs in 
600 -- TcRnDriver.tcRnGetInfo.  Large sigh.
601 \end{code}
602
603 %************************************************************************
604 %*                                                                      *
605                         Rebindable names
606         Dealing with rebindable syntax is driven by the 
607         Opt_NoImplicitPrelude dynamic flag.
608
609         In "deriving" code we don't want to use rebindable syntax
610         so we switch off the flag locally
611
612 %*                                                                      *
613 %************************************************************************
614
615 Haskell 98 says that when you say "3" you get the "fromInteger" from the
616 Standard Prelude, regardless of what is in scope.   However, to experiment
617 with having a language that is less coupled to the standard prelude, we're
618 trying a non-standard extension that instead gives you whatever "Prelude.fromInteger"
619 happens to be in scope.  Then you can
620         import Prelude ()
621         import MyPrelude as Prelude
622 to get the desired effect.
623
624 At the moment this just happens for
625   * fromInteger, fromRational on literals (in expressions and patterns)
626   * negate (in expressions)
627   * minus  (arising from n+k patterns)
628   * "do" notation
629
630 We store the relevant Name in the HsSyn tree, in 
631   * HsIntegral/HsFractional/HsIsString
632   * NegApp
633   * NPlusKPat
634   * HsDo
635 respectively.  Initially, we just store the "standard" name (PrelNames.fromIntegralName,
636 fromRationalName etc), but the renamer changes this to the appropriate user
637 name if Opt_NoImplicitPrelude is on.  That is what lookupSyntaxName does.
638
639 We treat the orignal (standard) names as free-vars too, because the type checker
640 checks the type of the user thing against the type of the standard thing.
641
642 \begin{code}
643 lookupSyntaxName :: Name                                -- The standard name
644                  -> RnM (SyntaxExpr Name, FreeVars)     -- Possibly a non-standard name
645 lookupSyntaxName std_name
646   = doptM Opt_ImplicitPrelude           `thenM` \ implicit_prelude -> 
647     if implicit_prelude then normal_case
648     else
649         -- Get the similarly named thing from the local environment
650     lookupOccRn (mkRdrUnqual (nameOccName std_name)) `thenM` \ usr_name ->
651     returnM (HsVar usr_name, unitFV usr_name)
652   where
653     normal_case = returnM (HsVar std_name, emptyFVs)
654
655 lookupSyntaxTable :: [Name]                             -- Standard names
656                   -> RnM (SyntaxTable Name, FreeVars)   -- See comments with HsExpr.ReboundNames
657 lookupSyntaxTable std_names
658   = doptM Opt_ImplicitPrelude           `thenM` \ implicit_prelude -> 
659     if implicit_prelude then normal_case 
660     else
661         -- Get the similarly named thing from the local environment
662     mappM (lookupOccRn . mkRdrUnqual . nameOccName) std_names   `thenM` \ usr_names ->
663
664     returnM (std_names `zip` map HsVar usr_names, mkFVs usr_names)
665   where
666     normal_case = returnM (std_names `zip` map HsVar std_names, emptyFVs)
667 \end{code}
668
669
670 %*********************************************************
671 %*                                                      *
672 \subsection{Binding}
673 %*                                                      *
674 %*********************************************************
675
676 \begin{code}
677 newLocalsRn :: [Located RdrName] -> RnM [Name]
678 newLocalsRn rdr_names_w_loc
679   = newUniqueSupply             `thenM` \ us ->
680     returnM (zipWith mk rdr_names_w_loc (uniqsFromSupply us))
681   where
682     mk (L loc rdr_name) uniq
683         | Just name <- isExact_maybe rdr_name = name
684                 -- This happens in code generated by Template Haskell 
685         | otherwise = ASSERT2( isUnqual rdr_name, ppr rdr_name )
686                         -- We only bind unqualified names here
687                         -- lookupRdrEnv doesn't even attempt to look up a qualified RdrName
688                       mkInternalName uniq (rdrNameOcc rdr_name) loc
689
690 bindLocatedLocalsRn :: SDoc     -- Documentation string for error message
691                     -> [Located RdrName]
692                     -> ([Name] -> RnM a)
693                     -> RnM a
694 bindLocatedLocalsRn doc_str rdr_names_w_loc enclosed_scope
695   =     -- Check for duplicate names
696     checkDupNames doc_str rdr_names_w_loc       `thenM_`
697
698         -- Warn about shadowing, but only in source modules
699     ifOptM Opt_WarnNameShadowing 
700       (checkShadowing doc_str rdr_names_w_loc)  `thenM_`
701
702         -- Make fresh Names and extend the environment
703     newLocalsRn rdr_names_w_loc         `thenM` \ names ->
704     getLocalRdrEnv                      `thenM` \ local_env ->
705     setLocalRdrEnv (extendLocalRdrEnv local_env names)
706                    (enclosed_scope names)
707
708
709 bindLocalNames :: [Name] -> RnM a -> RnM a
710 bindLocalNames names enclosed_scope
711   = getLocalRdrEnv              `thenM` \ name_env ->
712     setLocalRdrEnv (extendLocalRdrEnv name_env names)
713                     enclosed_scope
714
715 bindLocalNamesFV :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
716 bindLocalNamesFV names enclosed_scope
717   = do  { (result, fvs) <- bindLocalNames names enclosed_scope
718         ; returnM (result, delListFromNameSet fvs names) }
719
720
721 -------------------------------------
722         -- binLocalsFVRn is the same as bindLocalsRn
723         -- except that it deals with free vars
724 bindLocatedLocalsFV :: SDoc -> [Located RdrName] -> ([Name] -> RnM (a,FreeVars))
725   -> RnM (a, FreeVars)
726 bindLocatedLocalsFV doc rdr_names enclosed_scope
727   = bindLocatedLocalsRn doc rdr_names   $ \ names ->
728     enclosed_scope names                `thenM` \ (thing, fvs) ->
729     returnM (thing, delListFromNameSet fvs names)
730
731 -------------------------------------
732 bindTyVarsRn :: SDoc -> [LHsTyVarBndr RdrName]
733               -> ([LHsTyVarBndr Name] -> RnM a)
734               -> RnM a
735 -- Haskell-98 binding of type variables; e.g. within a data type decl
736 bindTyVarsRn doc_str tyvar_names enclosed_scope
737   = let
738         located_tyvars = hsLTyVarLocNames tyvar_names
739     in
740     bindLocatedLocalsRn doc_str located_tyvars  $ \ names ->
741     enclosed_scope (zipWith replace tyvar_names names)
742     where 
743         replace (L loc n1) n2 = L loc (replaceTyVarName n1 n2)
744
745 bindPatSigTyVars :: [LHsType RdrName] -> ([Name] -> RnM a) -> RnM a
746   -- Find the type variables in the pattern type 
747   -- signatures that must be brought into scope
748 bindPatSigTyVars tys thing_inside
749   = do  { scoped_tyvars <- doptM Opt_ScopedTypeVariables
750         ; if not scoped_tyvars then 
751                 thing_inside []
752           else 
753     do  { name_env <- getLocalRdrEnv
754         ; let locd_tvs  = [ tv | ty <- tys
755                                , tv <- extractHsTyRdrTyVars ty
756                                , not (unLoc tv `elemLocalRdrEnv` name_env) ]
757               nubbed_tvs = nubBy eqLocated locd_tvs
758                 -- The 'nub' is important.  For example:
759                 --      f (x :: t) (y :: t) = ....
760                 -- We don't want to complain about binding t twice!
761
762         ; bindLocatedLocalsRn doc_sig nubbed_tvs thing_inside }}
763   where
764     doc_sig = text "In a pattern type-signature"
765
766 bindPatSigTyVarsFV :: [LHsType RdrName]
767                    -> RnM (a, FreeVars)
768                    -> RnM (a, FreeVars)
769 bindPatSigTyVarsFV tys thing_inside
770   = bindPatSigTyVars tys        $ \ tvs ->
771     thing_inside                `thenM` \ (result,fvs) ->
772     returnM (result, fvs `delListFromNameSet` tvs)
773
774 bindSigTyVarsFV :: [Name]
775                 -> RnM (a, FreeVars)
776                 -> RnM (a, FreeVars)
777 bindSigTyVarsFV tvs thing_inside
778   = do  { scoped_tyvars <- doptM Opt_ScopedTypeVariables
779         ; if not scoped_tyvars then 
780                 thing_inside 
781           else
782                 bindLocalNamesFV tvs thing_inside }
783
784 extendTyVarEnvFVRn :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
785         -- This function is used only in rnSourceDecl on InstDecl
786 extendTyVarEnvFVRn tyvars thing_inside = bindLocalNamesFV tyvars thing_inside
787
788 -------------------------------------
789 checkDupNames :: SDoc
790               -> [Located RdrName]
791               -> RnM ()
792 checkDupNames doc_str rdr_names_w_loc
793   =     -- Check for duplicated names in a binding group
794     mappM_ (dupNamesErr doc_str) dups
795   where
796     (_, dups) = removeDups (\n1 n2 -> unLoc n1 `compare` unLoc n2) rdr_names_w_loc
797
798 -------------------------------------
799 checkShadowing doc_str loc_rdr_names
800   = getLocalRdrEnv              `thenM` \ local_env ->
801     getGlobalRdrEnv             `thenM` \ global_env ->
802     let
803       check_shadow (L loc rdr_name)
804         |  rdr_name `elemLocalRdrEnv` local_env 
805         || not (null (lookupGRE_RdrName rdr_name global_env ))
806         = addWarnAt loc (shadowedNameWarn doc_str rdr_name)
807         | otherwise = returnM ()
808     in
809     mappM_ check_shadow loc_rdr_names
810 \end{code}
811
812
813 %************************************************************************
814 %*                                                                      *
815 \subsection{Free variable manipulation}
816 %*                                                                      *
817 %************************************************************************
818
819 \begin{code}
820 -- A useful utility
821 mapFvRn f xs = mappM f xs       `thenM` \ stuff ->
822                let
823                   (ys, fvs_s) = unzip stuff
824                in
825                returnM (ys, plusFVs fvs_s)
826 \end{code}
827
828
829 %************************************************************************
830 %*                                                                      *
831 \subsection{Envt utility functions}
832 %*                                                                      *
833 %************************************************************************
834
835 \begin{code}
836 warnUnusedModules :: [(ModuleName,SrcSpan)] -> RnM ()
837 warnUnusedModules mods
838   = ifOptM Opt_WarnUnusedImports (mappM_ bleat mods)
839   where
840     bleat (mod,loc) = addWarnAt loc (mk_warn mod)
841     mk_warn m = vcat [ptext SLIT("Module") <+> quotes (ppr m)
842                         <+> text "is imported, but nothing from it is used,",
843                       nest 2 (ptext SLIT("except perhaps instances visible in") 
844                         <+> quotes (ppr m)),
845                       ptext SLIT("To suppress this warning, use:") 
846                         <+> ptext SLIT("import") <+> ppr m <> parens empty ]
847
848
849 warnUnusedImports, warnUnusedTopBinds :: [GlobalRdrElt] -> RnM ()
850 warnUnusedImports gres  = ifOptM Opt_WarnUnusedImports (warnUnusedGREs gres)
851 warnUnusedTopBinds gres = ifOptM Opt_WarnUnusedBinds   (warnUnusedGREs gres)
852
853 warnUnusedLocalBinds, warnUnusedMatches :: [Name] -> RnM ()
854 warnUnusedLocalBinds names = ifOptM Opt_WarnUnusedBinds   (warnUnusedLocals names)
855 warnUnusedMatches    names = ifOptM Opt_WarnUnusedMatches (warnUnusedLocals names)
856
857 -------------------------
858 --      Helpers
859 warnUnusedGREs gres 
860  = warnUnusedBinds [(n,p) | GRE {gre_name = n, gre_prov = p} <- gres]
861
862 warnUnusedLocals names
863  = warnUnusedBinds [(n,LocalDef) | n<-names]
864
865 warnUnusedBinds :: [(Name,Provenance)] -> RnM ()
866 warnUnusedBinds names  = mappM_ warnUnusedName (filter reportable names)
867  where reportable (name,_) 
868         | isWiredInName name = False    -- Don't report unused wired-in names
869                                         -- Otherwise we get a zillion warnings
870                                         -- from Data.Tuple
871         | otherwise = reportIfUnused (nameOccName name)
872
873 -------------------------
874
875 warnUnusedName :: (Name, Provenance) -> RnM ()
876 warnUnusedName (name, LocalDef)
877   = addUnusedWarning name (srcLocSpan (nameSrcLoc name)) 
878                      (ptext SLIT("Defined but not used"))
879
880 warnUnusedName (name, Imported is)
881   = mapM_ warn is
882   where
883     warn spec = addUnusedWarning name span msg
884         where
885            span = importSpecLoc spec
886            pp_mod = quotes (ppr (importSpecModule spec))
887            msg = ptext SLIT("Imported from") <+> pp_mod <+> ptext SLIT("but not used")
888
889 addUnusedWarning name span msg
890   = addWarnAt span $
891     sep [msg <> colon, 
892          nest 2 $ pprNonVarNameSpace (occNameSpace (nameOccName name))
893                         <+> quotes (ppr name)]
894 \end{code}
895
896 \begin{code}
897 addNameClashErrRn rdr_name names
898   = addErr (vcat [ptext SLIT("Ambiguous occurrence") <+> quotes (ppr rdr_name),
899                   ptext SLIT("It could refer to") <+> vcat (msg1 : msgs)])
900   where
901     (np1:nps) = names
902     msg1 = ptext  SLIT("either") <+> mk_ref np1
903     msgs = [ptext SLIT("    or") <+> mk_ref np | np <- nps]
904     mk_ref gre = quotes (ppr (gre_name gre)) <> comma <+> pprNameProvenance gre
905
906 shadowedNameWarn doc shadow
907   = hsep [ptext SLIT("This binding for"), 
908                quotes (ppr shadow),
909                ptext SLIT("shadows an existing binding")]
910     $$ doc
911
912 unknownNameErr rdr_name
913   = sep [ptext SLIT("Not in scope:"), 
914          nest 2 $ pprNonVarNameSpace (occNameSpace (rdrNameOcc rdr_name))
915                   <+> quotes (ppr rdr_name)]
916
917 unknownSubordinateErr doc op    -- Doc is "method of class" or 
918                                 -- "field of constructor"
919   = quotes (ppr op) <+> ptext SLIT("is not a (visible)") <+> doc
920
921 badOrigBinding name
922   = ptext SLIT("Illegal binding of built-in syntax:") <+> ppr (rdrNameOcc name)
923         -- The rdrNameOcc is because we don't want to print Prelude.(,)
924
925 dupNamesErr :: SDoc -> [Located RdrName] -> RnM ()
926 dupNamesErr descriptor located_names
927   = addErrAt big_loc $
928     vcat [ptext SLIT("Conflicting definitions for") <+> quotes (ppr name1),
929           locations, descriptor]
930   where
931     L _ name1 = head located_names
932     locs      = map getLoc located_names
933     big_loc   = foldr1 combineSrcSpans locs
934     one_line  = isOneLineSpan big_loc
935     locations | one_line  = empty 
936               | otherwise = ptext SLIT("Bound at:") <+> 
937                             vcat (map ppr (sortLe (<=) locs))
938
939 badQualBndrErr rdr_name
940   = ptext SLIT("Qualified name in binding position:") <+> ppr rdr_name
941
942 infixTyConWarn op
943   = vcat [ftext FSLIT("Accepting non-standard infix type constructor") <+> quotes (ppr op),
944           ftext FSLIT("Use -fglasgow-exts to avoid this warning")]
945 \end{code}