I have a compiler for a programming language that targets JavaScript. That language needs some global functions such as: alloc
, memcpy
, write
and so on. My question is: where should I position those functions? I have pretty much 2 options:
1: inside a self-contained object, runtime
. Compiled functions would need to receive that object:
function example_of_compiled_function(runtime, arg0, arg1){
var arrayPtr = runtime.alloc(arg0);
for (var i=0; i<arg0; ++i)
runtime.write(arrayPtr+i, arg1);
return arrayPtr;
};
2: globally. Compiled functions wouldn’t need to receive an additional object:
function example_of_compiled_function(arg0, arg1){
var arrayPtr = alloc(arg0);
for (var i=0; i<arg0; ++i)
write(arrayPtr+i, arg1);
return arrayPtr;
}
Both ways have problems. For (1), there is a considerable slowdown for accessing methods inside an object, and using compiled functions becomes more complicated since users have to manually create that object and feed it to them. For (2), it is faster and simpler, but might pollute the global namespace. Is there a satisfactory solution for this?
6
How about putting runtime
in a closure?
function mycode(runtime) {
function example_of_compiled_function(arg0, arg1){
var arrayPtr = runtime.alloc(arg0);
for (var i=0; i<arg0; ++i)
runtime.write(arrayPtr+i, arg1);
return arrayPtr;
}
};
Simply pass in runtime to this function (or any further generated functions), and it’ll be accessible to all code in the closure without explicitly passing it everywhere.
7