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