Var.lhs 14.5 KB
Newer Older
1
%
Simon Marlow's avatar
Simon Marlow committed
2
% (c) The University of Glasgow 2006
3 4 5 6 7
% (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
%
\section{@Vars@: Variables}

\begin{code}
Ian Lynagh's avatar
Ian Lynagh committed
8 9 10 11 12 13 14
{-# OPTIONS -fno-warn-tabs #-}
-- The above warning supression flag is a temporary kludge.
-- While working on this module you are encouraged to remove it and
-- detab the module (please do the detabbing in a separate patch). See
--     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#TabsvsSpaces
-- for details

15 16 17 18 19 20 21 22 23 24 25 26
-- |
-- #name_types#
-- GHC uses several kinds of name internally:
--
-- * 'OccName.OccName': see "OccName#name_types"
--
-- * 'RdrName.RdrName': see "RdrName#name_types"
--
-- * 'Name.Name': see "Name#name_types"
--
-- * 'Id.Id': see "Id#name_types"
--
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
27 28 29 30 31
-- * 'Var.Var' is a synonym for the 'Id.Id' type but it may additionally 
--   potentially contain type variables, which have a 'TypeRep.Kind' 
--   rather than a 'TypeRep.Type' and only contain some extra 
--   details during typechecking.
-- 
32 33 34
--   These 'Var.Var' names may either be global or local, see "Var#globalvslocal"
--
-- #globalvslocal#
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
35 36 37 38 39
-- Global 'Id's and 'Var's are those that are imported or correspond 
--    to a data constructor, primitive operation, or record selectors.
-- 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.

40
module Var (
41
        -- * The main data type and synonyms
42 43
        Var, CoVar, Id, DictId, DFunId, EvVar, EqVar, EvId, IpId,
        TyVar, TypeVar, KindVar, TKVar,
44

45
	-- ** Taking 'Var's apart
46
	varName, varUnique, varType, 
47 48 49

	-- ** Modifying 'Var's
	setVarName, setVarUnique, setVarType,
50 51

	-- ** Constructing, taking apart, modifying 'Id's
52
	mkGlobalVar, mkLocalVar, mkExportedLocalVar, mkCoVar,
53 54 55
	idInfo, idDetails,
	lazySetIdInfo, setIdDetails, globaliseId,
	setIdExported, setIdNotExported,
56 57

        -- ** Predicates
58
        isId, isTKVar, isTyVar, isTcTyVar,
59 60
        isLocalVar, isLocalId,
	isGlobalId, isExportedId,
61 62 63
	mustHaveLocalBinding,

	-- ** Constructing 'TyVar's
dreixel's avatar
dreixel committed
64
	mkTyVar, mkTcTyVar, mkKindVar,
65 66

	-- ** Taking 'TyVar's apart
67
        tyVarName, tyVarKind, tcTyVarDetails, setTcTyVarDetails,
68 69

	-- ** Modifying 'TyVar's
dreixel's avatar
dreixel committed
70 71
	setTyVarName, setTyVarUnique, setTyVarKind, updateTyVarKind,
        updateTyVarKindM
72

73 74 75
    ) where

#include "HsVersions.h"
76
#include "Typeable.h"
77

dreixel's avatar
dreixel committed
78
import {-# SOURCE #-}	TypeRep( Type, Kind, SuperKind )
79
import {-# SOURCE #-}	TcType( TcTyVarDetails, pprTcTyVarDetails )
80
import {-# SOURCE #-}	IdInfo( IdDetails, IdInfo, coVarDetails, vanillaIdInfo, pprIdDetails )
81

Simon Marlow's avatar
Simon Marlow committed
82 83
import Name hiding (varName)
import Unique
84
import Util
85
import FastTypes
86
import FastString
87
import Outputable
88 89

import Data.Data
90 91 92
\end{code}


93 94 95 96 97 98 99 100 101
%************************************************************************
%*									*
                     Synonyms									
%*									*
%************************************************************************
-- These synonyms are here and not in Id because otherwise we need a very
-- large number of SOURCE imports of Id.hs :-(

\begin{code}
Simon Peyton Jones's avatar
Simon Peyton Jones committed
102
type Id    = Var       -- A term-level identifier
dreixel's avatar
dreixel committed
103

104 105 106 107
type TyVar   = Var     -- Type *or* kind variable (historical)

type TKVar   = Var     -- Type *or* kind variable (historical)
type TypeVar = Var     -- Definitely a type variable
dreixel's avatar
dreixel committed
108 109
type KindVar = Var     -- Definitely a kind variable
     	       	       -- See Note [Kind and type variables]
110

Simon Peyton Jones's avatar
Simon Peyton Jones committed
111 112 113
-- See Note [Evidence: EvIds and CoVars]
type EvId   = Id        -- Term-level evidence: DictId, IpId, or EqVar
type EvVar  = EvId	-- ...historical name for EvId
114 115 116
type DFunId = Id	-- A dictionary function
type DictId = EvId	-- A dictionary variable
type IpId   = EvId      -- A term-level implicit parameter
batterseapower's avatar
batterseapower committed
117
type EqVar  = EvId      -- Boxed equality evidence
118

Simon Peyton Jones's avatar
Simon Peyton Jones committed
119
type CoVar = Id		-- See Note [Evidence: EvIds and CoVars]
120 121
\end{code}

Simon Peyton Jones's avatar
Simon Peyton Jones committed
122 123 124 125 126 127 128 129
Note [Evidence: EvIds and CoVars]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* An EvId (evidence Id) is a *boxed*, term-level evidence variable 
  (dictionary, implicit parameter, or equality).

* A CoVar (coercion variable) is an *unboxed* term-level evidence variable
  of type (t1 ~# t2).  So it's the unboxed version of an EqVar.

130 131 132 133
* Only CoVars can occur in Coercions, EqVars appear in TcCoercions.

* DictId, IpId, and EqVar are synonyms when we know what kind of
  evidence we are talking about.  For example, an EqVar has type (t1 ~ t2).
Simon Peyton Jones's avatar
Simon Peyton Jones committed
134

dreixel's avatar
dreixel committed
135 136 137 138 139 140
Note [Kind and type variables]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Before kind polymorphism, TyVar were used to mean type variables. Now
they are use to mean kind *or* type variables. KindVar is used when we
know for sure that it is a kind variable. In future, we might want to
go over the whole compiler code to use:
141 142
   - TKVar   to mean kind or type variables
   - TypeVar to mean         type variables only
dreixel's avatar
dreixel committed
143 144
   - KindVar to mean kind         variables

Simon Peyton Jones's avatar
Simon Peyton Jones committed
145

146 147 148 149 150 151 152 153 154 155 156 157 158
%************************************************************************
%*									*
\subsection{The main data type declarations}
%*									*
%************************************************************************


Every @Var@ has a @Unique@, to uniquify it and for fast comparison, a
@Type@, and an @IdInfo@ (non-essential info about it, e.g.,
strictness).  The essential info about different kinds of @Vars@ is
in its @VarDetails@.

\begin{code}
159 160
-- | Essentially a typed 'Name', that may also contain some additional information
-- about the 'Var' and it's use sites.
161
data Var
162
  = TyVar {  -- Type and kind variables
dreixel's avatar
dreixel committed
163
             -- see Note [Kind and type variables]
164
	varName    :: !Name,
165 166 167 168
	realUnique :: FastInt,	     -- Key for fast comparison
				     -- Identical to the Unique in the name,
				     -- cached here for speed
	varType    :: Kind           -- ^ The type or kind of the 'Var' in question
169
 }
170

171
  | TcTyVar { 				-- Used only during type inference
172 173
					-- Used for kind variables during 
					-- inference, as well
174
	varName        :: !Name,
175
	realUnique     :: FastInt,
176
	varType        :: Kind,
177
	tc_tv_details  :: TcTyVarDetails }
178

179
  | Id {
180 181
	varName    :: !Name,
	realUnique :: FastInt,
182
   	varType    :: Type,
183
	idScope    :: IdScope,
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
184 185
	id_details :: IdDetails,	-- Stable, doesn't change
	id_info    :: IdInfo }		-- Unstable, updated by simplifier
Ian Lynagh's avatar
Ian Lynagh committed
186
    deriving Typeable
187

188 189 190 191 192
data IdScope	-- See Note [GlobalId/LocalId]
  = GlobalId 
  | LocalId ExportFlag

data ExportFlag 
193 194
  = NotExported	-- ^ Not exported: may be discarded as dead code.
  | Exported	-- ^ Exported: kept alive
195 196
\end{code}

197 198
Note [GlobalId/LocalId]
~~~~~~~~~~~~~~~~~~~~~~~
199 200 201
A GlobalId is
  * always a constant (top-level)
  * imported, or data constructor, or primop, or record selector
202 203
  * has a Unique that is globally unique across the whole
    GHC invocation (a single invocation may compile multiple modules)
204 205
  * never treated as a candidate by the free-variable finder;
	it's a constant!
206 207 208 209

A LocalId is 
  * bound within an expression (lambda, case, local let(rec))
  * or defined at top level in the module being compiled
210
  * always treated as a candidate by the free-variable finder
211 212 213

After CoreTidy, top-level LocalIds are turned into GlobalIds

214
\begin{code}
215
instance Outputable Var where
216 217
  ppr var = ppr (varName var) <+> ifPprDebug (brackets (ppr_debug var))
-- Printing the type on every occurrence is too much!
ian@well-typed.com's avatar
ian@well-typed.com committed
218
--            <+> if (not (gopt Opt_SuppressVarKinds dflags))
219 220
--                then ifPprDebug (text "::" <+> ppr (tyVarKind var) <+> text ")")
--                else empty
221 222

ppr_debug :: Var -> SDoc
223 224
ppr_debug (TyVar {})                           = ptext (sLit "tv")
ppr_debug (TcTyVar {tc_tv_details = d})        = pprTcTyVarDetails d
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
225
ppr_debug (Id { idScope = s, id_details = d }) = ppr_id_scope s <> pprIdDetails d
226 227 228 229 230

ppr_id_scope :: IdScope -> SDoc
ppr_id_scope GlobalId              = ptext (sLit "gid")
ppr_id_scope (LocalId Exported)    = ptext (sLit "lidx")
ppr_id_scope (LocalId NotExported) = ptext (sLit "lid")
231

232
instance NamedThing Var where
233 234
  getName = varName

235
instance Uniquable Var where
236 237
  getUnique = varUnique

238
instance Eq Var where
239 240
    a == b = realUnique a ==# realUnique b

241
instance Ord Var where
242 243 244 245 246
    a <= b = realUnique a <=# realUnique b
    a <	 b = realUnique a <#  realUnique b
    a >= b = realUnique a >=# realUnique b
    a >	 b = realUnique a >#  realUnique b
    a `compare` b = varUnique a `compare` varUnique b
247 248 249 250 251 252

instance Data Var where
  -- don't traverse?
  toConstr _   = abstractConstr "Var"
  gunfold _ _  = error "gunfold"
  dataTypeOf _ = mkNoRepType "Var"
253 254 255 256
\end{code}


\begin{code}
257
varUnique :: Var -> Unique
258
varUnique var = mkUniqueGrimily (iBox (realUnique var))
259 260

setVarUnique :: Var -> Unique -> Var
261
setVarUnique var uniq 
262
  = var { realUnique = getKeyFastInt uniq, 
263
	  varName = setNameUnique (varName var) uniq }
264

265
setVarName :: Var -> Name -> Var
266
setVarName var new_name
267
  = var { realUnique = getKeyFastInt (getUnique new_name), 
268
   	  varName = new_name }
269 270 271

setVarType :: Id -> Type -> Id
setVarType id ty = id { varType = ty }
272 273 274 275 276
\end{code}


%************************************************************************
%*									*
dreixel's avatar
dreixel committed
277
\subsection{Type and kind variables}
278 279 280 281
%*									*
%************************************************************************

\begin{code}
twanvl's avatar
twanvl committed
282
tyVarName :: TyVar -> Name
283
tyVarName = varName
twanvl's avatar
twanvl committed
284 285

tyVarKind :: TyVar -> Kind
286
tyVarKind = varType
287

twanvl's avatar
twanvl committed
288
setTyVarUnique :: TyVar -> Unique -> TyVar
289
setTyVarUnique = setVarUnique
twanvl's avatar
twanvl committed
290 291

setTyVarName :: TyVar -> Name -> TyVar
292
setTyVarName   = setVarName
293 294

setTyVarKind :: TyVar -> Kind -> TyVar
295
setTyVarKind tv k = tv {varType = k}
dreixel's avatar
dreixel committed
296 297 298 299 300 301 302 303

updateTyVarKind :: (Kind -> Kind) -> TyVar -> TyVar
updateTyVarKind update tv = tv {varType = update (tyVarKind tv)}

updateTyVarKindM :: (Monad m) => (Kind -> m Kind) -> TyVar -> m TyVar
updateTyVarKindM update tv
  = do { k' <- update (tyVarKind tv)
       ; return $ tv {varType = k'} }
304 305 306
\end{code}

\begin{code}
307
mkTyVar :: Name -> Kind -> TyVar
308
mkTyVar name kind = TyVar { varName    = name
309
			  , realUnique = getKeyFastInt (nameUnique name)
310
			  , varType  = kind
311
			}
312

313 314
mkTcTyVar :: Name -> Kind -> TcTyVarDetails -> TyVar
mkTcTyVar name kind details
315
  = -- NB: 'kind' may be a coercion kind; cf, 'TcMType.newMetaCoVar'
316
    TcTyVar {	varName    = name,
317
		realUnique = getKeyFastInt (nameUnique name),
318
		varType  = kind,
319
		tc_tv_details = details
320
	}
321 322 323 324

tcTyVarDetails :: TyVar -> TcTyVarDetails
tcTyVarDetails (TcTyVar { tc_tv_details = details }) = details
tcTyVarDetails var = pprPanic "tcTyVarDetails" (ppr var)
325 326 327

setTcTyVarDetails :: TyVar -> TcTyVarDetails -> TyVar
setTcTyVarDetails tv details = tv { tc_tv_details = details }
dreixel's avatar
dreixel committed
328 329 330

mkKindVar :: Name -> SuperKind -> KindVar
-- mkKindVar take a SuperKind as argument because we don't have access
331
-- to superKind here.
dreixel's avatar
dreixel committed
332 333 334 335 336
mkKindVar name kind = TyVar
  { varName    = name
  , realUnique = getKeyFastInt (nameUnique name)
  , varType    = kind }

337 338 339 340
\end{code}

%************************************************************************
%*									*
341
\subsection{Ids}
342 343 344 345
%*									*
%************************************************************************

\begin{code}
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
346 347 348 349 350 351 352 353
idInfo :: Id -> IdInfo
idInfo (Id { id_info = info }) = info
idInfo other 	       	       = pprPanic "idInfo" (ppr other)

idDetails :: Id -> IdDetails
idDetails (Id { id_details = details }) = details
idDetails other 	       	        = pprPanic "idDetails" (ppr other)

354
-- The next three have a 'Var' suffix even though they always build
Gabor Greif's avatar
typos  
Gabor Greif committed
355
-- Ids, because Id.lhs uses 'mkGlobalId' etc with different types
356 357 358 359 360 361 362 363
mkGlobalVar :: IdDetails -> Name -> Type -> IdInfo -> Id
mkGlobalVar details name ty info
  = mk_id name ty GlobalId details info

mkLocalVar :: IdDetails -> Name -> Type -> IdInfo -> Id
mkLocalVar details name ty info
  = mk_id name ty (LocalId NotExported) details  info

364 365 366 367
mkCoVar :: Name -> Type -> CoVar
-- Coercion variables have no IdInfo
mkCoVar name ty = mk_id name ty (LocalId NotExported) coVarDetails vanillaIdInfo

368 369 370 371 372 373 374 375 376 377 378
-- | Exported 'Var's will not be removed as dead code
mkExportedLocalVar :: IdDetails -> Name -> Type -> IdInfo -> Id
mkExportedLocalVar details name ty info 
  = mk_id name ty (LocalId Exported) details info

mk_id :: Name -> Type -> IdScope -> IdDetails -> IdInfo -> Id
mk_id name ty scope details info
  = Id { varName    = name, 
	 realUnique = getKeyFastInt (nameUnique name),
	 varType    = ty,	
	 idScope    = scope,
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
379 380
	 id_details = details,
	 id_info    = info }
381 382 383

-------------------
lazySetIdInfo :: Id -> IdInfo -> Var
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
384
lazySetIdInfo id info = id { id_info = info }
385 386

setIdDetails :: Id -> IdDetails -> Id
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
387
setIdDetails id details = id { id_details = details }
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403

globaliseId :: Id -> Id
-- ^ If it's a local, make it global
globaliseId id = id { idScope = GlobalId }

setIdExported :: Id -> Id
-- ^ Exports the given local 'Id'. Can also be called on global 'Id's, such as data constructors
-- and class operations, which are born as global 'Id's and automatically exported
setIdExported id@(Id { idScope = LocalId {} }) = id { idScope = LocalId Exported }
setIdExported id@(Id { idScope = GlobalId })   = id
setIdExported tv	  	    	       = pprPanic "setIdExported" (ppr tv)

setIdNotExported :: Id -> Id
-- ^ We can only do this to LocalIds
setIdNotExported id = ASSERT( isLocalId id ) 
                      id { idScope = LocalId NotExported }
404 405
\end{code}

406 407
%************************************************************************
%*									*
408
\subsection{Predicates over variables}
409 410 411
%*									*
%************************************************************************

412
\begin{code}
413 414 415 416 417 418 419
isTyVar :: Var -> Bool
isTyVar = isTKVar     -- Historical

isTKVar :: Var -> Bool  -- True of both type and kind variables
isTKVar (TyVar {})   = True
isTKVar (TcTyVar {}) = True
isTKVar _            = False
420

421
isTcTyVar :: Var -> Bool
422
isTcTyVar (TcTyVar {}) = True
twanvl's avatar
twanvl committed
423
isTcTyVar _            = False
424

425 426 427
isId :: Var -> Bool
isId (Id {}) = True
isId _       = False
428

429 430 431
isLocalId :: Var -> Bool
isLocalId (Id { idScope = LocalId _ }) = True
isLocalId _                            = False
432

433
-- | 'isLocalVar' returns @True@ for type variables as well as local 'Id's
434 435
-- These are the variables that we need to pay attention to when finding free
-- variables, or doing dependency analysis.
436
isLocalVar :: Var -> Bool
437 438 439 440 441
isLocalVar v = not (isGlobalId v)

isGlobalId :: Var -> Bool
isGlobalId (Id { idScope = GlobalId }) = True
isGlobalId _                           = False
442

443
-- | 'mustHaveLocalBinding' returns @True@ of 'Id's and 'TyVar's
444
-- that must have a binding in this module.  The converse
445
-- is not quite right: there are some global 'Id's that must have
446 447
-- bindings, such as record selectors.  But that doesn't matter,
-- because it's only used for assertions
448
mustHaveLocalBinding	    :: Var -> Bool
449 450
mustHaveLocalBinding var = isLocalVar var

451
-- | 'isExportedIdVar' means \"don't throw this away\"
452 453 454 455
isExportedId :: Var -> Bool
isExportedId (Id { idScope = GlobalId })        = True
isExportedId (Id { idScope = LocalId Exported}) = True
isExportedId _ = False
456
\end{code}