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