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