Add deepseq dependency and a few NFData instances
[ghc.git] / compiler / basicTypes / OccName.hs
1 {-
2 (c) The University of Glasgow 2006
3 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 -}
5
6 {-# LANGUAGE DeriveDataTypeable #-}
7 {-# LANGUAGE BangPatterns #-}
8 {-# LANGUAGE OverloadedStrings #-}
9
10 -- |
11 -- #name_types#
12 -- GHC uses several kinds of name internally:
13 --
14 -- * 'OccName.OccName' represents names as strings with just a little more information:
15 -- the \"namespace\" that the name came from, e.g. the namespace of value, type constructors or
16 -- data constructors
17 --
18 -- * 'RdrName.RdrName': see "RdrName#name_types"
19 --
20 -- * 'Name.Name': see "Name#name_types"
21 --
22 -- * 'Id.Id': see "Id#name_types"
23 --
24 -- * 'Var.Var': see "Var#name_types"
25
26 module OccName (
27 -- * The 'NameSpace' type
28 NameSpace, -- Abstract
29
30 nameSpacesRelated,
31
32 -- ** Construction
33 -- $real_vs_source_data_constructors
34 tcName, clsName, tcClsName, dataName, varName,
35 tvName, srcDataName,
36
37 -- ** Pretty Printing
38 pprNameSpace, pprNonVarNameSpace, pprNameSpaceBrief,
39
40 -- * The 'OccName' type
41 OccName, -- Abstract, instance of Outputable
42 pprOccName,
43
44 -- ** Construction
45 mkOccName, mkOccNameFS,
46 mkVarOcc, mkVarOccFS,
47 mkDataOcc, mkDataOccFS,
48 mkTyVarOcc, mkTyVarOccFS,
49 mkTcOcc, mkTcOccFS,
50 mkClsOcc, mkClsOccFS,
51 mkDFunOcc,
52 setOccNameSpace,
53 demoteOccName,
54 HasOccName(..),
55
56 -- ** Derived 'OccName's
57 isDerivedOccName,
58 mkDataConWrapperOcc, mkWorkerOcc,
59 mkMatcherOcc, mkBuilderOcc,
60 mkDefaultMethodOcc,
61 mkNewTyCoOcc, mkClassOpAuxOcc,
62 mkCon2TagOcc, mkTag2ConOcc, mkMaxTagOcc,
63 mkClassDataConOcc, mkDictOcc, mkIPOcc,
64 mkSpecOcc, mkForeignExportOcc, mkRepEqOcc,
65 mkGenR, mkGen1R,
66 mkDataTOcc, mkDataCOcc, mkDataConWorkerOcc,
67 mkSuperDictSelOcc, mkSuperDictAuxOcc,
68 mkLocalOcc, mkMethodOcc, mkInstTyTcOcc,
69 mkInstTyCoOcc, mkEqPredCoOcc,
70 mkVectOcc, mkVectTyConOcc, mkVectDataConOcc, mkVectIsoOcc,
71 mkPDataTyConOcc, mkPDataDataConOcc,
72 mkPDatasTyConOcc, mkPDatasDataConOcc,
73 mkPReprTyConOcc,
74 mkPADFunOcc,
75 mkRecFldSelOcc,
76 mkTyConRepOcc,
77
78 -- ** Deconstruction
79 occNameFS, occNameString, occNameSpace,
80
81 isVarOcc, isTvOcc, isTcOcc, isDataOcc, isDataSymOcc, isSymOcc, isValOcc,
82 parenSymOcc, startsWithUnderscore,
83
84 isTcClsNameSpace, isTvNameSpace, isDataConNameSpace, isVarNameSpace, isValNameSpace,
85
86 -- * The 'OccEnv' type
87 OccEnv, emptyOccEnv, unitOccEnv, extendOccEnv, mapOccEnv,
88 lookupOccEnv, mkOccEnv, mkOccEnv_C, extendOccEnvList, elemOccEnv,
89 occEnvElts, foldOccEnv, plusOccEnv, plusOccEnv_C, extendOccEnv_C,
90 extendOccEnv_Acc, filterOccEnv, delListFromOccEnv, delFromOccEnv,
91 alterOccEnv, pprOccEnv,
92
93 -- * The 'OccSet' type
94 OccSet, emptyOccSet, unitOccSet, mkOccSet, extendOccSet,
95 extendOccSetList,
96 unionOccSets, unionManyOccSets, minusOccSet, elemOccSet,
97 isEmptyOccSet, intersectOccSet, intersectsOccSet,
98 filterOccSet,
99
100 -- * Tidying up
101 TidyOccEnv, emptyTidyOccEnv, initTidyOccEnv,
102 tidyOccName,
103 tidyOccNames, avoidClashesOccEnv,
104
105 -- FsEnv
106 FastStringEnv, emptyFsEnv, lookupFsEnv, extendFsEnv, mkFsEnv
107 ) where
108
109 import Util
110 import Unique
111 import DynFlags
112 import UniqFM
113 import UniqSet
114 import FastString
115 import FastStringEnv
116 import Outputable
117 import Lexeme
118 import Binary
119 import Control.DeepSeq
120 import Data.List (mapAccumL)
121 import Data.Char
122 import Data.Data
123
124 {-
125 ************************************************************************
126 * *
127 \subsection{Name space}
128 * *
129 ************************************************************************
130 -}
131
132 data NameSpace = VarName -- Variables, including "real" data constructors
133 | DataName -- "Source" data constructors
134 | TvName -- Type variables
135 | TcClsName -- Type constructors and classes; Haskell has them
136 -- in the same name space for now.
137 deriving( Eq, Ord )
138 {-! derive: Binary !-}
139
140 -- Note [Data Constructors]
141 -- see also: Note [Data Constructor Naming] in DataCon.hs
142 --
143 -- $real_vs_source_data_constructors
144 -- There are two forms of data constructor:
145 --
146 -- [Source data constructors] The data constructors mentioned in Haskell source code
147 --
148 -- [Real data constructors] The data constructors of the representation type, which may not be the same as the source type
149 --
150 -- For example:
151 --
152 -- > data T = T !(Int, Int)
153 --
154 -- The source datacon has type @(Int, Int) -> T@
155 -- The real datacon has type @Int -> Int -> T@
156 --
157 -- GHC chooses a representation based on the strictness etc.
158
159 tcName, clsName, tcClsName :: NameSpace
160 dataName, srcDataName :: NameSpace
161 tvName, varName :: NameSpace
162
163 -- Though type constructors and classes are in the same name space now,
164 -- the NameSpace type is abstract, so we can easily separate them later
165 tcName = TcClsName -- Type constructors
166 clsName = TcClsName -- Classes
167 tcClsName = TcClsName -- Not sure which!
168
169 dataName = DataName
170 srcDataName = DataName -- Haskell-source data constructors should be
171 -- in the Data name space
172
173 tvName = TvName
174 varName = VarName
175
176 isDataConNameSpace :: NameSpace -> Bool
177 isDataConNameSpace DataName = True
178 isDataConNameSpace _ = False
179
180 isTcClsNameSpace :: NameSpace -> Bool
181 isTcClsNameSpace TcClsName = True
182 isTcClsNameSpace _ = False
183
184 isTvNameSpace :: NameSpace -> Bool
185 isTvNameSpace TvName = True
186 isTvNameSpace _ = False
187
188 isVarNameSpace :: NameSpace -> Bool -- Variables or type variables, but not constructors
189 isVarNameSpace TvName = True
190 isVarNameSpace VarName = True
191 isVarNameSpace _ = False
192
193 isValNameSpace :: NameSpace -> Bool
194 isValNameSpace DataName = True
195 isValNameSpace VarName = True
196 isValNameSpace _ = False
197
198 pprNameSpace :: NameSpace -> SDoc
199 pprNameSpace DataName = text "data constructor"
200 pprNameSpace VarName = text "variable"
201 pprNameSpace TvName = text "type variable"
202 pprNameSpace TcClsName = text "type constructor or class"
203
204 pprNonVarNameSpace :: NameSpace -> SDoc
205 pprNonVarNameSpace VarName = empty
206 pprNonVarNameSpace ns = pprNameSpace ns
207
208 pprNameSpaceBrief :: NameSpace -> SDoc
209 pprNameSpaceBrief DataName = char 'd'
210 pprNameSpaceBrief VarName = char 'v'
211 pprNameSpaceBrief TvName = text "tv"
212 pprNameSpaceBrief TcClsName = text "tc"
213
214 -- demoteNameSpace lowers the NameSpace if possible. We can not know
215 -- in advance, since a TvName can appear in an HsTyVar.
216 -- See Note [Demotion] in RnEnv
217 demoteNameSpace :: NameSpace -> Maybe NameSpace
218 demoteNameSpace VarName = Nothing
219 demoteNameSpace DataName = Nothing
220 demoteNameSpace TvName = Nothing
221 demoteNameSpace TcClsName = Just DataName
222
223 {-
224 ************************************************************************
225 * *
226 \subsection[Name-pieces-datatypes]{The @OccName@ datatypes}
227 * *
228 ************************************************************************
229 -}
230
231 data OccName = OccName
232 { occNameSpace :: !NameSpace
233 , occNameFS :: !FastString
234 }
235
236 instance Eq OccName where
237 (OccName sp1 s1) == (OccName sp2 s2) = s1 == s2 && sp1 == sp2
238
239 instance Ord OccName where
240 -- Compares lexicographically, *not* by Unique of the string
241 compare (OccName sp1 s1) (OccName sp2 s2)
242 = (s1 `compare` s2) `thenCmp` (sp1 `compare` sp2)
243
244 instance Data OccName where
245 -- don't traverse?
246 toConstr _ = abstractConstr "OccName"
247 gunfold _ _ = error "gunfold"
248 dataTypeOf _ = mkNoRepType "OccName"
249
250 instance HasOccName OccName where
251 occName = id
252
253 instance NFData OccName where
254 rnf x = x `seq` ()
255
256 {-
257 ************************************************************************
258 * *
259 \subsection{Printing}
260 * *
261 ************************************************************************
262 -}
263
264 instance Outputable OccName where
265 ppr = pprOccName
266
267 instance OutputableBndr OccName where
268 pprBndr _ = ppr
269 pprInfixOcc n = pprInfixVar (isSymOcc n) (ppr n)
270 pprPrefixOcc n = pprPrefixVar (isSymOcc n) (ppr n)
271
272 pprOccName :: OccName -> SDoc
273 pprOccName (OccName sp occ)
274 = getPprStyle $ \ sty ->
275 if codeStyle sty
276 then ztext (zEncodeFS occ)
277 else pp_occ <> pp_debug sty
278 where
279 pp_debug sty | debugStyle sty = braces (pprNameSpaceBrief sp)
280 | otherwise = empty
281
282 pp_occ = sdocWithDynFlags $ \dflags ->
283 if gopt Opt_SuppressUniques dflags
284 then text (strip_th_unique (unpackFS occ))
285 else ftext occ
286
287 -- See Note [Suppressing uniques in OccNames]
288 strip_th_unique ('[' : c : _) | isAlphaNum c = []
289 strip_th_unique (c : cs) = c : strip_th_unique cs
290 strip_th_unique [] = []
291
292 {-
293 Note [Suppressing uniques in OccNames]
294 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
295 This is a hack to de-wobblify the OccNames that contain uniques from
296 Template Haskell that have been turned into a string in the OccName.
297 See Note [Unique OccNames from Template Haskell] in Convert.hs
298
299 ************************************************************************
300 * *
301 \subsection{Construction}
302 * *
303 ************************************************************************
304 -}
305
306 mkOccName :: NameSpace -> String -> OccName
307 mkOccName occ_sp str = OccName occ_sp (mkFastString str)
308
309 mkOccNameFS :: NameSpace -> FastString -> OccName
310 mkOccNameFS occ_sp fs = OccName occ_sp fs
311
312 mkVarOcc :: String -> OccName
313 mkVarOcc s = mkOccName varName s
314
315 mkVarOccFS :: FastString -> OccName
316 mkVarOccFS fs = mkOccNameFS varName fs
317
318 mkDataOcc :: String -> OccName
319 mkDataOcc = mkOccName dataName
320
321 mkDataOccFS :: FastString -> OccName
322 mkDataOccFS = mkOccNameFS dataName
323
324 mkTyVarOcc :: String -> OccName
325 mkTyVarOcc = mkOccName tvName
326
327 mkTyVarOccFS :: FastString -> OccName
328 mkTyVarOccFS fs = mkOccNameFS tvName fs
329
330 mkTcOcc :: String -> OccName
331 mkTcOcc = mkOccName tcName
332
333 mkTcOccFS :: FastString -> OccName
334 mkTcOccFS = mkOccNameFS tcName
335
336 mkClsOcc :: String -> OccName
337 mkClsOcc = mkOccName clsName
338
339 mkClsOccFS :: FastString -> OccName
340 mkClsOccFS = mkOccNameFS clsName
341
342 -- demoteOccName lowers the Namespace of OccName.
343 -- see Note [Demotion]
344 demoteOccName :: OccName -> Maybe OccName
345 demoteOccName (OccName space name) = do
346 space' <- demoteNameSpace space
347 return $ OccName space' name
348
349 -- Name spaces are related if there is a chance to mean the one when one writes
350 -- the other, i.e. variables <-> data constructors and type variables <-> type constructors
351 nameSpacesRelated :: NameSpace -> NameSpace -> Bool
352 nameSpacesRelated ns1 ns2 = ns1 == ns2 || otherNameSpace ns1 == ns2
353
354 otherNameSpace :: NameSpace -> NameSpace
355 otherNameSpace VarName = DataName
356 otherNameSpace DataName = VarName
357 otherNameSpace TvName = TcClsName
358 otherNameSpace TcClsName = TvName
359
360
361
362 {- | Other names in the compiler add additional information to an OccName.
363 This class provides a consistent way to access the underlying OccName. -}
364 class HasOccName name where
365 occName :: name -> OccName
366
367 {-
368 ************************************************************************
369 * *
370 Environments
371 * *
372 ************************************************************************
373
374 OccEnvs are used mainly for the envts in ModIfaces.
375
376 Note [The Unique of an OccName]
377 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
378 They are efficient, because FastStrings have unique Int# keys. We assume
379 this key is less than 2^24, and indeed FastStrings are allocated keys
380 sequentially starting at 0.
381
382 So we can make a Unique using
383 mkUnique ns key :: Unique
384 where 'ns' is a Char representing the name space. This in turn makes it
385 easy to build an OccEnv.
386 -}
387
388 instance Uniquable OccName where
389 -- See Note [The Unique of an OccName]
390 getUnique (OccName VarName fs) = mkVarOccUnique fs
391 getUnique (OccName DataName fs) = mkDataOccUnique fs
392 getUnique (OccName TvName fs) = mkTvOccUnique fs
393 getUnique (OccName TcClsName fs) = mkTcOccUnique fs
394
395 newtype OccEnv a = A (UniqFM a)
396 deriving Data
397
398 emptyOccEnv :: OccEnv a
399 unitOccEnv :: OccName -> a -> OccEnv a
400 extendOccEnv :: OccEnv a -> OccName -> a -> OccEnv a
401 extendOccEnvList :: OccEnv a -> [(OccName, a)] -> OccEnv a
402 lookupOccEnv :: OccEnv a -> OccName -> Maybe a
403 mkOccEnv :: [(OccName,a)] -> OccEnv a
404 mkOccEnv_C :: (a -> a -> a) -> [(OccName,a)] -> OccEnv a
405 elemOccEnv :: OccName -> OccEnv a -> Bool
406 foldOccEnv :: (a -> b -> b) -> b -> OccEnv a -> b
407 occEnvElts :: OccEnv a -> [a]
408 extendOccEnv_C :: (a->a->a) -> OccEnv a -> OccName -> a -> OccEnv a
409 extendOccEnv_Acc :: (a->b->b) -> (a->b) -> OccEnv b -> OccName -> a -> OccEnv b
410 plusOccEnv :: OccEnv a -> OccEnv a -> OccEnv a
411 plusOccEnv_C :: (a->a->a) -> OccEnv a -> OccEnv a -> OccEnv a
412 mapOccEnv :: (a->b) -> OccEnv a -> OccEnv b
413 delFromOccEnv :: OccEnv a -> OccName -> OccEnv a
414 delListFromOccEnv :: OccEnv a -> [OccName] -> OccEnv a
415 filterOccEnv :: (elt -> Bool) -> OccEnv elt -> OccEnv elt
416 alterOccEnv :: (Maybe elt -> Maybe elt) -> OccEnv elt -> OccName -> OccEnv elt
417
418 emptyOccEnv = A emptyUFM
419 unitOccEnv x y = A $ unitUFM x y
420 extendOccEnv (A x) y z = A $ addToUFM x y z
421 extendOccEnvList (A x) l = A $ addListToUFM x l
422 lookupOccEnv (A x) y = lookupUFM x y
423 mkOccEnv l = A $ listToUFM l
424 elemOccEnv x (A y) = elemUFM x y
425 foldOccEnv a b (A c) = foldUFM a b c
426 occEnvElts (A x) = eltsUFM x
427 plusOccEnv (A x) (A y) = A $ plusUFM x y
428 plusOccEnv_C f (A x) (A y) = A $ plusUFM_C f x y
429 extendOccEnv_C f (A x) y z = A $ addToUFM_C f x y z
430 extendOccEnv_Acc f g (A x) y z = A $ addToUFM_Acc f g x y z
431 mapOccEnv f (A x) = A $ mapUFM f x
432 mkOccEnv_C comb l = A $ addListToUFM_C comb emptyUFM l
433 delFromOccEnv (A x) y = A $ delFromUFM x y
434 delListFromOccEnv (A x) y = A $ delListFromUFM x y
435 filterOccEnv x (A y) = A $ filterUFM x y
436 alterOccEnv fn (A y) k = A $ alterUFM fn y k
437
438 instance Outputable a => Outputable (OccEnv a) where
439 ppr x = pprOccEnv ppr x
440
441 pprOccEnv :: (a -> SDoc) -> OccEnv a -> SDoc
442 pprOccEnv ppr_elt (A env) = pprUniqFM ppr_elt env
443
444 type OccSet = UniqSet OccName
445
446 emptyOccSet :: OccSet
447 unitOccSet :: OccName -> OccSet
448 mkOccSet :: [OccName] -> OccSet
449 extendOccSet :: OccSet -> OccName -> OccSet
450 extendOccSetList :: OccSet -> [OccName] -> OccSet
451 unionOccSets :: OccSet -> OccSet -> OccSet
452 unionManyOccSets :: [OccSet] -> OccSet
453 minusOccSet :: OccSet -> OccSet -> OccSet
454 elemOccSet :: OccName -> OccSet -> Bool
455 isEmptyOccSet :: OccSet -> Bool
456 intersectOccSet :: OccSet -> OccSet -> OccSet
457 intersectsOccSet :: OccSet -> OccSet -> Bool
458 filterOccSet :: (OccName -> Bool) -> OccSet -> OccSet
459
460 emptyOccSet = emptyUniqSet
461 unitOccSet = unitUniqSet
462 mkOccSet = mkUniqSet
463 extendOccSet = addOneToUniqSet
464 extendOccSetList = addListToUniqSet
465 unionOccSets = unionUniqSets
466 unionManyOccSets = unionManyUniqSets
467 minusOccSet = minusUniqSet
468 elemOccSet = elementOfUniqSet
469 isEmptyOccSet = isEmptyUniqSet
470 intersectOccSet = intersectUniqSets
471 intersectsOccSet s1 s2 = not (isEmptyOccSet (s1 `intersectOccSet` s2))
472 filterOccSet = filterUniqSet
473
474 {-
475 ************************************************************************
476 * *
477 \subsection{Predicates and taking them apart}
478 * *
479 ************************************************************************
480 -}
481
482 occNameString :: OccName -> String
483 occNameString (OccName _ s) = unpackFS s
484
485 setOccNameSpace :: NameSpace -> OccName -> OccName
486 setOccNameSpace sp (OccName _ occ) = OccName sp occ
487
488 isVarOcc, isTvOcc, isTcOcc, isDataOcc :: OccName -> Bool
489
490 isVarOcc (OccName VarName _) = True
491 isVarOcc _ = False
492
493 isTvOcc (OccName TvName _) = True
494 isTvOcc _ = False
495
496 isTcOcc (OccName TcClsName _) = True
497 isTcOcc _ = False
498
499 -- | /Value/ 'OccNames's are those that are either in
500 -- the variable or data constructor namespaces
501 isValOcc :: OccName -> Bool
502 isValOcc (OccName VarName _) = True
503 isValOcc (OccName DataName _) = True
504 isValOcc _ = False
505
506 isDataOcc (OccName DataName _) = True
507 isDataOcc _ = False
508
509 -- | Test if the 'OccName' is a data constructor that starts with
510 -- a symbol (e.g. @:@, or @[]@)
511 isDataSymOcc :: OccName -> Bool
512 isDataSymOcc (OccName DataName s) = isLexConSym s
513 isDataSymOcc _ = False
514 -- Pretty inefficient!
515
516 -- | Test if the 'OccName' is that for any operator (whether
517 -- it is a data constructor or variable or whatever)
518 isSymOcc :: OccName -> Bool
519 isSymOcc (OccName DataName s) = isLexConSym s
520 isSymOcc (OccName TcClsName s) = isLexSym s
521 isSymOcc (OccName VarName s) = isLexSym s
522 isSymOcc (OccName TvName s) = isLexSym s
523 -- Pretty inefficient!
524
525 parenSymOcc :: OccName -> SDoc -> SDoc
526 -- ^ Wrap parens around an operator
527 parenSymOcc occ doc | isSymOcc occ = parens doc
528 | otherwise = doc
529
530 startsWithUnderscore :: OccName -> Bool
531 -- ^ Haskell 98 encourages compilers to suppress warnings about unsed
532 -- names in a pattern if they start with @_@: this implements that test
533 startsWithUnderscore occ = headFS (occNameFS occ) == '_'
534
535 {-
536 ************************************************************************
537 * *
538 \subsection{Making system names}
539 * *
540 ************************************************************************
541
542 Here's our convention for splitting up the interface file name space:
543
544 d... dictionary identifiers
545 (local variables, so no name-clash worries)
546
547 All of these other OccNames contain a mixture of alphabetic
548 and symbolic characters, and hence cannot possibly clash with
549 a user-written type or function name
550
551 $f... Dict-fun identifiers (from inst decls)
552 $dmop Default method for 'op'
553 $pnC n'th superclass selector for class C
554 $wf Worker for function 'f'
555 $sf.. Specialised version of f
556 D:C Data constructor for dictionary for class C
557 NTCo:T Coercion connecting newtype T with its representation type
558 TFCo:R Coercion connecting a data family to its representation type R
559
560 In encoded form these appear as Zdfxxx etc
561
562 :... keywords (export:, letrec: etc.)
563 --- I THINK THIS IS WRONG!
564
565 This knowledge is encoded in the following functions.
566
567 @mk_deriv@ generates an @OccName@ from the prefix and a string.
568 NB: The string must already be encoded!
569 -}
570
571 -- | Build an 'OccName' derived from another 'OccName'.
572 --
573 -- Note that the pieces of the name are passed in as a @[FastString]@ so that
574 -- the whole name can be constructed with a single 'concatFS', minimizing
575 -- unnecessary intermediate allocations.
576 mk_deriv :: NameSpace
577 -> FastString -- ^ A prefix which distinguishes one sort of
578 -- derived name from another
579 -> [FastString] -- ^ The name we are deriving from in pieces which
580 -- will be concatenated.
581 -> OccName
582 mk_deriv occ_sp sys_prefix str =
583 mkOccNameFS occ_sp (concatFS $ sys_prefix : str)
584
585 isDerivedOccName :: OccName -> Bool
586 -- ^ Test for definitions internally generated by GHC. This predicte
587 -- is used to suppress printing of internal definitions in some debug prints
588 isDerivedOccName occ =
589 case occNameString occ of
590 '$':c:_ | isAlphaNum c -> True -- E.g. $wfoo
591 c:':':_ | isAlphaNum c -> True -- E.g. N:blah newtype coercions
592 _other -> False
593
594 mkDataConWrapperOcc, mkWorkerOcc,
595 mkMatcherOcc, mkBuilderOcc,
596 mkDefaultMethodOcc,
597 mkClassDataConOcc, mkDictOcc,
598 mkIPOcc, mkSpecOcc, mkForeignExportOcc, mkRepEqOcc,
599 mkGenR, mkGen1R,
600 mkDataConWorkerOcc, mkNewTyCoOcc,
601 mkInstTyCoOcc, mkEqPredCoOcc, mkClassOpAuxOcc,
602 mkCon2TagOcc, mkTag2ConOcc, mkMaxTagOcc,
603 mkTyConRepOcc
604 :: OccName -> OccName
605
606 -- These derived variables have a prefix that no Haskell value could have
607 mkDataConWrapperOcc = mk_simple_deriv varName "$W"
608 mkWorkerOcc = mk_simple_deriv varName "$w"
609 mkMatcherOcc = mk_simple_deriv varName "$m"
610 mkBuilderOcc = mk_simple_deriv varName "$b"
611 mkDefaultMethodOcc = mk_simple_deriv varName "$dm"
612 mkClassOpAuxOcc = mk_simple_deriv varName "$c"
613 mkDictOcc = mk_simple_deriv varName "$d"
614 mkIPOcc = mk_simple_deriv varName "$i"
615 mkSpecOcc = mk_simple_deriv varName "$s"
616 mkForeignExportOcc = mk_simple_deriv varName "$f"
617 mkRepEqOcc = mk_simple_deriv tvName "$r" -- In RULES involving Coercible
618 mkClassDataConOcc = mk_simple_deriv dataName "C:" -- Data con for a class
619 mkNewTyCoOcc = mk_simple_deriv tcName "N:" -- Coercion for newtypes
620 mkInstTyCoOcc = mk_simple_deriv tcName "D:" -- Coercion for type functions
621 mkEqPredCoOcc = mk_simple_deriv tcName "$co"
622
623 -- Used in derived instances
624 mkCon2TagOcc = mk_simple_deriv varName "$con2tag_"
625 mkTag2ConOcc = mk_simple_deriv varName "$tag2con_"
626 mkMaxTagOcc = mk_simple_deriv varName "$maxtag_"
627
628 -- TyConRepName stuff; see Note [Grand plan for Typeable] in TcTypeable
629 mkTyConRepOcc occ = mk_simple_deriv varName prefix occ
630 where
631 prefix | isDataOcc occ = "$tc'"
632 | otherwise = "$tc"
633
634 -- Generic deriving mechanism
635 mkGenR = mk_simple_deriv tcName "Rep_"
636 mkGen1R = mk_simple_deriv tcName "Rep1_"
637
638 -- Vectorisation
639 mkVectOcc, mkVectTyConOcc, mkVectDataConOcc, mkVectIsoOcc,
640 mkPADFunOcc, mkPReprTyConOcc,
641 mkPDataTyConOcc, mkPDataDataConOcc,
642 mkPDatasTyConOcc, mkPDatasDataConOcc
643 :: Maybe String -> OccName -> OccName
644 mkVectOcc = mk_simple_deriv_with varName "$v"
645 mkVectTyConOcc = mk_simple_deriv_with tcName "V:"
646 mkVectDataConOcc = mk_simple_deriv_with dataName "VD:"
647 mkVectIsoOcc = mk_simple_deriv_with varName "$vi"
648 mkPADFunOcc = mk_simple_deriv_with varName "$pa"
649 mkPReprTyConOcc = mk_simple_deriv_with tcName "VR:"
650 mkPDataTyConOcc = mk_simple_deriv_with tcName "VP:"
651 mkPDatasTyConOcc = mk_simple_deriv_with tcName "VPs:"
652 mkPDataDataConOcc = mk_simple_deriv_with dataName "VPD:"
653 mkPDatasDataConOcc = mk_simple_deriv_with dataName "VPDs:"
654
655 -- Overloaded record field selectors
656 mkRecFldSelOcc :: String -> OccName
657 mkRecFldSelOcc s = mk_deriv varName "$sel" [fsLit s]
658
659 mk_simple_deriv :: NameSpace -> FastString -> OccName -> OccName
660 mk_simple_deriv sp px occ = mk_deriv sp px [occNameFS occ]
661
662 mk_simple_deriv_with :: NameSpace -- ^ the namespace
663 -> FastString -- ^ an identifying prefix
664 -> Maybe String -- ^ another optional prefix
665 -> OccName -- ^ the 'OccName' to derive from
666 -> OccName
667 mk_simple_deriv_with sp px Nothing occ = mk_deriv sp px [occNameFS occ]
668 mk_simple_deriv_with sp px (Just with) occ =
669 mk_deriv sp px [fsLit with, fsLit "_", occNameFS occ]
670
671 -- Data constructor workers are made by setting the name space
672 -- of the data constructor OccName (which should be a DataName)
673 -- to VarName
674 mkDataConWorkerOcc datacon_occ = setOccNameSpace varName datacon_occ
675
676 mkSuperDictAuxOcc :: Int -> OccName -> OccName
677 mkSuperDictAuxOcc index cls_tc_occ
678 = mk_deriv varName "$cp" [fsLit $ show index, occNameFS cls_tc_occ]
679
680 mkSuperDictSelOcc :: Int -- ^ Index of superclass, e.g. 3
681 -> OccName -- ^ Class, e.g. @Ord@
682 -> OccName -- ^ Derived 'Occname', e.g. @$p3Ord@
683 mkSuperDictSelOcc index cls_tc_occ
684 = mk_deriv varName "$p" [fsLit $ show index, occNameFS cls_tc_occ]
685
686 mkLocalOcc :: Unique -- ^ Unique to combine with the 'OccName'
687 -> OccName -- ^ Local name, e.g. @sat@
688 -> OccName -- ^ Nice unique version, e.g. @$L23sat@
689 mkLocalOcc uniq occ
690 = mk_deriv varName "$L" [fsLit $ show uniq, occNameFS occ]
691 -- The Unique might print with characters
692 -- that need encoding (e.g. 'z'!)
693
694 -- | Derive a name for the representation type constructor of a
695 -- @data@\/@newtype@ instance.
696 mkInstTyTcOcc :: String -- ^ Family name, e.g. @Map@
697 -> OccSet -- ^ avoid these Occs
698 -> OccName -- ^ @R:Map@
699 mkInstTyTcOcc str = chooseUniqueOcc tcName ('R' : ':' : str)
700
701 mkDFunOcc :: String -- ^ Typically the class and type glommed together e.g. @OrdMaybe@.
702 -- Only used in debug mode, for extra clarity
703 -> Bool -- ^ Is this a hs-boot instance DFun?
704 -> OccSet -- ^ avoid these Occs
705 -> OccName -- ^ E.g. @$f3OrdMaybe@
706
707 -- In hs-boot files we make dict funs like $fx7ClsTy, which get bound to the real
708 -- thing when we compile the mother module. Reason: we don't know exactly
709 -- what the mother module will call it.
710
711 mkDFunOcc info_str is_boot set
712 = chooseUniqueOcc VarName (prefix ++ info_str) set
713 where
714 prefix | is_boot = "$fx"
715 | otherwise = "$f"
716
717 mkDataTOcc, mkDataCOcc
718 :: OccName -- ^ TyCon or data con string
719 -> OccSet -- ^ avoid these Occs
720 -> OccName -- ^ E.g. @$f3OrdMaybe@
721 -- data T = MkT ... deriving( Data ) needs definitions for
722 -- $tT :: Data.Generics.Basics.DataType
723 -- $cMkT :: Data.Generics.Basics.Constr
724 mkDataTOcc occ = chooseUniqueOcc VarName ("$t" ++ occNameString occ)
725 mkDataCOcc occ = chooseUniqueOcc VarName ("$c" ++ occNameString occ)
726
727 {-
728 Sometimes we need to pick an OccName that has not already been used,
729 given a set of in-use OccNames.
730 -}
731
732 chooseUniqueOcc :: NameSpace -> String -> OccSet -> OccName
733 chooseUniqueOcc ns str set = loop (mkOccName ns str) (0::Int)
734 where
735 loop occ n
736 | occ `elemOccSet` set = loop (mkOccName ns (str ++ show n)) (n+1)
737 | otherwise = occ
738
739 {-
740 We used to add a '$m' to indicate a method, but that gives rise to bad
741 error messages from the type checker when we print the function name or pattern
742 of an instance-decl binding. Why? Because the binding is zapped
743 to use the method name in place of the selector name.
744 (See TcClassDcl.tcMethodBind)
745
746 The way it is now, -ddump-xx output may look confusing, but
747 you can always say -dppr-debug to get the uniques.
748
749 However, we *do* have to zap the first character to be lower case,
750 because overloaded constructors (blarg) generate methods too.
751 And convert to VarName space
752
753 e.g. a call to constructor MkFoo where
754 data (Ord a) => Foo a = MkFoo a
755
756 If this is necessary, we do it by prefixing '$m'. These
757 guys never show up in error messages. What a hack.
758 -}
759
760 mkMethodOcc :: OccName -> OccName
761 mkMethodOcc occ@(OccName VarName _) = occ
762 mkMethodOcc occ = mk_simple_deriv varName "$m" occ
763
764 {-
765 ************************************************************************
766 * *
767 \subsection{Tidying them up}
768 * *
769 ************************************************************************
770
771 Before we print chunks of code we like to rename it so that
772 we don't have to print lots of silly uniques in it. But we mustn't
773 accidentally introduce name clashes! So the idea is that we leave the
774 OccName alone unless it accidentally clashes with one that is already
775 in scope; if so, we tack on '1' at the end and try again, then '2', and
776 so on till we find a unique one.
777
778 There's a wrinkle for operators. Consider '>>='. We can't use '>>=1'
779 because that isn't a single lexeme. So we encode it to 'lle' and *then*
780 tack on the '1', if necessary.
781
782 Note [TidyOccEnv]
783 ~~~~~~~~~~~~~~~~~
784 type TidyOccEnv = UniqFM Int
785
786 * Domain = The OccName's FastString. These FastStrings are "taken";
787 make sure that we don't re-use
788
789 * Int, n = A plausible starting point for new guesses
790 There is no guarantee that "FSn" is available;
791 you must look that up in the TidyOccEnv. But
792 it's a good place to start looking.
793
794 * When looking for a renaming for "foo2" we strip off the "2" and start
795 with "foo". Otherwise if we tidy twice we get silly names like foo23.
796
797 However, if it started with digits at the end, we always make a name
798 with digits at the end, rather than shortening "foo2" to just "foo",
799 even if "foo" is unused. Reasons:
800 - Plain "foo" might be used later
801 - We use trailing digits to subtly indicate a unification variable
802 in typechecker error message; see TypeRep.tidyTyVarBndr
803
804 We have to take care though! Consider a machine-generated module (Trac #10370)
805 module Foo where
806 a1 = e1
807 a2 = e2
808 ...
809 a2000 = e2000
810 Then "a1", "a2" etc are all marked taken. But now if we come across "a7" again,
811 we have to do a linear search to find a free one, "a2001". That might just be
812 acceptable once. But if we now come across "a8" again, we don't want to repeat
813 that search.
814
815 So we use the TidyOccEnv mapping for "a" (not "a7" or "a8") as our base for
816 starting the search; and we make sure to update the starting point for "a"
817 after we allocate a new one.
818
819
820 Node [Tidying multiple names at once]
821 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
822
823 Consider
824
825 > :t (id,id,id)
826
827 Every id contributes a type variable to the type signature, and all of them are
828 "a". If we tidy them one by one, we get
829
830 (id,id,id) :: (a2 -> a2, a1 -> a1, a -> a)
831
832 which is a bit unfortunate, as it unfairly renames only one of them. What we
833 would like to see is
834
835 (id,id,id) :: (a3 -> a3, a2 -> a2, a1 -> a1)
836
837 This is achieved in tidyOccNames. It still uses tidyOccName to rename each name
838 on its own, but it prepares the TidyEnv (using avoidClashesOccEnv), by “blocking” every
839 name that occurs twice in the map. This way, none of the "a"s will get the
840 priviledge of keeping this name, and all of them will get a suitable numbery by
841 tidyOccName.
842
843 It may be inappropriate to use tidyOccNames if the caller needs access to the
844 intermediate environments (e.g. to tidy the tyVarKind of a type variable). In that
845 case, avoidClashesOccEnv should be used directly, and tidyOccName afterwards.
846
847 This is #12382.
848
849 -}
850
851 type TidyOccEnv = UniqFM Int -- The in-scope OccNames
852 -- See Note [TidyOccEnv]
853
854 emptyTidyOccEnv :: TidyOccEnv
855 emptyTidyOccEnv = emptyUFM
856
857 initTidyOccEnv :: [OccName] -> TidyOccEnv -- Initialise with names to avoid!
858 initTidyOccEnv = foldl add emptyUFM
859 where
860 add env (OccName _ fs) = addToUFM env fs 1
861
862 -- see Note [Tidying multiple names at once]
863 tidyOccNames :: TidyOccEnv -> [OccName] -> (TidyOccEnv, [OccName])
864 tidyOccNames env occs = mapAccumL tidyOccName env' occs
865 where
866 env' = avoidClashesOccEnv env occs
867
868 avoidClashesOccEnv :: TidyOccEnv -> [OccName] -> TidyOccEnv
869 avoidClashesOccEnv env occs = go env emptyUFM occs
870 where
871 go env _ [] = env
872 go env seenOnce ((OccName _ fs):occs)
873 | fs `elemUFM` env = go env seenOnce occs
874 | fs `elemUFM` seenOnce = go (addToUFM env fs 1) seenOnce occs
875 | otherwise = go env (addToUFM seenOnce fs ()) occs
876
877 tidyOccName :: TidyOccEnv -> OccName -> (TidyOccEnv, OccName)
878 tidyOccName env occ@(OccName occ_sp fs)
879 | not (fs `elemUFM` env)
880 = (addToUFM env fs 1, occ) -- Desired OccName is free
881 | otherwise
882 = case lookupUFM env base1 of
883 Nothing -> (addToUFM env base1 2, OccName occ_sp base1)
884 Just n -> find 1 n
885 where
886 base :: String -- Drop trailing digits (see Note [TidyOccEnv])
887 base = dropWhileEndLE isDigit (unpackFS fs)
888 base1 = mkFastString (base ++ "1")
889
890 find !k !n
891 = case lookupUFM env new_fs of
892 Just {} -> find (k+1 :: Int) (n+k)
893 -- By using n+k, the n argument to find goes
894 -- 1, add 1, add 2, add 3, etc which
895 -- moves at quadratic speed through a dense patch
896
897 Nothing -> (new_env, OccName occ_sp new_fs)
898 where
899 new_fs = mkFastString (base ++ show n)
900 new_env = addToUFM (addToUFM env new_fs 1) base1 (n+1)
901 -- Update: base1, so that next time we'll start where we left off
902 -- new_fs, so that we know it is taken
903 -- If they are the same (n==1), the former wins
904 -- See Note [TidyOccEnv]
905
906 {-
907 ************************************************************************
908 * *
909 Binary instance
910 Here rather than BinIface because OccName is abstract
911 * *
912 ************************************************************************
913 -}
914
915 instance Binary NameSpace where
916 put_ bh VarName = do
917 putByte bh 0
918 put_ bh DataName = do
919 putByte bh 1
920 put_ bh TvName = do
921 putByte bh 2
922 put_ bh TcClsName = do
923 putByte bh 3
924 get bh = do
925 h <- getByte bh
926 case h of
927 0 -> do return VarName
928 1 -> do return DataName
929 2 -> do return TvName
930 _ -> do return TcClsName
931
932 instance Binary OccName where
933 put_ bh (OccName aa ab) = do
934 put_ bh aa
935 put_ bh ab
936 get bh = do
937 aa <- get bh
938 ab <- get bh
939 return (OccName aa ab)