lots of portability changes (#1405)
[ghc-hetmet.git] / compiler / basicTypes / OccName.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 %
5
6 \begin{code}
7 {-# OPTIONS -w #-}
8 -- The above warning supression flag is a temporary kludge.
9 -- While working on this module you are encouraged to remove it and fix
10 -- any warnings in the module. See
11 --     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
12 -- for details
13
14 module OccName (
15         -- * The NameSpace type; abstact
16         NameSpace, tcName, clsName, tcClsName, dataName, varName, 
17         tvName, srcDataName,
18
19         -- ** Printing
20         pprNameSpace, pprNonVarNameSpace, pprNameSpaceBrief,
21
22         -- * The OccName type
23         OccName,        -- Abstract, instance of Outputable
24         pprOccName, 
25
26         -- ** Construction      
27         mkOccName, mkOccNameFS, 
28         mkVarOcc, mkVarOccFS,
29         mkTyVarOcc,
30         mkDFunOcc,
31         mkTupleOcc, 
32         setOccNameSpace,
33
34         -- ** Derived OccNames
35         mkDataConWrapperOcc, mkWorkerOcc, mkDefaultMethodOcc,
36         mkDerivedTyConOcc, mkNewTyCoOcc,
37         mkClassTyConOcc, mkClassDataConOcc, mkDictOcc, mkIPOcc, 
38         mkSpecOcc, mkForeignExportOcc, mkGenOcc1, mkGenOcc2,
39         mkDataTOcc, mkDataCOcc, mkDataConWorkerOcc,
40         mkSuperDictSelOcc, mkLocalOcc, mkMethodOcc, mkInstTyTcOcc,
41         mkInstTyCoOcc, mkEqPredCoOcc,
42         mkVectOcc, mkVectTyConOcc, mkVectDataConOcc, mkVectIsoOcc,
43         mkPArrayTyConOcc, mkPArrayDataConOcc,
44         mkPReprTyConOcc,
45         mkPADFunOcc,
46
47         -- ** Deconstruction
48         occNameFS, occNameString, occNameSpace, 
49
50         isVarOcc, isTvOcc, isTcOcc, isDataOcc, isDataSymOcc, isSymOcc, isValOcc,
51         parenSymOcc, reportIfUnused, isTcClsName, isVarName,
52
53         isTupleOcc_maybe,
54
55         -- The OccEnv type
56         OccEnv, emptyOccEnv, unitOccEnv, extendOccEnv, mapOccEnv,
57         lookupOccEnv, mkOccEnv, mkOccEnv_C, extendOccEnvList, elemOccEnv,
58         occEnvElts, foldOccEnv, plusOccEnv, plusOccEnv_C, extendOccEnv_C,
59         filterOccEnv, delListFromOccEnv, delFromOccEnv,
60
61         -- The OccSet type
62         OccSet, emptyOccSet, unitOccSet, mkOccSet, extendOccSet, 
63         extendOccSetList,
64         unionOccSets, unionManyOccSets, minusOccSet, elemOccSet, occSetElts, 
65         foldOccSet, isEmptyOccSet, intersectOccSet, intersectsOccSet,
66                   
67         -- Tidying up
68         TidyOccEnv, emptyTidyOccEnv, tidyOccName, initTidyOccEnv,
69
70         -- The basic form of names
71         isLexCon, isLexVar, isLexId, isLexSym,
72         isLexConId, isLexConSym, isLexVarId, isLexVarSym,
73         startsVarSym, startsVarId, startsConSym, startsConId
74     ) where
75
76 #include "HsVersions.h"
77
78 import Util
79 import Unique
80 import BasicTypes
81 import StaticFlags
82 import UniqFM
83 import UniqSet
84 import FastString
85 import FastTypes
86 import Outputable
87 import Binary
88
89 import GHC.Exts
90 import Data.Char
91
92 -- Unicode TODO: put isSymbol in libcompat
93 #if !defined(__GLASGOW_HASKELL__) || __GLASGOW_HASKELL__ > 604
94 #else
95 isSymbol = const False
96 #endif
97
98 \end{code}
99
100 %************************************************************************
101 %*                                                                      *
102 \subsection{Name space}
103 %*                                                                      *
104 %************************************************************************
105
106 \begin{code}
107 data NameSpace = VarName        -- Variables, including "real" data constructors
108                | DataName       -- "Source" data constructors 
109                | TvName         -- Type variables
110                | TcClsName      -- Type constructors and classes; Haskell has them
111                                 -- in the same name space for now.
112                deriving( Eq, Ord )
113    {-! derive: Binary !-}
114
115 -- Note [Data Constructors]  
116 -- see also: Note [Data Constructor Naming] in DataCon.lhs
117 -- 
118 --      "Source" data constructors are the data constructors mentioned
119 --      in Haskell source code
120 --
121 --      "Real" data constructors are the data constructors of the
122 --      representation type, which may not be the same as the source
123 --      type
124
125 -- Example:
126 --      data T = T !(Int,Int)
127 --
128 -- The source datacon has type (Int,Int) -> T
129 -- The real   datacon has type Int -> Int -> T
130 -- GHC chooses a representation based on the strictness etc.
131
132
133 -- Though type constructors and classes are in the same name space now,
134 -- the NameSpace type is abstract, so we can easily separate them later
135 tcName    = TcClsName           -- Type constructors
136 clsName   = TcClsName           -- Classes
137 tcClsName = TcClsName           -- Not sure which!
138
139 dataName    = DataName
140 srcDataName = DataName  -- Haskell-source data constructors should be
141                         -- in the Data name space
142
143 tvName      = TvName
144 varName     = VarName
145
146 isTcClsName :: NameSpace -> Bool
147 isTcClsName TcClsName = True
148 isTcClsName _         = False
149
150 isVarName :: NameSpace -> Bool  -- Variables or type variables, but not constructors
151 isVarName TvName  = True
152 isVarName VarName = True
153 isVarName other   = False
154
155 pprNameSpace :: NameSpace -> SDoc
156 pprNameSpace DataName  = ptext SLIT("data constructor")
157 pprNameSpace VarName   = ptext SLIT("variable")
158 pprNameSpace TvName    = ptext SLIT("type variable")
159 pprNameSpace TcClsName = ptext SLIT("type constructor or class")
160
161 pprNonVarNameSpace :: NameSpace -> SDoc
162 pprNonVarNameSpace VarName = empty
163 pprNonVarNameSpace ns = pprNameSpace ns
164
165 pprNameSpaceBrief DataName  = char 'd'
166 pprNameSpaceBrief VarName   = char 'v'
167 pprNameSpaceBrief TvName    = ptext SLIT("tv")
168 pprNameSpaceBrief TcClsName = ptext SLIT("tc")
169 \end{code}
170
171
172 %************************************************************************
173 %*                                                                      *
174 \subsection[Name-pieces-datatypes]{The @OccName@ datatypes}
175 %*                                                                      *
176 %************************************************************************
177
178 \begin{code}
179 data OccName = OccName 
180     { occNameSpace  :: !NameSpace
181     , occNameFS     :: !FastString
182     }
183 \end{code}
184
185
186 \begin{code}
187 instance Eq OccName where
188     (OccName sp1 s1) == (OccName sp2 s2) = s1 == s2 && sp1 == sp2
189
190 instance Ord OccName where
191         -- Compares lexicographically, *not* by Unique of the string
192     compare (OccName sp1 s1) (OccName sp2 s2) 
193         = (s1  `compare` s2) `thenCmp` (sp1 `compare` sp2)
194 \end{code}
195
196
197 %************************************************************************
198 %*                                                                      *
199 \subsection{Printing}
200 %*                                                                      *
201 %************************************************************************
202  
203 \begin{code}
204 instance Outputable OccName where
205     ppr = pprOccName
206
207 pprOccName :: OccName -> SDoc
208 pprOccName (OccName sp occ) 
209   = getPprStyle $ \ sty ->
210     if codeStyle sty 
211         then ftext (zEncodeFS occ)
212         else ftext occ <> if debugStyle sty 
213                             then braces (pprNameSpaceBrief sp)
214                             else empty
215 \end{code}
216
217
218 %************************************************************************
219 %*                                                                      *
220 \subsection{Construction}
221 %*                                                                      *
222 %************************************************************************
223
224 \begin{code}
225 mkOccName :: NameSpace -> String -> OccName
226 mkOccName occ_sp str = OccName occ_sp (mkFastString str)
227
228 mkOccNameFS :: NameSpace -> FastString -> OccName
229 mkOccNameFS occ_sp fs = OccName occ_sp fs
230
231 mkVarOcc :: String -> OccName
232 mkVarOcc s = mkOccName varName s
233
234 mkVarOccFS :: FastString -> OccName
235 mkVarOccFS fs = mkOccNameFS varName fs
236
237 mkTyVarOcc :: FastString -> OccName
238 mkTyVarOcc fs = mkOccNameFS tvName fs
239 \end{code}
240
241
242 %************************************************************************
243 %*                                                                      *
244                 Environments
245 %*                                                                      *
246 %************************************************************************
247
248 OccEnvs are used mainly for the envts in ModIfaces.
249
250 They are efficient, because FastStrings have unique Int# keys.  We assume
251 this key is less than 2^24, so we can make a Unique using
252         mkUnique ns key  :: Unique
253 where 'ns' is a Char reprsenting the name space.  This in turn makes it
254 easy to build an OccEnv.
255
256 \begin{code}
257 instance Uniquable OccName where
258   getUnique (OccName ns fs)
259       = mkUnique char (iBox (uniqueOfFS fs))
260       where     -- See notes above about this getUnique function
261         char = case ns of
262                 VarName   -> 'i'
263                 DataName  -> 'd'
264                 TvName    -> 'v'
265                 TcClsName -> 't'
266
267 newtype OccEnv a = A (UniqFM a)
268
269 emptyOccEnv :: OccEnv a
270 unitOccEnv  :: OccName -> a -> OccEnv a
271 extendOccEnv :: OccEnv a -> OccName -> a -> OccEnv a
272 extendOccEnvList :: OccEnv a -> [(OccName, a)] -> OccEnv a
273 lookupOccEnv :: OccEnv a -> OccName -> Maybe a
274 mkOccEnv     :: [(OccName,a)] -> OccEnv a
275 mkOccEnv_C   :: (a -> a -> a) -> [(OccName,a)] -> OccEnv a
276 elemOccEnv   :: OccName -> OccEnv a -> Bool
277 foldOccEnv   :: (a -> b -> b) -> b -> OccEnv a -> b
278 occEnvElts   :: OccEnv a -> [a]
279 extendOccEnv_C :: (a->a->a) -> OccEnv a -> OccName -> a -> OccEnv a
280 plusOccEnv     :: OccEnv a -> OccEnv a -> OccEnv a
281 plusOccEnv_C   :: (a->a->a) -> OccEnv a -> OccEnv a -> OccEnv a
282 mapOccEnv      :: (a->b) -> OccEnv a -> OccEnv b
283 delFromOccEnv      :: OccEnv a -> OccName -> OccEnv a
284 delListFromOccEnv :: OccEnv a -> [OccName] -> OccEnv a
285 filterOccEnv       :: (elt -> Bool) -> OccEnv elt -> OccEnv elt
286
287 emptyOccEnv      = A emptyUFM
288 unitOccEnv x y = A $ unitUFM x y 
289 extendOccEnv (A x) y z = A $ addToUFM x y z
290 extendOccEnvList (A x) l = A $ addListToUFM x l
291 lookupOccEnv (A x) y = lookupUFM x y
292 mkOccEnv     l    = A $ listToUFM l
293 elemOccEnv x (A y)       = elemUFM x y
294 foldOccEnv a b (A c)     = foldUFM a b c 
295 occEnvElts (A x)         = eltsUFM x
296 plusOccEnv (A x) (A y)   = A $ plusUFM x y 
297 plusOccEnv_C f (A x) (A y)       = A $ plusUFM_C f x y 
298 extendOccEnv_C f (A x) y z   = A $ addToUFM_C f x y z
299 mapOccEnv f (A x)        = A $ mapUFM f x
300 mkOccEnv_C comb l = A $ addListToUFM_C comb emptyUFM l
301 delFromOccEnv (A x) y    = A $ delFromUFM x y
302 delListFromOccEnv (A x) y  = A $ delListFromUFM x y
303 filterOccEnv x (A y)       = A $ filterUFM x y
304
305 instance Outputable a => Outputable (OccEnv a) where
306     ppr (A x) = ppr x
307
308 type OccSet = UniqFM OccName
309
310 emptyOccSet       :: OccSet
311 unitOccSet        :: OccName -> OccSet
312 mkOccSet          :: [OccName] -> OccSet
313 extendOccSet      :: OccSet -> OccName -> OccSet
314 extendOccSetList  :: OccSet -> [OccName] -> OccSet
315 unionOccSets      :: OccSet -> OccSet -> OccSet
316 unionManyOccSets  :: [OccSet] -> OccSet
317 minusOccSet       :: OccSet -> OccSet -> OccSet
318 elemOccSet        :: OccName -> OccSet -> Bool
319 occSetElts        :: OccSet -> [OccName]
320 foldOccSet        :: (OccName -> b -> b) -> b -> OccSet -> b
321 isEmptyOccSet     :: OccSet -> Bool
322 intersectOccSet   :: OccSet -> OccSet -> OccSet
323 intersectsOccSet  :: OccSet -> OccSet -> Bool
324
325 emptyOccSet       = emptyUniqSet
326 unitOccSet        = unitUniqSet
327 mkOccSet          = mkUniqSet
328 extendOccSet      = addOneToUniqSet
329 extendOccSetList  = addListToUniqSet
330 unionOccSets      = unionUniqSets
331 unionManyOccSets  = unionManyUniqSets
332 minusOccSet       = minusUniqSet
333 elemOccSet        = elementOfUniqSet
334 occSetElts        = uniqSetToList
335 foldOccSet        = foldUniqSet
336 isEmptyOccSet     = isEmptyUniqSet
337 intersectOccSet   = intersectUniqSets
338 intersectsOccSet s1 s2 = not (isEmptyOccSet (s1 `intersectOccSet` s2))
339 \end{code}
340
341
342 %************************************************************************
343 %*                                                                      *
344 \subsection{Predicates and taking them apart}
345 %*                                                                      *
346 %************************************************************************
347
348 \begin{code}
349 occNameString :: OccName -> String
350 occNameString (OccName _ s) = unpackFS s
351
352 setOccNameSpace :: NameSpace -> OccName -> OccName
353 setOccNameSpace sp (OccName _ occ) = OccName sp occ
354
355 isVarOcc, isTvOcc, isDataSymOcc, isSymOcc, isTcOcc :: OccName -> Bool
356
357 isVarOcc (OccName VarName _) = True
358 isVarOcc other               = False
359
360 isTvOcc (OccName TvName _) = True
361 isTvOcc other              = False
362
363 isTcOcc (OccName TcClsName _) = True
364 isTcOcc other                 = False
365
366 isValOcc (OccName VarName  _) = True
367 isValOcc (OccName DataName _) = True
368 isValOcc other                = False
369
370 -- Data constructor operator (starts with ':', or '[]')
371 -- Pretty inefficient!
372 isDataSymOcc (OccName DataName s) = isLexConSym s
373 isDataSymOcc (OccName VarName s)  
374   | isLexConSym s = pprPanic "isDataSymOcc: check me" (ppr s)
375                 -- Jan06: I don't think this should happen
376 isDataSymOcc other                = False
377
378 isDataOcc (OccName DataName _) = True
379 isDataOcc (OccName VarName s)  
380   | isLexCon s = pprPanic "isDataOcc: check me" (ppr s)
381                 -- Jan06: I don't think this should happen
382 isDataOcc other                = False
383
384 -- Any operator (data constructor or variable)
385 -- Pretty inefficient!
386 isSymOcc (OccName DataName s)  = isLexConSym s
387 isSymOcc (OccName TcClsName s) = isLexConSym s
388 isSymOcc (OccName VarName s)   = isLexSym s
389 isSymOcc (OccName TvName s)    = isLexSym s
390
391 parenSymOcc :: OccName -> SDoc -> SDoc
392 -- Wrap parens around an operator
393 parenSymOcc occ doc | isSymOcc occ = parens doc
394                     | otherwise    = doc
395 \end{code}
396
397
398 \begin{code}
399 reportIfUnused :: OccName -> Bool
400   -- Haskell 98 encourages compilers to suppress warnings about
401   -- unused names in a pattern if they start with "_".
402 reportIfUnused occ = case occNameString occ of
403                         ('_' : _) -> False
404                         _other    -> True
405 \end{code}
406
407
408 %************************************************************************
409 %*                                                                      *
410 \subsection{Making system names}
411 %*                                                                      *
412 %************************************************************************
413
414 Here's our convention for splitting up the interface file name space:
415
416         d...            dictionary identifiers
417                         (local variables, so no name-clash worries)
418
419         $f...           dict-fun identifiers (from inst decls)
420         $dm...          default methods
421         $p...           superclass selectors
422         $w...           workers
423         :T...           compiler-generated tycons for dictionaries
424         :D...           ...ditto data cons
425         :Co...          ...ditto coercions
426         $sf..           specialised version of f
427
428         in encoded form these appear as Zdfxxx etc
429
430         :...            keywords (export:, letrec: etc.)
431 --- I THINK THIS IS WRONG!
432
433 This knowledge is encoded in the following functions.
434
435
436 @mk_deriv@ generates an @OccName@ from the prefix and a string.
437 NB: The string must already be encoded!
438
439 \begin{code}
440 mk_deriv :: NameSpace 
441          -> String              -- Distinguishes one sort of derived name from another
442          -> String
443          -> OccName
444
445 mk_deriv occ_sp sys_prefix str = mkOccName occ_sp (sys_prefix ++ str)
446 \end{code}
447
448 \begin{code}
449 mkDataConWrapperOcc, mkWorkerOcc, mkDefaultMethodOcc, mkDerivedTyConOcc,
450         mkClassTyConOcc, mkClassDataConOcc, mkDictOcc, mkIPOcc, 
451         mkSpecOcc, mkForeignExportOcc, mkGenOcc1, mkGenOcc2,
452         mkDataTOcc, mkDataCOcc, mkDataConWorkerOcc, mkNewTyCoOcc
453    :: OccName -> OccName
454
455 -- These derived variables have a prefix that no Haskell value could have
456 mkDataConWrapperOcc = mk_simple_deriv varName  "$W"
457 mkWorkerOcc         = mk_simple_deriv varName  "$w"
458 mkDefaultMethodOcc  = mk_simple_deriv varName  "$dm"
459 mkDerivedTyConOcc   = mk_simple_deriv tcName   ":"      -- The : prefix makes sure it classifies
460 mkClassTyConOcc     = mk_simple_deriv tcName   ":T"     -- as a tycon/datacon
461 mkClassDataConOcc   = mk_simple_deriv dataName ":D"     -- We go straight to the "real" data con
462                                                         -- for datacons from classes
463 mkDictOcc           = mk_simple_deriv varName  "$d"
464 mkIPOcc             = mk_simple_deriv varName  "$i"
465 mkSpecOcc           = mk_simple_deriv varName  "$s"
466 mkForeignExportOcc  = mk_simple_deriv varName  "$f"
467 mkNewTyCoOcc        = mk_simple_deriv tcName  ":Co"
468 mkInstTyCoOcc       = mk_simple_deriv tcName  ":CoF"     -- derived from rep ty
469 mkEqPredCoOcc       = mk_simple_deriv tcName  "$co"
470
471 -- Generic derivable classes
472 mkGenOcc1           = mk_simple_deriv varName  "$gfrom"
473 mkGenOcc2           = mk_simple_deriv varName  "$gto" 
474
475 -- data T = MkT ... deriving( Data ) needs defintions for 
476 --      $tT   :: Data.Generics.Basics.DataType
477 --      $cMkT :: Data.Generics.Basics.Constr
478 mkDataTOcc = mk_simple_deriv varName  "$t"
479 mkDataCOcc = mk_simple_deriv varName  "$c"
480
481 -- Vectorisation
482 mkVectOcc          = mk_simple_deriv varName  "$v_"
483 mkVectTyConOcc     = mk_simple_deriv tcName   ":V_"
484 mkVectDataConOcc   = mk_simple_deriv dataName ":VD_"
485 mkVectIsoOcc       = mk_simple_deriv varName  "$VI_"
486 mkPArrayTyConOcc   = mk_simple_deriv tcName   ":VP_"
487 mkPArrayDataConOcc = mk_simple_deriv dataName ":VPD_"
488 mkPReprTyConOcc    = mk_simple_deriv tcName   ":VR_"
489 mkPADFunOcc        = mk_simple_deriv varName  "$PA_"
490
491 mk_simple_deriv sp px occ = mk_deriv sp px (occNameString occ)
492
493 -- Data constructor workers are made by setting the name space
494 -- of the data constructor OccName (which should be a DataName)
495 -- to VarName
496 mkDataConWorkerOcc datacon_occ = setOccNameSpace varName datacon_occ 
497 \end{code}
498
499 \begin{code}
500 mkSuperDictSelOcc :: Int        -- Index of superclass, eg 3
501                   -> OccName    -- Class, eg "Ord"
502                   -> OccName    -- eg "$p3Ord"
503 mkSuperDictSelOcc index cls_occ
504   = mk_deriv varName "$p" (show index ++ occNameString cls_occ)
505
506 mkLocalOcc :: Unique            -- Unique
507            -> OccName           -- Local name (e.g. "sat")
508            -> OccName           -- Nice unique version ("$L23sat")
509 mkLocalOcc uniq occ
510    = mk_deriv varName ("$L" ++ show uniq) (occNameString occ)
511         -- The Unique might print with characters 
512         -- that need encoding (e.g. 'z'!)
513 \end{code}
514
515 Derive a name for the representation type constructor of a data/newtype
516 instance.
517
518 \begin{code}
519 mkInstTyTcOcc :: Int                    -- Index
520               -> OccName                -- Family name (e.g. "Map")
521               -> OccName                -- Nice unique version (":R23Map")
522 mkInstTyTcOcc index occ
523    = mk_deriv tcName (":R" ++ show index) (occNameString occ)
524 \end{code}
525
526 \begin{code}
527 mkDFunOcc :: String             -- Typically the class and type glommed together e.g. "OrdMaybe"
528                                 -- Only used in debug mode, for extra clarity
529           -> Bool               -- True <=> hs-boot instance dfun
530           -> Int                -- Unique index
531           -> OccName            -- "$f3OrdMaybe"
532
533 -- In hs-boot files we make dict funs like $fx7ClsTy, which get bound to the real
534 -- thing when we compile the mother module. Reason: we don't know exactly
535 -- what the  mother module will call it.
536
537 mkDFunOcc info_str is_boot index 
538   = mk_deriv VarName prefix string
539   where
540     prefix | is_boot   = "$fx"
541            | otherwise = "$f"
542     string | opt_PprStyle_Debug = show index ++ info_str
543            | otherwise          = show index
544 \end{code}
545
546 We used to add a '$m' to indicate a method, but that gives rise to bad
547 error messages from the type checker when we print the function name or pattern
548 of an instance-decl binding.  Why? Because the binding is zapped
549 to use the method name in place of the selector name.
550 (See TcClassDcl.tcMethodBind)
551
552 The way it is now, -ddump-xx output may look confusing, but
553 you can always say -dppr-debug to get the uniques.
554
555 However, we *do* have to zap the first character to be lower case,
556 because overloaded constructors (blarg) generate methods too.
557 And convert to VarName space
558
559 e.g. a call to constructor MkFoo where
560         data (Ord a) => Foo a = MkFoo a
561
562 If this is necessary, we do it by prefixing '$m'.  These 
563 guys never show up in error messages.  What a hack.
564
565 \begin{code}
566 mkMethodOcc :: OccName -> OccName
567 mkMethodOcc occ@(OccName VarName fs) = occ
568 mkMethodOcc occ                      = mk_simple_deriv varName "$m" occ
569 \end{code}
570
571
572 %************************************************************************
573 %*                                                                      *
574 \subsection{Tidying them up}
575 %*                                                                      *
576 %************************************************************************
577
578 Before we print chunks of code we like to rename it so that
579 we don't have to print lots of silly uniques in it.  But we mustn't
580 accidentally introduce name clashes!  So the idea is that we leave the
581 OccName alone unless it accidentally clashes with one that is already
582 in scope; if so, we tack on '1' at the end and try again, then '2', and
583 so on till we find a unique one.
584
585 There's a wrinkle for operators.  Consider '>>='.  We can't use '>>=1' 
586 because that isn't a single lexeme.  So we encode it to 'lle' and *then*
587 tack on the '1', if necessary.
588
589 \begin{code}
590 type TidyOccEnv = OccEnv Int    -- The in-scope OccNames
591         -- Range gives a plausible starting point for new guesses
592
593 emptyTidyOccEnv = emptyOccEnv
594
595 initTidyOccEnv :: [OccName] -> TidyOccEnv       -- Initialise with names to avoid!
596 initTidyOccEnv = foldl (\env occ -> extendOccEnv env occ 1) emptyTidyOccEnv
597
598 tidyOccName :: TidyOccEnv -> OccName -> (TidyOccEnv, OccName)
599
600 tidyOccName in_scope occ@(OccName occ_sp fs)
601   = case lookupOccEnv in_scope occ of
602         Nothing ->      -- Not already used: make it used
603                    (extendOccEnv in_scope occ 1, occ)
604
605         Just n  ->      -- Already used: make a new guess, 
606                         -- change the guess base, and try again
607                    tidyOccName  (extendOccEnv in_scope occ (n+1))
608                                 (mkOccName occ_sp (unpackFS fs ++ show n))
609 \end{code}
610
611 %************************************************************************
612 %*                                                                      *
613                 Stuff for dealing with tuples
614 %*                                                                      *
615 %************************************************************************
616
617 \begin{code}
618 mkTupleOcc :: NameSpace -> Boxity -> Arity -> OccName
619 mkTupleOcc ns bx ar = OccName ns (mkFastString str)
620   where
621         -- no need to cache these, the caching is done in the caller
622         -- (TysWiredIn.mk_tuple)
623     str = case bx of
624                 Boxed   -> '(' : commas ++ ")"
625                 Unboxed -> '(' : '#' : commas ++ "#)"
626
627     commas = take (ar-1) (repeat ',')
628
629 isTupleOcc_maybe :: OccName -> Maybe (NameSpace, Boxity, Arity)
630 -- Tuples are special, because there are so many of them!
631 isTupleOcc_maybe (OccName ns fs)
632   = case unpackFS fs of
633         '(':'#':',':rest -> Just (ns, Unboxed, 2 + count_commas rest)
634         '(':',':rest     -> Just (ns, Boxed,   2 + count_commas rest)
635         _other           -> Nothing
636   where
637     count_commas (',':rest) = 1 + count_commas rest
638     count_commas _          = 0
639 \end{code}
640
641 %************************************************************************
642 %*                                                                      *
643 \subsection{Lexical categories}
644 %*                                                                      *
645 %************************************************************************
646
647 These functions test strings to see if they fit the lexical categories
648 defined in the Haskell report.
649
650 \begin{code}
651 isLexCon,   isLexVar,    isLexId,    isLexSym    :: FastString -> Bool
652 isLexConId, isLexConSym, isLexVarId, isLexVarSym :: FastString -> Bool
653
654 isLexCon cs = isLexConId  cs || isLexConSym cs
655 isLexVar cs = isLexVarId  cs || isLexVarSym cs
656
657 isLexId  cs = isLexConId  cs || isLexVarId  cs
658 isLexSym cs = isLexConSym cs || isLexVarSym cs
659
660 -------------
661
662 isLexConId cs                           -- Prefix type or data constructors
663   | nullFS cs         = False           --      e.g. "Foo", "[]", "(,)" 
664   | cs == FSLIT("[]") = True
665   | otherwise         = startsConId (headFS cs)
666
667 isLexVarId cs                           -- Ordinary prefix identifiers
668   | nullFS cs         = False           --      e.g. "x", "_x"
669   | otherwise         = startsVarId (headFS cs)
670
671 isLexConSym cs                          -- Infix type or data constructors
672   | nullFS cs         = False           --      e.g. ":-:", ":", "->"
673   | cs == FSLIT("->") = True
674   | otherwise         = startsConSym (headFS cs)
675
676 isLexVarSym cs                          -- Infix identifiers
677   | nullFS cs         = False           --      e.g. "+"
678   | otherwise         = startsVarSym (headFS cs)
679
680 -------------
681 startsVarSym, startsVarId, startsConSym, startsConId :: Char -> Bool
682 startsVarSym c = isSymbolASCII c || (ord c > 0x7f && isSymbol c) -- Infix Ids
683 startsConSym c = c == ':'                               -- Infix data constructors
684 startsVarId c  = isLower c || c == '_'  -- Ordinary Ids
685 startsConId c  = isUpper c || c == '('  -- Ordinary type constructors and data constructors
686
687 isSymbolASCII c = c `elem` "!#$%&*+./<=>?@\\^|~-"
688 \end{code}
689
690 %************************************************************************
691 %*                                                                      *
692                 Binary instance
693     Here rather than BinIface because OccName is abstract
694 %*                                                                      *
695 %************************************************************************
696
697 \begin{code}
698 instance Binary NameSpace where
699     put_ bh VarName = do
700             putByte bh 0
701     put_ bh DataName = do
702             putByte bh 1
703     put_ bh TvName = do
704             putByte bh 2
705     put_ bh TcClsName = do
706             putByte bh 3
707     get bh = do
708             h <- getByte bh
709             case h of
710               0 -> do return VarName
711               1 -> do return DataName
712               2 -> do return TvName
713               _ -> do return TcClsName
714
715 instance Binary OccName where
716     put_ bh (OccName aa ab) = do
717             put_ bh aa
718             put_ bh ab
719     get bh = do
720           aa <- get bh
721           ab <- get bh
722           return (OccName aa ab)
723 \end{code}