Casting dynamic values
Marcin 'Qrczak' Kowalczyk
qrczak@knm.org.pl
Wed, 28 Nov 2001 14:22:32 +0000 (UTC)
27 Nov 2001 17:31:10 -0700, Alastair David Reid <reid@cs.utah.edu> pisze:
> If GHC is able to inline these functions, construction and
> deconstruction of the pair can probably be eliminated.
cast is compiled to something similar to this:
coerce :: a -> b -- this generates no runtime code
type Typeable a = a -> TypeRep
cast :: Typeable a -> Typeable b -> a -> Maybe b
cast t1 t2 x =
case t1 x of
rep1 -> case t2 (coerce x) of
rep2 -> case eqTypeRep rep1 rep2 of
True -> Just (coerce x)
False -> Nothing
Instances of Typeable should not look at their argument to determine
TypeRep of its type but unfortunately the compiler can't in general
assume that.
> But I don't think GHC can do this because AFAIK, GHC will not reduce
> literal string comparisions at compile time.
Since Oct 1 it tries to. Unfortunately string literals seem to be
floated out to toplevel before there are recognized as literals being
arguments of (==), and the rule doesn't work.
> [This is assuming that GHC's implementation of Typeof still uses
> strings. This may not be true though since there was talk of adding
> direct compiler support to make the implementation of typeof more
> efficient and, more importantly, less prone to programmer error.
It doesn't use strings for comparison but uniquely generated numbers.
But it's not safe either: uniqueness of these numbers relies on TyCon
objects being defined at the toplevel, with {-# NOINLINE #-}, and
I'm not sure if common subexpression elimination doesn't mess this up
(it corrupts similar cases).
Anyway equality on statically known TypeRep is not done at compile
time. I don't know why.
--
__("< Marcin Kowalczyk * qrczak@knm.org.pl http://qrczak.ids.net.pl/
\__/
^^
QRCZAK