Search code examples
recursionocamlbytecodeprimitive

Recursive definitions of values and bytecode calls to primitives


I'm trying to generate OCaml bytecode containing C_CALLs to these primitives:

caml_alloc_dummy
caml_alloc_dummy_function
caml_update_dummy
caml_alloc_dummy_float

which are all related to recursive definition of values (see <ocamlsource>/bytecomp/bytegen.ml)

To generate calls to the first three, this code is enough:

let rec myval = (f, 1, myval)
and f _ = match myval with (_, x, _) -> x;;

but I cannot imagine a piece of code for the last one, which should be specifically related to recursive definitions of float arrays.


Solution

  • This seems to do it (testing with 4.03.0):

    type t = { x : float }
    
    let rec r = { x = 0.1 +. 0.2 }
    

    Yes, the rec is useless, but the bytecode compiler isn't smart enough to see that. Note that records in which every field is a float are represented specially, with the floats unboxed.

    The generated bytecode:

    const 1
    ccall caml_alloc_dummy_float, 1
    push
    const 0.2
    push
    const 0.1
    ccall caml_add_float, 2
    makefloatblock 1
    push
    acc 1
    ccall caml_update_dummy, 2
    event "_none_" -1--1
    acc 0
    makeblock 1, 0
    pop 1
    setglobal Test!