aa253cf87843e07daff5ed8d8634b7f43cc340d6
[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 import {-# SOURCE #-} TypeRep( TyThing )
39
40 import OccName
41 import Module
42 import SrcLoc
43 import UniqFM
44 import Unique
45 import Maybes
46 import Binary
47 import FastMutInt
48 import FastTypes
49 import FastString
50 import Outputable
51
52 import Data.IORef
53 import Data.Array
54 \end{code}
55
56 %************************************************************************
57 %*                                                                      *
58 \subsection[Name-datatype]{The @Name@ datatype, and name construction}
59 %*                                                                      *
60 %************************************************************************
61  
62 \begin{code}
63 data Name = Name {
64                 n_sort :: NameSort,     -- What sort of name it is
65                 n_occ  :: !OccName,     -- Its occurrence name
66                 n_uniq :: FastInt,      -- UNPACK doesn't work, recursive type
67 --(note later when changing Int# -> FastInt: is that still true about UNPACK?)
68                 n_loc  :: !SrcSpan      -- Definition site
69             }
70
71 -- NOTE: we make the n_loc field strict to eliminate some potential
72 -- (and real!) space leaks, due to the fact that we don't look at
73 -- the SrcLoc in a Name all that often.
74
75 data NameSort
76   = External Module
77  
78   | WiredIn Module TyThing BuiltInSyntax
79         -- A variant of External, for wired-in things
80
81   | Internal            -- A user-defined Id or TyVar
82                         -- defined in the module being compiled
83
84   | System              -- A system-defined Id or TyVar.  Typically the
85                         -- OccName is very uninformative (like 's')
86
87 data BuiltInSyntax = BuiltInSyntax | UserSyntax
88 -- BuiltInSyntax is for things like (:), [], tuples etc, 
89 -- which have special syntactic forms.  They aren't "in scope"
90 -- as such.
91 \end{code}
92
93 Notes about the NameSorts:
94
95 1.  Initially, top-level Ids (including locally-defined ones) get External names, 
96     and all other local Ids get Internal names
97
98 2.  Things with a External name are given C static labels, so they finally
99     appear in the .o file's symbol table.  They appear in the symbol table
100     in the form M.n.  If originally-local things have this property they
101     must be made @External@ first.
102
103 3.  In the tidy-core phase, a External that is not visible to an importer
104     is changed to Internal, and a Internal that is visible is changed to External
105
106 4.  A System Name differs in the following ways:
107         a) has unique attached when printing dumps
108         b) unifier eliminates sys tyvars in favour of user provs where possible
109
110     Before anything gets printed in interface files or output code, it's
111     fed through a 'tidy' processor, which zaps the OccNames to have
112     unique names; and converts all sys-locals to user locals
113     If any desugarer sys-locals have survived that far, they get changed to
114     "ds1", "ds2", etc.
115
116 Built-in syntax => It's a syntactic form, not "in scope" (e.g. [])
117
118 Wired-in thing  => The thing (Id, TyCon) is fully known to the compiler, 
119                    not read from an interface file. 
120                    E.g. Bool, True, Int, Float, and many others
121
122 All built-in syntax is for wired-in things.
123
124 \begin{code}
125 nameUnique              :: Name -> Unique
126 nameOccName             :: Name -> OccName 
127 nameModule              :: Name -> Module
128 nameSrcLoc              :: Name -> SrcLoc
129 nameSrcSpan             :: Name -> SrcSpan
130
131 nameUnique  name = mkUniqueGrimily (iBox (n_uniq name))
132 nameOccName name = n_occ  name
133 nameSrcLoc  name = srcSpanStart (n_loc name)
134 nameSrcSpan name = n_loc  name
135 \end{code}
136
137 \begin{code}
138 nameIsLocalOrFrom :: Module -> Name -> Bool
139 isInternalName    :: Name -> Bool
140 isExternalName    :: Name -> Bool
141 isSystemName      :: Name -> Bool
142 isWiredInName     :: Name -> Bool
143
144 isWiredInName (Name {n_sort = WiredIn _ _ _}) = True
145 isWiredInName _                               = False
146
147 wiredInNameTyThing_maybe :: Name -> Maybe TyThing
148 wiredInNameTyThing_maybe (Name {n_sort = WiredIn _ thing _}) = Just thing
149 wiredInNameTyThing_maybe _                                   = Nothing
150
151 isBuiltInSyntax :: Name -> Bool
152 isBuiltInSyntax (Name {n_sort = WiredIn _ _ BuiltInSyntax}) = True
153 isBuiltInSyntax _                                           = False
154
155 isExternalName (Name {n_sort = External _})    = True
156 isExternalName (Name {n_sort = WiredIn _ _ _}) = True
157 isExternalName _                               = False
158
159 isInternalName name = not (isExternalName name)
160
161 nameModule name = nameModule_maybe name `orElse` pprPanic "nameModule" (ppr name)
162 nameModule_maybe :: Name -> Maybe Module
163 nameModule_maybe (Name { n_sort = External mod})    = Just mod
164 nameModule_maybe (Name { n_sort = WiredIn mod _ _}) = Just mod
165 nameModule_maybe _                                  = Nothing
166
167 nameIsLocalOrFrom from name
168   | isExternalName name = from == nameModule name
169   | otherwise           = True
170
171 isTyVarName :: Name -> Bool
172 isTyVarName name = isTvOcc (nameOccName name)
173
174 isTyConName :: Name -> Bool
175 isTyConName name = isTcOcc (nameOccName name)
176
177 isSystemName (Name {n_sort = System}) = True
178 isSystemName _                        = False
179 \end{code}
180
181
182 %************************************************************************
183 %*                                                                      *
184 \subsection{Making names}
185 %*                                                                      *
186 %************************************************************************
187
188 \begin{code}
189 mkInternalName :: Unique -> OccName -> SrcSpan -> Name
190 mkInternalName uniq occ loc = Name { n_uniq = getKeyFastInt uniq, n_sort = Internal, n_occ = occ, n_loc = loc }
191         -- NB: You might worry that after lots of huffing and
192         -- puffing we might end up with two local names with distinct
193         -- uniques, but the same OccName.  Indeed we can, but that's ok
194         --      * the insides of the compiler don't care: they use the Unique
195         --      * when printing for -ddump-xxx you can switch on -dppr-debug to get the
196         --        uniques if you get confused
197         --      * for interface files we tidyCore first, which puts the uniques
198         --        into the print name (see setNameVisibility below)
199
200 mkExternalName :: Unique -> Module -> OccName -> SrcSpan -> Name
201 mkExternalName uniq mod occ loc 
202   = Name { n_uniq = getKeyFastInt uniq, n_sort = External mod,
203            n_occ = occ, n_loc = loc }
204
205 mkWiredInName :: Module -> OccName -> Unique -> TyThing -> BuiltInSyntax
206         -> Name
207 mkWiredInName mod occ uniq thing built_in
208   = Name { n_uniq = getKeyFastInt uniq,
209            n_sort = WiredIn mod thing built_in,
210            n_occ = occ, n_loc = wiredInSrcSpan }
211
212 mkSystemName :: Unique -> OccName -> Name
213 mkSystemName uniq occ = Name { n_uniq = getKeyFastInt uniq, n_sort = System, 
214                                n_occ = occ, n_loc = noSrcSpan }
215
216 mkSystemVarName :: Unique -> FastString -> Name
217 mkSystemVarName uniq fs = mkSystemName uniq (mkVarOccFS fs)
218
219 mkSysTvName :: Unique -> FastString -> Name
220 mkSysTvName uniq fs = mkSystemName uniq (mkOccNameFS tvName fs) 
221
222 mkFCallName :: Unique -> String -> Name
223         -- The encoded string completely describes the ccall
224 mkFCallName uniq str =  Name { n_uniq = getKeyFastInt uniq, n_sort = Internal, 
225                                n_occ = mkVarOcc str, n_loc = noSrcSpan }
226
227 mkTickBoxOpName :: Unique -> String -> Name
228 mkTickBoxOpName uniq str 
229    = Name { n_uniq = getKeyFastInt uniq, n_sort = Internal, 
230             n_occ = mkVarOcc str, n_loc = noSrcSpan }
231
232 mkIPName :: Unique -> OccName -> Name
233 mkIPName uniq occ
234   = Name { n_uniq = getKeyFastInt uniq,
235            n_sort = Internal,
236            n_occ  = occ,
237            n_loc = noSrcSpan }
238 \end{code}
239
240 \begin{code}
241 -- When we renumber/rename things, we need to be
242 -- able to change a Name's Unique to match the cached
243 -- one in the thing it's the name of.  If you know what I mean.
244 setNameUnique :: Name -> Unique -> Name
245 setNameUnique name uniq = name {n_uniq = getKeyFastInt uniq}
246
247 tidyNameOcc :: Name -> OccName -> Name
248 -- We set the OccName of a Name when tidying
249 -- In doing so, we change System --> Internal, so that when we print
250 -- it we don't get the unique by default.  It's tidy now!
251 tidyNameOcc name@(Name { n_sort = System }) occ = name { n_occ = occ, n_sort = Internal}
252 tidyNameOcc name                            occ = name { n_occ = occ }
253
254 localiseName :: Name -> Name
255 localiseName n = n { n_sort = Internal }
256 \end{code}
257
258
259 %************************************************************************
260 %*                                                                      *
261 \subsection{Predicates and selectors}
262 %*                                                                      *
263 %************************************************************************
264
265 \begin{code}
266 hashName :: Name -> Int         -- ToDo: should really be Word
267 hashName name = getKey (nameUnique name) + 1
268         -- The +1 avoids keys with lots of zeros in the ls bits, which 
269         -- interacts badly with the cheap and cheerful multiplication in
270         -- hashExpr
271 \end{code}
272
273
274 %************************************************************************
275 %*                                                                      *
276 \subsection[Name-instances]{Instance declarations}
277 %*                                                                      *
278 %************************************************************************
279
280 \begin{code}
281 cmpName :: Name -> Name -> Ordering
282 cmpName n1 n2 = iBox (n_uniq n1) `compare` iBox (n_uniq n2)
283 \end{code}
284
285 \begin{code}
286 instance Eq Name where
287     a == b = case (a `compare` b) of { EQ -> True;  _ -> False }
288     a /= b = case (a `compare` b) of { EQ -> False; _ -> True }
289
290 instance Ord Name where
291     a <= b = case (a `compare` b) of { LT -> True;  EQ -> True;  GT -> False }
292     a <  b = case (a `compare` b) of { LT -> True;  EQ -> False; GT -> False }
293     a >= b = case (a `compare` b) of { LT -> False; EQ -> True;  GT -> True  }
294     a >  b = case (a `compare` b) of { LT -> False; EQ -> False; GT -> True  }
295     compare a b = cmpName a b
296
297 instance Uniquable Name where
298     getUnique = nameUnique
299
300 instance NamedThing Name where
301     getName n = n
302 \end{code}
303
304 %************************************************************************
305 %*                                                                      *
306 \subsection{Binary}
307 %*                                                                      *
308 %************************************************************************
309
310 \begin{code}
311 instance Binary Name where
312    put_ bh name = do
313       case getUserData bh of { 
314         UserData { ud_symtab_map = symtab_map_ref,
315                    ud_symtab_next = symtab_next } -> do
316          symtab_map <- readIORef symtab_map_ref
317          case lookupUFM symtab_map name of
318            Just (off,_) -> put_ bh off
319            Nothing -> do
320               off <- readFastMutInt symtab_next
321               writeFastMutInt symtab_next (off+1)
322               writeIORef symtab_map_ref
323                   $! addToUFM symtab_map name (off,name)
324               put_ bh off          
325      }
326
327    get bh = do
328         i <- get bh
329         return $! (ud_symtab (getUserData bh) ! i)
330 \end{code}
331
332 %************************************************************************
333 %*                                                                      *
334 \subsection{Pretty printing}
335 %*                                                                      *
336 %************************************************************************
337
338 \begin{code}
339 instance Outputable Name where
340     ppr name = pprName name
341
342 instance OutputableBndr Name where
343     pprBndr _ name = pprName name
344
345 pprName :: Name -> SDoc
346 pprName (Name {n_sort = sort, n_uniq = u, n_occ = occ})
347   = getPprStyle $ \ sty ->
348     case sort of
349       WiredIn mod _ builtin   -> pprExternal sty uniq mod occ True  builtin
350       External mod            -> pprExternal sty uniq mod occ False UserSyntax
351       System                  -> pprSystem sty uniq occ
352       Internal                -> pprInternal sty uniq occ
353   where uniq = mkUniqueGrimily (iBox u)
354
355 pprExternal :: PprStyle -> Unique -> Module -> OccName -> Bool -> BuiltInSyntax -> SDoc
356 pprExternal sty uniq mod occ is_wired is_builtin
357   | codeStyle sty        = ppr mod <> char '_' <> ppr_z_occ_name occ
358         -- In code style, always qualify
359         -- ToDo: maybe we could print all wired-in things unqualified
360         --       in code style, to reduce symbol table bloat?
361  | debugStyle sty       = ppr mod <> dot <> ppr_occ_name occ
362                 <> braces (hsep [if is_wired then ptext (sLit "(w)") else empty,
363                                  pprNameSpaceBrief (occNameSpace occ), 
364                                  pprUnique uniq])
365   | BuiltInSyntax <- is_builtin  = ppr_occ_name occ
366         -- never qualify builtin syntax
367   | NameQual modname <- qual_name = ppr modname <> dot <> ppr_occ_name occ
368         -- see HscTypes.mkPrintUnqualified and Outputable.QualifyName:
369   | NameNotInScope1 <- qual_name  = ppr mod <> dot <> ppr_occ_name occ
370   | NameNotInScope2 <- qual_name  = ppr (modulePackageId mod) <> char ':' <>
371                                     ppr (moduleName mod) <> dot <> ppr_occ_name occ
372   | otherwise                     = ppr_occ_name occ
373   where qual_name = qualName sty mod occ
374
375 pprInternal :: PprStyle -> Unique -> OccName -> SDoc
376 pprInternal sty uniq occ
377   | codeStyle sty  = pprUnique uniq
378   | debugStyle sty = ppr_occ_name occ <> braces (hsep [pprNameSpaceBrief (occNameSpace occ), 
379                                                        pprUnique uniq])
380   | dumpStyle sty  = ppr_occ_name occ <> char '_' <> pprUnique uniq
381                         -- For debug dumps, we're not necessarily dumping
382                         -- tidied code, so we need to print the uniques.
383   | otherwise      = ppr_occ_name occ   -- User style
384
385 -- Like Internal, except that we only omit the unique in Iface style
386 pprSystem :: PprStyle -> Unique -> OccName -> SDoc
387 pprSystem sty uniq occ
388   | codeStyle sty  = pprUnique uniq
389   | debugStyle sty = ppr_occ_name occ <> char '_' <> pprUnique uniq
390                      <> braces (pprNameSpaceBrief (occNameSpace occ))
391   | otherwise      = ppr_occ_name occ <> char '_' <> pprUnique uniq
392                                 -- If the tidy phase hasn't run, the OccName
393                                 -- is unlikely to be informative (like 's'),
394                                 -- so print the unique
395
396 ppr_occ_name :: OccName -> SDoc
397 ppr_occ_name occ = ftext (occNameFS occ)
398         -- Don't use pprOccName; instead, just print the string of the OccName; 
399         -- we print the namespace in the debug stuff above
400
401 -- In code style, we Z-encode the strings.  The results of Z-encoding each FastString are
402 -- cached behind the scenes in the FastString implementation.
403 ppr_z_occ_name :: OccName -> SDoc
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