Super-monster patch implementing the new typechecker -- at last
[ghc-hetmet.git] / compiler / basicTypes / Var.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 %
5 \section{@Vars@: Variables}
6
7 \begin{code}
8 -- |
9 -- #name_types#
10 -- GHC uses several kinds of name internally:
11 --
12 -- * 'OccName.OccName': see "OccName#name_types"
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' is a synonym for the 'Id.Id' type but it may additionally potentially contain type variables, 
21 --   which have a 'TypeRep.Kind' rather than a 'TypeRep.Type' and only contain some extra details during typechecking.
22 --   These 'Var.Var' names may either be global or local, see "Var#globalvslocal"
23 --
24 -- #globalvslocal#
25 -- Global 'Id's and 'Var's are those that are imported or correspond to a data constructor, primitive operation, or record selectors.
26 -- Local 'Id's and 'Var's are those bound within an expression (e.g. by a lambda) or at the top level of the module being compiled.
27 module Var (
28         -- * The main data type and synonyms
29         Var, TyVar, CoVar, Id, DictId, DFunId, EvVar, EvId, IpId,
30
31         -- ** Taking 'Var's apart
32         varName, varUnique, varType, 
33
34         -- ** Modifying 'Var's
35         setVarName, setVarUnique, setVarType,
36
37         -- ** Constructing, taking apart, modifying 'Id's
38         mkGlobalVar, mkLocalVar, mkExportedLocalVar, 
39         idInfo, idDetails,
40         lazySetIdInfo, setIdDetails, globaliseId,
41         setIdExported, setIdNotExported,
42
43         -- ** Predicates
44         isCoVar, isId, isTyCoVar, isTyVar, isTcTyVar,
45         isLocalVar, isLocalId,
46         isGlobalId, isExportedId,
47         mustHaveLocalBinding,
48
49         -- ** Constructing 'TyVar's
50         mkTyVar, mkTcTyVar, mkWildCoVar,
51
52         -- ** Taking 'TyVar's apart
53         tyVarName, tyVarKind, tcTyVarDetails,
54
55         -- ** Modifying 'TyVar's
56         setTyVarName, setTyVarUnique, setTyVarKind,
57
58         -- ** Constructing 'CoVar's
59         mkCoVar,
60
61         -- ** Taking 'CoVar's apart
62         coVarName,
63
64         -- ** Modifying 'CoVar's
65         setCoVarUnique, setCoVarName
66
67     ) where
68
69 #include "HsVersions.h"
70 #include "Typeable.h"
71
72 import {-# SOURCE #-}   TypeRep( Type, Kind )
73 import {-# SOURCE #-}   TcType( TcTyVarDetails, pprTcTyVarDetails )
74 import {-# SOURCE #-}   IdInfo( IdDetails, IdInfo, pprIdDetails )
75 import {-# SOURCE #-}   TypeRep( isCoercionKind )
76
77 import Name hiding (varName)
78 import Unique
79 import Util
80 import FastTypes
81 import FastString
82 import Outputable
83
84 import Data.Data
85 \end{code}
86
87
88 %************************************************************************
89 %*                                                                      *
90                      Synonyms                                                                   
91 %*                                                                      *
92 %************************************************************************
93 -- These synonyms are here and not in Id because otherwise we need a very
94 -- large number of SOURCE imports of Id.hs :-(
95
96 \begin{code}
97 type EvVar = Var        -- An evidence variable: dictionary or equality constraint
98                         -- Could be an DictId or a CoVar
99
100 type Id     = Var       -- A term-level identifier
101 type DFunId = Id        -- A dictionary function
102 type EvId   = Id        -- Term-level evidence: DictId or IpId
103 type DictId = EvId      -- A dictionary variable
104 type IpId   = EvId      -- A term-level implicit parameter
105
106 type TyVar = Var
107 type CoVar = TyVar      -- A coercion variable is simply a type 
108                         -- variable of kind @ty1 ~ ty2@. Hence its
109                         -- 'varType' is always @PredTy (EqPred t1 t2)@
110 \end{code}
111
112 %************************************************************************
113 %*                                                                      *
114 \subsection{The main data type declarations}
115 %*                                                                      *
116 %************************************************************************
117
118
119 Every @Var@ has a @Unique@, to uniquify it and for fast comparison, a
120 @Type@, and an @IdInfo@ (non-essential info about it, e.g.,
121 strictness).  The essential info about different kinds of @Vars@ is
122 in its @VarDetails@.
123
124 \begin{code}
125 -- | Essentially a typed 'Name', that may also contain some additional information
126 -- about the 'Var' and it's use sites.
127 data Var
128   = TyVar {
129         varName    :: !Name,
130         realUnique :: FastInt,          -- Key for fast comparison
131                                         -- Identical to the Unique in the name,
132                                         -- cached here for speed
133         varType       :: Kind,          -- ^ The type or kind of the 'Var' in question
134         isCoercionVar :: Bool
135  }
136
137   | TcTyVar {                           -- Used only during type inference
138                                         -- Used for kind variables during 
139                                         -- inference, as well
140         varName        :: !Name,
141         realUnique     :: FastInt,
142         varType        :: Kind,
143         tc_tv_details  :: TcTyVarDetails }
144
145   | Id {
146         varName    :: !Name,
147         realUnique :: FastInt,
148         varType    :: Type,
149         idScope    :: IdScope,
150         id_details :: IdDetails,        -- Stable, doesn't change
151         id_info    :: IdInfo }          -- Unstable, updated by simplifier
152
153 data IdScope    -- See Note [GlobalId/LocalId]
154   = GlobalId 
155   | LocalId ExportFlag
156
157 data ExportFlag 
158   = NotExported -- ^ Not exported: may be discarded as dead code.
159   | Exported    -- ^ Exported: kept alive
160 \end{code}
161
162 Note [GlobalId/LocalId]
163 ~~~~~~~~~~~~~~~~~~~~~~~
164 A GlobalId is
165   * always a constant (top-level)
166   * imported, or data constructor, or primop, or record selector
167   * has a Unique that is globally unique across the whole
168     GHC invocation (a single invocation may compile multiple modules)
169   * never treated as a candidate by the free-variable finder;
170         it's a constant!
171
172 A LocalId is 
173   * bound within an expression (lambda, case, local let(rec))
174   * or defined at top level in the module being compiled
175   * always treated as a candidate by the free-variable finder
176
177 After CoreTidy, top-level LocalIds are turned into GlobalIds
178
179 \begin{code}
180 instance Outputable Var where
181   ppr var = ppr (varName var) <+> ifPprDebug (brackets (ppr_debug var))
182
183 ppr_debug :: Var -> SDoc
184 ppr_debug (TyVar {})                          = ptext (sLit "tv")
185 ppr_debug (TcTyVar {tc_tv_details = d})       = pprTcTyVarDetails d
186 ppr_debug (Id { idScope = s, id_details = d }) = ppr_id_scope s <> pprIdDetails d
187
188 ppr_id_scope :: IdScope -> SDoc
189 ppr_id_scope GlobalId              = ptext (sLit "gid")
190 ppr_id_scope (LocalId Exported)    = ptext (sLit "lidx")
191 ppr_id_scope (LocalId NotExported) = ptext (sLit "lid")
192
193 instance Show Var where
194   showsPrec p var = showsPrecSDoc p (ppr var)
195
196 instance NamedThing Var where
197   getName = varName
198
199 instance Uniquable Var where
200   getUnique = varUnique
201
202 instance Eq Var where
203     a == b = realUnique a ==# realUnique b
204
205 instance Ord Var where
206     a <= b = realUnique a <=# realUnique b
207     a <  b = realUnique a <#  realUnique b
208     a >= b = realUnique a >=# realUnique b
209     a >  b = realUnique a >#  realUnique b
210     a `compare` b = varUnique a `compare` varUnique b
211
212 INSTANCE_TYPEABLE0(Var,varTc,"Var")
213
214 instance Data Var where
215   -- don't traverse?
216   toConstr _   = abstractConstr "Var"
217   gunfold _ _  = error "gunfold"
218   dataTypeOf _ = mkNoRepType "Var"
219 \end{code}
220
221
222 \begin{code}
223 varUnique :: Var -> Unique
224 varUnique var = mkUniqueGrimily (iBox (realUnique var))
225
226 setVarUnique :: Var -> Unique -> Var
227 setVarUnique var uniq 
228   = var { realUnique = getKeyFastInt uniq, 
229           varName = setNameUnique (varName var) uniq }
230
231 setVarName :: Var -> Name -> Var
232 setVarName var new_name
233   = var { realUnique = getKeyFastInt (getUnique new_name), 
234           varName = new_name }
235
236 setVarType :: Id -> Type -> Id
237 setVarType id ty = id { varType = ty }
238 \end{code}
239
240
241 %************************************************************************
242 %*                                                                      *
243 \subsection{Type variables}
244 %*                                                                      *
245 %************************************************************************
246
247 \begin{code}
248 tyVarName :: TyVar -> Name
249 tyVarName = varName
250
251 tyVarKind :: TyVar -> Kind
252 tyVarKind = varType
253
254 setTyVarUnique :: TyVar -> Unique -> TyVar
255 setTyVarUnique = setVarUnique
256
257 setTyVarName :: TyVar -> Name -> TyVar
258 setTyVarName   = setVarName
259
260 setTyVarKind :: TyVar -> Kind -> TyVar
261 setTyVarKind tv k = tv {varType = k}
262 \end{code}
263
264 \begin{code}
265 mkTyVar :: Name -> Kind -> TyVar
266 mkTyVar name kind = ASSERT( not (isCoercionKind kind ) )
267                     TyVar { varName    = name
268                           , realUnique = getKeyFastInt (nameUnique name)
269                           , varType  = kind
270                           , isCoercionVar    = False
271                         }
272
273 mkTcTyVar :: Name -> Kind -> TcTyVarDetails -> TyVar
274 mkTcTyVar name kind details
275   = -- NB: 'kind' may be a coercion kind; cf, 'TcMType.newMetaCoVar'
276     TcTyVar {   varName    = name,
277                 realUnique = getKeyFastInt (nameUnique name),
278                 varType  = kind,
279                 tc_tv_details = details
280         }
281
282 tcTyVarDetails :: TyVar -> TcTyVarDetails
283 tcTyVarDetails (TcTyVar { tc_tv_details = details }) = details
284 tcTyVarDetails var = pprPanic "tcTyVarDetails" (ppr var)
285 \end{code}
286
287 %************************************************************************
288 %*                                                                      *
289 \subsection{Coercion variables}
290 %*                                                                      *
291 %************************************************************************
292
293 \begin{code}
294 coVarName :: CoVar -> Name
295 coVarName = varName
296
297 setCoVarUnique :: CoVar -> Unique -> CoVar
298 setCoVarUnique = setVarUnique
299
300 setCoVarName :: CoVar -> Name -> CoVar
301 setCoVarName   = setVarName
302
303 mkCoVar :: Name -> Kind -> CoVar
304 mkCoVar name kind = ASSERT( isCoercionKind kind )
305                     TyVar { varName       = name
306                           , realUnique    = getKeyFastInt (nameUnique name)
307                           , varType       = kind
308                           , isCoercionVar = True
309                         }
310
311 mkWildCoVar :: Kind -> TyVar
312 -- ^ Create a type variable that is never referred to, so its unique doesn't 
313 -- matter
314 mkWildCoVar = mkCoVar (mkSysTvName (mkBuiltinUnique 1) (fsLit "co_wild"))
315 \end{code}
316
317 %************************************************************************
318 %*                                                                      *
319 \subsection{Ids}
320 %*                                                                      *
321 %************************************************************************
322
323 \begin{code}
324 idInfo :: Id -> IdInfo
325 idInfo (Id { id_info = info }) = info
326 idInfo other                   = pprPanic "idInfo" (ppr other)
327
328 idDetails :: Id -> IdDetails
329 idDetails (Id { id_details = details }) = details
330 idDetails other                         = pprPanic "idDetails" (ppr other)
331
332 -- The next three have a 'Var' suffix even though they always build
333 -- Ids, becuase Id.lhs uses 'mkGlobalId' etc with different types
334 mkGlobalVar :: IdDetails -> Name -> Type -> IdInfo -> Id
335 mkGlobalVar details name ty info
336   = mk_id name ty GlobalId details info
337
338 mkLocalVar :: IdDetails -> Name -> Type -> IdInfo -> Id
339 mkLocalVar details name ty info
340   = mk_id name ty (LocalId NotExported) details  info
341
342 -- | Exported 'Var's will not be removed as dead code
343 mkExportedLocalVar :: IdDetails -> Name -> Type -> IdInfo -> Id
344 mkExportedLocalVar details name ty info 
345   = mk_id name ty (LocalId Exported) details info
346
347 mk_id :: Name -> Type -> IdScope -> IdDetails -> IdInfo -> Id
348 mk_id name ty scope details info
349   = Id { varName    = name, 
350          realUnique = getKeyFastInt (nameUnique name),
351          varType    = ty,       
352          idScope    = scope,
353          id_details = details,
354          id_info    = info }
355
356 -------------------
357 lazySetIdInfo :: Id -> IdInfo -> Var
358 lazySetIdInfo id info = id { id_info = info }
359
360 setIdDetails :: Id -> IdDetails -> Id
361 setIdDetails id details = id { id_details = details }
362
363 globaliseId :: Id -> Id
364 -- ^ If it's a local, make it global
365 globaliseId id = id { idScope = GlobalId }
366
367 setIdExported :: Id -> Id
368 -- ^ Exports the given local 'Id'. Can also be called on global 'Id's, such as data constructors
369 -- and class operations, which are born as global 'Id's and automatically exported
370 setIdExported id@(Id { idScope = LocalId {} }) = id { idScope = LocalId Exported }
371 setIdExported id@(Id { idScope = GlobalId })   = id
372 setIdExported tv                               = pprPanic "setIdExported" (ppr tv)
373
374 setIdNotExported :: Id -> Id
375 -- ^ We can only do this to LocalIds
376 setIdNotExported id = ASSERT( isLocalId id ) 
377                       id { idScope = LocalId NotExported }
378 \end{code}
379
380 %************************************************************************
381 %*                                                                      *
382 \subsection{Predicates over variables}
383 %*                                                                      *
384 %************************************************************************
385
386 \begin{code}
387 isTyCoVar :: Var -> Bool        -- True of both type and coercion variables
388 isTyCoVar (TyVar {})   = True
389 isTyCoVar (TcTyVar {}) = True
390 isTyCoVar _            = False
391
392 isTyVar :: Var -> Bool          -- True of both type variables only
393 isTyVar v@(TyVar {}) = not (isCoercionVar v)
394 isTyVar (TcTyVar {}) = True
395 isTyVar _            = False
396
397 isCoVar :: Var -> Bool          -- Only works after type checking (sigh)
398 isCoVar v@(TyVar {}) = isCoercionVar v
399 isCoVar _            = False
400
401 isTcTyVar :: Var -> Bool
402 isTcTyVar (TcTyVar {}) = True
403 isTcTyVar _            = False
404
405 isId :: Var -> Bool
406 isId (Id {}) = True
407 isId _       = False
408
409 isLocalId :: Var -> Bool
410 isLocalId (Id { idScope = LocalId _ }) = True
411 isLocalId _                            = False
412
413 -- | 'isLocalVar' returns @True@ for type variables as well as local 'Id's
414 -- These are the variables that we need to pay attention to when finding free
415 -- variables, or doing dependency analysis.
416 isLocalVar :: Var -> Bool
417 isLocalVar v = not (isGlobalId v)
418
419 isGlobalId :: Var -> Bool
420 isGlobalId (Id { idScope = GlobalId }) = True
421 isGlobalId _                           = False
422
423 -- | 'mustHaveLocalBinding' returns @True@ of 'Id's and 'TyVar's
424 -- that must have a binding in this module.  The converse
425 -- is not quite right: there are some global 'Id's that must have
426 -- bindings, such as record selectors.  But that doesn't matter,
427 -- because it's only used for assertions
428 mustHaveLocalBinding        :: Var -> Bool
429 mustHaveLocalBinding var = isLocalVar var
430
431 -- | 'isExportedIdVar' means \"don't throw this away\"
432 isExportedId :: Var -> Bool
433 isExportedId (Id { idScope = GlobalId })        = True
434 isExportedId (Id { idScope = LocalId Exported}) = True
435 isExportedId _ = False
436 \end{code}