1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
/// @file WASM export surface for the gonix evaluator.
/// These are the C entry points that the Go host (wazero) calls into.
/// Handles are indices into a GC-rooted handle table.

#include "lix/libexpr/eval.hh"
#include "lix/libexpr/value.hh"
#include "lix/libexpr/wasm-codec.hh"
#include "lix/libstore/globals.hh"
#include "lix/libstore/store-api.hh"
#include "lix/libstore/wasm-store.hh"
#include "lix/libutil/async.hh"
#include "lix/libutil/box_ptr.hh"
#include "lix/libutil/error.hh"
#include "lix/libutil/logging.hh"
#include "lix/libutil/config.hh"

#include <cstdint>
#include <cstring>
#include <string>
#include <vector>
#include <memory>

#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#define WASM_EXPORT EMSCRIPTEN_KEEPALIVE
#else
#define WASM_EXPORT
#endif

namespace {

// ---------------------------------------------------------------------------
// Global evaluator state
// ---------------------------------------------------------------------------

std::unique_ptr<nix::AsyncIoRoot> g_aio;
std::unique_ptr<nix::Evaluator> g_evaluator;
std::optional<nix::box_ptr<nix::EvalState>> g_state;
std::string g_last_error;

// Handle table — keeps Values alive across calls from Go.
// Index 0 is reserved (invalid handle).
std::vector<nix::RootValue> g_handles;

int32_t newHandle(nix::Value v)
{
    g_handles.push_back(nix::allocRootValue(v));
    return static_cast<int32_t>(g_handles.size() - 1);
}

nix::Value * getHandle(int32_t h)
{
    if (h <= 0 || static_cast<size_t>(h) >= g_handles.size()) {
        return nullptr;
    }
    return g_handles[h].get();
}

// Write a string into a caller-provided buffer, null-terminate, return length.
int32_t writeStr(const std::string & s, char * buf, int32_t max_len)
{
    int32_t n = std::min(static_cast<int32_t>(s.size()), max_len - 1);
    memcpy(buf, s.data(), n);
    buf[n] = '\0';
    return n;
}

// Record an error for later retrieval by nix_last_error().
#define CATCH_INTO_LAST_ERROR(ret)      \
    catch (nix::Error & e)              \
    {                                   \
        g_last_error = e.msg();         \
        return ret;                     \
    }                                   \
    catch (std::exception & e)          \
    {                                   \
        g_last_error = e.what();        \
        return ret;                     \
    }                                   \
    catch (...)                         \
    {                                   \
        g_last_error = "unknown error"; \
        return ret;                     \
    }

} // anonymous namespace

extern "C" {

// ---------------------------------------------------------------------------
// nix_init: initialise the evaluator with the store directory.
// Called once by Go before any eval calls.
// ---------------------------------------------------------------------------
WASM_EXPORT
void nix_init(const char * store_dir, int32_t /*len*/)
{
    try {
        nix::initLibStore();
        nix::initLibExpr();

        // Build a WasmStore — all store I/O goes through the Go host.
        nix::WasmStoreConfig cfg(nix::StringMap{});
        auto store = nix::make_ref<nix::WasmStore>("wasm", "wasm://", std::move(cfg));

        // Reserve handle 0 as invalid.
        g_handles.emplace_back();

        // Set up the async I/O root (KJ shim — no real event loop in WASM).
        g_aio = std::make_unique<nix::AsyncIoRoot>();

        // Create the evaluator.
        nix::SearchPath searchPath;
        g_evaluator = std::make_unique<nix::Evaluator>(*g_aio, searchPath, nix::ref<nix::Store>(store));

        // Create an EvalState via the Evaluator's begin() factory.
        g_state.emplace(g_evaluator->begin(*g_aio));
    } catch (...) {
        g_last_error = "nix_init failed";
    }
}

// ---------------------------------------------------------------------------
// nix_eval_expr: parse and evaluate a Nix expression string.
// Returns a handle, or -1 on error.
// ---------------------------------------------------------------------------
WASM_EXPORT
int32_t nix_eval_expr(const char * expr, int32_t /*len*/)
try {
    if (!g_state || !g_evaluator) {
        g_last_error = "not initialised";
        return -1;
    }
    nix::Expr & e = g_evaluator->parseExprFromString(std::string(expr), nix::CanonPath::root);
    nix::Value v = (*g_state)->eval(e);
    return newHandle(v);
}
CATCH_INTO_LAST_ERROR(-1)

// ---------------------------------------------------------------------------
// nix_force_value: force a value to WHNF.
// Returns the same handle, or -1 on error.
// ---------------------------------------------------------------------------
WASM_EXPORT
int32_t nix_force_value(int32_t handle)
try {
    if (!g_state) {
        g_last_error = "not initialised";
        return -1;
    }
    nix::Value * v = getHandle(handle);
    if (!v) {
        g_last_error = "invalid handle";
        return -1;
    }
    (*g_state)->forceValue(*v, nix::noPos);
    return handle;
}
CATCH_INTO_LAST_ERROR(-1)

// ---------------------------------------------------------------------------
// nix_value_type: return the ValueType of a forced value as an int.
// ---------------------------------------------------------------------------
WASM_EXPORT
int32_t nix_value_type(int32_t handle)
{
    nix::Value * v = getHandle(handle);
    if (!v) {
        return -1;
    }
    return static_cast<int32_t>(v->type());
}

// ---------------------------------------------------------------------------
// nix_value_ptr: return the WASM linear-memory address of the identity of a
// value for cycle/repeat detection — mirroring cppnix print.cc's ValuesSeen.
//
// For attrs values, returns the Bindings* pointer: two Value objects wrapping
// the same underlying attribute set share a Bindings* and will return the
// same address.  This is the key to detecting the derivation `all` cycle,
// where `all[0]` is a different Value* than the top-level output attrset but
// both share the same Bindings*.
//
// For list values, returns the list-items pointer.
//
// For all other types (or invalid handles), returns 0 (no cycle tracking).
// ---------------------------------------------------------------------------
WASM_EXPORT
uint32_t nix_value_ptr(int32_t handle)
{
    nix::Value * v = getHandle(handle);
    if (!v) {
        return 0;
    }
    switch (v->type()) {
    case nix::nAttrs:
        if (!v->attrs()) {
            return 0;
        }
        return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(v->attrs()));
    case nix::nList:
        // Use the raw list-element array pointer (unique per list allocation).
        return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(v->listElems()));
    case nix::nThunk:
    case nix::nInt:
    case nix::nFloat:
    case nix::nBool:
    case nix::nString:
    case nix::nPath:
    case nix::nNull:
    case nix::nFunction:
    case nix::nExternal:
        return 0;
    }
}

