OccName.lhs 22.1 KB
Newer Older
1
%
Simon Marlow's avatar
Simon Marlow committed
2
% (c) The University of Glasgow 2006
3 4 5 6
% (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
%

\begin{code}
7
{-# OPTIONS -w #-}
8 9 10
-- The above warning supression flag is a temporary kludge.
-- While working on this module you are encouraged to remove it and fix
-- any warnings in the module. See
11
--     http://hackage.haskell.org/trac/ghc/wiki/CodingStyle#Warnings
12 13
-- for details

14
module OccName (
15
	-- * The NameSpace type; abstact
16
	NameSpace, tcName, clsName, tcClsName, dataName, varName, 
17
	tvName, srcDataName,
18

19 20 21 22
	-- ** Printing
	pprNameSpace, pprNonVarNameSpace, pprNameSpaceBrief,

	-- * The OccName type
23
	OccName, 	-- Abstract, instance of Outputable
24
	pprOccName, 
25

26 27 28 29 30 31 32 33 34
	-- ** Construction	
	mkOccName, mkOccNameFS, 
	mkVarOcc, mkVarOccFS,
	mkTyVarOcc,
	mkDFunOcc,
	mkTupleOcc, 
	setOccNameSpace,

	-- ** Derived OccNames
35 36
	mkDataConWrapperOcc, mkWorkerOcc, mkDefaultMethodOcc,
	mkDerivedTyConOcc, mkNewTyCoOcc,
37 38 39
  	mkClassTyConOcc, mkClassDataConOcc, mkDictOcc, mkIPOcc, 
 	mkSpecOcc, mkForeignExportOcc, mkGenOcc1, mkGenOcc2,
	mkDataTOcc, mkDataCOcc, mkDataConWorkerOcc,
40
	mkSuperDictSelOcc, mkLocalOcc, mkMethodOcc, mkInstTyTcOcc,
41
	mkInstTyCoOcc, mkEqPredCoOcc,
42
        mkVectOcc, mkVectTyConOcc, mkVectDataConOcc, mkVectIsoOcc,
43 44 45
        mkPArrayTyConOcc, mkPArrayDataConOcc,
        mkPReprTyConOcc,
        mkPADFunOcc,
46 47 48 49 50 51 52 53 54

	-- ** Deconstruction
	occNameFS, occNameString, occNameSpace, 

	isVarOcc, isTvOcc, isTcOcc, isDataOcc, isDataSymOcc, isSymOcc, isValOcc,
	parenSymOcc, reportIfUnused, isTcClsName, isVarName,

	isTupleOcc_maybe,

55
	-- The OccEnv type
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
56
	OccEnv, emptyOccEnv, unitOccEnv, extendOccEnv, mapOccEnv,
57
	lookupOccEnv, mkOccEnv, mkOccEnv_C, extendOccEnvList, elemOccEnv,
58
	occEnvElts, foldOccEnv, plusOccEnv, plusOccEnv_C, extendOccEnv_C,
59 60

	-- The OccSet type
61 62
	OccSet, emptyOccSet, unitOccSet, mkOccSet, extendOccSet, 
	extendOccSetList,
63 64 65
	unionOccSets, unionManyOccSets, minusOccSet, elemOccSet, occSetElts, 
	foldOccSet, isEmptyOccSet, intersectOccSet, intersectsOccSet,

66 67 68
	-- Tidying up
	TidyOccEnv, emptyTidyOccEnv, tidyOccName, initTidyOccEnv,

69 70 71
	-- The basic form of names
	isLexCon, isLexVar, isLexId, isLexSym,
	isLexConId, isLexConSym, isLexVarId, isLexVarSym,
72
	startsVarSym, startsVarId, startsConSym, startsConId
73 74 75 76
    ) where

#include "HsVersions.h"

Simon Marlow's avatar
Simon Marlow committed
77 78 79 80
import Util
import Unique
import BasicTypes
import StaticFlags
81 82
import UniqFM
import UniqSet
83
import FastString
84
import Outputable
85 86
import Binary

Simon Marlow's avatar
Simon Marlow committed
87 88
import GHC.Exts
import Data.Char
89

90 91 92 93 94
-- Unicode TODO: put isSymbol in libcompat
#if __GLASGOW_HASKELL__ > 604
#else
isSymbol = const False
#endif
95 96 97 98 99 100 101 102 103 104

\end{code}

%************************************************************************
%*									*
\subsection{Name space}
%*									*
%************************************************************************

\begin{code}
105 106
data NameSpace = VarName	-- Variables, including "real" data constructors
	       | DataName	-- "Source" data constructors 
107 108
	       | TvName		-- Type variables
	       | TcClsName	-- Type constructors and classes; Haskell has them
109
				-- in the same name space for now.
110
	       deriving( Eq, Ord )
111
   {-! derive: Binary !-}
112

113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
-- Note [Data Constructors]  
-- see also: Note [Data Constructor Naming] in DataCon.lhs
-- 
--	"Source" data constructors are the data constructors mentioned
--	in Haskell source code
--
--	"Real" data constructors are the data constructors of the
--	representation type, which may not be the same as the source
--	type

-- Example:
--	data T = T !(Int,Int)
--
-- The source datacon has type (Int,Int) -> T
-- The real   datacon has type Int -> Int -> T
-- GHC chooses a representation based on the strictness etc.


131 132 133 134 135 136
-- Though type constructors and classes are in the same name space now,
-- the NameSpace type is abstract, so we can easily separate them later
tcName    = TcClsName		-- Type constructors
clsName   = TcClsName		-- Classes
tcClsName = TcClsName		-- Not sure which!

137 138 139
dataName    = DataName
srcDataName = DataName	-- Haskell-source data constructors should be
			-- in the Data name space
140

141 142
tvName      = TvName
varName     = VarName
143

144 145 146 147 148 149 150 151 152
isTcClsName :: NameSpace -> Bool
isTcClsName TcClsName = True
isTcClsName _	      = False

isVarName :: NameSpace -> Bool	-- Variables or type variables, but not constructors
isVarName TvName  = True
isVarName VarName = True
isVarName other   = False

153 154 155 156 157 158 159 160 161
pprNameSpace :: NameSpace -> SDoc
pprNameSpace DataName  = ptext SLIT("data constructor")
pprNameSpace VarName   = ptext SLIT("variable")
pprNameSpace TvName    = ptext SLIT("type variable")
pprNameSpace TcClsName = ptext SLIT("type constructor or class")

pprNonVarNameSpace :: NameSpace -> SDoc
pprNonVarNameSpace VarName = empty
pprNonVarNameSpace ns = pprNameSpace ns
162

163 164 165 166
pprNameSpaceBrief DataName  = char 'd'
pprNameSpaceBrief VarName   = char 'v'
pprNameSpaceBrief TvName    = ptext SLIT("tv")
pprNameSpaceBrief TcClsName = ptext SLIT("tc")
167 168 169 170 171 172 173 174 175 176
\end{code}


%************************************************************************
%*									*
\subsection[Name-pieces-datatypes]{The @OccName@ datatypes}
%*									*
%************************************************************************

\begin{code}
177
data OccName = OccName 
178
    { occNameSpace  :: !NameSpace
179
    , occNameFS     :: !FastString
180
    }
181 182 183 184 185 186 187 188
\end{code}


\begin{code}
instance Eq OccName where
    (OccName sp1 s1) == (OccName sp2 s2) = s1 == s2 && sp1 == sp2

instance Ord OccName where
189 190 191
	-- Compares lexicographically, *not* by Unique of the string
    compare (OccName sp1 s1) (OccName sp2 s2) 
	= (s1  `compare` s2) `thenCmp` (sp1 `compare` sp2)
192 193 194 195 196 197 198 199 200 201 202
\end{code}


%************************************************************************
%*									*
\subsection{Printing}
%*									*
%************************************************************************
 
\begin{code}
instance Outputable OccName where
203
    ppr = pprOccName
204 205

pprOccName :: OccName -> SDoc
206 207
pprOccName (OccName sp occ) 
  = getPprStyle $ \ sty ->
208 209 210 211 212
    if codeStyle sty 
	then ftext (zEncodeFS occ)
	else ftext occ <> if debugStyle sty 
			    then braces (pprNameSpaceBrief sp)
			    else empty
213 214 215 216 217 218 219
\end{code}


%************************************************************************
%*									*
\subsection{Construction}
%*									*
220
%************************************************************************
221 222

\begin{code}
223
mkOccName :: NameSpace -> String -> OccName
224
mkOccName occ_sp str = OccName occ_sp (mkFastString str)
225

226 227
mkOccNameFS :: NameSpace -> FastString -> OccName
mkOccNameFS occ_sp fs = OccName occ_sp fs
228

229 230
mkVarOcc :: String -> OccName
mkVarOcc s = mkOccName varName s
231

232 233
mkVarOccFS :: FastString -> OccName
mkVarOccFS fs = mkOccNameFS varName fs
234

235 236 237
mkTyVarOcc :: FastString -> OccName
mkTyVarOcc fs = mkOccNameFS tvName fs
\end{code}
238

239

240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
%************************************************************************
%*									*
		Environments
%*									*
%************************************************************************

OccEnvs are used mainly for the envts in ModIfaces.

They are efficient, because FastStrings have unique Int# keys.  We assume
this key is less than 2^24, so we can make a Unique using
	mkUnique ns key  :: Unique
where 'ns' is a Char reprsenting the name space.  This in turn makes it
easy to build an OccEnv.

\begin{code}
instance Uniquable OccName where
  getUnique (OccName ns fs)
      = mkUnique char (I# (uniqueOfFS fs))
      where	-- See notes above about this getUnique function
        char = case ns of
		VarName   -> 'i'
		DataName  -> 'd'
		TvName    -> 'v'
		TcClsName -> 't'

type OccEnv a = UniqFM a

emptyOccEnv :: OccEnv a
unitOccEnv  :: OccName -> a -> OccEnv a
extendOccEnv :: OccEnv a -> OccName -> a -> OccEnv a
extendOccEnvList :: OccEnv a -> [(OccName, a)] -> OccEnv a
lookupOccEnv :: OccEnv a -> OccName -> Maybe a
mkOccEnv     :: [(OccName,a)] -> OccEnv a
273
mkOccEnv_C   :: (a -> a -> a) -> [(OccName,a)] -> OccEnv a
274 275 276 277
elemOccEnv   :: OccName -> OccEnv a -> Bool
foldOccEnv   :: (a -> b -> b) -> b -> OccEnv a -> b
occEnvElts   :: OccEnv a -> [a]
extendOccEnv_C :: (a->a->a) -> OccEnv a -> OccName -> a -> OccEnv a
278
plusOccEnv     :: OccEnv a -> OccEnv a -> OccEnv a
279
plusOccEnv_C   :: (a->a->a) -> OccEnv a -> OccEnv a -> OccEnv a
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
280
mapOccEnv      :: (a->b) -> OccEnv a -> OccEnv b
281 282 283 284 285 286 287 288 289 290

emptyOccEnv  	 = emptyUFM
unitOccEnv   	 = unitUFM
extendOccEnv 	 = addToUFM
extendOccEnvList = addListToUFM
lookupOccEnv 	 = lookupUFM
mkOccEnv         = listToUFM
elemOccEnv	 = elemUFM
foldOccEnv	 = foldUFM
occEnvElts 	 = eltsUFM
291
plusOccEnv	 = plusUFM
292 293
plusOccEnv_C	 = plusUFM_C
extendOccEnv_C   = addToUFM_C
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
294
mapOccEnv	 = mapUFM
295

296 297
mkOccEnv_C comb l = addListToUFM_C comb emptyOccEnv l

298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
type OccSet = UniqFM OccName

emptyOccSet	  :: OccSet
unitOccSet	  :: OccName -> OccSet
mkOccSet          :: [OccName] -> OccSet
extendOccSet      :: OccSet -> OccName -> OccSet
extendOccSetList  :: OccSet -> [OccName] -> OccSet
unionOccSets	  :: OccSet -> OccSet -> OccSet
unionManyOccSets  :: [OccSet] -> OccSet
minusOccSet 	  :: OccSet -> OccSet -> OccSet
elemOccSet	  :: OccName -> OccSet -> Bool
occSetElts	  :: OccSet -> [OccName]
foldOccSet	  :: (OccName -> b -> b) -> b -> OccSet -> b
isEmptyOccSet	  :: OccSet -> Bool
intersectOccSet   :: OccSet -> OccSet -> OccSet
intersectsOccSet  :: OccSet -> OccSet -> Bool

emptyOccSet	  = emptyUniqSet
unitOccSet	  = unitUniqSet
mkOccSet          = mkUniqSet
extendOccSet	  = addOneToUniqSet
extendOccSetList  = addListToUniqSet
unionOccSets      = unionUniqSets
unionManyOccSets  = unionManyUniqSets
minusOccSet	  = minusUniqSet
elemOccSet        = elementOfUniqSet
occSetElts        = uniqSetToList
foldOccSet	  = foldUniqSet
isEmptyOccSet     = isEmptyUniqSet
intersectOccSet   = intersectUniqSets
intersectsOccSet s1 s2 = not (isEmptyOccSet (s1 `intersectOccSet` s2))
\end{code}


332 333
%************************************************************************
%*									*
334
\subsection{Predicates and taking them apart}
335 336 337
%*									*
%************************************************************************

338 339
\begin{code}
occNameString :: OccName -> String
340
occNameString (OccName _ s) = unpackFS s
341

342 343
setOccNameSpace :: NameSpace -> OccName -> OccName
setOccNameSpace sp (OccName _ occ) = OccName sp occ
344

345 346 347 348
isVarOcc, isTvOcc, isDataSymOcc, isSymOcc, isTcOcc :: OccName -> Bool

isVarOcc (OccName VarName _) = True
isVarOcc other               = False
349

350 351
isTvOcc (OccName TvName _) = True
isTvOcc other              = False
352

353 354 355
isTcOcc (OccName TcClsName _) = True
isTcOcc other                 = False

356 357 358 359
isValOcc (OccName VarName  _) = True
isValOcc (OccName DataName _) = True
isValOcc other		      = False

360 361
-- Data constructor operator (starts with ':', or '[]')
-- Pretty inefficient!
362
isDataSymOcc (OccName DataName s) = isLexConSym s
363 364 365
isDataSymOcc (OccName VarName s)  
  | isLexConSym s = pprPanic "isDataSymOcc: check me" (ppr s)
		-- Jan06: I don't think this should happen
366
isDataSymOcc other		  = False
367

368
isDataOcc (OccName DataName _) = True
369 370 371
isDataOcc (OccName VarName s)  
  | isLexCon s = pprPanic "isDataOcc: check me" (ppr s)
		-- Jan06: I don't think this should happen
372
isDataOcc other		       = False
373

374 375
-- Any operator (data constructor or variable)
-- Pretty inefficient!
376 377 378
isSymOcc (OccName DataName s)  = isLexConSym s
isSymOcc (OccName TcClsName s) = isLexConSym s
isSymOcc (OccName VarName s)   = isLexSym s
379 380 381 382 383 384
isSymOcc other		       = False

parenSymOcc :: OccName -> SDoc -> SDoc
-- Wrap parens around an operator
parenSymOcc occ doc | isSymOcc occ = parens doc
		    | otherwise    = doc
385
\end{code}
386 387


388 389 390 391
\begin{code}
reportIfUnused :: OccName -> Bool
  -- Haskell 98 encourages compilers to suppress warnings about
  -- unused names in a pattern if they start with "_".
392
reportIfUnused occ = case occNameString occ of
393
			('_' : _) -> False
394
			_other    -> True
395 396 397
\end{code}


398 399 400 401 402
%************************************************************************
%*									*
\subsection{Making system names}
%*									*
%************************************************************************
403

404
Here's our convention for splitting up the interface file name space:
405

406 407
	d...		dictionary identifiers
			(local variables, so no name-clash worries)
408

409
	$f...		dict-fun identifiers (from inst decls)
410
	$dm...		default methods
411 412
	$p...		superclass selectors
	$w...		workers
apt's avatar
apt committed
413 414
	:T...		compiler-generated tycons for dictionaries
	:D...		...ditto data cons
SamB's avatar
SamB committed
415
        :Co...          ...ditto coercions
416
	$sf..		specialised version of f
417

418
	in encoded form these appear as Zdfxxx etc
419

420
	:...		keywords (export:, letrec: etc.)
apt's avatar
apt committed
421
--- I THINK THIS IS WRONG!
422

423 424 425
This knowledge is encoded in the following functions.


apt's avatar
apt committed
426
@mk_deriv@ generates an @OccName@ from the prefix and a string.
427
NB: The string must already be encoded!
428 429

\begin{code}
430 431
mk_deriv :: NameSpace 
	 -> String		-- Distinguishes one sort of derived name from another
432
	 -> String
433
	 -> OccName
434

435
mk_deriv occ_sp sys_prefix str = mkOccName occ_sp (sys_prefix ++ str)
436
\end{code}
437

438
\begin{code}
439 440 441
mkDataConWrapperOcc, mkWorkerOcc, mkDefaultMethodOcc, mkDerivedTyConOcc,
  	mkClassTyConOcc, mkClassDataConOcc, mkDictOcc, mkIPOcc, 
 	mkSpecOcc, mkForeignExportOcc, mkGenOcc1, mkGenOcc2,
442
	mkDataTOcc, mkDataCOcc, mkDataConWorkerOcc, mkNewTyCoOcc
443 444
   :: OccName -> OccName

445
-- These derived variables have a prefix that no Haskell value could have
446
mkDataConWrapperOcc = mk_simple_deriv varName  "$W"
447 448 449 450
mkWorkerOcc         = mk_simple_deriv varName  "$w"
mkDefaultMethodOcc  = mk_simple_deriv varName  "$dm"
mkDerivedTyConOcc   = mk_simple_deriv tcName   ":"	-- The : prefix makes sure it classifies
mkClassTyConOcc     = mk_simple_deriv tcName   ":T"	-- as a tycon/datacon
451 452
mkClassDataConOcc   = mk_simple_deriv dataName ":D"	-- We go straight to the "real" data con
							-- for datacons from classes
453 454 455 456
mkDictOcc	    = mk_simple_deriv varName  "$d"
mkIPOcc		    = mk_simple_deriv varName  "$i"
mkSpecOcc	    = mk_simple_deriv varName  "$s"
mkForeignExportOcc  = mk_simple_deriv varName  "$f"
457
mkNewTyCoOcc        = mk_simple_deriv tcName  ":Co"
458
mkInstTyCoOcc       = mk_simple_deriv tcName  ":CoF"     -- derived from rep ty
459
mkEqPredCoOcc	    = mk_simple_deriv tcName  "$co"
460 461 462 463 464 465 466 467 468 469 470

-- Generic derivable classes
mkGenOcc1           = mk_simple_deriv varName  "$gfrom"
mkGenOcc2           = mk_simple_deriv varName  "$gto" 

-- data T = MkT ... deriving( Data ) needs defintions for 
--	$tT   :: Data.Generics.Basics.DataType
--	$cMkT :: Data.Generics.Basics.Constr
mkDataTOcc = mk_simple_deriv varName  "$t"
mkDataCOcc = mk_simple_deriv varName  "$c"

471
-- Vectorisation
472 473 474 475 476 477
mkVectOcc          = mk_simple_deriv varName  "$v_"
mkVectTyConOcc     = mk_simple_deriv tcName   ":V_"
mkVectDataConOcc   = mk_simple_deriv dataName ":VD_"
mkVectIsoOcc       = mk_simple_deriv varName  "$VI_"
mkPArrayTyConOcc   = mk_simple_deriv tcName   ":VP_"
mkPArrayDataConOcc = mk_simple_deriv dataName ":VPD_"
478
mkPReprTyConOcc    = mk_simple_deriv tcName   ":VR_"
479
mkPADFunOcc        = mk_simple_deriv varName  "$PA_"
480

481
mk_simple_deriv sp px occ = mk_deriv sp px (occNameString occ)
482 483 484

-- Data constructor workers are made by setting the name space
-- of the data constructor OccName (which should be a DataName)
485
-- to VarName
486
mkDataConWorkerOcc datacon_occ = setOccNameSpace varName datacon_occ 
487 488 489 490 491
\end{code}

\begin{code}
mkSuperDictSelOcc :: Int 	-- Index of superclass, eg 3
		  -> OccName 	-- Class, eg "Ord"
492
		  -> OccName	-- eg "$p3Ord"
493
mkSuperDictSelOcc index cls_occ
494
  = mk_deriv varName "$p" (show index ++ occNameString cls_occ)
495 496 497 498 499

mkLocalOcc :: Unique 		-- Unique
	   -> OccName		-- Local name (e.g. "sat")
	   -> OccName		-- Nice unique version ("$L23sat")
mkLocalOcc uniq occ
500 501 502
   = mk_deriv varName ("$L" ++ show uniq) (occNameString occ)
	-- The Unique might print with characters 
	-- that need encoding (e.g. 'z'!)
503 504
\end{code}

505 506
Derive a name for the representation type constructor of a data/newtype
instance.
507

508
\begin{code}
509
mkInstTyTcOcc :: Int			-- Index
510
	      -> OccName		-- Family name (e.g. "Map")
511
	      -> OccName		-- Nice unique version (":R23Map")
512
mkInstTyTcOcc index occ
513
   = mk_deriv tcName (":R" ++ show index) (occNameString occ)
514
\end{code}
515 516

\begin{code}
517
mkDFunOcc :: String		-- Typically the class and type glommed together e.g. "OrdMaybe"
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
				-- Only used in debug mode, for extra clarity
	  -> Bool		-- True <=> hs-boot instance dfun
	  -> Int		-- Unique index
	  -> OccName		-- "$f3OrdMaybe"

-- In hs-boot files we make dict funs like $fx7ClsTy, which get bound to the real
-- thing when we compile the mother module. Reason: we don't know exactly
-- what the  mother module will call it.

mkDFunOcc info_str is_boot index 
  = mk_deriv VarName prefix string
  where
    prefix | is_boot   = "$fx"
	   | otherwise = "$f"
    string | opt_PprStyle_Debug = show index ++ info_str
	   | otherwise		= show index
534 535
\end{code}

536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557
We used to add a '$m' to indicate a method, but that gives rise to bad
error messages from the type checker when we print the function name or pattern
of an instance-decl binding.  Why? Because the binding is zapped
to use the method name in place of the selector name.
(See TcClassDcl.tcMethodBind)

The way it is now, -ddump-xx output may look confusing, but
you can always say -dppr-debug to get the uniques.

However, we *do* have to zap the first character to be lower case,
because overloaded constructors (blarg) generate methods too.
And convert to VarName space

e.g. a call to constructor MkFoo where
	data (Ord a) => Foo a = MkFoo a

If this is necessary, we do it by prefixing '$m'.  These 
guys never show up in error messages.  What a hack.

\begin{code}
mkMethodOcc :: OccName -> OccName
mkMethodOcc occ@(OccName VarName fs) = occ
558
mkMethodOcc occ			     = mk_simple_deriv varName "$m" occ
559 560
\end{code}

561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579

%************************************************************************
%*									*
\subsection{Tidying them up}
%*									*
%************************************************************************

Before we print chunks of code we like to rename it so that
we don't have to print lots of silly uniques in it.  But we mustn't
accidentally introduce name clashes!  So the idea is that we leave the
OccName alone unless it accidentally clashes with one that is already
in scope; if so, we tack on '1' at the end and try again, then '2', and
so on till we find a unique one.

There's a wrinkle for operators.  Consider '>>='.  We can't use '>>=1' 
because that isn't a single lexeme.  So we encode it to 'lle' and *then*
tack on the '1', if necessary.

\begin{code}
580 581 582 583
type TidyOccEnv = OccEnv Int	-- The in-scope OccNames
	-- Range gives a plausible starting point for new guesses

emptyTidyOccEnv = emptyOccEnv
584 585

initTidyOccEnv :: [OccName] -> TidyOccEnv	-- Initialise with names to avoid!
586
initTidyOccEnv = foldl (\env occ -> extendOccEnv env occ 1) emptyTidyOccEnv
587 588 589

tidyOccName :: TidyOccEnv -> OccName -> (TidyOccEnv, OccName)

590
tidyOccName in_scope occ@(OccName occ_sp fs)
591 592 593 594 595 596 597
  = case lookupOccEnv in_scope occ of
	Nothing -> 	-- Not already used: make it used
		   (extendOccEnv in_scope occ 1, occ)

	Just n  -> 	-- Already used: make a new guess, 
			-- change the guess base, and try again
		   tidyOccName  (extendOccEnv in_scope occ (n+1))
598
				(mkOccName occ_sp (unpackFS fs ++ show n))
599 600
\end{code}

601 602 603 604 605 606 607 608
%************************************************************************
%*									*
		Stuff for dealing with tuples
%*									*
%************************************************************************

\begin{code}
mkTupleOcc :: NameSpace -> Boxity -> Arity -> OccName
609
mkTupleOcc ns bx ar = OccName ns (mkFastString str)
610
  where
611 612 613 614 615 616 617
 	-- no need to cache these, the caching is done in the caller
	-- (TysWiredIn.mk_tuple)
    str = case bx of
		Boxed   -> '(' : commas ++ ")"
		Unboxed -> '(' : '#' : commas ++ "#)"

    commas = take (ar-1) (repeat ',')
618 619 620 621 622

isTupleOcc_maybe :: OccName -> Maybe (NameSpace, Boxity, Arity)
-- Tuples are special, because there are so many of them!
isTupleOcc_maybe (OccName ns fs)
  = case unpackFS fs of
623 624 625
	'(':'#':',':rest -> Just (ns, Unboxed, 2 + count_commas rest)
	'(':',':rest     -> Just (ns, Boxed,   2 + count_commas rest)
	_other           -> Nothing
626
  where
627 628
    count_commas (',':rest) = 1 + count_commas rest
    count_commas _          = 0
629
\end{code}
630 631 632

%************************************************************************
%*									*
apt's avatar
apt committed
633
\subsection{Lexical categories}
634 635 636
%*									*
%************************************************************************

637 638
These functions test strings to see if they fit the lexical categories
defined in the Haskell report.
639 640

\begin{code}
641 642
isLexCon,   isLexVar,    isLexId,    isLexSym    :: FastString -> Bool
isLexConId, isLexConSym, isLexVarId, isLexVarSym :: FastString -> Bool
643

644 645
isLexCon cs = isLexConId  cs || isLexConSym cs
isLexVar cs = isLexVarId  cs || isLexVarSym cs
646

647 648
isLexId  cs = isLexConId  cs || isLexVarId  cs
isLexSym cs = isLexConSym cs || isLexVarSym cs
649

650
-------------
651

652
isLexConId cs				-- Prefix type or data constructors
653
  | nullFS cs	      = False		-- 	e.g. "Foo", "[]", "(,)" 
654
  | cs == FSLIT("[]") = True
655
  | otherwise	      = startsConId (headFS cs)
656

657
isLexVarId cs				-- Ordinary prefix identifiers
658
  | nullFS cs	      = False		-- 	e.g. "x", "_x"
659
  | otherwise         = startsVarId (headFS cs)
660

661
isLexConSym cs				-- Infix type or data constructors
662
  | nullFS cs	      = False		--	e.g. ":-:", ":", "->"
663
  | cs == FSLIT("->") = True
664
  | otherwise	      = startsConSym (headFS cs)
665 666

isLexVarSym cs				-- Infix identifiers
667
  | nullFS cs	      = False		-- 	e.g. "+"
668
  | otherwise         = startsVarSym (headFS cs)
669 670

-------------
671
startsVarSym, startsVarId, startsConSym, startsConId :: Char -> Bool
672
startsVarSym c = isSymbolASCII c || (ord c > 0x7f && isSymbol c) -- Infix Ids
673
startsConSym c = c == ':'				-- Infix data constructors
674 675
startsVarId c  = isLower c || c == '_'	-- Ordinary Ids
startsConId c  = isUpper c || c == '('	-- Ordinary type constructors and data constructors
676

677
isSymbolASCII c = c `elem` "!#$%&*+./<=>?@\\^|~-"
678
\end{code}
679 680 681 682 683 684 685 686

%************************************************************************
%*									*
		Binary instance
    Here rather than BinIface because OccName is abstract
%*									*
%************************************************************************

687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713
\begin{code}
instance Binary NameSpace where
    put_ bh VarName = do
	    putByte bh 0
    put_ bh DataName = do
	    putByte bh 1
    put_ bh TvName = do
	    putByte bh 2
    put_ bh TcClsName = do
	    putByte bh 3
    get bh = do
	    h <- getByte bh
	    case h of
	      0 -> do return VarName
	      1 -> do return DataName
	      2 -> do return TvName
	      _ -> do return TcClsName

instance Binary OccName where
    put_ bh (OccName aa ab) = do
	    put_ bh aa
	    put_ bh ab
    get bh = do
	  aa <- get bh
	  ab <- get bh
	  return (OccName aa ab)
\end{code}