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
#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
50
import FastTypes
Simon Marlow's avatar
Simon Marlow committed
51
import FastString
52
import Outputable
53

Simon Marlow's avatar
Simon Marlow committed
54 55
import Data.IORef
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 69
		n_uniq :: FastInt,      -- UNPACK doesn't work, recursive type
--(note later when changing Int# -> FastInt: is that still true about UNPACK?)
70
		n_loc  :: !SrcSpan	-- Definition site
71 72
	    }

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

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

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

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

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

95 96
Notes about the NameSorts:

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

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

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

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

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

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

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

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

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

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

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

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

161
isInternalName name = not (isExternalName name)
162

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

169 170 171 172
nameIsLocalOrFrom from name
  | isExternalName name = from == nameModule name
  | otherwise		= True

173 174
isTyVarName :: Name -> Bool
isTyVarName name = isTvOcc (nameOccName name)
175

176 177 178
isTyConName :: Name -> Bool
isTyConName name = isTcOcc (nameOccName name)

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


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

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

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

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

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

218 219
mkSystemVarName :: Unique -> FastString -> Name
mkSystemVarName uniq fs = mkSystemName uniq (mkVarOccFS fs)
220

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

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

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

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

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

249 250 251 252 253 254
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 }
255

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


261 262 263 264 265 266 267
%************************************************************************
%*									*
\subsection{Predicates and selectors}
%*									*
%************************************************************************

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

275

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

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

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

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

299
instance Uniquable Name where
300
    getUnique = nameUnique
301

302
instance NamedThing Name where
303
    getName n = n
304 305
\end{code}

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 331 332
%************************************************************************
%*									*
\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}
333

334 335 336 337 338
%************************************************************************
%*									*
\subsection{Pretty printing}
%*									*
%************************************************************************
339 340 341

\begin{code}
instance Outputable Name where
342 343
    ppr name = pprName name

344 345 346
instance OutputableBndr Name where
    pprBndr _ name = pprName name

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

twanvl's avatar
twanvl committed
357
pprExternal :: PprStyle -> Unique -> Module -> OccName -> Bool -> BuiltInSyntax -> SDoc
358
pprExternal sty uniq mod occ is_wired is_builtin
Simon Marlow's avatar
Simon Marlow committed
359
  | codeStyle sty        = ppr mod <> char '_' <> ppr_z_occ_name occ
360 361 362
	-- 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
363 364 365 366
 | 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])
367
  | BuiltInSyntax <- is_builtin  = ppr_occ_name occ
368
	-- never qualify builtin syntax
369 370 371 372 373
  | 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
374
  | otherwise		          = ppr_occ_name occ
375
  where qual_name = qualName sty mod occ
376

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

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

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

-- 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
405
ppr_z_occ_name :: OccName -> SDoc
406
ppr_z_occ_name occ = ftext (zEncodeFS (occNameFS occ))
407

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

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

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

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

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

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