/compiler/basicTypes/OccName.lhs

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