// ---------------------------------------------------------------------------
// nix_get_string / nix_get_int / nix_get_float / nix_get_bool
// ---------------------------------------------------------------------------
WASM_EXPORT
int32_t nix_get_string(int32_t handle, char * buf, int32_t max_len)
try {
    nix::Value * v = getHandle(handle);
    if (!v) {
        g_last_error = "invalid handle";
        return -1;
    }
    return writeStr(std::string(v->str()), buf, max_len);
}
CATCH_INTO_LAST_ERROR(-1)

WASM_EXPORT
int64_t nix_get_int(int32_t handle)
{
    nix::Value * v = getHandle(handle);
    if (!v) {
        return 0;
    }
    return v->integer().value;
}

WASM_EXPORT
double nix_get_float(int32_t handle)
{
    nix::Value * v = getHandle(handle);
    if (!v) {
        return 0.0;
    }
    return v->fpoint();
}

WASM_EXPORT
int32_t nix_get_bool(int32_t handle)
{
    nix::Value * v = getHandle(handle);
    if (!v) {
        return 0;
    }
    return v->boolean() ? 1 : 0;
}

// ---------------------------------------------------------------------------
// nix_get_attr: look up an attribute by name, return a new handle.
// ---------------------------------------------------------------------------
WASM_EXPORT
int32_t nix_get_attr(int32_t handle, const char * name, int32_t /*name_len*/)
try {
    if (!g_state) {
        g_last_error = "not initialised";
        return -1;
    }
    nix::Value * v = getHandle(handle);
    if (!v) {
        g_last_error = "invalid handle";
        return -1;
    }
    (*g_state)->forceAttrs(*v, nix::noPos, "while getting attribute");
    auto sym = (*g_state)->ctx.symbols.create(name);
    auto * attr = v->attrs()->get(sym);
    if (!attr) {
        g_last_error = std::string("missing attribute: ") + name;
        return -1;
    }
    return newHandle(attr->value);
}
CATCH_INTO_LAST_ERROR(-1)

// ---------------------------------------------------------------------------
// nix_get_attr_names: write newline-separated attribute names into buf.
// ---------------------------------------------------------------------------
WASM_EXPORT
int32_t nix_get_attr_names(int32_t handle, char * buf, int32_t max_len)
try {
    if (!g_state) {
        g_last_error = "not initialised";
        return -1;
    }
    nix::Value * v = getHandle(handle);
    if (!v) {
        g_last_error = "invalid handle";
        return -1;
    }
    (*g_state)->forceAttrs(*v, nix::noPos, "while listing attributes");
    std::string result;
    for (auto & attr : *v->attrs()) {
        result += (*g_state)->ctx.symbols[attr.name];
        result += '\n';
    }
    return writeStr(result, buf, max_len);
}
CATCH_INTO_LAST_ERROR(-1)

// ---------------------------------------------------------------------------
// nix_list_length / nix_list_get
// ---------------------------------------------------------------------------
WASM_EXPORT
int32_t nix_list_length(int32_t handle)
try {
    if (!g_state) {
        g_last_error = "not initialised";
        return -1;
    }
    nix::Value * v = getHandle(handle);
    if (!v) {
        g_last_error = "invalid handle";
        return -1;
    }
    (*g_state)->forceList(*v, nix::noPos, "while getting list length");
    return static_cast<int32_t>(v->listSize());
}
CATCH_INTO_LAST_ERROR(-1)

