Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,15 @@ initializes its WebAssembly module on first use.
```ts
import { createEvaluator } from "nix-eval";

const evaluator = await createEvaluator();
const evaluator = await createEvaluator({ strict: true });
const result = await evaluator.eval("6 * 7");

console.log(result.output); // "42"
```

Pass `{ strict: true }` to force the final value before rendering. This resolves
lazy values in attribute sets and lists instead of displaying `<CODE>`.

Pass a location as the second argument to associate diagnostics with a source
name. It defaults to `"<string>"`.

Expand Down
2 changes: 1 addition & 1 deletion demo/src/evaluator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export interface EvalErrorEvent {
export type NixEval = (source: string) => Promise<void>;

export async function createNixEvaluator(el: EventTarget): Promise<NixEval> {
const ev = await createEvaluator();
const ev = await createEvaluator({ strict: true });

return async (source: string): Promise<void> => {
const start = performance.now();
Expand Down
7 changes: 7 additions & 0 deletions demo/vite.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { defineConfig } from "vite";

export default defineConfig({
optimizeDeps: {
exclude: ["nix-eval"],
},
});
33 changes: 26 additions & 7 deletions rust/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ struct Output {
ast: String,
}

fn eval(source: &str, location: &str) -> Output {
fn eval(source: &str, location: &str, strict: bool) -> Output {
let mut output = Output::default();
let mut builder = tvix_eval::Evaluation::builder_pure();
let source_map = builder.source_map().clone();
Expand All @@ -26,7 +26,14 @@ fn eval(source: &str, location: &str) -> Output {
let mut runtime_observer = TracingObserver::new(&mut output.trace);
builder.set_runtime_observer(Some(&mut runtime_observer));

builder.build().evaluate(source, Some(location.into()))
builder
.mode(if strict {
tvix_eval::EvalMode::Strict
} else {
tvix_eval::EvalMode::Lazy
})
.build()
.evaluate(source, Some(location.into()))
};

if let Some(expr) = &result.expr {
Expand Down Expand Up @@ -55,8 +62,8 @@ fn eval(source: &str, location: &str) -> Output {
}

#[wasm_bindgen(js_name = evaluate)]
pub fn eval_wasm(source: &str, location: &str) -> String {
let output = eval(source, location);
pub fn eval_wasm(source: &str, location: &str, strict: bool) -> String {
let output = eval(source, location, strict);
serde_json::json!({
"errors": output.errors,
"warnings": output.warnings,
Expand All @@ -74,7 +81,7 @@ mod tests {

#[test]
fn evaluates_a_pure_expression() {
let result = eval("6 * 7", "/input.nix");
let result = eval("6 * 7", "/input.nix", false);

assert_eq!(result.output, "42");
assert!(result.warnings.is_empty());
Expand All @@ -86,7 +93,7 @@ mod tests {

#[test]
fn returns_parse_errors_as_data() {
let result = eval("let", "/input.nix");
let result = eval("let", "/input.nix", false);

assert!(result.output.is_empty());
assert!(result.warnings.is_empty());
Expand All @@ -97,8 +104,20 @@ mod tests {
#[test]
fn serializes_output_for_wasm() {
let output: serde_json::Value =
serde_json::from_str(&eval_wasm("6 * 7", "/input.nix")).unwrap();
serde_json::from_str(&eval_wasm("6 * 7", "/input.nix", false)).unwrap();

assert_eq!(output["output"], "42");
}

#[test]
fn strict_evaluation_forces_nested_values() {
let source = "{ value = builtins.concatStringsSep \"\" [ \"hello\" \" world\" ]; }";

assert!(eval(source, "/input.nix", false).output.contains("<CODE>"));
let strict_output = eval(source, "/input.nix", true).output;
assert!(
strict_output.contains("hello world"),
"unexpected strict output: {strict_output}"
);
}
}
4 changes: 4 additions & 0 deletions src/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ export type Output = {
ast: string;
};

export type EvaluatorOptions = {
strict?: boolean;
};

export interface Evaluator {
eval(source: string, location?: string): Promise<Output>;
}
Expand Down
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
export type { Evaluator, Output } from "#src/common.js";
export type { Evaluator, EvaluatorOptions, Output } from "#src/common.js";
export { createEvaluator } from "#src/sync.js";
12 changes: 11 additions & 1 deletion src/sync.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { describe, expect, it, vi } from "vitest";

vi.mock("#wasm/nix_eval.js", () => ({
default: vi.fn().mockResolvedValue(undefined),
evaluate: vi.fn((source: string, _location: string) =>
evaluate: vi.fn((source: string, _location: string, _strict: boolean) =>
JSON.stringify({
errors: "",
warnings: "",
Expand Down Expand Up @@ -40,4 +40,14 @@ describe("createEvaluator", () => {
expect(result.output).toBe("42");
expect(result.errors).toBe("");
});

it("passes the strict option to the WASM binding", async () => {
const mod = await import("#wasm/nix_eval.js");
const evaluate = mod.evaluate as ReturnType<typeof vi.fn>;
const evaluator = await createEvaluator({ strict: true });

await evaluator.eval("6 * 7");

expect(evaluate).toHaveBeenLastCalledWith("6 * 7", "/input.nix", true);
});
});
6 changes: 3 additions & 3 deletions src/sync.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
import * as wasm from "#wasm/nix_eval.js";
import { parseOutput } from "#src/common.js";
import type { Evaluator } from "#src/common.js";
import type { Evaluator, EvaluatorOptions } from "#src/common.js";

let initialized: Promise<void> | undefined;

export async function createEvaluator(): Promise<Evaluator> {
export async function createEvaluator({ strict = false }: EvaluatorOptions = {}): Promise<Evaluator> {
initialized ??= Promise.resolve(
typeof wasm.default === "function" ? wasm.default() : undefined,
).then(() => undefined);
await initialized;

return {
async eval(source, location = "/input.nix") {
return parseOutput(wasm.evaluate(source, location));
return parseOutput(wasm.evaluate(source, location, strict));
},
};
}
Loading