lots of portability changes (#1405)
[ghc-hetmet.git] / compiler / basicTypes / Name.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 %
5 \section[Name]{@Name@: to transmit name info from renamer to typechecker}
6
7 \begin{code}
8 {-# OPTIONS -w #-}
9 -- The above warning supression flag is a temporary kludge.
10 -- While working on this module you are encouraged to remove it and fix
11 -- any warnings in the module. See
12 --     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
13 -- for details
14
15 module Name (
16         -- Re-export the OccName stuff
17         module OccName,
18
19         -- The Name type
20         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,
32
33         nameSrcLoc, nameSrcSpan, pprNameLoc,
34
35         isSystemName, isInternalName, isExternalName,
36         isTyVarName, isTyConName, isWiredInName, isBuiltInSyntax,
37         wiredInNameTyThing_maybe, 
38         nameIsLocalOrFrom,
39         
40         -- Class NamedThing and overloaded friends
41         NamedThing(..),
42         getSrcLoc, getSrcSpan, getOccString
43     ) where
44
45 #include "HsVersions.h"
46
47 import {-# SOURCE #-} TypeRep( TyThing )
48
49 import OccName
50 import Module
51 import SrcLoc
52 import UniqFM
53 import Unique
54 import Maybes
55 import Binary
56 import FastMutInt
57 import FastTypes
58 import FastString
59 import Outputable
60
61 import Data.IORef
62 import Data.Array
63 \end{code}
64
65 %************************************************************************
66 %*                                                                      *
67 \subsection[Name-datatype]{The @Name@ datatype, and name construction}
68 %*                                                                      *
69 %************************************************************************
70  
71 \begin{code}
72 data Name = Name {
73                 n_sort :: NameSort,     -- What sort of name it is
74                 n_occ  :: !OccName,     -- Its occurrence name
75                 n_uniq :: FastInt,      -- UNPACK doesn't work, recursive type
76 --(note later when changing Int# -> FastInt: is that still true about UNPACK?)
77                 n_loc  :: !SrcSpan      -- Definition site
78             }
79
80 -- NOTE: we make the n_loc field strict to eliminate some potential
81 -- (and real!) space leaks, due to the fact that we don't look at
82 -- the SrcLoc in a Name all that often.
83
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                         -- defined in the module being compiled
92
93   | System              -- A system-defined Id or TyVar.  Typically the
94                         -- OccName is very uninformative (like 's')
95
96 data BuiltInSyntax = BuiltInSyntax | UserSyntax
97 -- BuiltInSyntax is for things like (:), [], tuples etc, 
98 -- which have special syntactic forms.  They aren't "in scope"
99 -- as such.
100 \end{code}
101
102 Notes about the NameSorts:
103
104 1.  Initially, top-level Ids (including locally-defined ones) get External names, 
105     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     appear in the .o file's symbol table.  They appear in the symbol table
109     in the form M.n.  If originally-local things have this property they
110     must be made @External@ first.
111
112 3.  In the tidy-core phase, a External that is not visible to an importer
113     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         a) has unique attached when printing dumps
117         b) unifier eliminates sys tyvars in favour of user provs where possible
118
119     Before anything gets printed in interface files or output code, it's
120     fed through a 'tidy' processor, which zaps the OccNames to have
121     unique names; and converts all sys-locals to user locals
122     If any desugarer sys-locals have survived that far, they get changed to
123     "ds1", "ds2", etc.
124
125 Built-in syntax => It's a syntactic form, not "in scope" (e.g. [])
126
127 Wired-in thing  => The thing (Id, TyCon) is fully known to the compiler, 
128                    not read from an interface file. 
129                    E.g. Bool, True, Int, Float, and many others
130
131 All built-in syntax is for wired-in things.
132
133 \begin{code}
134 nameUnique              :: Name -> Unique
135 nameOccName             :: Name -> OccName 
136 nameModule              :: Name -> Module
137 nameSrcLoc              :: Name -> SrcLoc
138 nameSrcSpan             :: Name -> SrcSpan
139
140 nameUnique  name = mkUniqueGrimily (iBox (n_uniq name))
141 nameOccName name = n_occ  name
142 nameSrcLoc  name = srcSpanStart (n_loc name)
143 nameSrcSpan name = n_loc  name
144 \end{code}
145
146 \begin{code}
147 nameIsLocalOrFrom :: Module -> Name -> Bool
148 isInternalName    :: Name -> Bool
149 isExternalName    :: Name -> Bool
150 isSystemName      :: Name -> Bool
151 isWiredInName     :: Name -> Bool
152
153 isWiredInName (Name {n_sort = WiredIn _ _ _}) = True
154 isWiredInName other                           = False
155
156 wiredInNameTyThing_maybe :: Name -> Maybe TyThing
157 wiredInNameTyThing_maybe (Name {n_sort = WiredIn _ thing _}) = Just thing
158 wiredInNameTyThing_maybe other                               = Nothing
159
160 isBuiltInSyntax (Name {n_sort = WiredIn _ _ BuiltInSyntax}) = True
161 isBuiltInSyntax other                                       = False
162
163 isExternalName (Name {n_sort = External _})    = True
164 isExternalName (Name {n_sort = WiredIn _ _ _}) = True
165 isExternalName other                           = False
166
167 isInternalName name = not (isExternalName name)
168
169 nameModule name = nameModule_maybe name `orElse` pprPanic "nameModule" (ppr name)
170 nameModule_maybe (Name { n_sort = External mod})    = Just mod
171 nameModule_maybe (Name { n_sort = WiredIn mod _ _}) = Just mod
172 nameModule_maybe name                               = Nothing
173
174 nameIsLocalOrFrom from name
175   | isExternalName name = from == nameModule name
176   | otherwise           = True
177
178 isTyVarName :: Name -> Bool
179 isTyVarName name = isTvOcc (nameOccName name)
180
181 isTyConName :: Name -> Bool
182 isTyConName name = isTcOcc (nameOccName name)
183
184 isSystemName (Name {n_sort = System}) = True
185 isSystemName other                    = False
186 \end{code}
187
188
189 %************************************************************************
190 %*                                                                      *
191 \subsection{Making names}
192 %*                                                                      *
193 %************************************************************************
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         -- NB: You might worry that after lots of huffing and
199         -- puffing we might end up with two local names with distinct
200         -- uniques, but the same OccName.  Indeed we can, but that's ok
201         --      * the insides of the compiler don't care: they use the Unique
202         --      * when printing for -ddump-xxx you can switch on -dppr-debug to get the
203         --        uniques if you get confused
204         --      * for interface files we tidyCore first, which puts the uniques
205         --        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 mkWiredInName :: Module -> OccName -> Unique -> TyThing -> BuiltInSyntax
213         -> Name
214 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 mkSystemVarName :: Unique -> FastString -> Name
224 mkSystemVarName uniq fs = mkSystemName uniq (mkVarOccFS fs)
225
226 mkSysTvName :: Unique -> FastString -> Name
227 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 mkTickBoxOpName :: Unique -> String -> Name
235 mkTickBoxOpName uniq str 
236    = Name { n_uniq = getKeyFastInt uniq, n_sort = Internal, 
237             n_occ = mkVarOcc str, n_loc = noSrcSpan }
238
239 mkIPName :: Unique -> OccName -> Name
240 mkIPName uniq occ
241   = Name { n_uniq = getKeyFastInt uniq,
242            n_sort = Internal,
243            n_occ  = occ,
244            n_loc = noSrcSpan }
245 \end{code}
246
247 \begin{code}
248 -- When we renumber/rename things, we need to be
249 -- able to change a Name's Unique to match the cached
250 -- 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 tidyNameOcc :: Name -> OccName -> Name
255 -- We set the OccName of a Name when tidying
256 -- In doing so, we change System --> Internal, so that when we print
257 -- it we don't get the unique by default.  It's tidy now!
258 tidyNameOcc name@(Name { n_sort = System }) occ = name { n_occ = occ, n_sort = Internal}
259 tidyNameOcc name                            occ = name { n_occ = occ }
260
261 localiseName :: Name -> Name
262 localiseName n = n { n_sort = Internal }
263 \end{code}
264
265
266 %************************************************************************
267 %*                                                                      *
268 \subsection{Predicates and selectors}
269 %*                                                                      *
270 %************************************************************************
271
272 \begin{code}
273 hashName :: Name -> Int         -- ToDo: should really be Word
274 hashName name = getKey (nameUnique name) + 1
275         -- The +1 avoids keys with lots of zeros in the ls bits, which 
276         -- interacts badly with the cheap and cheerful multiplication in
277         -- hashExpr
278 \end{code}
279
280
281 %************************************************************************
282 %*                                                                      *
283 \subsection[Name-instances]{Instance declarations}
284 %*                                                                      *
285 %************************************************************************
286
287 \begin{code}
288 cmpName n1 n2 = iBox (n_uniq n1) `compare` iBox (n_uniq n2)
289 \end{code}
290
291 \begin{code}
292 instance Eq Name where
293     a == b = case (a `compare` b) of { EQ -> True;  _ -> False }
294     a /= b = case (a `compare` b) of { EQ -> False; _ -> True }
295
296 instance Ord Name where
297     a <= b = case (a `compare` b) of { LT -> True;  EQ -> True;  GT -> False }
298     a <  b = case (a `compare` b) of { LT -> True;  EQ -> False; GT -> False }
299     a >= b = case (a `compare` b) of { LT -> False; EQ -> True;  GT -> True  }
300     a >  b = case (a `compare` b) of { LT -> False; EQ -> False; GT -> True  }
301     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 \end{code}
309
310 %************************************************************************
311 %*                                                                      *
312 \subsection{Binary}
313 %*                                                                      *
314 %************************************************************************
315
316 \begin{code}
317 instance Binary Name where
318    put_ bh name = do
319       case getUserData bh of { 
320         UserData { ud_symtab_map = symtab_map_ref,
321                    ud_symtab_next = symtab_next } -> do
322          symtab_map <- readIORef symtab_map_ref
323          case lookupUFM symtab_map name of
324            Just (off,_) -> put_ bh off
325            Nothing -> do
326               off <- readFastMutInt symtab_next
327               writeFastMutInt symtab_next (off+1)
328               writeIORef symtab_map_ref
329                   $! addToUFM symtab_map name (off,name)
330               put_ bh off          
331      }
332
333    get bh = do
334         i <- get bh
335         return $! (ud_symtab (getUserData bh) ! i)
336 \end{code}
337
338 %************************************************************************
339 %*                                                                      *
340 \subsection{Pretty printing}
341 %*                                                                      *
342 %************************************************************************
343
344 \begin{code}
345 instance Outputable Name where
346     ppr name = pprName name
347
348 instance OutputableBndr Name where
349     pprBndr _ name = pprName name
350
351 pprName name@(Name {n_sort = sort, n_uniq = u, n_occ = occ})
352   = getPprStyle $ \ sty ->
353     case sort of
354       WiredIn mod _ builtin   -> pprExternal sty uniq mod occ True  builtin
355       External mod            -> pprExternal sty uniq mod occ False UserSyntax
356       System                  -> pprSystem sty uniq occ
357       Internal                -> pprInternal sty uniq occ
358   where uniq = mkUniqueGrimily (iBox u)
359
360 pprExternal sty uniq mod occ is_wired is_builtin
361   | codeStyle sty        = ppr mod <> char '_' <> ppr_z_occ_name occ
362         -- In code style, always qualify
363         -- ToDo: maybe we could print all wired-in things unqualified
364         --       in code style, to reduce symbol table bloat?
365  | debugStyle sty       = ppr mod <> dot <> ppr_occ_name occ
366                 <> braces (hsep [if is_wired then ptext SLIT("(w)") else empty,
367                                  pprNameSpaceBrief (occNameSpace occ), 
368                                  pprUnique uniq])
369   | BuiltInSyntax <- is_builtin  = ppr_occ_name occ
370         -- never qualify builtin syntax
371   | NameQual modname <- qual_name = ppr modname <> dot <> ppr_occ_name occ
372         -- see HscTypes.mkPrintUnqualified and Outputable.QualifyName:
373   | NameNotInScope1 <- qual_name  = ppr mod <> dot <> ppr_occ_name occ
374   | NameNotInScope2 <- qual_name  = ppr (modulePackageId mod) <> char ':' <>
375                                     ppr (moduleName mod) <> dot <> ppr_occ_name occ
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   | dumpStyle sty  = ppr_occ_name occ <> char '_' <> pprUnique uniq
384                         -- For debug dumps, we're not necessarily dumping
385                         -- tidied code, so we need to print the uniques.
386   | otherwise      = ppr_occ_name occ   -- User style
387
388 -- Like Internal, except that we only omit the unique in Iface style
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                                 -- If the tidy phase hasn't run, the OccName
395                                 -- is unlikely to be informative (like 's'),
396                                 -- so print the unique
397
398 ppr_occ_name occ = ftext (occNameFS occ)
399         -- Don't use pprOccName; instead, just print the string of the OccName; 
400         -- we print the namespace in the debug stuff above
401
402 -- In code style, we Z-encode the strings.  The results of Z-encoding each FastString are
403 -- cached behind the scenes in the FastString implementation.
404 ppr_z_occ_name occ = ftext (zEncodeFS (occNameFS occ))
405
406 -- Prints (if mod information is available) "Defined at <loc>" or 
407 --  "Defined in <mod>" information for a Name.
408 pprNameLoc :: Name -> SDoc
409 pprNameLoc name
410   | isGoodSrcSpan loc = pprDefnLoc loc
411   | isInternalName name || isSystemName name 
412                       = ptext SLIT("<no location info>")
413   | otherwise         = ptext SLIT("Defined in ") <> ppr (nameModule name)
414   where loc = nameSrcSpan name
415 \end{code}
416
417 %************************************************************************
418 %*                                                                      *
419 \subsection{Overloaded functions related to Names}
420 %*                                                                      *
421 %************************************************************************
422
423 \begin{code}
424 class NamedThing a where
425     getOccName :: a -> OccName
426     getName    :: a -> Name
427
428     getOccName n = nameOccName (getName n)      -- Default method
429 \end{code}
430
431 \begin{code}
432 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 \end{code}
440