WASM_EXPORT
int32_t nix_list_get(int32_t handle, int32_t idx)
try {
    if (!g_state) {
        g_last_error = "not initialised";
        return -1;
    }
    nix::Value * v = getHandle(handle);
    if (!v) {
        g_last_error = "invalid handle";
        return -1;
    }
    (*g_state)->forceList(*v, nix::noPos, "while indexing list");
    if (idx < 0 || static_cast<size_t>(idx) >= v->listSize()) {
        g_last_error = "list index out of range";
        return -1;
    }
    return newHandle(v->listElems()[idx]);
}
CATCH_INTO_LAST_ERROR(-1)

// ---------------------------------------------------------------------------
// nix_builtin_names: return the ordered list of builtin names (in the same
// order as the C++ base environment) as a codec-encoded list of scalars.
// This lets the Go evaluator construct a builtins env with matching displacements.
// ---------------------------------------------------------------------------
WASM_EXPORT
int32_t nix_builtin_names(char * resp, int32_t resp_max)
try {
    if (!g_evaluator) {
        g_last_error = "not initialised";
        return -1;
    }

    // Walk the static env to collect names sorted by displacement value.
    const auto & se = *g_evaluator->builtins.staticEnv;
    std::vector<std::pair<uint32_t, std::string>> byDispl;
    for (auto it = se.vars.cbegin(); it != se.vars.cend(); ++it) {
        byDispl.push_back({static_cast<uint32_t>(it->second), std::string(g_evaluator->symbols[it->first])});
    }
    std::sort(byDispl.begin(), byDispl.end());

    // Encode as a codec list of scalars: "[" *( len ":" name ";" ) "]"
    std::string items;
    for (const auto & [displ, name] : byDispl) {
        std::string item = nix::wasm_codec::encScalar(name);
        items += std::to_string(item.size()) + ":" + item + ";";
    }
    std::string inner = "[" + items + "]";
    std::string msg = nix::wasm_codec::message(inner);

    if (static_cast<int32_t>(msg.size()) > resp_max) {
        g_last_error = "builtin names too large for buffer";
        return -1;
    }
    memcpy(resp, msg.data(), msg.size());
    return static_cast<int32_t>(msg.size());
}
CATCH_INTO_LAST_ERROR(-1)

// ---------------------------------------------------------------------------
// nix_parse_expr: parse a Nix expression and return the post-finalize AST
// in codec wire format.  Returns bytes written, or negative on error.
//
// base_path is an absolute directory path (e.g. "/testfs/sub/") used to
// resolve relative path literals like ./foo.nix.  Pass "/" for the legacy
// behaviour where ./foo → /foo in the AST.
//
// file_path is the absolute path of the file being parsed (e.g. "/testfs/sub/foo.nix").
// It is used only for position information (file field in {file, line, column} attrs).
// Pass an empty string or "/" if unknown.
// ---------------------------------------------------------------------------
WASM_EXPORT
int32_t nix_parse_expr(
    const char * expr,
    int32_t expr_len,
    const char * base_path,
    int32_t base_path_len,
    const char * file_path,
    int32_t file_path_len,
    char * resp,
    int32_t resp_max
)
try {
    if (!g_state || !g_evaluator) {
        g_last_error = "not initialised";
        return -1;
    }

    std::string src(expr, static_cast<size_t>(expr_len));
    std::string base(base_path, static_cast<size_t>(base_path_len));
    std::string filePath(file_path, static_cast<size_t>(file_path_len));
    nix::CanonPath basePath(base);
    nix::Expr & e = g_evaluator->parseExprFromString(src, nix::SourcePath(basePath));

    std::string encoded =
        nix::wasm_codec::encodeExpr(e, g_evaluator->symbols, g_evaluator->positions, filePath);
    std::string msg = nix::wasm_codec::message(encoded);

    if (static_cast<int32_t>(msg.size()) > resp_max) {
        g_last_error = "parse result too large for buffer";
        return -1;
    }
    memcpy(resp, msg.data(), msg.size());
    return static_cast<int32_t>(msg.size());
}
CATCH_INTO_LAST_ERROR(-1)

// ---------------------------------------------------------------------------
// nix_free_value: release a handle.
// ---------------------------------------------------------------------------
WASM_EXPORT
void nix_free_value(int32_t handle)
{
    if (handle > 0 && static_cast<size_t>(handle) < g_handles.size()) {
        g_handles[handle].reset();
    }
}

// ---------------------------------------------------------------------------
// nix_last_error: retrieve the last error message.
// ---------------------------------------------------------------------------
WASM_EXPORT
int32_t nix_last_error(char * buf, int32_t max_len)
{
    return writeStr(g_last_error, buf, max_len);
}

} // extern "C"