root/compiler/basicTypes/Name.lhs

Revision cb5a3f2d66e4dac2f6f44f56e365d18df884c943, 20.2 KB (checked in by Simon Peyton Jones <simonpj@…>, 2 months ago)

Make the LocalRdrEnv? keep track of all the Names that are in scope

This allows us to give a sensible error message when a Template Haskell
splice generates an occurrence without a binding site.

Fixes Trac #5959 and #5971

  • Property mode set to 100644
Line 
1%
2% (c) The University of Glasgow 2006
3% (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4%
5\section[Name]{@Name@: to transmit name info from renamer to typechecker}
6
7\begin{code}
8{-# OPTIONS -fno-warn-tabs #-}
9-- The above warning supression flag is a temporary kludge.
10-- While working on this module you are encouraged to remove it and
11-- detab the module (please do the detabbing in a separate patch). See
12--     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#TabsvsSpaces
13-- for details
14
15-- |
16-- #name_types#
17-- GHC uses several kinds of name internally:
18--
19-- * 'OccName.OccName': see "OccName#name_types"
20--
21-- * 'RdrName.RdrName': see "RdrName#name_types"
22--
23-- *  'Name.Name' is the type of names that have had their scoping and binding resolved. They
24--   have an 'OccName.OccName' but also a 'Unique.Unique' that disambiguates Names that have
25--   the same 'OccName.OccName' and indeed is used for all 'Name.Name' comparison. Names
26--   also contain information about where they originated from, see "Name#name_sorts"
27--
28-- * 'Id.Id': see "Id#name_types"
29--
30-- * 'Var.Var': see "Var#name_types"
31--
32-- #name_sorts#
33-- Names are one of:
34--
35--  * External, if they name things declared in other modules. Some external
36--    Names are wired in, i.e. they name primitives defined in the compiler itself
37--
38--  * Internal, if they name things in the module being compiled. Some internal
39--    Names are system names, if they are names manufactured by the compiler
40
41module Name (
42        -- * The main types
43        Name,                                   -- Abstract
44        BuiltInSyntax(..),
45
46        -- ** Creating 'Name's
47        mkSystemName, mkSystemNameAt,
48        mkInternalName, mkDerivedInternalName, 
49        mkSystemVarName, mkSysTvName, 
50        mkFCallName,
51        mkExternalName, mkWiredInName,
52
53        -- ** Manipulating and deconstructing 'Name's
54        nameUnique, setNameUnique,
55        nameOccName, nameModule, nameModule_maybe,
56        tidyNameOcc, 
57        hashName, localiseName,
58        mkLocalisedOccName,
59
60        nameSrcLoc, nameSrcSpan, pprNameDefnLoc, pprDefinedAt,
61
62        -- ** Predicates on 'Name's
63        isSystemName, isInternalName, isExternalName,
64        isTyVarName, isTyConName, isDataConName, 
65        isValName, isVarName,
66        isWiredInName, isBuiltInSyntax,
67        wiredInNameTyThing_maybe, 
68        nameIsLocalOrFrom, stableNameCmp,
69
70        -- * Class 'NamedThing' and overloaded friends
71        NamedThing(..),
72        getSrcLoc, getSrcSpan, getOccString,
73
74        pprInfixName, pprPrefixName, pprModulePrefix,
75
76        -- Re-export the OccName stuff
77        module OccName
78    ) where
79
80#include "Typeable.h"
81
82import {-# SOURCE #-} TypeRep( TyThing )
83
84import OccName
85import Module
86import SrcLoc
87import Unique
88import Util
89import Maybes
90import Binary
91import StaticFlags
92import FastTypes
93import FastString
94import Outputable
95
96import Data.Data
97\end{code}
98
99%************************************************************************
100%*                                                                      *
101\subsection[Name-datatype]{The @Name@ datatype, and name construction}
102%*                                                                      *
103%************************************************************************
104 
105\begin{code}
106-- | A unique, unambigious name for something, containing information about where
107-- that thing originated.
108data Name = Name {
109                n_sort :: NameSort,     -- What sort of name it is
110                n_occ  :: !OccName,     -- Its occurrence name
111                n_uniq :: FastInt,      -- UNPACK doesn't work, recursive type
112--(note later when changing Int# -> FastInt: is that still true about UNPACK?)
113                n_loc  :: !SrcSpan      -- Definition site
114            }
115    deriving Typeable
116
117-- NOTE: we make the n_loc field strict to eliminate some potential
118-- (and real!) space leaks, due to the fact that we don't look at
119-- the SrcLoc in a Name all that often.
120
121data NameSort
122  = External Module
123 
124  | WiredIn Module TyThing BuiltInSyntax
125        -- A variant of External, for wired-in things
126
127  | Internal            -- A user-defined Id or TyVar
128                        -- defined in the module being compiled
129
130  | System              -- A system-defined Id or TyVar.  Typically the
131                        -- OccName is very uninformative (like 's')
132
133-- | BuiltInSyntax is for things like @(:)@, @[]@ and tuples,
134-- which have special syntactic forms.  They aren't in scope
135-- as such.
136data BuiltInSyntax = BuiltInSyntax | UserSyntax
137\end{code}
138
139Notes about the NameSorts:
140
1411.  Initially, top-level Ids (including locally-defined ones) get External names,
142    and all other local Ids get Internal names
143
1442.  Things with a External name are given C static labels, so they finally
145    appear in the .o file's symbol table.  They appear in the symbol table
146    in the form M.n.  If originally-local things have this property they
147    must be made @External@ first.
148
1493.  In the tidy-core phase, a External that is not visible to an importer
150    is changed to Internal, and a Internal that is visible is changed to External
151
1524.  A System Name differs in the following ways:
153        a) has unique attached when printing dumps
154        b) unifier eliminates sys tyvars in favour of user provs where possible
155
156    Before anything gets printed in interface files or output code, it's
157    fed through a 'tidy' processor, which zaps the OccNames to have
158    unique names; and converts all sys-locals to user locals
159    If any desugarer sys-locals have survived that far, they get changed to
160    "ds1", "ds2", etc.
161
162Built-in syntax => It's a syntactic form, not "in scope" (e.g. [])
163
164Wired-in thing  => The thing (Id, TyCon) is fully known to the compiler,
165                   not read from an interface file.
166                   E.g. Bool, True, Int, Float, and many others
167
168All built-in syntax is for wired-in things.
169
170\begin{code}
171instance HasOccName Name where
172  occName = nameOccName
173
174nameUnique              :: Name -> Unique
175nameOccName             :: Name -> OccName 
176nameModule              :: Name -> Module
177nameSrcLoc              :: Name -> SrcLoc
178nameSrcSpan             :: Name -> SrcSpan
179
180nameUnique  name = mkUniqueGrimily (iBox (n_uniq name))
181nameOccName name = n_occ  name
182nameSrcLoc  name = srcSpanStart (n_loc name)
183nameSrcSpan name = n_loc  name
184\end{code}
185
186%************************************************************************
187%*                                                                      *
188\subsection{Predicates on names}
189%*                                                                      *
190%************************************************************************
191
192\begin{code}
193nameIsLocalOrFrom :: Module -> Name -> Bool
194isInternalName    :: Name -> Bool
195isExternalName    :: Name -> Bool
196isSystemName      :: Name -> Bool
197isWiredInName     :: Name -> Bool
198
199isWiredInName (Name {n_sort = WiredIn _ _ _}) = True
200isWiredInName _                               = False
201
202wiredInNameTyThing_maybe :: Name -> Maybe TyThing
203wiredInNameTyThing_maybe (Name {n_sort = WiredIn _ thing _}) = Just thing
204wiredInNameTyThing_maybe _                                   = Nothing
205
206isBuiltInSyntax :: Name -> Bool
207isBuiltInSyntax (Name {n_sort = WiredIn _ _ BuiltInSyntax}) = True
208isBuiltInSyntax _                                           = False
209
210isExternalName (Name {n_sort = External _})    = True
211isExternalName (Name {n_sort = WiredIn _ _ _}) = True
212isExternalName _                               = False
213
214isInternalName name = not (isExternalName name)
215
216nameModule name = nameModule_maybe name `orElse` pprPanic "nameModule" (ppr name)
217nameModule_maybe :: Name -> Maybe Module
218nameModule_maybe (Name { n_sort = External mod})    = Just mod
219nameModule_maybe (Name { n_sort = WiredIn mod _ _}) = Just mod
220nameModule_maybe _                                  = Nothing
221
222nameIsLocalOrFrom from name
223  | isExternalName name = from == nameModule name
224  | otherwise           = True
225
226isTyVarName :: Name -> Bool
227isTyVarName name = isTvOcc (nameOccName name)
228
229isTyConName :: Name -> Bool
230isTyConName name = isTcOcc (nameOccName name)
231
232isDataConName :: Name -> Bool
233isDataConName name = isDataOcc (nameOccName name)
234
235isValName :: Name -> Bool
236isValName name = isValOcc (nameOccName name)
237
238isVarName :: Name -> Bool
239isVarName = isVarOcc . nameOccName
240
241isSystemName (Name {n_sort = System}) = True
242isSystemName _                        = False
243\end{code}
244
245
246%************************************************************************
247%*                                                                      *
248\subsection{Making names}
249%*                                                                      *
250%************************************************************************
251
252\begin{code}
253-- | Create a name which is (for now at least) local to the current module and hence
254-- does not need a 'Module' to disambiguate it from other 'Name's
255mkInternalName :: Unique -> OccName -> SrcSpan -> Name
256mkInternalName uniq occ loc = Name { n_uniq = getKeyFastInt uniq
257                                   , n_sort = Internal
258                                   , n_occ = occ
259                                   , n_loc = loc }
260        -- NB: You might worry that after lots of huffing and
261        -- puffing we might end up with two local names with distinct
262        -- uniques, but the same OccName.  Indeed we can, but that's ok
263        --      * the insides of the compiler don't care: they use the Unique
264        --      * when printing for -ddump-xxx you can switch on -dppr-debug to get the
265        --        uniques if you get confused
266        --      * for interface files we tidyCore first, which makes
267        --        the OccNames distinct when they need to be
268
269mkDerivedInternalName :: (OccName -> OccName) -> Unique -> Name -> Name
270mkDerivedInternalName derive_occ uniq (Name { n_occ = occ, n_loc = loc })
271  = Name { n_uniq = getKeyFastInt uniq, n_sort = Internal
272         , n_occ = derive_occ occ, n_loc = loc }
273
274-- | Create a name which definitely originates in the given module
275mkExternalName :: Unique -> Module -> OccName -> SrcSpan -> Name
276mkExternalName uniq mod occ loc
277  = Name { n_uniq = getKeyFastInt uniq, n_sort = External mod,
278           n_occ = occ, n_loc = loc }
279
280-- | Create a name which is actually defined by the compiler itself
281mkWiredInName :: Module -> OccName -> Unique -> TyThing -> BuiltInSyntax -> Name
282mkWiredInName mod occ uniq thing built_in
283  = Name { n_uniq = getKeyFastInt uniq,
284           n_sort = WiredIn mod thing built_in,
285           n_occ = occ, n_loc = wiredInSrcSpan }
286
287-- | Create a name brought into being by the compiler
288mkSystemName :: Unique -> OccName -> Name
289mkSystemName uniq occ = mkSystemNameAt uniq occ noSrcSpan
290
291mkSystemNameAt :: Unique -> OccName -> SrcSpan -> Name
292mkSystemNameAt uniq occ loc = Name { n_uniq = getKeyFastInt uniq, n_sort = System 
293                                   , n_occ = occ, n_loc = loc }
294
295mkSystemVarName :: Unique -> FastString -> Name
296mkSystemVarName uniq fs = mkSystemName uniq (mkVarOccFS fs)
297
298mkSysTvName :: Unique -> FastString -> Name
299mkSysTvName uniq fs = mkSystemName uniq (mkOccNameFS tvName fs)
300
301-- | Make a name for a foreign call
302mkFCallName :: Unique -> String -> Name
303mkFCallName uniq str = mkInternalName uniq (mkVarOcc str) noSrcSpan
304   -- The encoded string completely describes the ccall
305\end{code}
306
307\begin{code}
308-- When we renumber/rename things, we need to be
309-- able to change a Name's Unique to match the cached
310-- one in the thing it's the name of.  If you know what I mean.
311setNameUnique :: Name -> Unique -> Name
312setNameUnique name uniq = name {n_uniq = getKeyFastInt uniq}
313
314tidyNameOcc :: Name -> OccName -> Name
315-- We set the OccName of a Name when tidying
316-- In doing so, we change System --> Internal, so that when we print
317-- it we don't get the unique by default.  It's tidy now!
318tidyNameOcc name@(Name { n_sort = System }) occ = name { n_occ = occ, n_sort = Internal}
319tidyNameOcc name                            occ = name { n_occ = occ }
320
321-- | Make the 'Name' into an internal name, regardless of what it was to begin with
322localiseName :: Name -> Name
323localiseName n = n { n_sort = Internal }
324\end{code}
325
326\begin{code}
327-- |Create a localised variant of a name. 
328--
329-- If the name is external, encode the original's module name to disambiguate.
330--
331mkLocalisedOccName :: Module -> (Maybe String -> OccName -> OccName) -> Name -> OccName
332mkLocalisedOccName this_mod mk_occ name = mk_occ origin (nameOccName name)
333  where
334    origin
335      | nameIsLocalOrFrom this_mod name = Nothing
336      | otherwise                       = Just (moduleNameColons . moduleName . nameModule $ name)
337\end{code}
338
339%************************************************************************
340%*                                                                      *
341\subsection{Hashing and comparison}
342%*                                                                      *
343%************************************************************************
344
345\begin{code}
346hashName :: Name -> Int         -- ToDo: should really be Word
347hashName name = getKey (nameUnique name) + 1
348        -- The +1 avoids keys with lots of zeros in the ls bits, which
349        -- interacts badly with the cheap and cheerful multiplication in
350        -- hashExpr
351
352cmpName :: Name -> Name -> Ordering
353cmpName n1 n2 = iBox (n_uniq n1) `compare` iBox (n_uniq n2)
354
355stableNameCmp :: Name -> Name -> Ordering
356-- Compare lexicographically
357stableNameCmp (Name { n_sort = s1, n_occ = occ1 })
358              (Name { n_sort = s2, n_occ = occ2 })
359  = (s1 `sort_cmp` s2) `thenCmp` (occ1 `compare` occ2)
360    -- The ordinary compare on OccNames is lexicogrpahic
361  where
362    -- Later constructors are bigger
363    sort_cmp (External m1) (External m2)       = m1 `stableModuleCmp` m2
364    sort_cmp (External {}) _                   = LT
365    sort_cmp (WiredIn {}) (External {})        = GT
366    sort_cmp (WiredIn m1 _ _) (WiredIn m2 _ _) = m1 `stableModuleCmp` m2
367    sort_cmp (WiredIn {})     _                = LT
368    sort_cmp Internal         (External {})    = GT
369    sort_cmp Internal         (WiredIn {})     = GT
370    sort_cmp Internal         Internal         = EQ
371    sort_cmp Internal         System           = LT
372    sort_cmp System           System           = EQ
373    sort_cmp System           _                = GT
374\end{code}
375
376%************************************************************************
377%*                                                                      *
378\subsection[Name-instances]{Instance declarations}
379%*                                                                      *
380%************************************************************************
381
382\begin{code}
383instance Eq Name where
384    a == b = case (a `compare` b) of { EQ -> True;  _ -> False }
385    a /= b = case (a `compare` b) of { EQ -> False; _ -> True }
386
387instance Ord Name where
388    a <= b = case (a `compare` b) of { LT -> True;  EQ -> True;  GT -> False }
389    a <  b = case (a `compare` b) of { LT -> True;  EQ -> False; GT -> False }
390    a >= b = case (a `compare` b) of { LT -> False; EQ -> True;  GT -> True  }
391    a >  b = case (a `compare` b) of { LT -> False; EQ -> False; GT -> True  }
392    compare a b = cmpName a b
393
394instance Uniquable Name where
395    getUnique = nameUnique
396
397instance NamedThing Name where
398    getName n = n
399
400instance Data Name where
401  -- don't traverse?
402  toConstr _   = abstractConstr "Name"
403  gunfold _ _  = error "gunfold"
404  dataTypeOf _ = mkNoRepType "Name"
405\end{code}
406
407%************************************************************************
408%*                                                                      *
409\subsection{Binary}
410%*                                                                      *
411%************************************************************************
412
413\begin{code}
414instance Binary Name where
415   put_ bh name =
416      case getUserData bh of 
417        UserData{ ud_put_name = put_name } -> put_name bh name
418
419   get bh =
420      case getUserData bh of
421        UserData { ud_get_name = get_name } -> get_name bh
422\end{code}
423
424%************************************************************************
425%*                                                                      *
426\subsection{Pretty printing}
427%*                                                                      *
428%************************************************************************
429
430\begin{code}
431instance Outputable Name where
432    ppr name = pprName name
433
434instance OutputableBndr Name where
435    pprBndr _ name = pprName name
436    pprInfixOcc  = pprInfixName
437    pprPrefixOcc = pprPrefixName
438
439
440pprName :: Name -> SDoc
441pprName n@(Name {n_sort = sort, n_uniq = u, n_occ = occ})
442  = getPprStyle $ \ sty ->
443    case sort of
444      WiredIn mod _ builtin   -> pprExternal sty uniq mod occ n True  builtin
445      External mod            -> pprExternal sty uniq mod occ n False UserSyntax
446      System                  -> pprSystem sty uniq occ
447      Internal                -> pprInternal sty uniq occ
448  where uniq = mkUniqueGrimily (iBox u)
449
450pprExternal :: PprStyle -> Unique -> Module -> OccName -> Name -> Bool -> BuiltInSyntax -> SDoc
451pprExternal sty uniq mod occ name is_wired is_builtin
452  | codeStyle sty = ppr mod <> char '_' <> ppr_z_occ_name occ
453        -- In code style, always qualify
454        -- ToDo: maybe we could print all wired-in things unqualified
455        --       in code style, to reduce symbol table bloat?
456  | debugStyle sty = pp_mod <> ppr_occ_name occ
457                     <> braces (hsep [if is_wired then ptext (sLit "(w)") else empty,
458                                      pprNameSpaceBrief (occNameSpace occ), 
459                                      pprUnique uniq])
460  | BuiltInSyntax <- is_builtin = ppr_occ_name occ  -- Never qualify builtin syntax
461  | otherwise                   = pprModulePrefix sty mod name <> ppr_occ_name occ
462  where
463    pp_mod | opt_SuppressModulePrefixes = empty
464           | otherwise                  = ppr mod <> dot
465
466pprInternal :: PprStyle -> Unique -> OccName -> SDoc
467pprInternal sty uniq occ
468  | codeStyle sty  = pprUnique uniq
469  | debugStyle sty = ppr_occ_name occ <> braces (hsep [pprNameSpaceBrief (occNameSpace occ), 
470                                                       pprUnique uniq])
471  | dumpStyle sty  = ppr_occ_name occ <> ppr_underscore_unique uniq
472                        -- For debug dumps, we're not necessarily dumping
473                        -- tidied code, so we need to print the uniques.
474  | otherwise      = ppr_occ_name occ   -- User style
475
476-- Like Internal, except that we only omit the unique in Iface style
477pprSystem :: PprStyle -> Unique -> OccName -> SDoc
478pprSystem sty uniq occ
479  | codeStyle sty  = pprUnique uniq
480  | debugStyle sty = ppr_occ_name occ <> ppr_underscore_unique uniq
481                     <> braces (pprNameSpaceBrief (occNameSpace occ))
482  | otherwise      = ppr_occ_name occ <> ppr_underscore_unique uniq
483                                -- If the tidy phase hasn't run, the OccName
484                                -- is unlikely to be informative (like 's'),
485                                -- so print the unique
486
487
488pprModulePrefix :: PprStyle -> Module -> Name -> SDoc
489-- Print the "M." part of a name, based on whether it's in scope or not
490-- See Note [Printing original names] in HscTypes
491pprModulePrefix sty mod name
492  | opt_SuppressModulePrefixes = empty
493 
494  | otherwise
495  = case qualName sty name of              -- See Outputable.QualifyName:
496      NameQual modname -> ppr modname <> dot       -- Name is in scope       
497      NameNotInScope1  -> ppr mod <> dot           -- Not in scope
498      NameNotInScope2  -> ppr (modulePackageId mod) <> colon     -- Module not in
499                          <> ppr (moduleName mod) <> dot         -- scope eithber
500      _otherwise       -> empty
501
502ppr_underscore_unique :: Unique -> SDoc
503-- Print an underscore separating the name from its unique
504-- But suppress it if we aren't printing the uniques anyway
505ppr_underscore_unique uniq
506  | opt_SuppressUniques = empty
507  | otherwise           = char '_' <> pprUnique uniq
508
509ppr_occ_name :: OccName -> SDoc
510ppr_occ_name occ = ftext (occNameFS occ)
511        -- Don't use pprOccName; instead, just print the string of the OccName;
512        -- we print the namespace in the debug stuff above
513
514-- In code style, we Z-encode the strings.  The results of Z-encoding each FastString are
515-- cached behind the scenes in the FastString implementation.
516ppr_z_occ_name :: OccName -> SDoc
517ppr_z_occ_name occ = ftext (zEncodeFS (occNameFS occ))
518
519-- Prints (if mod information is available) "Defined at <loc>" or
520--  "Defined in <mod>" information for a Name.
521pprDefinedAt :: Name -> SDoc
522pprDefinedAt name = ptext (sLit "Defined") <+> pprNameDefnLoc name
523
524pprNameDefnLoc :: Name -> SDoc
525-- Prints "at <loc>" or
526--     or "in <mod>" depending on what info is available
527pprNameDefnLoc name
528  = case nameSrcLoc name of
529         -- nameSrcLoc rather than nameSrcSpan
530         -- It seems less cluttered to show a location
531         -- rather than a span for the definition point
532       RealSrcLoc s -> ptext (sLit "at") <+> ppr s
533       UnhelpfulLoc s
534         | isInternalName name || isSystemName name
535         -> ptext (sLit "at") <+> ftext s
536         | otherwise
537         -> ptext (sLit "in") <+> quotes (ppr (nameModule name))
538\end{code}
539
540%************************************************************************
541%*                                                                      *
542\subsection{Overloaded functions related to Names}
543%*                                                                      *
544%************************************************************************
545
546\begin{code}
547-- | A class allowing convenient access to the 'Name' of various datatypes
548class NamedThing a where
549    getOccName :: a -> OccName
550    getName    :: a -> Name
551
552    getOccName n = nameOccName (getName n)      -- Default method
553\end{code}
554
555\begin{code}
556getSrcLoc           :: NamedThing a => a -> SrcLoc
557getSrcSpan          :: NamedThing a => a -> SrcSpan
558getOccString        :: NamedThing a => a -> String
559
560getSrcLoc           = nameSrcLoc           . getName
561getSrcSpan          = nameSrcSpan          . getName
562getOccString        = occNameString        . getOccName
563
564pprInfixName, pprPrefixName :: (Outputable a, NamedThing a) => a -> SDoc
565-- See Outputable.pprPrefixVar, pprInfixVar;
566-- add parens or back-quotes as appropriate
567pprInfixName  n = pprInfixVar  (isSymOcc (getOccName n)) (ppr n)
568pprPrefixName n = pprPrefixVar (isSymOcc (getOccName n)) (ppr n)
569\end{code}
Note: See TracBrowser for help on using the browser.