Version française
Home     About     Download     Resources     Contact us    

This site is updated infrequently. For up-to-date information, please visit the new OCaml website at

Browse thread
High-performance bytecode interpreter in OCaml
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Grant Olson <olsongt@v...>
Subject: RE: [Caml-list] High-performance bytecode interpreter in OCaml

> As for CPS, what I meant is implementing each bytecode 
> instruction as a function that takes a continuation (next 
> instruction?).
> 	Thanks, Joel

Once again I made the mistake of following up on google groups! Anyway,
nothing good was on tv so I wrote up a better example.

I think you'd make things too complicated with CPS.  Why not just create a
dispatcher function and opcode instructions that are all tail recursive?
Without knowing the internals, I don't see how it could be that much slower
than CPS and is much easier for us humans to read.  Anyway, here's a trivial


Stupid vm.  It is initailized with an instruction counter of zero
  and has one register that is initially zero.  There are four instructions:

    'i' - increment the register
    'd' - decrement the register
    'p' - print the value of the register
    'r' - reset the instruction counter to zero


type vm = {current_inst:int;register:int;bytecode:string}

let create_vm b =

let inc_inst v =
  {v with current_inst=v.current_inst+1}

let update_reg v i =
  {v with register=v.register+i}

let update_reg_and_inc v i =
  let new_v = update_reg v i in
    inc_inst new_v

let rec dispatch v =
  let opcode=v.bytecode.[v.current_inst] in
      match opcode with
        'i' -> inc v
      | 'd' -> dec v
      | 'p' -> print v
      | 'r' -> reset v
and inc v =
  let new_v = update_reg_and_inc v 1 in
    dispatch new_v
and dec v =
  let new_v = update_reg_and_inc v 1 in
    dispatch new_v
and print v =
  Printf.printf "%i\n" v.register;
  dispatch (inc_inst v)
and reset v =
  dispatch {v with current_inst=0}

let vm_instance = create_vm "piiipdpdddddddpiiiprpididi"    
let _ = dispatch vm_instance