Name.lhs 13.7 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, nameSrcSpan,
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, getSrcSpan, 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  :: !SrcSpan	-- 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
\begin{code}
nameUnique		:: Name -> Unique
nameOccName		:: Name -> OccName 
nameModule		:: Name -> Module
nameSrcLoc		:: Name -> SrcLoc
130
nameSrcSpan		:: Name -> SrcSpan
131

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

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

145 146
isWiredInName (Name {n_sort = WiredIn _ _ _}) = True
isWiredInName other			      = False
147

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

152 153
isBuiltInSyntax (Name {n_sort = WiredIn _ _ BuiltInSyntax}) = True
isBuiltInSyntax other			 	            = False
154

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

159
isInternalName name = not (isExternalName name)
160

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

166 167 168 169
nameIsLocalOrFrom from name
  | isExternalName name = from == nameModule name
  | otherwise		= True

170 171
isTyVarName :: Name -> Bool
isTyVarName name = isTvOcc (nameOccName name)
172

173 174 175
isTyConName :: Name -> Bool
isTyConName name = isTcOcc (nameOccName name)

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


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

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

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

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

211
mkSystemName :: Unique -> OccName -> Name
212
mkSystemName uniq occ = Name { n_uniq = getKey# uniq, n_sort = System, 
213
			       n_occ = occ, n_loc = noSrcSpan }
214

215 216
mkSystemVarName :: Unique -> FastString -> Name
mkSystemVarName uniq fs = mkSystemName uniq (mkVarOccFS fs)
217

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

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

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

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

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

246 247 248 249 250 251
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 }
252

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


258 259 260 261 262 263 264
%************************************************************************
%*									*
\subsection{Predicates and selectors}
%*									*
%************************************************************************

\begin{code}
265 266 267 268 269
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
270 271
\end{code}

272

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

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

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

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

295
instance Uniquable Name where
296
    getUnique = nameUnique
297

298
instance NamedThing Name where
299
    getName n = n
300 301
\end{code}

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 327 328
%************************************************************************
%*									*
\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}
329

330 331 332 333 334
%************************************************************************
%*									*
\subsection{Pretty printing}
%*									*
%************************************************************************
335 336 337

\begin{code}
instance Outputable Name where
338 339
    ppr name = pprName name

340 341 342
instance OutputableBndr Name where
    pprBndr _ name = pprName name

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

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

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

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

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

-- 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))
393
\end{code}
394

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

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

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

\begin{code}
getSrcLoc	    :: NamedThing a => a -> SrcLoc
411
getSrcSpan	    :: NamedThing a => a -> SrcSpan
412
getOccString	    :: NamedThing a => a -> String
413

414
getSrcLoc	    = nameSrcLoc	   . getName
415
getSrcSpan	    = nameSrcSpan	   . getName
416
getOccString 	    = occNameString	   . getOccName
417 418
\end{code}