Name.lhs 14.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
%
\section[Name]{@Name@: to transmit name info from renamer to typechecker}

\begin{code}
8
{-# OPTIONS -w #-}
9 10 11
-- The above warning supression flag is a temporary kludge.
-- While working on this module you are encouraged to remove it and fix
-- any warnings in the module. See
Ian Lynagh's avatar
Ian Lynagh committed
12
--     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
13 14
-- for details

15
module Name (
16 17
	-- Re-export the OccName stuff
	module OccName,
18

19 20
	-- The Name type
	Name,					-- Abstract
21
	BuiltInSyntax(..), 
22
	mkInternalName, mkSystemName,
23
	mkSystemVarName, mkSysTvName, 
24
	mkFCallName, mkIPName,
25
        mkTickBoxOpName,
26
	mkExternalName, mkWiredInName,
27

28
	nameUnique, setNameUnique,
29
	nameOccName, nameModule, nameModule_maybe,
30
	tidyNameOcc, 
31
	hashName, localiseName,
sof's avatar
sof committed
32

33
	nameSrcLoc, nameSrcSpan, pprNameLoc,
34

35
	isSystemName, isInternalName, isExternalName,
36
	isTyVarName, isTyConName, isWiredInName, isBuiltInSyntax,
37
	wiredInNameTyThing_maybe, 
38
	nameIsLocalOrFrom,
39
	
40 41
	-- Class NamedThing and overloaded friends
	NamedThing(..),
42
	getSrcLoc, getSrcSpan, getOccString
43
    ) where
44

45 46
#include "HsVersions.h"

47 48
import {-# SOURCE #-} TypeRep( TyThing )

Simon Marlow's avatar
Simon Marlow committed
49 50 51 52 53 54
import OccName
import Module
import SrcLoc
import UniqFM
import Unique
import Maybes
55 56
import Binary
import FastMutInt
Simon Marlow's avatar
Simon Marlow committed
57
import FastString
58
import Outputable
59

Simon Marlow's avatar
Simon Marlow committed
60 61 62
import Data.IORef
import GHC.Exts
import Data.Array
63 64
\end{code}

65 66
%************************************************************************
%*									*
67
\subsection[Name-datatype]{The @Name@ datatype, and name construction}
68 69
%*									*
%************************************************************************
70
 
71
\begin{code}
72 73
data Name = Name {
		n_sort :: NameSort,	-- What sort of name it is
74
		n_occ  :: !OccName,	-- Its occurrence name
75
		n_uniq :: Int#,         -- UNPACK doesn't work, recursive type
76
		n_loc  :: !SrcSpan	-- Definition site
77 78
	    }

79 80 81 82
-- 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.

83
data NameSort
84
  = External Module
85
 
86
  | WiredIn Module TyThing BuiltInSyntax
87
	-- A variant of External, for wired-in things
88

89
  | Internal		-- A user-defined Id or TyVar
90 91 92 93
			-- defined in the module being compiled

  | System		-- A system-defined Id or TyVar.  Typically the
			-- OccName is very uninformative (like 's')
94 95 96 97 98

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

101 102
Notes about the NameSorts:

103 104
1.  Initially, top-level Ids (including locally-defined ones) get External names, 
    and all other local Ids get Internal names
105

106
2.  Things with a External name are given C static labels, so they finally
107 108
    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
109
    must be made @External@ first.
110

111 112
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
113 114

4.  A System Name differs in the following ways:
115 116 117 118 119 120 121 122 123
	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.

124 125 126 127 128 129 130 131
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.

132 133 134 135 136
\begin{code}
nameUnique		:: Name -> Unique
nameOccName		:: Name -> OccName 
nameModule		:: Name -> Module
nameSrcLoc		:: Name -> SrcLoc
137
nameSrcSpan		:: Name -> SrcSpan
138

139
nameUnique  name = mkUniqueGrimily (I# (n_uniq name))
140
nameOccName name = n_occ  name
141 142
nameSrcLoc  name = srcSpanStart (n_loc name)
nameSrcSpan name = n_loc  name
143 144 145
\end{code}

\begin{code}
146 147 148 149
nameIsLocalOrFrom :: Module -> Name -> Bool
isInternalName	  :: Name -> Bool
isExternalName	  :: Name -> Bool
isSystemName	  :: Name -> Bool
150 151
isWiredInName	  :: Name -> Bool

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

155
wiredInNameTyThing_maybe :: Name -> Maybe TyThing
156 157
wiredInNameTyThing_maybe (Name {n_sort = WiredIn _ thing _}) = Just thing
wiredInNameTyThing_maybe other				     = Nothing
158

159 160
isBuiltInSyntax (Name {n_sort = WiredIn _ _ BuiltInSyntax}) = True
isBuiltInSyntax other			 	            = False
161

162 163 164
isExternalName (Name {n_sort = External _})    = True
isExternalName (Name {n_sort = WiredIn _ _ _}) = True
isExternalName other                           = False
165

166
isInternalName name = not (isExternalName name)
167

168
nameModule name = nameModule_maybe name `orElse` pprPanic "nameModule" (ppr name)
169 170 171
nameModule_maybe (Name { n_sort = External mod})    = Just mod
nameModule_maybe (Name { n_sort = WiredIn mod _ _}) = Just mod
nameModule_maybe name				    = Nothing
172

173 174 175 176
nameIsLocalOrFrom from name
  | isExternalName name = from == nameModule name
  | otherwise		= True

177 178
isTyVarName :: Name -> Bool
isTyVarName name = isTvOcc (nameOccName name)
179

180 181 182
isTyConName :: Name -> Bool
isTyConName name = isTcOcc (nameOccName name)

183 184 185 186 187 188 189 190 191 192
isSystemName (Name {n_sort = System}) = True
isSystemName other		      = False
\end{code}


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

194
\begin{code}
195
mkInternalName :: Unique -> OccName -> SrcSpan -> Name
196
mkInternalName uniq occ loc = Name { n_uniq = getKey# uniq, n_sort = Internal, n_occ = occ, n_loc = loc }
197 198 199 200 201 202 203 204
	-- 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)
205

206
mkExternalName :: Unique -> Module -> OccName -> SrcSpan -> Name
207 208
mkExternalName uniq mod occ loc 
  = Name { n_uniq = getKey# uniq, n_sort = External mod,
209
           n_occ = occ, n_loc = loc }
210

211 212 213
mkWiredInName :: Module -> OccName -> Unique -> TyThing -> BuiltInSyntax
        -> Name
mkWiredInName mod occ uniq thing built_in
214
  = Name { n_uniq = getKey# uniq,
215
	   n_sort = WiredIn mod thing built_in,
216
	   n_occ = occ, n_loc = wiredInSrcSpan }
217

218
mkSystemName :: Unique -> OccName -> Name
219
mkSystemName uniq occ = Name { n_uniq = getKey# uniq, n_sort = System, 
220
			       n_occ = occ, n_loc = noSrcSpan }
221

222 223
mkSystemVarName :: Unique -> FastString -> Name
mkSystemVarName uniq fs = mkSystemName uniq (mkVarOccFS fs)
224

225 226
mkSysTvName :: Unique -> FastString -> Name
mkSysTvName uniq fs = mkSystemName uniq (mkOccNameFS tvName fs) 
227

228
mkFCallName :: Unique -> String -> Name
229
	-- The encoded string completely describes the ccall
230
mkFCallName uniq str =  Name { n_uniq = getKey# uniq, n_sort = Internal, 
231
			       n_occ = mkVarOcc str, n_loc = noSrcSpan }
232

233 234 235
mkTickBoxOpName :: Unique -> String -> Name
mkTickBoxOpName uniq str 
   = Name { n_uniq = getKey# uniq, n_sort = Internal, 
236
	    n_occ = mkVarOcc str, n_loc = noSrcSpan }
237

238 239
mkIPName :: Unique -> OccName -> Name
mkIPName uniq occ
240
  = Name { n_uniq = getKey# uniq,
241
	   n_sort = Internal,
242
	   n_occ  = occ,
243
	   n_loc = noSrcSpan }
244 245 246
\end{code}

\begin{code}
247 248 249
-- 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.
250 251
setNameUnique :: Name -> Unique -> Name
setNameUnique name uniq = name {n_uniq = getKey# uniq}
252

253 254 255 256 257 258
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 }
259

260
localiseName :: Name -> Name
261
localiseName n = n { n_sort = Internal }
sof's avatar
sof committed
262 263 264
\end{code}


265 266 267 268 269 270 271
%************************************************************************
%*									*
\subsection{Predicates and selectors}
%*									*
%************************************************************************

\begin{code}
272 273 274 275 276
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
277 278
\end{code}

279

280 281 282 283 284 285 286
%************************************************************************
%*									*
\subsection[Name-instances]{Instance declarations}
%*									*
%************************************************************************

\begin{code}
287
cmpName n1 n2 = I# (n_uniq n1) `compare` I# (n_uniq n2)
288 289 290 291
\end{code}

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

instance Ord Name where
296 297
    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 }
298 299 300
    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
301

302
instance Uniquable Name where
303
    getUnique = nameUnique
304

305
instance NamedThing Name where
306
    getName n = n
307 308
\end{code}

309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
%************************************************************************
%*									*
\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}
336

337 338 339 340 341
%************************************************************************
%*									*
\subsection{Pretty printing}
%*									*
%************************************************************************
342 343 344

\begin{code}
instance Outputable Name where
345 346
    ppr name = pprName name

347 348 349
instance OutputableBndr Name where
    pprBndr _ name = pprName name

350
pprName name@(Name {n_sort = sort, n_uniq = u#, n_occ = occ})
351
  = getPprStyle $ \ sty ->
352
    case sort of
353 354
      WiredIn mod _ builtin   -> pprExternal sty uniq mod occ True  builtin
      External mod  	      -> pprExternal sty uniq mod occ False UserSyntax
355 356
      System   		      -> pprSystem sty uniq occ
      Internal    	      -> pprInternal sty uniq occ
357
  where uniq = mkUniqueGrimily (I# u#)
358

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

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

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 403

-- 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))
404 405 406 407 408 409 410

-- Prints "Defined at <loc>" or "Defined in <mod>" information for a Name.
pprNameLoc :: Name -> SDoc
pprNameLoc name
  | isGoodSrcSpan loc = pprDefnLoc loc
  | otherwise         = ptext SLIT("Defined in ") <> ppr (nameModule name)
  where loc = nameSrcSpan name
411
\end{code}
412

413 414 415 416 417 418 419 420
%************************************************************************
%*									*
\subsection{Overloaded functions related to Names}
%*									*
%************************************************************************

\begin{code}
class NamedThing a where
421
    getOccName :: a -> OccName
422 423 424
    getName    :: a -> Name

    getOccName n = nameOccName (getName n)	-- Default method
425 426 427 428
\end{code}

\begin{code}
getSrcLoc	    :: NamedThing a => a -> SrcLoc
429
getSrcSpan	    :: NamedThing a => a -> SrcSpan
430
getOccString	    :: NamedThing a => a -> String
431

432
getSrcLoc	    = nameSrcLoc	   . getName
433
getSrcSpan	    = nameSrcSpan	   . getName
434
getOccString 	    = occNameString	   . getOccName
435 436
\end{code}