7747daf66e765add9309d4b8e5740680f0771f20
[ghc-hetmet.git] / ghc / compiler / basicTypes / Name.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
3 %
4 \section[Name]{@Name@: to transmit name info from renamer to typechecker}
5
6 \begin{code}
7 #include "HsVersions.h"
8
9 module Name (
10         Module(..),
11
12         OrigName(..), -- glorified pair
13         qualToOrigName, -- a Qual to an OrigName
14
15         RdrName(..),
16         preludeQual,
17         moduleNamePair,
18         isUnqual,
19         isQual,
20         isRdrLexCon, isRdrLexConOrSpecial,
21         appendRdr,
22         showRdr,
23         cmpRdr,
24
25         Name,
26         Provenance,
27         mkLocalName, isLocalName, 
28         mkTopLevName, mkImportedName, oddlyImportedName,
29         mkImplicitName, isImplicitName,
30         mkPrimitiveName, mkWiredInName,
31         mkCompoundName, mkCompoundName2,
32
33         mkFunTyConName, mkTupleDataConName, mkTupleTyConName,
34         mkTupNameStr,
35
36         NamedThing(..), -- class
37         ExportFlag(..),
38         isExported{-overloaded-}, exportFlagOn{-not-},
39
40         nameUnique, changeUnique,
41         nameOccName,
42 --      nameOrigName, : not exported
43         nameExportFlag,
44         nameSrcLoc,
45         nameImpLocs,
46         nameImportFlag,
47         isLocallyDefinedName, isWiredInName,
48
49         origName, moduleOf, nameOf,
50         getOccName, getExportFlag,
51         getSrcLoc, getImpLocs,
52         isLocallyDefined,
53         getLocalName,
54
55         isSymLexeme, pprSym, pprNonSym,
56         isLexCon, isLexVar, isLexId, isLexSym, isLexSpecialSym,
57         isLexConId, isLexConSym, isLexVarId, isLexVarSym
58     ) where
59
60 IMP_Ubiq()
61
62 import CmdLineOpts      ( maybe_CompilingPrelude )
63 import CStrings         ( identToC, cSEP )
64 import Outputable       ( Outputable(..) )
65 import PprStyle         ( PprStyle(..), codeStyle )
66 import PrelMods         ( pRELUDE )
67 import Pretty
68 import SrcLoc           ( mkBuiltinSrcLoc, mkUnknownSrcLoc )
69 import Unique           ( funTyConKey, mkTupleDataConUnique, mkTupleTyConUnique,
70                           pprUnique, Unique
71                         )
72 import Util             ( thenCmp, _CMP_STRING_, nOfThem, panic, assertPanic )
73
74 #ifdef REALLY_HASKELL_1_3
75 ord = fromEnum :: Char -> Int
76 #endif
77 \end{code}
78
79 %************************************************************************
80 %*                                                                      *
81 \subsection[RdrName]{The @RdrName@ datatype; names read from files}
82 %*                                                                      *
83 %************************************************************************
84
85 \begin{code}
86 type Module = FAST_STRING
87
88 data OrigName = OrigName Module FAST_STRING
89
90 qualToOrigName (Qual m n) = OrigName m n
91
92 data RdrName
93   = Unqual FAST_STRING
94   | Qual   Module FAST_STRING
95
96 preludeQual n = Qual pRELUDE n
97
98 moduleNamePair (Qual m n) = (m, n)  -- we make *no* claim whether this
99                                     -- constitutes an original name or
100                                     -- an occurrence name, or anything else
101
102 isUnqual (Unqual _) = True
103 isUnqual (Qual _ _) = False
104
105 isQual (Unqual _) = False
106 isQual (Qual _ _) = True
107
108 isRdrLexCon (Unqual n) = isLexCon n
109 isRdrLexCon (Qual m n) = isLexCon n
110
111 isRdrLexConOrSpecial (Unqual n) = isLexCon n || isLexSpecialSym n
112 isRdrLexConOrSpecial (Qual m n) = isLexCon n || isLexSpecialSym n
113
114 appendRdr (Unqual n) str = Unqual (n _APPEND_ str)
115 appendRdr (Qual m n) str = Qual m (n _APPEND_ str)
116
117 cmpRdr (Unqual  n1) (Unqual  n2) = _CMP_STRING_ n1 n2
118 cmpRdr (Unqual  n1) (Qual m2 n2) = LT_
119 cmpRdr (Qual m1 n1) (Unqual  n2) = GT_
120 cmpRdr (Qual m1 n1) (Qual m2 n2) = _CMP_STRING_ n1 n2 `thenCmp` _CMP_STRING_ m1 m2
121                                    -- always compare module-names *second*
122
123 cmpOrig (OrigName m1 n1) (OrigName m2 n2)
124   = _CMP_STRING_ n1 n2 `thenCmp` _CMP_STRING_ m1 m2 -- again; module-names *second*
125
126 instance Eq RdrName where
127     a == b = case (a `cmp` b) of { EQ_ -> True;  _ -> False }
128     a /= b = case (a `cmp` b) of { EQ_ -> False; _ -> True }
129
130 instance Ord RdrName where
131     a <= b = case (a `cmp` b) of { LT_ -> True;  EQ_ -> True;  GT__ -> False }
132     a <  b = case (a `cmp` b) of { LT_ -> True;  EQ_ -> False; GT__ -> False }
133     a >= b = case (a `cmp` b) of { LT_ -> False; EQ_ -> True;  GT__ -> True  }
134     a >  b = case (a `cmp` b) of { LT_ -> False; EQ_ -> False; GT__ -> True  }
135
136 instance Ord3 RdrName where
137     cmp = cmpRdr
138
139 instance NamedThing RdrName where
140     -- We're sorta faking it here
141     getName (Unqual n)
142       = Local u n True locn
143       where
144         u    = panic "NamedThing.RdrName:Unique1"
145         locn = panic "NamedThing.RdrName:locn"
146
147     getName rdr_name@(Qual m n)
148       = Global u m n prov ex [rdr_name]
149       where
150         u    = panic "NamedThing.RdrName:Unique"
151         prov = panic "NamedThing.RdrName:Provenance"
152         ex   = panic "NamedThing.RdrName:ExportFlag"
153
154 instance Outputable RdrName where
155     ppr sty (Unqual n) = pp_name sty n
156     ppr sty (Qual m n) = ppBeside (pp_mod sty m) (pp_name sty n)
157
158 pp_mod PprForC             m = ppBesides [identToC m, ppPStr cSEP]
159 pp_mod (PprForAsm False _) m = ppBesides [identToC m, ppPStr cSEP]
160 pp_mod (PprForAsm True  _) m = ppBesides [ppPStr cSEP, identToC m, ppPStr cSEP]
161 pp_mod _                   m = ppBesides [ppPStr m, ppChar '.']
162
163 pp_name sty n | codeStyle sty = identToC n
164               | otherwise     = ppPStr n              
165
166 showRdr sty rdr = ppShow 100 (ppr sty rdr)
167
168 -------------------------
169 instance Eq OrigName where
170     a == b = case (a `cmp` b) of { EQ_ -> True;  _ -> False }
171     a /= b = case (a `cmp` b) of { EQ_ -> False; _ -> True }
172
173 instance Ord OrigName where
174     a <= b = case (a `cmp` b) of { LT_ -> True;  EQ_ -> True;  GT__ -> False }
175     a <  b = case (a `cmp` b) of { LT_ -> True;  EQ_ -> False; GT__ -> False }
176     a >= b = case (a `cmp` b) of { LT_ -> False; EQ_ -> True;  GT__ -> True  }
177     a >  b = case (a `cmp` b) of { LT_ -> False; EQ_ -> False; GT__ -> True  }
178
179 instance Ord3 OrigName where
180     cmp = cmpOrig
181
182 instance NamedThing OrigName where -- faking it
183     getName (OrigName m n) = getName (Qual m n)
184
185 instance Outputable OrigName where -- ditto
186     ppr sty (OrigName m n) = ppr sty (Qual m n)
187 \end{code}
188
189 %************************************************************************
190 %*                                                                      *
191 \subsection[Name-datatype]{The @Name@ datatype}
192 %*                                                                      *
193 %************************************************************************
194
195 \begin{code}
196 data Name
197   = Local    Unique
198              FAST_STRING
199              Bool       -- True <=> emphasize Unique when
200                         -- printing; this is just an esthetic thing...
201              SrcLoc
202
203   | Global   Unique
204              Module     -- original name
205              FAST_STRING
206              Provenance -- where it came from
207              ExportFlag -- is it exported?
208              [RdrName]  -- ordered occurrence names (usually just one);
209                         -- first may be *un*qual.
210
211 data Provenance
212   = LocalDef SrcLoc     -- locally defined; give its source location
213                         
214   | Imported ExportFlag -- how it was imported
215              SrcLoc     -- *original* source location
216              [SrcLoc]   -- any import source location(s)
217
218   | Implicit
219   | Primitive           -- really and truly primitive thing (not
220                         -- definable in Haskell)
221   | WiredIn  Bool       -- something defined in Haskell; True <=>
222                         -- definition is in the module in question;
223                         -- this probably comes from the -fcompiling-prelude=...
224                         -- flag.
225 \end{code}
226
227 \begin{code}
228 mkLocalName = Local
229
230 mkTopLevName   u (OrigName m n) locn exp occs = Global u m n (LocalDef locn) exp occs
231 mkImportedName u (OrigName m n) imp locn imp_locs exp occs = Global u m n (Imported imp locn imp_locs) exp occs
232
233 mkImplicitName :: Unique -> OrigName -> Name
234 mkImplicitName u (OrigName m n) = Global u m n Implicit NotExported []
235
236 mkPrimitiveName :: Unique -> OrigName -> Name
237 mkPrimitiveName u (OrigName m n)  = Global u m n Primitive NotExported []
238
239 mkWiredInName :: Unique -> OrigName -> Name
240 mkWiredInName u (OrigName m n)
241   = Global u m n (WiredIn from_here) (if from_here then ExportAll else NotExported) []
242   where
243     from_here
244       = case maybe_CompilingPrelude of
245           Nothing  -> False
246           Just mod -> mod == _UNPK_ m
247
248 mkCompoundName :: Unique
249                -> Module
250                -> FAST_STRING   -- indicates what kind of compound thing it is (e.g., "sdsel")
251                -> [Either OrigName FAST_STRING] -- "dot" these names together
252                -> Name          -- from which we get provenance, etc....
253                -> Name          -- result!
254
255 mkCompoundName u m str ns (Local _ _ _ _) = panic "mkCompoundName:Local?"
256 mkCompoundName u m str ns (Global _ _ _ prov exp _)
257   = Global u m (_CONCAT_ (glue ns [str])) prov exp []
258
259 glue []                       acc = reverse acc
260 glue (Left (OrigName m n):ns) acc = glue ns (_CONS_ '.' n : _CONS_ '.' m : acc)
261 glue (Right n            :ns) acc = glue ns (_CONS_ '.' n : acc)
262
263 -- this ugly one is used for instance-y things
264 mkCompoundName2 :: Unique
265                 -> Module
266                 -> FAST_STRING  -- indicates what kind of compound thing it is
267                 -> [Either OrigName FAST_STRING] -- "dot" these names together
268                 -> Bool         -- True <=> defined in this module
269                 -> SrcLoc       
270                 -> Name         -- result!
271
272 mkCompoundName2 u m str ns from_here locn
273   = Global u m (_CONCAT_ (glue ns [str]))
274              (if from_here then LocalDef locn else Imported ExportAll locn [])
275              ExportAll{-instances-}
276              []
277
278 mkFunTyConName
279   = mkPrimitiveName funTyConKey                (OrigName pRELUDE SLIT("->"))
280 mkTupleDataConName arity
281   = mkWiredInName (mkTupleDataConUnique arity) (OrigName pRELUDE (mkTupNameStr arity))
282 mkTupleTyConName   arity
283   = mkWiredInName (mkTupleTyConUnique   arity) (OrigName pRELUDE (mkTupNameStr arity))
284
285 mkTupNameStr 0 = SLIT("()")
286 mkTupNameStr 1 = panic "Name.mkTupNameStr: 1 ???"
287 mkTupNameStr 2 = SLIT("(,)")   -- not strictly necessary
288 mkTupNameStr 3 = SLIT("(,,)")  -- ditto
289 mkTupNameStr 4 = SLIT("(,,,)") -- ditto
290 mkTupNameStr n
291   = _PK_ ("(" ++ nOfThem (n-1) ',' ++ ")")
292
293         -- ToDo: what about module ???
294         -- ToDo: exported when compiling builtin ???
295
296 isLocalName (Local _ _ _ _) = True
297 isLocalName _               = False
298
299 -- things the compiler "knows about" are in some sense
300 -- "imported".  When we are compiling the module where
301 -- the entities are defined, we need to be able to pick
302 -- them out, often in combination with isLocallyDefined.
303 oddlyImportedName (Global _ _ _ Primitive   _ _) = True
304 oddlyImportedName (Global _ _ _ (WiredIn _) _ _) = True
305 oddlyImportedName _                              = False
306
307 isImplicitName (Global _ _ _ Implicit _ _) = True
308 isImplicitName _                           = False
309 \end{code}
310
311 %************************************************************************
312 %*                                                                      *
313 \subsection[Name-instances]{Instance declarations}
314 %*                                                                      *
315 %************************************************************************
316
317 \begin{code}
318 cmpName n1 n2 = c n1 n2
319   where
320     c (Local  u1 _ _ _)     (Local  u2 _ _ _)     = cmp u1 u2
321     c (Local   _ _ _ _)     _                     = LT_
322     c (Global u1 _ _ _ _ _) (Global u2 _ _ _ _ _) = cmp u1 u2
323     c (Global  _ _ _ _ _ _) _                     = GT_
324 \end{code}
325
326 \begin{code}
327 instance Eq Name where
328     a == b = case (a `cmp` b) of { EQ_ -> True;  _ -> False }
329     a /= b = case (a `cmp` b) of { EQ_ -> False; _ -> True }
330
331 instance Ord Name where
332     a <= b = case (a `cmp` b) of { LT_ -> True;  EQ_ -> True;  GT__ -> False }
333     a <  b = case (a `cmp` b) of { LT_ -> True;  EQ_ -> False; GT__ -> False }
334     a >= b = case (a `cmp` b) of { LT_ -> False; EQ_ -> True;  GT__ -> True  }
335     a >  b = case (a `cmp` b) of { LT_ -> False; EQ_ -> False; GT__ -> True  }
336
337 instance Ord3 Name where
338     cmp = cmpName
339
340 instance Uniquable Name where
341     uniqueOf = nameUnique
342
343 instance NamedThing Name where
344     getName n = n
345 \end{code}
346
347 \begin{code}
348 nameUnique (Local  u _ _ _)     = u
349 nameUnique (Global u _ _ _ _ _) = u
350
351 -- when we renumber/rename things, we need to be
352 -- able to change a Name's Unique to match the cached
353 -- one in the thing it's the name of.  If you know what I mean.
354 changeUnique (Local      _ n b l)    u = Local u n b l
355 changeUnique (Global   _ m n p e os) u = Global u m n p e os
356
357 nameOrigName msg (Global _ m n _ _ _) = OrigName m n
358 #ifdef DEBUG
359 nameOrigName msg (Local  _ n _ _)     = panic ("nameOrigName:Local:"++msg++":"++ _UNPK_ n)
360 #endif
361
362 nameOccName (Local  _ n _ _)         = Unqual n
363 nameOccName (Global _ m n _ _ []  )  = Qual m n
364 nameOccName (Global _ m n _ _ (o:_)) = o
365
366 nameExportFlag (Local  _ _ _ _)       = NotExported
367 nameExportFlag (Global _ _ _ _ exp _) = exp
368
369 nameSrcLoc (Local  _ _ _ loc)                    = loc
370 nameSrcLoc (Global _ _ _ (LocalDef loc)     _ _) = loc
371 nameSrcLoc (Global _ _ _ (Imported _ loc _) _ _) = loc
372 nameSrcLoc (Global _ _ _ Implicit           _ _) = mkUnknownSrcLoc
373 nameSrcLoc (Global _ _ _ Primitive          _ _) = mkBuiltinSrcLoc
374 nameSrcLoc (Global _ _ _ (WiredIn _)        _ _) = mkBuiltinSrcLoc
375   
376 nameImpLocs (Global _ _ _ (Imported _ _ locs) _ _) = locs
377 nameImpLocs _                                      = []
378
379 nameImportFlag (Local  _ _ _ _)                      = NotExported
380 nameImportFlag (Global _ _ _ (LocalDef _)       _ _) = ExportAll
381 nameImportFlag (Global _ _ _ (Imported exp _ _) _ _) = exp
382 nameImportFlag (Global _ _ _ Implicit           _ _) = ExportAll
383 nameImportFlag (Global _ _ _ Primitive          _ _) = ExportAll
384 nameImportFlag (Global _ _ _ (WiredIn _)        _ _) = ExportAll
385
386 isLocallyDefinedName (Local  _ _ _ _)                       = True
387 isLocallyDefinedName (Global _ _ _ (LocalDef _)        _ _) = True
388 isLocallyDefinedName (Global _ _ _ (Imported _ _ _)    _ _) = False
389 isLocallyDefinedName (Global _ _ _ Implicit            _ _) = False
390 isLocallyDefinedName (Global _ _ _ Primitive           _ _) = False
391 isLocallyDefinedName (Global _ _ _ (WiredIn from_here) _ _) = from_here
392
393 isWiredInName (Global _ _ _ (WiredIn _) _ _) = True
394 isWiredInName _                              = False
395 \end{code}
396
397 \begin{code}
398 instance Outputable Name where
399     ppr sty (Local u n emph_uniq _)
400       | codeStyle sty = pprUnique u
401       | emph_uniq     = ppBesides [pprUnique u, ppStr "{-", ppPStr n, ppStr "-}"]
402       | otherwise     = ppBesides [ppPStr n, ppStr "{-", pprUnique u, ppStr "-}"]
403
404     ppr PprDebug   (Global   u m n  _ _ _)        = ppBesides [ppr PprDebug (Qual m n), ppStr "{-", pprUnique u, ppStr "-}"]
405     ppr PprForUser (Global   u m n _ _ []  )      = ppr PprForUser (Qual m n)
406     ppr PprForUser (Global   u m n _ _ occs)      = ppr PprForUser (head occs)
407     ppr PprShowAll (Global   u m n prov exp occs) = pp_all (Qual m n) prov exp occs
408     ppr sty        (Global   u m n _ _ _)         = ppr sty (Qual m n)
409
410 pp_all orig prov exp occs
411   = ppBesides [ppr PprShowAll orig, ppr PprShowAll occs, pp_prov prov, pp_exp exp]
412
413 pp_exp NotExported = ppNil
414 pp_exp ExportAll   = ppPStr SLIT("/EXP(..)")
415 pp_exp ExportAbs   = ppPStr SLIT("/EXP")
416
417 pp_prov Implicit    = ppPStr SLIT("/IMPLICIT")
418 pp_prov Primitive   = ppPStr SLIT("/PRIMITIVE")
419 pp_prov (WiredIn _) = ppPStr SLIT("/WIREDIN")
420 pp_prov _           = ppNil
421 \end{code}
422
423 %************************************************************************
424 %*                                                                      *
425 \subsection[ExportFlag-datatype]{The @ExportFlag@ datatype}
426 %*                                                                      *
427 %************************************************************************
428
429 The export flag @ExportAll@ means `export all there is', so there are
430 times when it is attached to a class or data type which has no
431 ops/constructors (if the class/type was imported abstractly).  In
432 fact, @ExportAll@ is attached to everything except to classes/types
433 which are being {\em exported} abstractly, regardless of how they were
434 imported.
435
436 \begin{code}
437 data ExportFlag
438   = ExportAll           -- export with all constructors/methods
439   | ExportAbs           -- export abstractly (tycons/classes only)
440   | NotExported
441
442 exportFlagOn NotExported = False
443 exportFlagOn _           = True
444
445 isExported a = exportFlagOn (getExportFlag a)
446 \end{code}
447
448 %************************************************************************
449 %*                                                                      *
450 \subsection{Overloaded functions related to Names}
451 %*                                                                      *
452 %************************************************************************
453
454 \begin{code}
455 class NamedThing a where
456     getName :: a -> Name
457 \end{code}
458
459 \begin{code}
460 origName            :: NamedThing a => String -> a -> OrigName
461 moduleOf            :: OrigName -> Module
462 nameOf              :: OrigName -> FAST_STRING
463
464 getOccName          :: NamedThing a => a -> RdrName
465 getLocalName        :: NamedThing a => a -> FAST_STRING
466 getExportFlag       :: NamedThing a => a -> ExportFlag
467 getSrcLoc           :: NamedThing a => a -> SrcLoc
468 getImpLocs          :: NamedThing a => a -> [SrcLoc]
469 isLocallyDefined    :: NamedThing a => a -> Bool
470
471 origName str n      = nameOrigName str (getName n)
472
473 moduleOf (OrigName m n) = m
474 nameOf   (OrigName m n) = n
475
476 getLocalName n
477   = case (getName n) of
478       Global _ m n _ _ _ -> n
479       Local  _ n _ _     -> n
480
481 getOccName          = nameOccName          . getName
482 getExportFlag       = nameExportFlag       . getName
483 getSrcLoc           = nameSrcLoc           . getName
484 getImpLocs          = nameImpLocs          . getName
485 isLocallyDefined    = isLocallyDefinedName . getName
486 \end{code}
487
488 These functions test strings to see if they fit the lexical categories
489 defined in the Haskell report.  Normally applied as in e.g. @isCon
490 (getLocalName foo)@.
491
492 \begin{code}
493 isLexCon, isLexVar, isLexId, isLexSym, isLexConId, isLexConSym,
494  isLexVarId, isLexVarSym, isLexSpecialSym :: FAST_STRING -> Bool
495
496 isLexCon cs = isLexConId  cs || isLexConSym cs
497 isLexVar cs = isLexVarId  cs || isLexVarSym cs
498
499 isLexId  cs = isLexConId  cs || isLexVarId  cs
500 isLexSym cs = isLexConSym cs || isLexVarSym cs
501
502 -------------
503
504 isLexConId cs
505   | _NULL_ cs   = False
506   | otherwise   = isUpper c || isUpperISO c
507   where                                 
508     c = _HEAD_ cs
509
510 isLexVarId cs
511   | _NULL_ cs    = False
512   | otherwise    = isLower c || isLowerISO c
513   where
514     c = _HEAD_ cs
515
516 isLexConSym cs
517   | _NULL_ cs   = False
518   | otherwise   = c  == ':'
519 --             || c  == '('     -- (), (,), (,,), ...
520                || cs == SLIT("->")
521 --             || cs == SLIT("[]")
522   where
523     c = _HEAD_ cs
524
525 isLexVarSym cs
526   | _NULL_ cs = False
527   | otherwise = isSymbolASCII c
528              || isSymbolISO c
529 --           || c  == '('       -- (), (,), (,,), ...
530 --           || cs == SLIT("[]")
531   where
532     c = _HEAD_ cs
533
534 isLexSpecialSym cs
535   | _NULL_ cs = False
536   | otherwise = c  == '('       -- (), (,), (,,), ...
537              || cs == SLIT("[]")
538   where
539     c = _HEAD_ cs
540
541 -------------
542 isSymbolASCII c = c `elem` "!#$%&*+./<=>?@\\^|~-"
543 isSymbolISO   c = ord c `elem` (0xd7 : 0xf7 : [0xa1 .. 0xbf])
544 isUpperISO    c = 0xc0 <= oc && oc <= 0xde && oc /= 0xd7 where oc = ord c
545 isLowerISO    c = 0xdf <= oc && oc <= 0xff && oc /= 0xf7 where oc = ord c
546 \end{code}
547
548 And one ``higher-level'' interface to those:
549
550 \begin{code}
551 isSymLexeme :: NamedThing a => a -> Bool
552
553 isSymLexeme v
554   = let str = getLocalName v in isLexSym str
555
556 -- print `vars`, (op) correctly
557 pprSym, pprNonSym :: (NamedThing name, Outputable name) => PprStyle -> name -> Pretty
558
559 pprSym sty var
560   = let
561         str = getLocalName var
562     in
563     if isLexSym str && not (isLexSpecialSym str)
564     then ppr sty var
565     else ppBesides [ppChar '`', ppr sty var, ppChar '`']
566
567 pprNonSym sty var
568   = if isSymLexeme var
569     then ppParens (ppr sty var)
570     else ppr sty var
571 \end{code}