WIP, memoize lazy evaluation wrappers

This commit is contained in:
Sven Slootweg 2022-02-02 14:16:02 +01:00
parent 7f3eda388c
commit 4cb239c6a0
6 changed files with 36 additions and 20 deletions

1
.gitignore vendored
View file

@ -1,2 +1,3 @@
node_modules
private-notes.txt
old

38
run.js
View file

@ -4,6 +4,7 @@ const fs = require("fs");
const assert = require("assert");
const transpile = require("./src/transpile");
const measureTime = require("./src/astformer/util/measure-time");
assert(process.argv[2] != null);
@ -12,13 +13,34 @@ const nixFile = fs.readFileSync(nixFilePath, "utf8");
let transpiled = transpile(nixFile);
const api = {
builtins: {},
$$jsNix$memoize: function (func) {
let isCalled = false;
let storedResult;
return function (arg) {
if (isCalled === false) {
storedResult = func(arg);
isCalled = true;
}
return storedResult;
};
}
};
// TODO: Switch to Node `vm` API instead, and check whether there's a polyfill for it for non-Node environments, build a custom one if not
const context = { module: {}, exports: {} };
context.module.exports = exports;
new Function("module", transpiled)(context.module);
console.log("-- EVALUATION RESULT:");
console.log(eval(transpiled)({
builtins: {},
$$jsNix$extend: function (base, props) {
let newObject = Object.create(base);
Object.assign(newObject, props);
return newObject;
}
}));
// Warm-up for hot VM performance testing
// for (let i = 0; i < 10000; i++) {
// context.module.exports(api);
// }
console.log(measureTime(() => context.module.exports(api)));

View file

@ -1,5 +1,7 @@
"use strict";
// FIXME: Make separate package, measure-function-call or so
function hrtimeToNanoseconds(time) {
// If the numbers here become big enough to cause loss of precision, we probably have bigger issues than numeric precision...
return (time[0] * 1e9) + time[1];

View file

@ -13,7 +13,7 @@ let tmplCallLazy = template(`
`);
let tmplLazyWrapper = template(`(
() => %%expression%%
$$jsNix$memoize(() => %%expression%%)
)`);
let tmplLazyWrapperRecursive = template(`(

View file

@ -34,7 +34,7 @@ let tmplFunctionCall = template(`
// NOTE: Duplicated from `attribute-sets` for now
let tmplLazyWrapper = template(`(
() => %%expression%%
$$jsNix$memoize(() => %%expression%%)
)`);
function functionDefinition({ universal, formals, body }) {

View file

@ -17,20 +17,11 @@ const printAst = require("../print-ast");
// FIXME: Make strict mode! Otherwise objects will inherit from `global`
let tmplModule = template(`
module.exports = function({ builtins, $$jsNix$extend }) {
module.exports = function({ builtins, $$jsNix$memoize }) {
return %%contents%%;
};
`);
let tmplLetIn = template(`
(() => {
%%letBindings%%
return %%expression%%;
})()
`);
let tmplObjectDynamic = template(`
(() => {
let $$nixJS_object = {};