Name.lhs 13.5 KB
Newer Older
1
%
Simon Marlow's avatar
Simon Marlow committed
2
% (c) The University of Glasgow 2006
3
% (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 5 6 7 8
%
\section[Name]{@Name@: to transmit name info from renamer to typechecker}

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

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

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

26
	nameSrcLoc,
27

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

38 39
#include "HsVersions.h"

40 41
import {-# SOURCE #-} TypeRep( TyThing )

Simon Marlow's avatar
Simon Marlow committed
42 43 44 45 46 47
import OccName
import Module
import SrcLoc
import UniqFM
import Unique
import Maybes
48 49
import Binary
import FastMutInt
Simon Marlow's avatar
Simon Marlow committed
50
import FastString
51
import Outputable
52

Simon Marlow's avatar
Simon Marlow committed
53 54 55
import Data.IORef
import GHC.Exts
import Data.Array
56 57
\end{code}

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

72 73 74 75
-- 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.

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

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

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

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

94 95
Notes about the NameSorts:

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

99
2.  Things with a External name are given C static labels, so they finally
100 101
    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
102
    must be made @External@ first.
103

104 105
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
106 107

4.  A System Name differs in the following ways:
108 109 110 111 112 113 114 115 116
	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.

117 118 119 120 121 122 123 124
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.

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

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

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

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

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

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

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

157
isInternalName name = not (isExternalName name)
158

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

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

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

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

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


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

185
\begin{code}
186
mkInternalName :: Unique -> OccName -> SrcLoc -> Name
187
mkInternalName uniq occ loc = Name { n_uniq = getKey# uniq, n_sort = Internal, n_occ = occ, n_loc = loc }
188 189 190 191 192 193 194 195
	-- 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)
196

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

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

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

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

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

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

224 225 226 227 228
mkTickBoxOpName :: Unique -> String -> Name
mkTickBoxOpName uniq str 
   = Name { n_uniq = getKey# uniq, n_sort = Internal, 
	    n_occ = mkVarOcc str, n_loc = noSrcLoc }

229 230
mkIPName :: Unique -> OccName -> Name
mkIPName uniq occ
231
  = Name { n_uniq = getKey# uniq,
232
	   n_sort = Internal,
233
	   n_occ  = occ,
234
	   n_loc = noSrcLoc }
235 236 237
\end{code}

\begin{code}
238 239 240
-- 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.
241 242
setNameUnique :: Name -> Unique -> Name
setNameUnique name uniq = name {n_uniq = getKey# uniq}
243

244 245 246 247 248 249
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 }
250

251
localiseName :: Name -> Name
252
localiseName n = n { n_sort = Internal }
sof's avatar
sof committed
253 254 255
\end{code}


256 257 258 259 260 261 262
%************************************************************************
%*									*
\subsection{Predicates and selectors}
%*									*
%************************************************************************

\begin{code}
263 264 265 266 267
hashName :: Name -> Int		-- ToDo: should really be Word
hashName name = getKey (nameUnique name) + 1
	-- The +1 avoids keys with lots of zeros in the ls bits, which 
	-- interacts badly with the cheap and cheerful multiplication in
	-- hashExpr
268 269
\end{code}

270

271 272 273 274 275 276 277
%************************************************************************
%*									*
\subsection[Name-instances]{Instance declarations}
%*									*
%************************************************************************

\begin{code}
278
cmpName n1 n2 = I# (n_uniq n1) `compare` I# (n_uniq n2)
279 280 281 282
\end{code}

\begin{code}
instance Eq Name where
283 284
    a == b = case (a `compare` b) of { EQ -> True;  _ -> False }
    a /= b = case (a `compare` b) of { EQ -> False; _ -> True }
285 286

instance Ord Name where
287 288
    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 }
289 290 291
    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
292

293
instance Uniquable Name where
294
    getUnique = nameUnique
295

296
instance NamedThing Name where
297
    getName n = n
298 299
\end{code}

300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
%************************************************************************
%*									*
\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}
327

328 329 330 331 332
%************************************************************************
%*									*
\subsection{Pretty printing}
%*									*
%************************************************************************
333 334 335

\begin{code}
instance Outputable Name where
336 337
    ppr name = pprName name

338 339 340
instance OutputableBndr Name where
    pprBndr _ name = pprName name

341
pprName name@(Name {n_sort = sort, n_uniq = u#, n_occ = occ})
342
  = getPprStyle $ \ sty ->
343
    case sort of
344 345
      WiredIn mod _ builtin   -> pprExternal sty uniq mod occ True  builtin
      External mod  	      -> pprExternal sty uniq mod occ False UserSyntax
346 347
      System   		      -> pprSystem sty uniq occ
      Internal    	      -> pprInternal sty uniq occ
348
  where uniq = mkUniqueGrimily (I# u#)
349

350
pprExternal sty uniq mod occ is_wired is_builtin
Simon Marlow's avatar
Simon Marlow committed
351
  | codeStyle sty        = ppr mod <> char '_' <> ppr_z_occ_name occ
352 353 354
	-- 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
355 356 357 358
 | 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])
359
  | BuiltInSyntax <- is_builtin  = ppr_occ_name occ
360
	-- never qualify builtin syntax
Simon Marlow's avatar
Simon Marlow committed
361 362 363
  | 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
364

365
pprInternal sty uniq occ
366
  | codeStyle sty  = pprUnique uniq
367
  | debugStyle sty = ppr_occ_name occ <> braces (hsep [pprNameSpaceBrief (occNameSpace occ), 
368
				 		       pprUnique uniq])
369 370 371
  | 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.
372
  | otherwise      = ppr_occ_name occ	-- User style
373

374 375
-- Like Internal, except that we only omit the unique in Iface style
pprSystem sty uniq occ
376
  | codeStyle sty  = pprUnique uniq
377
  | debugStyle sty = ppr_occ_name occ <> char '_' <> pprUnique uniq
378
		     <> braces (pprNameSpaceBrief (occNameSpace occ))
379
  | otherwise	   = ppr_occ_name occ <> char '_' <> pprUnique uniq
380 381 382
				-- If the tidy phase hasn't run, the OccName
				-- is unlikely to be informative (like 's'),
				-- so print the unique
383

384
ppr_occ_name occ = ftext (occNameFS occ)
385 386
	-- Don't use pprOccName; instead, just print the string of the OccName; 
	-- we print the namespace in the debug stuff above
387 388 389 390

-- 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))
391
\end{code}
392

393 394 395 396 397 398 399 400
%************************************************************************
%*									*
\subsection{Overloaded functions related to Names}
%*									*
%************************************************************************

\begin{code}
class NamedThing a where
401
    getOccName :: a -> OccName
402 403 404
    getName    :: a -> Name

    getOccName n = nameOccName (getName n)	-- Default method
405 406 407 408
\end{code}

\begin{code}
getSrcLoc	    :: NamedThing a => a -> SrcLoc
409
getOccString	    :: NamedThing a => a -> String
410

411
getSrcLoc	    = nameSrcLoc	   . getName
412
getOccString 	    = occNameString	   . getOccName
413 414
\end{code}