Version française
Home     About     Download     Resources     Contact us    
Browse thread
Re: subtyping and inheritance
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: David Monniaux <monniaux@c...>
Subject: Musings on Obj.magic (Was: subtyping and inheritance)
Here are some slightly off-thread remarks on Obj.magic and why it can be
good:

On Mon, 25 Jan 1999, Markus Mottl wrote:

> Nice example code! I don't know what "Obj.magic" does internally,
> but I believe it can do real black (= unintended) magic, too.

Obj.magic is defined as the identity from any type to any type. Its
semantics are highly dependent on the memory layout of OCaml, and you can
do nasty things like:
# (((Obj.magic A),(Obj.magic B)) : int*int);;
- : int * int = 0, 1

This depends on the fact that in an enumerated datatype, 0-ary
constructors are encoded exactly as integers are encoded. Thus the first
constructor is seen as 0, the second as 1...

Now there are some legitimate (ie non implementation-dependent) uses of
Obj.magic. First, its semantics are well-defined when there exists a proof
of well-typedness in a stronger type system than OCaml's. For instance,
programs exported from Coq may need to be manually patched by inserting
Obj.magic at some places. This has to do with the fact that Coq's typing
is impredicative while OCaml's is not.

Second, it's needed for the toplevel, for printing out values. The type
safety of the procedure that prints the value of the expression the user
has just input relies on the overall safety of the OCaml type checker and
the subject reduction property of OCaml. This means that if the
typechecker says "hey, it's an int*int" you can trust it and cast the
return value into a int*int using Obj.magic. Of course, you can see that
as well-typedness in a proof system that is powerful enough to certify
OCaml's typechecker.

Regards, D. Monniaux