Name.lhs 14.8 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
57
import FastTypes
Simon Marlow's avatar
Simon Marlow committed
58
import FastString
59
import Outputable
60

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

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

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

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

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

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

102 103
Notes about the NameSorts:

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

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

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

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

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

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

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

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

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

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

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

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

167
isInternalName name = not (isExternalName name)
168

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

280

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

\begin{code}
288
cmpName n1 n2 = iBox (n_uniq n1) `compare` iBox (n_uniq n2)
289 290 291 292
\end{code}

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

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

303
instance Uniquable Name where
304
    getUnique = nameUnique
305

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

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 336
%************************************************************************
%*									*
\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}
337

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

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

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

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

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

379
pprInternal sty uniq occ
380
  | codeStyle sty  = pprUnique uniq
381
  | debugStyle sty = ppr_occ_name occ <> braces (hsep [pprNameSpaceBrief (occNameSpace occ), 
382
				 		       pprUnique uniq])
383 384 385
  | 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.
386
  | otherwise      = ppr_occ_name occ	-- User style
387

388 389
-- Like Internal, except that we only omit the unique in Iface style
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

398
ppr_occ_name occ = ftext (occNameFS occ)
399 400
	-- Don't use pprOccName; instead, just print the string of the OccName; 
	-- we print the namespace in the debug stuff above
401 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.
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 412
  | isInternalName name || isSystemName name 
                      = ptext SLIT("<no location info>")
413 414
  | otherwise         = ptext SLIT("Defined in ") <> ppr (nameModule name)
  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}