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