PageRenderTime 27ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/compiler/basicTypes/OccName.lhs

https://github.com/luite/ghc
Haskell | 943 lines | 651 code | 163 blank | 129 comment | 40 complexity | 4fbbdc8a2d992d60456053587624f6ad MD5 | raw file
  1. %
  2. % (c) The University of Glasgow 2006
  3. % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
  4. %
  5. \begin{code}
  6. -- |
  7. -- #name_types#
  8. -- GHC uses several kinds of name internally:
  9. --
  10. -- * 'OccName.OccName' represents names as strings with just a little more information:
  11. -- the \"namespace\" that the name came from, e.g. the namespace of value, type constructors or
  12. -- data constructors
  13. --
  14. -- * 'RdrName.RdrName': see "RdrName#name_types"
  15. --
  16. -- * 'Name.Name': see "Name#name_types"
  17. --
  18. -- * 'Id.Id': see "Id#name_types"
  19. --
  20. -- * 'Var.Var': see "Var#name_types"
  21. {-# OPTIONS -fno-warn-tabs #-}
  22. -- The above warning supression flag is a temporary kludge.
  23. -- While working on this module you are encouraged to remove it and
  24. -- detab the module (please do the detabbing in a separate patch). See
  25. -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#TabsvsSpaces
  26. -- for details
  27. module OccName (
  28. -- * The 'NameSpace' type
  29. NameSpace, -- Abstract
  30. -- ** Construction
  31. -- $real_vs_source_data_constructors
  32. tcName, clsName, tcClsName, dataName, varName,
  33. tvName, srcDataName,
  34. -- ** Pretty Printing
  35. pprNameSpace, pprNonVarNameSpace, pprNameSpaceBrief,
  36. -- * The 'OccName' type
  37. OccName, -- Abstract, instance of Outputable
  38. pprOccName,
  39. -- ** Construction
  40. mkOccName, mkOccNameFS,
  41. mkVarOcc, mkVarOccFS,
  42. mkDataOcc, mkDataOccFS,
  43. mkTyVarOcc, mkTyVarOccFS,
  44. mkTcOcc, mkTcOccFS,
  45. mkClsOcc, mkClsOccFS,
  46. mkDFunOcc,
  47. mkTupleOcc,
  48. setOccNameSpace,
  49. demoteOccName,
  50. HasOccName(..),
  51. -- ** Derived 'OccName's
  52. isDerivedOccName,
  53. mkDataConWrapperOcc, mkWorkerOcc, mkDefaultMethodOcc, mkGenDefMethodOcc,
  54. mkDerivedTyConOcc, mkNewTyCoOcc, mkClassOpAuxOcc,
  55. mkCon2TagOcc, mkTag2ConOcc, mkMaxTagOcc,
  56. mkClassDataConOcc, mkDictOcc, mkIPOcc,
  57. mkSpecOcc, mkForeignExportOcc, mkGenOcc1, mkGenOcc2,
  58. mkGenD, mkGenR, mkGen1R, mkGenRCo, mkGenC, mkGenS,
  59. mkDataTOcc, mkDataCOcc, mkDataConWorkerOcc,
  60. mkSuperDictSelOcc, mkLocalOcc, mkMethodOcc, mkInstTyTcOcc,
  61. mkInstTyCoOcc, mkEqPredCoOcc,
  62. mkVectOcc, mkVectTyConOcc, mkVectDataConOcc, mkVectIsoOcc,
  63. mkPDataTyConOcc, mkPDataDataConOcc,
  64. mkPDatasTyConOcc, mkPDatasDataConOcc,
  65. mkPReprTyConOcc,
  66. mkPADFunOcc,
  67. -- ** Deconstruction
  68. occNameFS, occNameString, occNameSpace,
  69. isVarOcc, isTvOcc, isTcOcc, isDataOcc, isDataSymOcc, isSymOcc, isValOcc,
  70. parenSymOcc, startsWithUnderscore,
  71. isTcClsNameSpace, isTvNameSpace, isDataConNameSpace, isVarNameSpace, isValNameSpace,
  72. isTupleOcc_maybe,
  73. -- * The 'OccEnv' type
  74. OccEnv, emptyOccEnv, unitOccEnv, extendOccEnv, mapOccEnv,
  75. lookupOccEnv, mkOccEnv, mkOccEnv_C, extendOccEnvList, elemOccEnv,
  76. occEnvElts, foldOccEnv, plusOccEnv, plusOccEnv_C, extendOccEnv_C,
  77. extendOccEnv_Acc, filterOccEnv, delListFromOccEnv, delFromOccEnv,
  78. -- * The 'OccSet' type
  79. OccSet, emptyOccSet, unitOccSet, mkOccSet, extendOccSet,
  80. extendOccSetList,
  81. unionOccSets, unionManyOccSets, minusOccSet, elemOccSet, occSetElts,
  82. foldOccSet, isEmptyOccSet, intersectOccSet, intersectsOccSet,
  83. -- * Tidying up
  84. TidyOccEnv, emptyTidyOccEnv, tidyOccName, initTidyOccEnv,
  85. -- * Lexical characteristics of Haskell names
  86. isLexCon, isLexVar, isLexId, isLexSym,
  87. isLexConId, isLexConSym, isLexVarId, isLexVarSym,
  88. startsVarSym, startsVarId, startsConSym, startsConId
  89. ) where
  90. #include "Typeable.h"
  91. import Util
  92. import Unique
  93. import BasicTypes
  94. import DynFlags
  95. import UniqFM
  96. import UniqSet
  97. import FastString
  98. import Outputable
  99. import Binary
  100. import Data.Char
  101. import Data.Data
  102. \end{code}
  103. %************************************************************************
  104. %* *
  105. \subsection{Name space}
  106. %* *
  107. %************************************************************************
  108. \begin{code}
  109. data NameSpace = VarName -- Variables, including "real" data constructors
  110. | DataName -- "Source" data constructors
  111. | TvName -- Type variables
  112. | TcClsName -- Type constructors and classes; Haskell has them
  113. -- in the same name space for now.
  114. deriving( Eq, Ord )
  115. {-! derive: Binary !-}
  116. -- Note [Data Constructors]
  117. -- see also: Note [Data Constructor Naming] in DataCon.lhs
  118. --
  119. -- $real_vs_source_data_constructors
  120. -- There are two forms of data constructor:
  121. --
  122. -- [Source data constructors] The data constructors mentioned in Haskell source code
  123. --
  124. -- [Real data constructors] The data constructors of the representation type, which may not be the same as the source type
  125. --
  126. -- For example:
  127. --
  128. -- > data T = T !(Int, Int)
  129. --
  130. -- The source datacon has type @(Int, Int) -> T@
  131. -- The real datacon has type @Int -> Int -> T@
  132. --
  133. -- GHC chooses a representation based on the strictness etc.
  134. tcName, clsName, tcClsName :: NameSpace
  135. dataName, srcDataName :: NameSpace
  136. tvName, varName :: NameSpace
  137. -- Though type constructors and classes are in the same name space now,
  138. -- the NameSpace type is abstract, so we can easily separate them later
  139. tcName = TcClsName -- Type constructors
  140. clsName = TcClsName -- Classes
  141. tcClsName = TcClsName -- Not sure which!
  142. dataName = DataName
  143. srcDataName = DataName -- Haskell-source data constructors should be
  144. -- in the Data name space
  145. tvName = TvName
  146. varName = VarName
  147. isDataConNameSpace :: NameSpace -> Bool
  148. isDataConNameSpace DataName = True
  149. isDataConNameSpace _ = False
  150. isTcClsNameSpace :: NameSpace -> Bool
  151. isTcClsNameSpace TcClsName = True
  152. isTcClsNameSpace _ = False
  153. isTvNameSpace :: NameSpace -> Bool
  154. isTvNameSpace TvName = True
  155. isTvNameSpace _ = False
  156. isVarNameSpace :: NameSpace -> Bool -- Variables or type variables, but not constructors
  157. isVarNameSpace TvName = True
  158. isVarNameSpace VarName = True
  159. isVarNameSpace _ = False
  160. isValNameSpace :: NameSpace -> Bool
  161. isValNameSpace DataName = True
  162. isValNameSpace VarName = True
  163. isValNameSpace _ = False
  164. pprNameSpace :: NameSpace -> SDoc
  165. pprNameSpace DataName = ptext (sLit "data constructor")
  166. pprNameSpace VarName = ptext (sLit "variable")
  167. pprNameSpace TvName = ptext (sLit "type variable")
  168. pprNameSpace TcClsName = ptext (sLit "type constructor or class")
  169. pprNonVarNameSpace :: NameSpace -> SDoc
  170. pprNonVarNameSpace VarName = empty
  171. pprNonVarNameSpace ns = pprNameSpace ns
  172. pprNameSpaceBrief :: NameSpace -> SDoc
  173. pprNameSpaceBrief DataName = char 'd'
  174. pprNameSpaceBrief VarName = char 'v'
  175. pprNameSpaceBrief TvName = ptext (sLit "tv")
  176. pprNameSpaceBrief TcClsName = ptext (sLit "tc")
  177. -- demoteNameSpace lowers the NameSpace if possible. We can not know
  178. -- in advance, since a TvName can appear in an HsTyVar.
  179. -- See Note [Demotion] in RnEnv
  180. demoteNameSpace :: NameSpace -> Maybe NameSpace
  181. demoteNameSpace VarName = Nothing
  182. demoteNameSpace DataName = Nothing
  183. demoteNameSpace TvName = Nothing
  184. demoteNameSpace TcClsName = Just DataName
  185. \end{code}
  186. %************************************************************************
  187. %* *
  188. \subsection[Name-pieces-datatypes]{The @OccName@ datatypes}
  189. %* *
  190. %************************************************************************
  191. \begin{code}
  192. data OccName = OccName
  193. { occNameSpace :: !NameSpace
  194. , occNameFS :: !FastString
  195. }
  196. deriving Typeable
  197. \end{code}
  198. \begin{code}
  199. instance Eq OccName where
  200. (OccName sp1 s1) == (OccName sp2 s2) = s1 == s2 && sp1 == sp2
  201. instance Ord OccName where
  202. -- Compares lexicographically, *not* by Unique of the string
  203. compare (OccName sp1 s1) (OccName sp2 s2)
  204. = (s1 `compare` s2) `thenCmp` (sp1 `compare` sp2)
  205. instance Data OccName where
  206. -- don't traverse?
  207. toConstr _ = abstractConstr "OccName"
  208. gunfold _ _ = error "gunfold"
  209. dataTypeOf _ = mkNoRepType "OccName"
  210. \end{code}
  211. %************************************************************************
  212. %* *
  213. \subsection{Printing}
  214. %* *
  215. %************************************************************************
  216. \begin{code}
  217. instance Outputable OccName where
  218. ppr = pprOccName
  219. pprOccName :: OccName -> SDoc
  220. pprOccName (OccName sp occ)
  221. = getPprStyle $ \ sty ->
  222. if codeStyle sty
  223. then ztext (zEncodeFS occ)
  224. else pp_occ <> pp_debug sty
  225. where
  226. pp_debug sty | debugStyle sty = braces (pprNameSpaceBrief sp)
  227. | otherwise = empty
  228. pp_occ = sdocWithDynFlags $ \dflags ->
  229. if gopt Opt_SuppressUniques dflags
  230. then text (strip_th_unique (unpackFS occ))
  231. else ftext occ
  232. -- See Note [Suppressing uniques in OccNames]
  233. strip_th_unique ('[' : c : _) | isAlphaNum c = []
  234. strip_th_unique (c : cs) = c : strip_th_unique cs
  235. strip_th_unique [] = []
  236. \end{code}
  237. Note [Suppressing uniques in OccNames]
  238. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  239. This is a hack to de-wobblify the OccNames that contain uniques from
  240. Template Haskell that have been turned into a string in the OccName.
  241. See Note [Unique OccNames from Template Haskell] in Convert.hs
  242. %************************************************************************
  243. %* *
  244. \subsection{Construction}
  245. %* *
  246. %************************************************************************
  247. \begin{code}
  248. mkOccName :: NameSpace -> String -> OccName
  249. mkOccName occ_sp str = OccName occ_sp (mkFastString str)
  250. mkOccNameFS :: NameSpace -> FastString -> OccName
  251. mkOccNameFS occ_sp fs = OccName occ_sp fs
  252. mkVarOcc :: String -> OccName
  253. mkVarOcc s = mkOccName varName s
  254. mkVarOccFS :: FastString -> OccName
  255. mkVarOccFS fs = mkOccNameFS varName fs
  256. mkDataOcc :: String -> OccName
  257. mkDataOcc = mkOccName dataName
  258. mkDataOccFS :: FastString -> OccName
  259. mkDataOccFS = mkOccNameFS dataName
  260. mkTyVarOcc :: String -> OccName
  261. mkTyVarOcc = mkOccName tvName
  262. mkTyVarOccFS :: FastString -> OccName
  263. mkTyVarOccFS fs = mkOccNameFS tvName fs
  264. mkTcOcc :: String -> OccName
  265. mkTcOcc = mkOccName tcName
  266. mkTcOccFS :: FastString -> OccName
  267. mkTcOccFS = mkOccNameFS tcName
  268. mkClsOcc :: String -> OccName
  269. mkClsOcc = mkOccName clsName
  270. mkClsOccFS :: FastString -> OccName
  271. mkClsOccFS = mkOccNameFS clsName
  272. -- demoteOccName lowers the Namespace of OccName.
  273. -- see Note [Demotion]
  274. demoteOccName :: OccName -> Maybe OccName
  275. demoteOccName (OccName space name) = do
  276. space' <- demoteNameSpace space
  277. return $ OccName space' name
  278. {- | Other names in the compiler add aditional information to an OccName.
  279. This class provides a consistent way to access the underlying OccName. -}
  280. class HasOccName name where
  281. occName :: name -> OccName
  282. \end{code}
  283. %************************************************************************
  284. %* *
  285. Environments
  286. %* *
  287. %************************************************************************
  288. OccEnvs are used mainly for the envts in ModIfaces.
  289. Note [The Unique of an OccName]
  290. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  291. They are efficient, because FastStrings have unique Int# keys. We assume
  292. this key is less than 2^24, and indeed FastStrings are allocated keys
  293. sequentially starting at 0.
  294. So we can make a Unique using
  295. mkUnique ns key :: Unique
  296. where 'ns' is a Char representing the name space. This in turn makes it
  297. easy to build an OccEnv.
  298. \begin{code}
  299. instance Uniquable OccName where
  300. -- See Note [The Unique of an OccName]
  301. getUnique (OccName VarName fs) = mkVarOccUnique fs
  302. getUnique (OccName DataName fs) = mkDataOccUnique fs
  303. getUnique (OccName TvName fs) = mkTvOccUnique fs
  304. getUnique (OccName TcClsName fs) = mkTcOccUnique fs
  305. newtype OccEnv a = A (UniqFM a)
  306. emptyOccEnv :: OccEnv a
  307. unitOccEnv :: OccName -> a -> OccEnv a
  308. extendOccEnv :: OccEnv a -> OccName -> a -> OccEnv a
  309. extendOccEnvList :: OccEnv a -> [(OccName, a)] -> OccEnv a
  310. lookupOccEnv :: OccEnv a -> OccName -> Maybe a
  311. mkOccEnv :: [(OccName,a)] -> OccEnv a
  312. mkOccEnv_C :: (a -> a -> a) -> [(OccName,a)] -> OccEnv a
  313. elemOccEnv :: OccName -> OccEnv a -> Bool
  314. foldOccEnv :: (a -> b -> b) -> b -> OccEnv a -> b
  315. occEnvElts :: OccEnv a -> [a]
  316. extendOccEnv_C :: (a->a->a) -> OccEnv a -> OccName -> a -> OccEnv a
  317. extendOccEnv_Acc :: (a->b->b) -> (a->b) -> OccEnv b -> OccName -> a -> OccEnv b
  318. plusOccEnv :: OccEnv a -> OccEnv a -> OccEnv a
  319. plusOccEnv_C :: (a->a->a) -> OccEnv a -> OccEnv a -> OccEnv a
  320. mapOccEnv :: (a->b) -> OccEnv a -> OccEnv b
  321. delFromOccEnv :: OccEnv a -> OccName -> OccEnv a
  322. delListFromOccEnv :: OccEnv a -> [OccName] -> OccEnv a
  323. filterOccEnv :: (elt -> Bool) -> OccEnv elt -> OccEnv elt
  324. emptyOccEnv = A emptyUFM
  325. unitOccEnv x y = A $ unitUFM x y
  326. extendOccEnv (A x) y z = A $ addToUFM x y z
  327. extendOccEnvList (A x) l = A $ addListToUFM x l
  328. lookupOccEnv (A x) y = lookupUFM x y
  329. mkOccEnv l = A $ listToUFM l
  330. elemOccEnv x (A y) = elemUFM x y
  331. foldOccEnv a b (A c) = foldUFM a b c
  332. occEnvElts (A x) = eltsUFM x
  333. plusOccEnv (A x) (A y) = A $ plusUFM x y
  334. plusOccEnv_C f (A x) (A y) = A $ plusUFM_C f x y
  335. extendOccEnv_C f (A x) y z = A $ addToUFM_C f x y z
  336. extendOccEnv_Acc f g (A x) y z = A $ addToUFM_Acc f g x y z
  337. mapOccEnv f (A x) = A $ mapUFM f x
  338. mkOccEnv_C comb l = A $ addListToUFM_C comb emptyUFM l
  339. delFromOccEnv (A x) y = A $ delFromUFM x y
  340. delListFromOccEnv (A x) y = A $ delListFromUFM x y
  341. filterOccEnv x (A y) = A $ filterUFM x y
  342. instance Outputable a => Outputable (OccEnv a) where
  343. ppr (A x) = ppr x
  344. type OccSet = UniqSet OccName
  345. emptyOccSet :: OccSet
  346. unitOccSet :: OccName -> OccSet
  347. mkOccSet :: [OccName] -> OccSet
  348. extendOccSet :: OccSet -> OccName -> OccSet
  349. extendOccSetList :: OccSet -> [OccName] -> OccSet
  350. unionOccSets :: OccSet -> OccSet -> OccSet
  351. unionManyOccSets :: [OccSet] -> OccSet
  352. minusOccSet :: OccSet -> OccSet -> OccSet
  353. elemOccSet :: OccName -> OccSet -> Bool
  354. occSetElts :: OccSet -> [OccName]
  355. foldOccSet :: (OccName -> b -> b) -> b -> OccSet -> b
  356. isEmptyOccSet :: OccSet -> Bool
  357. intersectOccSet :: OccSet -> OccSet -> OccSet
  358. intersectsOccSet :: OccSet -> OccSet -> Bool
  359. emptyOccSet = emptyUniqSet
  360. unitOccSet = unitUniqSet
  361. mkOccSet = mkUniqSet
  362. extendOccSet = addOneToUniqSet
  363. extendOccSetList = addListToUniqSet
  364. unionOccSets = unionUniqSets
  365. unionManyOccSets = unionManyUniqSets
  366. minusOccSet = minusUniqSet
  367. elemOccSet = elementOfUniqSet
  368. occSetElts = uniqSetToList
  369. foldOccSet = foldUniqSet
  370. isEmptyOccSet = isEmptyUniqSet
  371. intersectOccSet = intersectUniqSets
  372. intersectsOccSet s1 s2 = not (isEmptyOccSet (s1 `intersectOccSet` s2))
  373. \end{code}
  374. %************************************************************************
  375. %* *
  376. \subsection{Predicates and taking them apart}
  377. %* *
  378. %************************************************************************
  379. \begin{code}
  380. occNameString :: OccName -> String
  381. occNameString (OccName _ s) = unpackFS s
  382. setOccNameSpace :: NameSpace -> OccName -> OccName
  383. setOccNameSpace sp (OccName _ occ) = OccName sp occ
  384. isVarOcc, isTvOcc, isTcOcc, isDataOcc :: OccName -> Bool
  385. isVarOcc (OccName VarName _) = True
  386. isVarOcc _ = False
  387. isTvOcc (OccName TvName _) = True
  388. isTvOcc _ = False
  389. isTcOcc (OccName TcClsName _) = True
  390. isTcOcc _ = False
  391. -- | /Value/ 'OccNames's are those that are either in
  392. -- the variable or data constructor namespaces
  393. isValOcc :: OccName -> Bool
  394. isValOcc (OccName VarName _) = True
  395. isValOcc (OccName DataName _) = True
  396. isValOcc _ = False
  397. isDataOcc (OccName DataName _) = True
  398. isDataOcc (OccName VarName s)
  399. | isLexCon s = pprPanic "isDataOcc: check me" (ppr s)
  400. -- Jan06: I don't think this should happen
  401. isDataOcc _ = False
  402. -- | Test if the 'OccName' is a data constructor that starts with
  403. -- a symbol (e.g. @:@, or @[]@)
  404. isDataSymOcc :: OccName -> Bool
  405. isDataSymOcc (OccName DataName s) = isLexConSym s
  406. isDataSymOcc (OccName VarName s)
  407. | isLexConSym s = pprPanic "isDataSymOcc: check me" (ppr s)
  408. -- Jan06: I don't think this should happen
  409. isDataSymOcc _ = False
  410. -- Pretty inefficient!
  411. -- | Test if the 'OccName' is that for any operator (whether
  412. -- it is a data constructor or variable or whatever)
  413. isSymOcc :: OccName -> Bool
  414. isSymOcc (OccName DataName s) = isLexConSym s
  415. isSymOcc (OccName TcClsName s) = isLexConSym s || isLexVarSym s
  416. isSymOcc (OccName VarName s) = isLexSym s
  417. isSymOcc (OccName TvName s) = isLexSym s
  418. -- Pretty inefficient!
  419. parenSymOcc :: OccName -> SDoc -> SDoc
  420. -- ^ Wrap parens around an operator
  421. parenSymOcc occ doc | isSymOcc occ = parens doc
  422. | otherwise = doc
  423. \end{code}
  424. \begin{code}
  425. startsWithUnderscore :: OccName -> Bool
  426. -- ^ Haskell 98 encourages compilers to suppress warnings about unsed
  427. -- names in a pattern if they start with @_@: this implements that test
  428. startsWithUnderscore occ = case occNameString occ of
  429. ('_' : _) -> True
  430. _other -> False
  431. \end{code}
  432. %************************************************************************
  433. %* *
  434. \subsection{Making system names}
  435. %* *
  436. %************************************************************************
  437. Here's our convention for splitting up the interface file name space:
  438. d... dictionary identifiers
  439. (local variables, so no name-clash worries)
  440. All of these other OccNames contain a mixture of alphabetic
  441. and symbolic characters, and hence cannot possibly clash with
  442. a user-written type or function name
  443. $f... Dict-fun identifiers (from inst decls)
  444. $dmop Default method for 'op'
  445. $pnC n'th superclass selector for class C
  446. $wf Worker for functtoin 'f'
  447. $sf.. Specialised version of f
  448. T:C Tycon for dictionary for class C
  449. D:C Data constructor for dictionary for class C
  450. NTCo:T Coercion connecting newtype T with its representation type
  451. TFCo:R Coercion connecting a data family to its respresentation type R
  452. In encoded form these appear as Zdfxxx etc
  453. :... keywords (export:, letrec: etc.)
  454. --- I THINK THIS IS WRONG!
  455. This knowledge is encoded in the following functions.
  456. @mk_deriv@ generates an @OccName@ from the prefix and a string.
  457. NB: The string must already be encoded!
  458. \begin{code}
  459. mk_deriv :: NameSpace
  460. -> String -- Distinguishes one sort of derived name from another
  461. -> String
  462. -> OccName
  463. mk_deriv occ_sp sys_prefix str = mkOccName occ_sp (sys_prefix ++ str)
  464. isDerivedOccName :: OccName -> Bool
  465. isDerivedOccName occ =
  466. case occNameString occ of
  467. '$':c:_ | isAlphaNum c -> True
  468. ':':c:_ | isAlphaNum c -> True
  469. _other -> False
  470. \end{code}
  471. \begin{code}
  472. mkDataConWrapperOcc, mkWorkerOcc, mkDefaultMethodOcc, mkGenDefMethodOcc,
  473. mkDerivedTyConOcc, mkClassDataConOcc, mkDictOcc,
  474. mkIPOcc, mkSpecOcc, mkForeignExportOcc, mkGenOcc1, mkGenOcc2,
  475. mkGenD, mkGenR, mkGen1R, mkGenRCo,
  476. mkDataTOcc, mkDataCOcc, mkDataConWorkerOcc, mkNewTyCoOcc,
  477. mkInstTyCoOcc, mkEqPredCoOcc, mkClassOpAuxOcc,
  478. mkCon2TagOcc, mkTag2ConOcc, mkMaxTagOcc
  479. :: OccName -> OccName
  480. -- These derived variables have a prefix that no Haskell value could have
  481. mkDataConWrapperOcc = mk_simple_deriv varName "$W"
  482. mkWorkerOcc = mk_simple_deriv varName "$w"
  483. mkDefaultMethodOcc = mk_simple_deriv varName "$dm"
  484. mkGenDefMethodOcc = mk_simple_deriv varName "$gdm"
  485. mkClassOpAuxOcc = mk_simple_deriv varName "$c"
  486. mkDerivedTyConOcc = mk_simple_deriv tcName ":" -- The : prefix makes sure it classifies as a tycon/datacon
  487. mkClassDataConOcc = mk_simple_deriv dataName "D:" -- We go straight to the "real" data con
  488. -- for datacons from classes
  489. mkDictOcc = mk_simple_deriv varName "$d"
  490. mkIPOcc = mk_simple_deriv varName "$i"
  491. mkSpecOcc = mk_simple_deriv varName "$s"
  492. mkForeignExportOcc = mk_simple_deriv varName "$f"
  493. mkNewTyCoOcc = mk_simple_deriv tcName "NTCo:" -- Coercion for newtypes
  494. mkInstTyCoOcc = mk_simple_deriv tcName "TFCo:" -- Coercion for type functions
  495. mkEqPredCoOcc = mk_simple_deriv tcName "$co"
  496. -- used in derived instances
  497. mkCon2TagOcc = mk_simple_deriv varName "$con2tag_"
  498. mkTag2ConOcc = mk_simple_deriv varName "$tag2con_"
  499. mkMaxTagOcc = mk_simple_deriv varName "$maxtag_"
  500. -- Generic derivable classes (old)
  501. mkGenOcc1 = mk_simple_deriv varName "$gfrom"
  502. mkGenOcc2 = mk_simple_deriv varName "$gto"
  503. -- Generic deriving mechanism (new)
  504. mkGenD = mk_simple_deriv tcName "D1"
  505. mkGenC :: OccName -> Int -> OccName
  506. mkGenC occ m = mk_deriv tcName ("C1_" ++ show m) (occNameString occ)
  507. mkGenS :: OccName -> Int -> Int -> OccName
  508. mkGenS occ m n = mk_deriv tcName ("S1_" ++ show m ++ "_" ++ show n)
  509. (occNameString occ)
  510. mkGenR = mk_simple_deriv tcName "Rep_"
  511. mkGen1R = mk_simple_deriv tcName "Rep1_"
  512. mkGenRCo = mk_simple_deriv tcName "CoRep_"
  513. -- data T = MkT ... deriving( Data ) needs definitions for
  514. -- $tT :: Data.Generics.Basics.DataType
  515. -- $cMkT :: Data.Generics.Basics.Constr
  516. mkDataTOcc = mk_simple_deriv varName "$t"
  517. mkDataCOcc = mk_simple_deriv varName "$c"
  518. -- Vectorisation
  519. mkVectOcc, mkVectTyConOcc, mkVectDataConOcc, mkVectIsoOcc,
  520. mkPADFunOcc, mkPReprTyConOcc,
  521. mkPDataTyConOcc, mkPDataDataConOcc,
  522. mkPDatasTyConOcc, mkPDatasDataConOcc
  523. :: Maybe String -> OccName -> OccName
  524. mkVectOcc = mk_simple_deriv_with varName "$v"
  525. mkVectTyConOcc = mk_simple_deriv_with tcName "V:"
  526. mkVectDataConOcc = mk_simple_deriv_with dataName "VD:"
  527. mkVectIsoOcc = mk_simple_deriv_with varName "$vi"
  528. mkPADFunOcc = mk_simple_deriv_with varName "$pa"
  529. mkPReprTyConOcc = mk_simple_deriv_with tcName "VR:"
  530. mkPDataTyConOcc = mk_simple_deriv_with tcName "VP:"
  531. mkPDatasTyConOcc = mk_simple_deriv_with tcName "VPs:"
  532. mkPDataDataConOcc = mk_simple_deriv_with dataName "VPD:"
  533. mkPDatasDataConOcc = mk_simple_deriv_with dataName "VPDs:"
  534. mk_simple_deriv :: NameSpace -> String -> OccName -> OccName
  535. mk_simple_deriv sp px occ = mk_deriv sp px (occNameString occ)
  536. mk_simple_deriv_with :: NameSpace -> String -> Maybe String -> OccName -> OccName
  537. mk_simple_deriv_with sp px Nothing occ = mk_deriv sp px (occNameString occ)
  538. mk_simple_deriv_with sp px (Just with) occ = mk_deriv sp (px ++ with ++ "_") (occNameString occ)
  539. -- Data constructor workers are made by setting the name space
  540. -- of the data constructor OccName (which should be a DataName)
  541. -- to VarName
  542. mkDataConWorkerOcc datacon_occ = setOccNameSpace varName datacon_occ
  543. \end{code}
  544. \begin{code}
  545. mkSuperDictSelOcc :: Int -- ^ Index of superclass, e.g. 3
  546. -> OccName -- ^ Class, e.g. @Ord@
  547. -> OccName -- ^ Derived 'Occname', e.g. @$p3Ord@
  548. mkSuperDictSelOcc index cls_tc_occ
  549. = mk_deriv varName "$p" (show index ++ occNameString cls_tc_occ)
  550. mkLocalOcc :: Unique -- ^ Unique to combine with the 'OccName'
  551. -> OccName -- ^ Local name, e.g. @sat@
  552. -> OccName -- ^ Nice unique version, e.g. @$L23sat@
  553. mkLocalOcc uniq occ
  554. = mk_deriv varName ("$L" ++ show uniq) (occNameString occ)
  555. -- The Unique might print with characters
  556. -- that need encoding (e.g. 'z'!)
  557. \end{code}
  558. \begin{code}
  559. -- | Derive a name for the representation type constructor of a
  560. -- @data@\/@newtype@ instance.
  561. mkInstTyTcOcc :: String -- ^ Family name, e.g. @Map@
  562. -> OccSet -- ^ avoid these Occs
  563. -> OccName -- ^ @R:Map@
  564. mkInstTyTcOcc str set =
  565. chooseUniqueOcc tcName ('R' : ':' : str) set
  566. \end{code}
  567. \begin{code}
  568. mkDFunOcc :: String -- ^ Typically the class and type glommed together e.g. @OrdMaybe@.
  569. -- Only used in debug mode, for extra clarity
  570. -> Bool -- ^ Is this a hs-boot instance DFun?
  571. -> OccSet -- ^ avoid these Occs
  572. -> OccName -- ^ E.g. @$f3OrdMaybe@
  573. -- In hs-boot files we make dict funs like $fx7ClsTy, which get bound to the real
  574. -- thing when we compile the mother module. Reason: we don't know exactly
  575. -- what the mother module will call it.
  576. mkDFunOcc info_str is_boot set
  577. = chooseUniqueOcc VarName (prefix ++ info_str) set
  578. where
  579. prefix | is_boot = "$fx"
  580. | otherwise = "$f"
  581. \end{code}
  582. Sometimes we need to pick an OccName that has not already been used,
  583. given a set of in-use OccNames.
  584. \begin{code}
  585. chooseUniqueOcc :: NameSpace -> String -> OccSet -> OccName
  586. chooseUniqueOcc ns str set = loop (mkOccName ns str) (0::Int)
  587. where
  588. loop occ n
  589. | occ `elemOccSet` set = loop (mkOccName ns (str ++ show n)) (n+1)
  590. | otherwise = occ
  591. \end{code}
  592. We used to add a '$m' to indicate a method, but that gives rise to bad
  593. error messages from the type checker when we print the function name or pattern
  594. of an instance-decl binding. Why? Because the binding is zapped
  595. to use the method name in place of the selector name.
  596. (See TcClassDcl.tcMethodBind)
  597. The way it is now, -ddump-xx output may look confusing, but
  598. you can always say -dppr-debug to get the uniques.
  599. However, we *do* have to zap the first character to be lower case,
  600. because overloaded constructors (blarg) generate methods too.
  601. And convert to VarName space
  602. e.g. a call to constructor MkFoo where
  603. data (Ord a) => Foo a = MkFoo a
  604. If this is necessary, we do it by prefixing '$m'. These
  605. guys never show up in error messages. What a hack.
  606. \begin{code}
  607. mkMethodOcc :: OccName -> OccName
  608. mkMethodOcc occ@(OccName VarName _) = occ
  609. mkMethodOcc occ = mk_simple_deriv varName "$m" occ
  610. \end{code}
  611. %************************************************************************
  612. %* *
  613. \subsection{Tidying them up}
  614. %* *
  615. %************************************************************************
  616. Before we print chunks of code we like to rename it so that
  617. we don't have to print lots of silly uniques in it. But we mustn't
  618. accidentally introduce name clashes! So the idea is that we leave the
  619. OccName alone unless it accidentally clashes with one that is already
  620. in scope; if so, we tack on '1' at the end and try again, then '2', and
  621. so on till we find a unique one.
  622. There's a wrinkle for operators. Consider '>>='. We can't use '>>=1'
  623. because that isn't a single lexeme. So we encode it to 'lle' and *then*
  624. tack on the '1', if necessary.
  625. Note [TidyOccEnv]
  626. ~~~~~~~~~~~~~~~~~
  627. type TidyOccEnv = UniqFM Int
  628. * Domain = The OccName's FastString. These FastStrings are "taken";
  629. make sure that we don't re-use
  630. * Int, n = A plausible starting point for new guesses
  631. There is no guarantee that "FSn" is available;
  632. you must look that up in the TidyOccEnv. But
  633. it's a good place to start looking.
  634. * When looking for a renaming for "foo2" we strip off the "2" and start
  635. with "foo". Otherwise if we tidy twice we get silly names like foo23.
  636. \begin{code}
  637. type TidyOccEnv = UniqFM Int -- The in-scope OccNames
  638. -- See Note [TidyOccEnv]
  639. emptyTidyOccEnv :: TidyOccEnv
  640. emptyTidyOccEnv = emptyUFM
  641. initTidyOccEnv :: [OccName] -> TidyOccEnv -- Initialise with names to avoid!
  642. initTidyOccEnv = foldl add emptyUFM
  643. where
  644. add env (OccName _ fs) = addToUFM env fs 1
  645. tidyOccName :: TidyOccEnv -> OccName -> (TidyOccEnv, OccName)
  646. tidyOccName env occ@(OccName occ_sp fs)
  647. = case lookupUFM env fs of
  648. Just n -> find n
  649. Nothing -> (addToUFM env fs 1, occ)
  650. where
  651. base :: String -- Drop trailing digits (see Note [TidyOccEnv])
  652. base = reverse (dropWhile isDigit (reverse (unpackFS fs)))
  653. find n
  654. = case lookupUFM env new_fs of
  655. Just n' -> find (n1 `max` n')
  656. -- The max ensures that n increases, avoiding loops
  657. Nothing -> (addToUFM (addToUFM env fs n1) new_fs n1,
  658. OccName occ_sp new_fs)
  659. -- We update only the beginning and end of the
  660. -- chain that find explores; it's a little harder to
  661. -- update the middle and there's no real need.
  662. where
  663. n1 = n+1
  664. new_fs = mkFastString (base ++ show n)
  665. \end{code}
  666. %************************************************************************
  667. %* *
  668. Stuff for dealing with tuples
  669. %* *
  670. %************************************************************************
  671. \begin{code}
  672. mkTupleOcc :: NameSpace -> TupleSort -> Arity -> OccName
  673. mkTupleOcc ns sort ar = OccName ns (mkFastString str)
  674. where
  675. -- no need to cache these, the caching is done in the caller
  676. -- (TysWiredIn.mk_tuple)
  677. str = case sort of
  678. UnboxedTuple -> '(' : '#' : commas ++ "#)"
  679. BoxedTuple -> '(' : commas ++ ")"
  680. ConstraintTuple -> '(' : commas ++ ")"
  681. -- Cute hack: reuse the standard tuple OccNames (and hence code)
  682. -- for fact tuples, but give them different Uniques so they are not equal.
  683. --
  684. -- You might think that this will go wrong because isTupleOcc_maybe won't
  685. -- be able to tell the difference between boxed tuples and fact tuples. BUT:
  686. -- 1. Fact tuples never occur directly in user code, so it doesn't matter
  687. -- that we can't detect them in Orig OccNames originating from the user
  688. -- programs (or those built by setRdrNameSpace used on an Exact tuple Name)
  689. -- 2. Interface files have a special representation for tuple *occurrences*
  690. -- in IfaceTyCons, their workers (in IfaceSyn) and their DataCons (in case
  691. -- alternatives). Thus we don't rely on the OccName to figure out what kind
  692. -- of tuple an occurrence was trying to use in these situations.
  693. -- 3. We *don't* represent tuple data type declarations specially, so those
  694. -- are still turned into wired-in names via isTupleOcc_maybe. But that's OK
  695. -- because we don't actually need to declare fact tuples thanks to this hack.
  696. --
  697. -- So basically any OccName like (,,) flowing to isTupleOcc_maybe will always
  698. -- refer to the standard boxed tuple. Cool :-)
  699. commas = take (ar-1) (repeat ',')
  700. isTupleOcc_maybe :: OccName -> Maybe (NameSpace, TupleSort, Arity)
  701. -- Tuples are special, because there are so many of them!
  702. isTupleOcc_maybe (OccName ns fs)
  703. = case unpackFS fs of
  704. '(':'#':',':rest -> Just (ns, UnboxedTuple, 2 + count_commas rest)
  705. '(':',':rest -> Just (ns, BoxedTuple, 2 + count_commas rest)
  706. _other -> Nothing
  707. where
  708. count_commas (',':rest) = 1 + count_commas rest
  709. count_commas _ = 0
  710. \end{code}
  711. %************************************************************************
  712. %* *
  713. \subsection{Lexical categories}
  714. %* *
  715. %************************************************************************
  716. These functions test strings to see if they fit the lexical categories
  717. defined in the Haskell report.
  718. \begin{code}
  719. isLexCon, isLexVar, isLexId, isLexSym :: FastString -> Bool
  720. isLexConId, isLexConSym, isLexVarId, isLexVarSym :: FastString -> Bool
  721. isLexCon cs = isLexConId cs || isLexConSym cs
  722. isLexVar cs = isLexVarId cs || isLexVarSym cs
  723. isLexId cs = isLexConId cs || isLexVarId cs
  724. isLexSym cs = isLexConSym cs || isLexVarSym cs
  725. -------------
  726. isLexConId cs -- Prefix type or data constructors
  727. | nullFS cs = False -- e.g. "Foo", "[]", "(,)"
  728. | cs == (fsLit "[]") = True
  729. | otherwise = startsConId (headFS cs)
  730. isLexVarId cs -- Ordinary prefix identifiers
  731. | nullFS cs = False -- e.g. "x", "_x"
  732. | otherwise = startsVarId (headFS cs)
  733. isLexConSym cs -- Infix type or data constructors
  734. | nullFS cs = False -- e.g. ":-:", ":", "->"
  735. | cs == (fsLit "->") = True
  736. | otherwise = startsConSym (headFS cs)
  737. isLexVarSym cs -- Infix identifiers
  738. | nullFS cs = False -- e.g. "+"
  739. | otherwise = startsVarSym (headFS cs)
  740. -------------
  741. startsVarSym, startsVarId, startsConSym, startsConId :: Char -> Bool
  742. startsVarSym c = isSymbolASCII c || (ord c > 0x7f && isSymbol c) -- Infix Ids
  743. startsConSym c = c == ':' -- Infix data constructors
  744. startsVarId c = isLower c || c == '_' -- Ordinary Ids
  745. startsConId c = isUpper c || c == '(' -- Ordinary type constructors and data constructors
  746. isSymbolASCII :: Char -> Bool
  747. isSymbolASCII c = c `elem` "!#$%&*+./<=>?@\\^|~-"
  748. \end{code}
  749. %************************************************************************
  750. %* *
  751. Binary instance
  752. Here rather than BinIface because OccName is abstract
  753. %* *
  754. %************************************************************************
  755. \begin{code}
  756. instance Binary NameSpace where
  757. put_ bh VarName = do
  758. putByte bh 0
  759. put_ bh DataName = do
  760. putByte bh 1
  761. put_ bh TvName = do
  762. putByte bh 2
  763. put_ bh TcClsName = do
  764. putByte bh 3
  765. get bh = do
  766. h <- getByte bh
  767. case h of
  768. 0 -> do return VarName
  769. 1 -> do return DataName
  770. 2 -> do return TvName
  771. _ -> do return TcClsName
  772. instance Binary OccName where
  773. put_ bh (OccName aa ab) = do
  774. put_ bh aa
  775. put_ bh ab
  776. get bh = do
  777. aa <- get bh
  778. ab <- get bh
  779. return (OccName aa ab)
  780. \end{code}