Name.lhs 13.4 KB
Newer Older
1
%
2
% (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 4 5 6 7
%
\section[Name]{@Name@: to transmit name info from renamer to typechecker}

\begin{code}
module Name (
8 9
	-- Re-export the OccName stuff
	module OccName,
10

11 12
	-- The Name type
	Name,					-- Abstract
13
	BuiltInSyntax(..), 
14
	mkInternalName, mkSystemName,
15
	mkSystemVarName, mkSysTvName, 
16
	mkFCallName, mkIPName,
17
	mkExternalName, mkWiredInName,
18

19
	nameUnique, setNameUnique,
20
	nameOccName, nameModule, nameModule_maybe,
21
	tidyNameOcc, 
22
	hashName, localiseName,
sof's avatar
sof committed
23

24
	nameSrcLoc,
25

26
	isSystemName, isInternalName, isExternalName,
27
	isTyVarName, isTyConName, isWiredInName, isBuiltInSyntax,
28
	wiredInNameTyThing_maybe, 
29
	nameIsLocalOrFrom,
30
	
31 32
	-- Class NamedThing and overloaded friends
	NamedThing(..),
33
	getSrcLoc, getOccString
34
    ) where
35

36 37
#include "HsVersions.h"

38 39
import {-# SOURCE #-} TypeRep( TyThing )

40
import OccName		-- All of it
Simon Marlow's avatar
Simon Marlow committed
41
import Module		( Module )
42
import SrcLoc		( noSrcLoc, wiredInSrcLoc, SrcLoc )
43
import UniqFM           ( lookupUFM, addToUFM )
44 45
import Unique		( Unique, Uniquable(..), getKey, pprUnique,
                          mkUniqueGrimily, getKey# )
46
import Maybes		( orElse, isJust )
47 48
import Binary
import FastMutInt
49
import FastString	( FastString, zEncodeFS )
50
import Outputable
51

52
import DATA_IOREF
53
import GLAEXTS          ( Int#, Int(..) )
54
import Data.Array       ( (!) )
55 56
\end{code}

57 58
%************************************************************************
%*									*
59
\subsection[Name-datatype]{The @Name@ datatype, and name construction}
60 61
%*									*
%************************************************************************
62
 
63
\begin{code}
64 65
data Name = Name {
		n_sort :: NameSort,	-- What sort of name it is
66
		n_occ  :: !OccName,	-- Its occurrence name
67
		n_uniq :: Int#,         -- UNPACK doesn't work, recursive type
68
		n_loc  :: !SrcLoc	-- Definition site
69 70
	    }

71 72 73 74
-- NOTE: we make the n_loc field strict to eliminate some potential
-- (and real!) space leaks, due to the fact that we don't look at
-- the SrcLoc in a Name all that often.

75
data NameSort
76
  = External Module
77
 
78
  | WiredIn Module TyThing BuiltInSyntax
79
	-- A variant of External, for wired-in things
80

81
  | Internal		-- A user-defined Id or TyVar
82 83 84 85
			-- defined in the module being compiled

  | System		-- A system-defined Id or TyVar.  Typically the
			-- OccName is very uninformative (like 's')
86 87 88 89 90

data BuiltInSyntax = BuiltInSyntax | UserSyntax
-- BuiltInSyntax is for things like (:), [], tuples etc, 
-- which have special syntactic forms.  They aren't "in scope"
-- as such.
91 92
\end{code}

93 94
Notes about the NameSorts:

95 96
1.  Initially, top-level Ids (including locally-defined ones) get External names, 
    and all other local Ids get Internal names
97

98
2.  Things with a External name are given C static labels, so they finally
99 100
    appear in the .o file's symbol table.  They appear in the symbol table
    in the form M.n.  If originally-local things have this property they
101
    must be made @External@ first.
102

103 104
3.  In the tidy-core phase, a External that is not visible to an importer
    is changed to Internal, and a Internal that is visible is changed to External
105 106

4.  A System Name differs in the following ways:
107 108 109 110 111 112 113 114 115
	a) has unique attached when printing dumps
	b) unifier eliminates sys tyvars in favour of user provs where possible

    Before anything gets printed in interface files or output code, it's
    fed through a 'tidy' processor, which zaps the OccNames to have
    unique names; and converts all sys-locals to user locals
    If any desugarer sys-locals have survived that far, they get changed to
    "ds1", "ds2", etc.

116 117 118 119 120 121 122 123
Built-in syntax => It's a syntactic form, not "in scope" (e.g. [])

Wired-in thing  => The thing (Id, TyCon) is fully known to the compiler, 
		   not read from an interface file. 
		   E.g. Bool, True, Int, Float, and many others

All built-in syntax is for wired-in things.

124 125 126 127 128 129
\begin{code}
nameUnique		:: Name -> Unique
nameOccName		:: Name -> OccName 
nameModule		:: Name -> Module
nameSrcLoc		:: Name -> SrcLoc

130
nameUnique  name = mkUniqueGrimily (I# (n_uniq name))
131 132 133 134 135
nameOccName name = n_occ  name
nameSrcLoc  name = n_loc  name
\end{code}

\begin{code}
136 137 138 139
nameIsLocalOrFrom :: Module -> Name -> Bool
isInternalName	  :: Name -> Bool
isExternalName	  :: Name -> Bool
isSystemName	  :: Name -> Bool
140 141
isWiredInName	  :: Name -> Bool

142 143
isWiredInName (Name {n_sort = WiredIn _ _ _}) = True
isWiredInName other			      = False
144

145
wiredInNameTyThing_maybe :: Name -> Maybe TyThing
146 147
wiredInNameTyThing_maybe (Name {n_sort = WiredIn _ thing _}) = Just thing
wiredInNameTyThing_maybe other				     = Nothing
148

149 150
isBuiltInSyntax (Name {n_sort = WiredIn _ _ BuiltInSyntax}) = True
isBuiltInSyntax other			 	            = False
151

152 153 154
isExternalName (Name {n_sort = External _})    = True
isExternalName (Name {n_sort = WiredIn _ _ _}) = True
isExternalName other                           = False
155

156
isInternalName name = not (isExternalName name)
157

158
nameModule name = nameModule_maybe name `orElse` pprPanic "nameModule" (ppr name)
159 160 161
nameModule_maybe (Name { n_sort = External mod})    = Just mod
nameModule_maybe (Name { n_sort = WiredIn mod _ _}) = Just mod
nameModule_maybe name				    = Nothing
162

163 164 165 166
nameIsLocalOrFrom from name
  | isExternalName name = from == nameModule name
  | otherwise		= True

167 168
isTyVarName :: Name -> Bool
isTyVarName name = isTvOcc (nameOccName name)
169

170 171 172
isTyConName :: Name -> Bool
isTyConName name = isTcOcc (nameOccName name)

173 174 175 176 177 178 179 180 181 182
isSystemName (Name {n_sort = System}) = True
isSystemName other		      = False
\end{code}


%************************************************************************
%*									*
\subsection{Making names}
%*									*
%************************************************************************
183

184
\begin{code}
185
mkInternalName :: Unique -> OccName -> SrcLoc -> Name
186
mkInternalName uniq occ loc = Name { n_uniq = getKey# uniq, n_sort = Internal, n_occ = occ, n_loc = loc }
187 188 189 190 191 192 193 194
	-- NB: You might worry that after lots of huffing and
	-- puffing we might end up with two local names with distinct
	-- uniques, but the same OccName.  Indeed we can, but that's ok
	--	* the insides of the compiler don't care: they use the Unique
	--	* when printing for -ddump-xxx you can switch on -dppr-debug to get the
	--	  uniques if you get confused
	--	* for interface files we tidyCore first, which puts the uniques
	--	  into the print name (see setNameVisibility below)
195

196 197 198
mkExternalName :: Unique -> Module -> OccName -> SrcLoc -> Name
mkExternalName uniq mod occ loc 
  = Name { n_uniq = getKey# uniq, n_sort = External mod,
199
           n_occ = occ, n_loc = loc }
200

201 202 203
mkWiredInName :: Module -> OccName -> Unique -> TyThing -> BuiltInSyntax
        -> Name
mkWiredInName mod occ uniq thing built_in
204
  = Name { n_uniq = getKey# uniq,
205
	   n_sort = WiredIn mod thing built_in,
206
	   n_occ = occ, n_loc = wiredInSrcLoc }
207

208
mkSystemName :: Unique -> OccName -> Name
209
mkSystemName uniq occ = Name { n_uniq = getKey# uniq, n_sort = System, 
210 211
			       n_occ = occ, n_loc = noSrcLoc }

212 213
mkSystemVarName :: Unique -> FastString -> Name
mkSystemVarName uniq fs = mkSystemName uniq (mkVarOccFS fs)
214

215 216
mkSysTvName :: Unique -> FastString -> Name
mkSysTvName uniq fs = mkSystemName uniq (mkOccNameFS tvName fs) 
217

218
mkFCallName :: Unique -> String -> Name
219
	-- The encoded string completely describes the ccall
220
mkFCallName uniq str =  Name { n_uniq = getKey# uniq, n_sort = Internal, 
221
			       n_occ = mkVarOcc str, n_loc = noSrcLoc }
222

223 224
mkIPName :: Unique -> OccName -> Name
mkIPName uniq occ
225
  = Name { n_uniq = getKey# uniq,
226
	   n_sort = Internal,
227
	   n_occ  = occ,
228
	   n_loc = noSrcLoc }
229 230 231
\end{code}

\begin{code}
232 233 234
-- When we renumber/rename things, we need to be
-- able to change a Name's Unique to match the cached
-- one in the thing it's the name of.  If you know what I mean.
235 236
setNameUnique :: Name -> Unique -> Name
setNameUnique name uniq = name {n_uniq = getKey# uniq}
237

238 239 240 241 242 243
tidyNameOcc :: Name -> OccName -> Name
-- We set the OccName of a Name when tidying
-- In doing so, we change System --> Internal, so that when we print
-- it we don't get the unique by default.  It's tidy now!
tidyNameOcc name@(Name { n_sort = System }) occ = name { n_occ = occ, n_sort = Internal}
tidyNameOcc name 			    occ = name { n_occ = occ }
244

245
localiseName :: Name -> Name
246
localiseName n = n { n_sort = Internal }
sof's avatar
sof committed
247 248 249
\end{code}


250 251 252 253 254 255 256
%************************************************************************
%*									*
\subsection{Predicates and selectors}
%*									*
%************************************************************************

\begin{code}
257
hashName :: Name -> Int
258
hashName name = getKey (nameUnique name)
259 260
\end{code}

261

262 263 264 265 266 267 268
%************************************************************************
%*									*
\subsection[Name-instances]{Instance declarations}
%*									*
%************************************************************************

\begin{code}
269
cmpName n1 n2 = I# (n_uniq n1) `compare` I# (n_uniq n2)
270 271 272 273
\end{code}

\begin{code}
instance Eq Name where
274 275
    a == b = case (a `compare` b) of { EQ -> True;  _ -> False }
    a /= b = case (a `compare` b) of { EQ -> False; _ -> True }
276 277

instance Ord Name where
278 279
    a <= b = case (a `compare` b) of { LT -> True;  EQ -> True;  GT -> False }
    a <	 b = case (a `compare` b) of { LT -> True;  EQ -> False; GT -> False }
280 281 282
    a >= b = case (a `compare` b) of { LT -> False; EQ -> True;  GT -> True  }
    a >	 b = case (a `compare` b) of { LT -> False; EQ -> False; GT -> True  }
    compare a b = cmpName a b
283

284
instance Uniquable Name where
285
    getUnique = nameUnique
286

287
instance NamedThing Name where
288
    getName n = n
289 290
\end{code}

291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
%************************************************************************
%*									*
\subsection{Binary}
%*									*
%************************************************************************

\begin{code}
instance Binary Name where
   put_ bh name = do
      case getUserData bh of { 
        UserData { ud_symtab_map = symtab_map_ref,
                   ud_symtab_next = symtab_next } -> do
         symtab_map <- readIORef symtab_map_ref
         case lookupUFM symtab_map name of
           Just (off,_) -> put_ bh off
           Nothing -> do
              off <- readFastMutInt symtab_next
              writeFastMutInt symtab_next (off+1)
              writeIORef symtab_map_ref
                  $! addToUFM symtab_map name (off,name)
              put_ bh off          
     }

   get bh = do
        i <- get bh
        return $! (ud_symtab (getUserData bh) ! i)
\end{code}
318

319 320 321 322 323
%************************************************************************
%*									*
\subsection{Pretty printing}
%*									*
%************************************************************************
324 325 326

\begin{code}
instance Outputable Name where
327 328
    ppr name = pprName name

329 330 331
instance OutputableBndr Name where
    pprBndr _ name = pprName name

332
pprName name@(Name {n_sort = sort, n_uniq = u#, n_occ = occ})
333
  = getPprStyle $ \ sty ->
334
    case sort of
335 336
      WiredIn mod _ builtin   -> pprExternal sty uniq mod occ True  builtin
      External mod  	      -> pprExternal sty uniq mod occ False UserSyntax
337 338
      System   		      -> pprSystem sty uniq occ
      Internal    	      -> pprInternal sty uniq occ
339
  where uniq = mkUniqueGrimily (I# u#)
340

341
pprExternal sty uniq mod occ is_wired is_builtin
Simon Marlow's avatar
Simon Marlow committed
342
  | codeStyle sty        = ppr mod <> char '_' <> ppr_z_occ_name occ
343 344 345
	-- In code style, always qualify
	-- ToDo: maybe we could print all wired-in things unqualified
	-- 	 in code style, to reduce symbol table bloat?
Simon Marlow's avatar
Simon Marlow committed
346 347 348 349
 | debugStyle sty       = ppr mod <> dot <> ppr_occ_name occ
		<> braces (hsep [if is_wired then ptext SLIT("(w)") else empty,
				 pprNameSpaceBrief (occNameSpace occ), 
		 		 pprUnique uniq])
350
  | BuiltInSyntax <- is_builtin  = ppr_occ_name occ
351
	-- never qualify builtin syntax
Simon Marlow's avatar
Simon Marlow committed
352 353 354
  | Just mod <- qualName sty mod occ = ppr mod <> dot <> ppr_occ_name occ
        -- the PrintUnqualified tells us how to qualify this Name, if at all
  | otherwise		          = ppr_occ_name occ
355

356
pprInternal sty uniq occ
357
  | codeStyle sty  = pprUnique uniq
358
  | debugStyle sty = ppr_occ_name occ <> braces (hsep [pprNameSpaceBrief (occNameSpace occ), 
359
				 		       pprUnique uniq])
360 361 362
  | dumpStyle sty  = ppr_occ_name occ <> char '_' <> pprUnique uniq
			-- For debug dumps, we're not necessarily dumping
			-- tidied code, so we need to print the uniques.
363
  | otherwise      = ppr_occ_name occ	-- User style
364

365 366
-- Like Internal, except that we only omit the unique in Iface style
pprSystem sty uniq occ
367
  | codeStyle sty  = pprUnique uniq
368
  | debugStyle sty = ppr_occ_name occ <> char '_' <> pprUnique uniq
369
		     <> braces (pprNameSpaceBrief (occNameSpace occ))
370
  | otherwise	   = ppr_occ_name occ <> char '_' <> pprUnique uniq
371 372 373
				-- If the tidy phase hasn't run, the OccName
				-- is unlikely to be informative (like 's'),
				-- so print the unique
374

375
ppr_occ_name occ = ftext (occNameFS occ)
376 377
	-- Don't use pprOccName; instead, just print the string of the OccName; 
	-- we print the namespace in the debug stuff above
378 379 380 381

-- In code style, we Z-encode the strings.  The results of Z-encoding each FastString are
-- cached behind the scenes in the FastString implementation.
ppr_z_occ_name occ = ftext (zEncodeFS (occNameFS occ))
382
\end{code}
383

384 385 386 387 388 389 390 391
%************************************************************************
%*									*
\subsection{Overloaded functions related to Names}
%*									*
%************************************************************************

\begin{code}
class NamedThing a where
392
    getOccName :: a -> OccName
393 394 395
    getName    :: a -> Name

    getOccName n = nameOccName (getName n)	-- Default method
396 397 398 399
\end{code}

\begin{code}
getSrcLoc	    :: NamedThing a => a -> SrcLoc
400
getOccString	    :: NamedThing a => a -> String
401

402
getSrcLoc	    = nameSrcLoc	   . getName
403
getOccString 	    = occNameString	   . getOccName
404 405
\end{code}