Version française
Home     About     Download     Resources     Contact us    
Browse thread
Is this use of Object.magic safe?
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Stephan Houben <stephan@p...>
Subject: Is this use of Object.magic safe?
Hello list,

I am currently writing a small interpreted language for my app.
The language is dynamically typed, which means that a value is represented
somewhat like this:

type value =
  True | False
| Int of int
| String of string
| Array of value array

Now a well-known optimisation for such an interpreter is to make small
int's not heap-allocated objects but to represent them directly in the pointer.
In fact, O'Caml itself already does this. Moreover, it allows access to
this info via the Obj module.

My idea is to make "value" an abstract type, and have a separate type
allocated_value, which doesn't contain the Int constructor:

type value
 
type allocated_value =
  True | False
| String of string
| Array of value

Then I can use Obj.magic to make constructor and destructor functions
for value:

let value_of_int (i : int) : value =
  Obj.magic i

let value_of_allocated_value (av :allocated_value) : value=
  Obj.magic av
 
let unwrap (int_func : int -> 'a) 
                (aval_func : allocated_value -> 'a)
                (v : value) : 'a =
  if Obj.is_int (Obj.repr v)
  then int_func (Obj.magic v)
  else aval_func (Obj.magic v) 

I have three questions:
1. Is this safe w.r.t. the garbage collector? Or am I going to confuse the GC?
2. Can I safely marshall values?
3. Is it worth the trouble? Perhaps O'Caml already does something smart
   when a constructor of the form `Int of int' is encountered?

Stephan
-- 
ir. Stephan H.M.J. Houben
tel. +31-40-2474358 / +31-40-2743497
e-mail: stephanh@win.tue.nl