Name.lhs 15 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, pprNameLoc,
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
import {-# SOURCE #-} TypeRep( TyThing )

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

Simon Marlow's avatar
Simon Marlow committed
52 53
import Data.IORef
import Data.Array
54 55
\end{code}

56 57
%************************************************************************
%*									*
58
\subsection[Name-datatype]{The @Name@ datatype, and name construction}
59 60
%*									*
%************************************************************************
61
 
62
\begin{code}
63 64
data Name = Name {
		n_sort :: NameSort,	-- What sort of name it is
65
		n_occ  :: !OccName,	-- Its occurrence name
66 67
		n_uniq :: FastInt,      -- UNPACK doesn't work, recursive type
--(note later when changing Int# -> FastInt: is that still true about UNPACK?)
68
		n_loc  :: !SrcSpan	-- 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
\begin{code}
nameUnique		:: Name -> Unique
nameOccName		:: Name -> OccName 
nameModule		:: Name -> Module
nameSrcLoc		:: Name -> SrcLoc
129
nameSrcSpan		:: Name -> SrcSpan
130

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

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

144
isWiredInName (Name {n_sort = WiredIn _ _ _}) = True
twanvl's avatar
twanvl committed
145
isWiredInName _                               = False
146

147
wiredInNameTyThing_maybe :: Name -> Maybe TyThing
148
wiredInNameTyThing_maybe (Name {n_sort = WiredIn _ thing _}) = Just thing
twanvl's avatar
twanvl committed
149
wiredInNameTyThing_maybe _                                   = Nothing
150

twanvl's avatar
twanvl committed
151
isBuiltInSyntax :: Name -> Bool
152
isBuiltInSyntax (Name {n_sort = WiredIn _ _ BuiltInSyntax}) = True
twanvl's avatar
twanvl committed
153
isBuiltInSyntax _                                           = False
154

155 156
isExternalName (Name {n_sort = External _})    = True
isExternalName (Name {n_sort = WiredIn _ _ _}) = True
twanvl's avatar
twanvl committed
157
isExternalName _                               = False
158

159
isInternalName name = not (isExternalName name)
160

161
nameModule name = nameModule_maybe name `orElse` pprPanic "nameModule" (ppr name)
twanvl's avatar
twanvl committed
162
nameModule_maybe :: Name -> Maybe Module
163 164
nameModule_maybe (Name { n_sort = External mod})    = Just mod
nameModule_maybe (Name { n_sort = WiredIn mod _ _}) = Just mod
twanvl's avatar
twanvl committed
165
nameModule_maybe _                                  = Nothing
166

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

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

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

177
isSystemName (Name {n_sort = System}) = True
twanvl's avatar
twanvl committed
178
isSystemName _                        = False
179 180 181 182 183 184 185 186
\end{code}


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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

273

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

\begin{code}
twanvl's avatar
twanvl committed
281
cmpName :: Name -> Name -> Ordering
282
cmpName n1 n2 = iBox (n_uniq n1) `compare` iBox (n_uniq n2)
283 284 285 286
\end{code}

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

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

297
instance Uniquable Name where
298
    getUnique = nameUnique
299

300
instance NamedThing Name where
301
    getName n = n
302 303
\end{code}

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 329 330
%************************************************************************
%*									*
\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}
331

332 333 334 335 336
%************************************************************************
%*									*
\subsection{Pretty printing}
%*									*
%************************************************************************
337 338 339

\begin{code}
instance Outputable Name where
340 341
    ppr name = pprName name

342 343 344
instance OutputableBndr Name where
    pprBndr _ name = pprName name

twanvl's avatar
twanvl committed
345 346
pprName :: Name -> SDoc
pprName (Name {n_sort = sort, n_uniq = u, n_occ = occ})
347
  = getPprStyle $ \ sty ->
348
    case sort of
349 350
      WiredIn mod _ builtin   -> pprExternal sty uniq mod occ True  builtin
      External mod  	      -> pprExternal sty uniq mod occ False UserSyntax
351 352
      System   		      -> pprSystem sty uniq occ
      Internal    	      -> pprInternal sty uniq occ
353
  where uniq = mkUniqueGrimily (iBox u)
354

twanvl's avatar
twanvl committed
355
pprExternal :: PprStyle -> Unique -> Module -> OccName -> Bool -> BuiltInSyntax -> SDoc
356
pprExternal sty uniq mod occ is_wired is_builtin
Simon Marlow's avatar
Simon Marlow committed
357
  | codeStyle sty        = ppr mod <> char '_' <> ppr_z_occ_name occ
358 359 360
	-- 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
361
 | debugStyle sty       = ppr mod <> dot <> ppr_occ_name occ
Ian Lynagh's avatar
Ian Lynagh committed
362
		<> braces (hsep [if is_wired then ptext (sLit "(w)") else empty,
Simon Marlow's avatar
Simon Marlow committed
363 364
				 pprNameSpaceBrief (occNameSpace occ), 
		 		 pprUnique uniq])
365
  | BuiltInSyntax <- is_builtin  = ppr_occ_name occ
366
	-- never qualify builtin syntax
367 368 369 370 371
  | NameQual modname <- qual_name = ppr modname <> dot <> ppr_occ_name occ
        -- see HscTypes.mkPrintUnqualified and Outputable.QualifyName:
  | NameNotInScope1 <- qual_name  = ppr mod <> dot <> ppr_occ_name occ
  | NameNotInScope2 <- qual_name  = ppr (modulePackageId mod) <> char ':' <>
                                    ppr (moduleName mod) <> dot <> ppr_occ_name occ
Simon Marlow's avatar
Simon Marlow committed
372
  | otherwise		          = ppr_occ_name occ
373
  where qual_name = qualName sty mod occ
374

twanvl's avatar
twanvl committed
375
pprInternal :: PprStyle -> Unique -> OccName -> SDoc
376
pprInternal sty uniq occ
377
  | codeStyle sty  = pprUnique uniq
378
  | debugStyle sty = ppr_occ_name occ <> braces (hsep [pprNameSpaceBrief (occNameSpace occ), 
379
				 		       pprUnique uniq])
380 381 382
  | 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.
383
  | otherwise      = ppr_occ_name occ	-- User style
384

385
-- Like Internal, except that we only omit the unique in Iface style
twanvl's avatar
twanvl committed
386
pprSystem :: PprStyle -> Unique -> OccName -> SDoc
387
pprSystem sty uniq occ
388
  | codeStyle sty  = pprUnique uniq
389
  | debugStyle sty = ppr_occ_name occ <> char '_' <> pprUnique uniq
390
		     <> braces (pprNameSpaceBrief (occNameSpace occ))
391
  | otherwise	   = ppr_occ_name occ <> char '_' <> pprUnique uniq
392 393 394
				-- If the tidy phase hasn't run, the OccName
				-- is unlikely to be informative (like 's'),
				-- so print the unique
395

twanvl's avatar
twanvl committed
396
ppr_occ_name :: OccName -> SDoc
397
ppr_occ_name occ = ftext (occNameFS occ)
398 399
	-- Don't use pprOccName; instead, just print the string of the OccName; 
	-- we print the namespace in the debug stuff above
400 401 402

-- In code style, we Z-encode the strings.  The results of Z-encoding each FastString are
-- cached behind the scenes in the FastString implementation.
twanvl's avatar
twanvl committed
403
ppr_z_occ_name :: OccName -> SDoc
404
ppr_z_occ_name occ = ftext (zEncodeFS (occNameFS occ))
405

406 407
-- Prints (if mod information is available) "Defined at <loc>" or 
--  "Defined in <mod>" information for a Name.
408 409 410
pprNameLoc :: Name -> SDoc
pprNameLoc name
  | isGoodSrcSpan loc = pprDefnLoc loc
411
  | isInternalName name || isSystemName name 
Ian Lynagh's avatar
Ian Lynagh committed
412 413
                      = ptext (sLit "<no location info>")
  | otherwise         = ptext (sLit "Defined in ") <> ppr (nameModule name)
414
  where loc = nameSrcSpan name
415
\end{code}
416

417 418 419 420 421 422 423 424
%************************************************************************
%*									*
\subsection{Overloaded functions related to Names}
%*									*
%************************************************************************

\begin{code}
class NamedThing a where
425
    getOccName :: a -> OccName
426 427 428
    getName    :: a -> Name

    getOccName n = nameOccName (getName n)	-- Default method
429 430 431 432
\end{code}

\begin{code}
getSrcLoc	    :: NamedThing a => a -> SrcLoc
433
getSrcSpan	    :: NamedThing a => a -> SrcSpan
434
getOccString	    :: NamedThing a => a -> String
435

436
getSrcLoc	    = nameSrcLoc	   . getName
437
getSrcSpan	    = nameSrcSpan	   . getName
438
getOccString 	    = occNameString	   . getOccName
439 440
\end{code}