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