Fix an error message
[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)
575   = do  { glaExts <- doptM Opt_GlasgowExts
576         ; when (not glaExts) (addWarnAt loc (infixTyConWarn n))
577         ; lookupFixityRn n }
578
579 ---------------
580 dataTcOccs :: RdrName -> [RdrName]
581 -- If the input is a data constructor, return both it and a type
582 -- constructor.  This is useful when we aren't sure which we are
583 -- looking at.
584 dataTcOccs rdr_name
585   | Just n <- isExact_maybe rdr_name            -- Ghastly special case
586   , n `hasKey` consDataConKey = [rdr_name]      -- see note below
587   | isDataOcc occ             = [rdr_name_tc, rdr_name]
588   | otherwise                 = [rdr_name]
589   where    
590     occ         = rdrNameOcc rdr_name
591     rdr_name_tc = setRdrNameSpace rdr_name tcName
592
593 -- If the user typed "[]" or "(,,)", we'll generate an Exact RdrName,
594 -- and setRdrNameSpace generates an Orig, which is fine
595 -- But it's not fine for (:), because there *is* no corresponding type
596 -- constructor.  If we generate an Orig tycon for GHC.Base.(:), it'll
597 -- appear to be in scope (because Orig's simply allocate a new name-cache
598 -- entry) and then we get an error when we use dataTcOccs in 
599 -- TcRnDriver.tcRnGetInfo.  Large sigh.
600 \end{code}
601
602 %************************************************************************
603 %*                                                                      *
604                         Rebindable names
605         Dealing with rebindable syntax is driven by the 
606         Opt_NoImplicitPrelude dynamic flag.
607
608         In "deriving" code we don't want to use rebindable syntax
609         so we switch off the flag locally
610
611 %*                                                                      *
612 %************************************************************************
613
614 Haskell 98 says that when you say "3" you get the "fromInteger" from the
615 Standard Prelude, regardless of what is in scope.   However, to experiment
616 with having a language that is less coupled to the standard prelude, we're
617 trying a non-standard extension that instead gives you whatever "Prelude.fromInteger"
618 happens to be in scope.  Then you can
619         import Prelude ()
620         import MyPrelude as Prelude
621 to get the desired effect.
622
623 At the moment this just happens for
624   * fromInteger, fromRational on literals (in expressions and patterns)
625   * negate (in expressions)
626   * minus  (arising from n+k patterns)
627   * "do" notation
628
629 We store the relevant Name in the HsSyn tree, in 
630   * HsIntegral/HsFractional/HsIsString
631   * NegApp
632   * NPlusKPat
633   * HsDo
634 respectively.  Initially, we just store the "standard" name (PrelNames.fromIntegralName,
635 fromRationalName etc), but the renamer changes this to the appropriate user
636 name if Opt_NoImplicitPrelude is on.  That is what lookupSyntaxName does.
637
638 We treat the orignal (standard) names as free-vars too, because the type checker
639 checks the type of the user thing against the type of the standard thing.
640
641 \begin{code}
642 lookupSyntaxName :: Name                                -- The standard name
643                  -> RnM (SyntaxExpr Name, FreeVars)     -- Possibly a non-standard name
644 lookupSyntaxName std_name
645   = doptM Opt_ImplicitPrelude           `thenM` \ implicit_prelude -> 
646     if implicit_prelude then normal_case
647     else
648         -- Get the similarly named thing from the local environment
649     lookupOccRn (mkRdrUnqual (nameOccName std_name)) `thenM` \ usr_name ->
650     returnM (HsVar usr_name, unitFV usr_name)
651   where
652     normal_case = returnM (HsVar std_name, emptyFVs)
653
654 lookupSyntaxTable :: [Name]                             -- Standard names
655                   -> RnM (SyntaxTable Name, FreeVars)   -- See comments with HsExpr.ReboundNames
656 lookupSyntaxTable std_names
657   = doptM Opt_ImplicitPrelude           `thenM` \ implicit_prelude -> 
658     if implicit_prelude then normal_case 
659     else
660         -- Get the similarly named thing from the local environment
661     mappM (lookupOccRn . mkRdrUnqual . nameOccName) std_names   `thenM` \ usr_names ->
662
663     returnM (std_names `zip` map HsVar usr_names, mkFVs usr_names)
664   where
665     normal_case = returnM (std_names `zip` map HsVar std_names, emptyFVs)
666 \end{code}
667
668
669 %*********************************************************
670 %*                                                      *
671 \subsection{Binding}
672 %*                                                      *
673 %*********************************************************
674
675 \begin{code}
676 newLocalsRn :: [Located RdrName] -> RnM [Name]
677 newLocalsRn rdr_names_w_loc
678   = newUniqueSupply             `thenM` \ us ->
679     returnM (zipWith mk rdr_names_w_loc (uniqsFromSupply us))
680   where
681     mk (L loc rdr_name) uniq
682         | Just name <- isExact_maybe rdr_name = name
683                 -- This happens in code generated by Template Haskell 
684         | otherwise = ASSERT2( isUnqual rdr_name, ppr rdr_name )
685                         -- We only bind unqualified names here
686                         -- lookupRdrEnv doesn't even attempt to look up a qualified RdrName
687                       mkInternalName uniq (rdrNameOcc rdr_name) loc
688
689 bindLocatedLocalsRn :: SDoc     -- Documentation string for error message
690                     -> [Located RdrName]
691                     -> ([Name] -> RnM a)
692                     -> RnM a
693 bindLocatedLocalsRn doc_str rdr_names_w_loc enclosed_scope
694   =     -- Check for duplicate names
695     checkDupNames doc_str rdr_names_w_loc       `thenM_`
696
697         -- Warn about shadowing, but only in source modules
698     ifOptM Opt_WarnNameShadowing 
699       (checkShadowing doc_str rdr_names_w_loc)  `thenM_`
700
701         -- Make fresh Names and extend the environment
702     newLocalsRn rdr_names_w_loc         `thenM` \ names ->
703     getLocalRdrEnv                      `thenM` \ local_env ->
704     setLocalRdrEnv (extendLocalRdrEnv local_env names)
705                    (enclosed_scope names)
706
707
708 bindLocalNames :: [Name] -> RnM a -> RnM a
709 bindLocalNames names enclosed_scope
710   = getLocalRdrEnv              `thenM` \ name_env ->
711     setLocalRdrEnv (extendLocalRdrEnv name_env names)
712                     enclosed_scope
713
714 bindLocalNamesFV :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
715 bindLocalNamesFV names enclosed_scope
716   = do  { (result, fvs) <- bindLocalNames names enclosed_scope
717         ; returnM (result, delListFromNameSet fvs names) }
718
719
720 -------------------------------------
721         -- binLocalsFVRn is the same as bindLocalsRn
722         -- except that it deals with free vars
723 bindLocatedLocalsFV :: SDoc -> [Located RdrName] -> ([Name] -> RnM (a,FreeVars))
724   -> RnM (a, FreeVars)
725 bindLocatedLocalsFV doc rdr_names enclosed_scope
726   = bindLocatedLocalsRn doc rdr_names   $ \ names ->
727     enclosed_scope names                `thenM` \ (thing, fvs) ->
728     returnM (thing, delListFromNameSet fvs names)
729
730 -------------------------------------
731 bindTyVarsRn :: SDoc -> [LHsTyVarBndr RdrName]
732               -> ([LHsTyVarBndr Name] -> RnM a)
733               -> RnM a
734 -- Haskell-98 binding of type variables; e.g. within a data type decl
735 bindTyVarsRn doc_str tyvar_names enclosed_scope
736   = let
737         located_tyvars = hsLTyVarLocNames tyvar_names
738     in
739     bindLocatedLocalsRn doc_str located_tyvars  $ \ names ->
740     enclosed_scope (zipWith replace tyvar_names names)
741     where 
742         replace (L loc n1) n2 = L loc (replaceTyVarName n1 n2)
743
744 bindPatSigTyVars :: [LHsType RdrName] -> ([Name] -> RnM a) -> RnM a
745   -- Find the type variables in the pattern type 
746   -- signatures that must be brought into scope
747 bindPatSigTyVars tys thing_inside
748   = do  { scoped_tyvars <- doptM Opt_ScopedTypeVariables
749         ; if not scoped_tyvars then 
750                 thing_inside []
751           else 
752     do  { name_env <- getLocalRdrEnv
753         ; let locd_tvs  = [ tv | ty <- tys
754                                , tv <- extractHsTyRdrTyVars ty
755                                , not (unLoc tv `elemLocalRdrEnv` name_env) ]
756               nubbed_tvs = nubBy eqLocated locd_tvs
757                 -- The 'nub' is important.  For example:
758                 --      f (x :: t) (y :: t) = ....
759                 -- We don't want to complain about binding t twice!
760
761         ; bindLocatedLocalsRn doc_sig nubbed_tvs thing_inside }}
762   where
763     doc_sig = text "In a pattern type-signature"
764
765 bindPatSigTyVarsFV :: [LHsType RdrName]
766                    -> RnM (a, FreeVars)
767                    -> RnM (a, FreeVars)
768 bindPatSigTyVarsFV tys thing_inside
769   = bindPatSigTyVars tys        $ \ tvs ->
770     thing_inside                `thenM` \ (result,fvs) ->
771     returnM (result, fvs `delListFromNameSet` tvs)
772
773 bindSigTyVarsFV :: [Name]
774                 -> RnM (a, FreeVars)
775                 -> RnM (a, FreeVars)
776 bindSigTyVarsFV tvs thing_inside
777   = do  { scoped_tyvars <- doptM Opt_ScopedTypeVariables
778         ; if not scoped_tyvars then 
779                 thing_inside 
780           else
781                 bindLocalNamesFV tvs thing_inside }
782
783 extendTyVarEnvFVRn :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
784         -- This function is used only in rnSourceDecl on InstDecl
785 extendTyVarEnvFVRn tyvars thing_inside = bindLocalNamesFV tyvars thing_inside
786
787 -------------------------------------
788 checkDupNames :: SDoc
789               -> [Located RdrName]
790               -> RnM ()
791 checkDupNames doc_str rdr_names_w_loc
792   =     -- Check for duplicated names in a binding group
793     mappM_ (dupNamesErr doc_str) dups
794   where
795     (_, dups) = removeDups (\n1 n2 -> unLoc n1 `compare` unLoc n2) rdr_names_w_loc
796
797 -------------------------------------
798 checkShadowing doc_str loc_rdr_names
799   = getLocalRdrEnv              `thenM` \ local_env ->
800     getGlobalRdrEnv             `thenM` \ global_env ->
801     let
802       check_shadow (L loc rdr_name)
803         |  rdr_name `elemLocalRdrEnv` local_env 
804         || not (null (lookupGRE_RdrName rdr_name global_env ))
805         = addWarnAt loc (shadowedNameWarn doc_str rdr_name)
806         | otherwise = returnM ()
807     in
808     mappM_ check_shadow loc_rdr_names
809 \end{code}
810
811
812 %************************************************************************
813 %*                                                                      *
814 \subsection{Free variable manipulation}
815 %*                                                                      *
816 %************************************************************************
817
818 \begin{code}
819 -- A useful utility
820 mapFvRn f xs = mappM f xs       `thenM` \ stuff ->
821                let
822                   (ys, fvs_s) = unzip stuff
823                in
824                returnM (ys, plusFVs fvs_s)
825 \end{code}
826
827
828 %************************************************************************
829 %*                                                                      *
830 \subsection{Envt utility functions}
831 %*                                                                      *
832 %************************************************************************
833
834 \begin{code}
835 warnUnusedModules :: [(ModuleName,SrcSpan)] -> RnM ()
836 warnUnusedModules mods
837   = ifOptM Opt_WarnUnusedImports (mappM_ bleat mods)
838   where
839     bleat (mod,loc) = addWarnAt loc (mk_warn mod)
840     mk_warn m = vcat [ptext SLIT("Module") <+> quotes (ppr m)
841                         <+> text "is imported, but nothing from it is used,",
842                       nest 2 (ptext SLIT("except perhaps instances visible in") 
843                         <+> quotes (ppr m)),
844                       ptext SLIT("To suppress this warning, use:") 
845                         <+> ptext SLIT("import") <+> ppr m <> parens empty ]
846
847
848 warnUnusedImports, warnUnusedTopBinds :: [GlobalRdrElt] -> RnM ()
849 warnUnusedImports gres  = ifOptM Opt_WarnUnusedImports (warnUnusedGREs gres)
850 warnUnusedTopBinds gres = ifOptM Opt_WarnUnusedBinds   (warnUnusedGREs gres)
851
852 warnUnusedLocalBinds, warnUnusedMatches :: [Name] -> RnM ()
853 warnUnusedLocalBinds names = ifOptM Opt_WarnUnusedBinds   (warnUnusedLocals names)
854 warnUnusedMatches    names = ifOptM Opt_WarnUnusedMatches (warnUnusedLocals names)
855
856 -------------------------
857 --      Helpers
858 warnUnusedGREs gres 
859  = warnUnusedBinds [(n,p) | GRE {gre_name = n, gre_prov = p} <- gres]
860
861 warnUnusedLocals names
862  = warnUnusedBinds [(n,LocalDef) | n<-names]
863
864 warnUnusedBinds :: [(Name,Provenance)] -> RnM ()
865 warnUnusedBinds names  = mappM_ warnUnusedName (filter reportable names)
866  where reportable (name,_) 
867         | isWiredInName name = False    -- Don't report unused wired-in names
868                                         -- Otherwise we get a zillion warnings
869                                         -- from Data.Tuple
870         | otherwise = reportIfUnused (nameOccName name)
871
872 -------------------------
873
874 warnUnusedName :: (Name, Provenance) -> RnM ()
875 warnUnusedName (name, LocalDef)
876   = addUnusedWarning name (srcLocSpan (nameSrcLoc name)) 
877                      (ptext SLIT("Defined but not used"))
878
879 warnUnusedName (name, Imported is)
880   = mapM_ warn is
881   where
882     warn spec = addUnusedWarning name span msg
883         where
884            span = importSpecLoc spec
885            pp_mod = quotes (ppr (importSpecModule spec))
886            msg = ptext SLIT("Imported from") <+> pp_mod <+> ptext SLIT("but not used")
887
888 addUnusedWarning name span msg
889   = addWarnAt span $
890     sep [msg <> colon, 
891          nest 2 $ pprNonVarNameSpace (occNameSpace (nameOccName name))
892                         <+> quotes (ppr name)]
893 \end{code}
894
895 \begin{code}
896 addNameClashErrRn rdr_name names
897   = addErr (vcat [ptext SLIT("Ambiguous occurrence") <+> quotes (ppr rdr_name),
898                   ptext SLIT("It could refer to") <+> vcat (msg1 : msgs)])
899   where
900     (np1:nps) = names
901     msg1 = ptext  SLIT("either") <+> mk_ref np1
902     msgs = [ptext SLIT("    or") <+> mk_ref np | np <- nps]
903     mk_ref gre = quotes (ppr (gre_name gre)) <> comma <+> pprNameProvenance gre
904
905 shadowedNameWarn doc shadow
906   = hsep [ptext SLIT("This binding for"), 
907                quotes (ppr shadow),
908                ptext SLIT("shadows an existing binding")]
909     $$ doc
910
911 unknownNameErr rdr_name
912   = sep [ptext SLIT("Not in scope:"), 
913          nest 2 $ pprNonVarNameSpace (occNameSpace (rdrNameOcc rdr_name))
914                   <+> quotes (ppr rdr_name)]
915
916 unknownSubordinateErr doc op    -- Doc is "method of class" or 
917                                 -- "field of constructor"
918   = quotes (ppr op) <+> ptext SLIT("is not a (visible)") <+> doc
919
920 badOrigBinding name
921   = ptext SLIT("Illegal binding of built-in syntax:") <+> ppr (rdrNameOcc name)
922         -- The rdrNameOcc is because we don't want to print Prelude.(,)
923
924 dupNamesErr :: SDoc -> [Located RdrName] -> RnM ()
925 dupNamesErr descriptor located_names
926   = addErrAt big_loc $
927     vcat [ptext SLIT("Conflicting definitions for") <+> quotes (ppr name1),
928           locations, descriptor]
929   where
930     L _ name1 = head located_names
931     locs      = map getLoc located_names
932     big_loc   = foldr1 combineSrcSpans locs
933     one_line  = isOneLineSpan big_loc
934     locations | one_line  = empty 
935               | otherwise = ptext SLIT("Bound at:") <+> 
936                             vcat (map ppr (sortLe (<=) locs))
937
938 badQualBndrErr rdr_name
939   = ptext SLIT("Qualified name in binding position:") <+> ppr rdr_name
940
941 infixTyConWarn op
942   = vcat [ftext FSLIT("Accepting non-standard infix type constructor") <+> quotes (ppr op),
943           ftext FSLIT("Use -fglasgow-exts to avoid this warning")]
944 \end{code}