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