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