Skip to main content

alef_e2e/codegen/
zig.rs

1//! Zig e2e test generator using std.testing.
2//!
3//! Generates `packages/zig/src/<crate>_test.zig` files from JSON fixtures,
4//! driven entirely by `E2eConfig` and `CallConfig`.
5
6use crate::config::E2eConfig;
7use crate::escape::{escape_zig, sanitize_filename};
8use crate::field_access::FieldResolver;
9use crate::fixture::{Assertion, Fixture, FixtureGroup};
10use alef_core::backend::GeneratedFile;
11use alef_core::config::ResolvedCrateConfig;
12use alef_core::hash::{self, CommentStyle};
13use alef_core::template_versions::toolchain;
14use anyhow::Result;
15use heck::{ToShoutySnakeCase, ToSnakeCase};
16use std::collections::HashSet;
17use std::fmt::Write as FmtWrite;
18use std::path::PathBuf;
19
20use super::E2eCodegen;
21use super::client;
22use super::streaming_assertions::{StreamingFieldResolver, is_streaming_virtual_field};
23
24/// Zig e2e code generator.
25pub struct ZigE2eCodegen;
26
27impl E2eCodegen for ZigE2eCodegen {
28    fn generate(
29        &self,
30        groups: &[FixtureGroup],
31        e2e_config: &E2eConfig,
32        config: &ResolvedCrateConfig,
33        _type_defs: &[alef_core::ir::TypeDef],
34    ) -> Result<Vec<GeneratedFile>> {
35        let lang = self.language_name();
36        let output_base = PathBuf::from(e2e_config.effective_output()).join(lang);
37
38        let mut files = Vec::new();
39
40        // Resolve call config with overrides.
41        let call = &e2e_config.call;
42        let overrides = call.overrides.get(lang);
43        let _module_path = overrides
44            .and_then(|o| o.module.as_ref())
45            .cloned()
46            .unwrap_or_else(|| call.module.clone());
47        let function_name = overrides
48            .and_then(|o| o.function.as_ref())
49            .cloned()
50            .unwrap_or_else(|| call.function.clone());
51        let result_var = &call.result_var;
52
53        // Resolve package config.
54        let zig_pkg = e2e_config.resolve_package("zig");
55        let pkg_path = zig_pkg
56            .as_ref()
57            .and_then(|p| p.path.as_ref())
58            .cloned()
59            .unwrap_or_else(|| "../../packages/zig".to_string());
60        let pkg_name = zig_pkg
61            .as_ref()
62            .and_then(|p| p.name.as_ref())
63            .cloned()
64            .unwrap_or_else(|| config.name.to_snake_case());
65
66        // Generate build.zig.zon (Zig package manifest).
67        files.push(GeneratedFile {
68            path: output_base.join("build.zig.zon"),
69            content: render_build_zig_zon(&pkg_name, &pkg_path, e2e_config.dep_mode),
70            generated_header: false,
71        });
72
73        // Get the module name for imports.
74        let module_name = config.zig_module_name();
75        let ffi_prefix = config.ffi_prefix();
76
77        // Generate build.zig - collect test file names first.
78        let field_resolver = FieldResolver::new(
79            &e2e_config.fields,
80            &e2e_config.fields_optional,
81            &e2e_config.result_fields,
82            &e2e_config.fields_array,
83            &e2e_config.fields_method_calls,
84        );
85
86        // Generate test files per category and collect their names.
87        let mut test_filenames: Vec<String> = Vec::new();
88        for group in groups {
89            let active: Vec<&Fixture> = group
90                .fixtures
91                .iter()
92                .filter(|f| super::should_include_fixture(f, lang, e2e_config))
93                .collect();
94
95            if active.is_empty() {
96                continue;
97            }
98
99            let filename = format!("{}_test.zig", sanitize_filename(&group.category));
100            test_filenames.push(filename.clone());
101            let content = render_test_file(
102                &group.category,
103                &active,
104                e2e_config,
105                &function_name,
106                result_var,
107                &e2e_config.call.args,
108                &field_resolver,
109                &e2e_config.fields_enum,
110                &module_name,
111                &ffi_prefix,
112            );
113            files.push(GeneratedFile {
114                path: output_base.join("src").join(filename),
115                content,
116                generated_header: true,
117            });
118        }
119
120        // Generate build.zig with collected test files.
121        files.insert(
122            files
123                .iter()
124                .position(|f| f.path.file_name().is_some_and(|n| n == "build.zig.zon"))
125                .unwrap_or(1),
126            GeneratedFile {
127                path: output_base.join("build.zig"),
128                content: render_build_zig(
129                    &test_filenames,
130                    &pkg_name,
131                    &module_name,
132                    &config.ffi_lib_name(),
133                    &config.ffi_crate_path(),
134                    &e2e_config.test_documents_relative_from(0),
135                ),
136                generated_header: false,
137            },
138        );
139
140        Ok(files)
141    }
142
143    fn language_name(&self) -> &'static str {
144        "zig"
145    }
146}
147
148// ---------------------------------------------------------------------------
149// Rendering
150// ---------------------------------------------------------------------------
151
152fn render_build_zig_zon(pkg_name: &str, pkg_path: &str, dep_mode: crate::config::DependencyMode) -> String {
153    let dep_block = match dep_mode {
154        crate::config::DependencyMode::Registry => {
155            // For registry mode, use a dummy hash (in real Zig, hash must be computed).
156            format!(
157                r#".{{
158            .url = "https://registry.example.com/{pkg_name}/v0.1.0.tar.gz",
159            .hash = "0000000000000000000000000000000000000000000000000000000000000000",
160        }}"#
161            )
162        }
163        crate::config::DependencyMode::Local => {
164            format!(r#".{{ .path = "{pkg_path}" }}"#)
165        }
166    };
167
168    let min_zig = toolchain::MIN_ZIG_VERSION;
169    // Zig 0.16+ requires a fingerprint of the form (crc32_ieee(name) << 32) | id.
170    let name_bytes: &[u8] = b"e2e_zig";
171    let mut crc: u32 = 0xffff_ffff;
172    for byte in name_bytes {
173        crc ^= *byte as u32;
174        for _ in 0..8 {
175            let mask = (crc & 1).wrapping_neg();
176            crc = (crc >> 1) ^ (0xedb8_8320 & mask);
177        }
178    }
179    let name_crc: u32 = !crc;
180    let mut id: u32 = 0x811c_9dc5;
181    for byte in name_bytes {
182        id ^= *byte as u32;
183        id = id.wrapping_mul(0x0100_0193);
184    }
185    if id == 0 || id == 0xffff_ffff {
186        id = 0x1;
187    }
188    let fingerprint: u64 = ((name_crc as u64) << 32) | (id as u64);
189    format!(
190        r#".{{
191    .name = .e2e_zig,
192    .version = "0.1.0",
193    .fingerprint = 0x{fingerprint:016x},
194    .minimum_zig_version = "{min_zig}",
195    .dependencies = .{{
196        .{pkg_name} = {dep_block},
197    }},
198    .paths = .{{
199        "build.zig",
200        "build.zig.zon",
201        "src",
202    }},
203}}
204"#
205    )
206}
207
208fn render_build_zig(
209    test_filenames: &[String],
210    pkg_name: &str,
211    module_name: &str,
212    ffi_lib_name: &str,
213    ffi_crate_path: &str,
214    test_documents_path: &str,
215) -> String {
216    if test_filenames.is_empty() {
217        return r#"const std = @import("std");
218
219pub fn build(b: *std.Build) void {
220    const target = b.standardTargetOptions(.{});
221    const optimize = b.standardOptimizeOption(.{});
222
223    const test_step = b.step("test", "Run tests");
224}
225"#
226        .to_string();
227    }
228
229    // The Zig build script wires up three names that all derive from the
230    // crate config:
231    //   * `ffi_lib_name`     — the dynamic library to link (e.g. `mylib_ffi`).
232    //   * `pkg_name`         — the Zig package directory and source file stem
233    //                          under `packages/zig/src/<pkg_name>.zig`.
234    //   * `module_name`      — the Zig `@import("...")` identifier other test
235    //                          files use to import the binding module.
236    // Callers pass these in resolved form so this function never embeds a
237    // downstream crate's name.
238    let mut content = String::from("const std = @import(\"std\");\n\npub fn build(b: *std.Build) void {\n");
239    content.push_str("    const target = b.standardTargetOptions(.{});\n");
240    content.push_str("    const optimize = b.standardOptimizeOption(.{});\n");
241    content.push_str("    const test_step = b.step(\"test\", \"Run tests\");\n");
242    let _ = writeln!(
243        content,
244        "    const ffi_path = b.option([]const u8, \"ffi_path\", \"Path to directory containing lib{ffi_lib_name}\") orelse \"../../target/debug\";"
245    );
246    let _ = writeln!(
247        content,
248        "    const ffi_include = b.option([]const u8, \"ffi_include_path\", \"Path to directory containing FFI header\") orelse \"{ffi_crate_path}/include\";"
249    );
250    let _ = writeln!(content);
251    let _ = writeln!(
252        content,
253        "    const {module_name}_module = b.addModule(\"{module_name}\", .{{"
254    );
255    let _ = writeln!(
256        content,
257        "        .root_source_file = b.path(\"../../packages/zig/src/{pkg_name}.zig\"),"
258    );
259    content.push_str("        .target = target,\n");
260    content.push_str("        .optimize = optimize,\n");
261    // Zig 0.16 requires explicit libc linking for any module that transitively
262    // references stdlib C bindings (e.g. `c.getenv` via std.posix). The shared
263    // binding module pulls in the FFI header, so libc is always required.
264    content.push_str("        .link_libc = true,\n");
265    content.push_str("    });\n");
266    let _ = writeln!(
267        content,
268        "    {module_name}_module.addLibraryPath(.{{ .cwd_relative = ffi_path }});"
269    );
270    let _ = writeln!(
271        content,
272        "    {module_name}_module.addIncludePath(.{{ .cwd_relative = ffi_include }});"
273    );
274    let _ = writeln!(
275        content,
276        "    {module_name}_module.linkSystemLibrary(\"{ffi_lib_name}\", .{{}});"
277    );
278    let _ = writeln!(content);
279
280    for filename in test_filenames {
281        // Convert filename like "basic_test.zig" to a test name
282        let test_name = filename.trim_end_matches("_test.zig");
283        content.push_str(&format!("    const {test_name}_module = b.createModule(.{{\n"));
284        content.push_str(&format!("        .root_source_file = b.path(\"src/{filename}\"),\n"));
285        content.push_str("        .target = target,\n");
286        content.push_str("        .optimize = optimize,\n");
287        // Each test module also needs libc linking because it imports the binding
288        // module (which references C stdlib symbols) and may directly call helpers
289        // like `std.c.getenv` for env-var-driven mock-server URLs.
290        content.push_str("        .link_libc = true,\n");
291        content.push_str("    });\n");
292        content.push_str(&format!(
293            "    {test_name}_module.addImport(\"{module_name}\", {module_name}_module);\n"
294        ));
295        // Zig 0.16: addTest hashes its output binary path off the artifact `.name`.
296        // Without an explicit name, every addTest call defaults to "test", colliding
297        // in the cache — only one binary survives, every other addRunArtifact fails
298        // with FileNotFound at its computed path. Setting a unique name per test
299        // module produces a distinct .zig-cache/o/<hash>/<name> binary for each.
300        //
301        // Zig 0.16 ALSO defaults to the self-hosted backend on aarch64-linux for
302        // Debug builds. That backend emits the test binary at a different cache
303        // path (or with different permissions) than the build system's RunStep
304        // computes when reading `getEmittedBin()`, so every `addRunArtifact` call
305        // fails with `FileNotFound` at `.zig-cache/o/<hash>/<name>` even though
306        // the compile step reports success. Forcing `.use_llvm = true` pins the
307        // LLVM backend, which keeps the emitted binary at the path the RunStep
308        // expects. Other Zig backends (x86_64 macOS/Linux) already default to
309        // LLVM, so this is a no-op there.
310        content.push_str(&format!("    const {test_name}_tests = b.addTest(.{{\n"));
311        content.push_str(&format!("        .name = \"{test_name}_test\",\n"));
312        content.push_str(&format!("        .root_module = {test_name}_module,\n"));
313        content.push_str("        .use_llvm = true,\n");
314        content.push_str("    });\n");
315        // Install the test artifact so its emitted binary is materialised at a
316        // stable, on-disk location (`zig-out/bin/<name>`) in addition to the
317        // cache. RunStep still resolves to the cache path via `getEmittedBin`,
318        // but the install-step dependency forces the build system to actually
319        // place the binary on disk before the run step executes — defensive
320        // against any future backend that elides cache-path materialisation
321        // when no install step references the artifact.
322        content.push_str(&format!("    b.installArtifact({test_name}_tests);\n"));
323        content.push_str(&format!(
324            "    const {test_name}_run = b.addRunArtifact({test_name}_tests);\n"
325        ));
326        content.push_str(&format!(
327            "    {test_name}_run.setCwd(b.path(\"{test_documents_path}\"));\n"
328        ));
329        content.push_str(&format!("    test_step.dependOn(&{test_name}_run.step);\n\n"));
330    }
331
332    content.push_str("}\n");
333    content
334}
335
336// ---------------------------------------------------------------------------
337// HTTP server test rendering — shared-driver integration
338// ---------------------------------------------------------------------------
339
340/// Renderer that emits Zig `test "..." { ... }` blocks targeting a mock server
341/// via `std.http.Client`. Satisfies [`client::TestClientRenderer`] so the shared
342/// [`client::http_call::render_http_test`] driver drives the call sequence.
343struct ZigTestClientRenderer;
344
345impl client::TestClientRenderer for ZigTestClientRenderer {
346    fn language_name(&self) -> &'static str {
347        "zig"
348    }
349
350    fn render_test_open(&self, out: &mut String, fn_name: &str, description: &str, skip_reason: Option<&str>) {
351        if let Some(reason) = skip_reason {
352            let _ = writeln!(out, "test \"{fn_name}\" {{");
353            let _ = writeln!(out, "    // {description}");
354            let _ = writeln!(out, "    // skipped: {reason}");
355            let _ = writeln!(out, "    return error.SkipZigTest;");
356        } else {
357            let _ = writeln!(out, "test \"{fn_name}\" {{");
358            let _ = writeln!(out, "    // {description}");
359        }
360    }
361
362    fn render_test_close(&self, out: &mut String) {
363        let _ = writeln!(out, "}}");
364    }
365
366    fn render_call(&self, out: &mut String, ctx: &client::CallCtx<'_>) {
367        let method = ctx.method.to_uppercase();
368        let fixture_id = ctx.path.trim_start_matches("/fixtures/");
369
370        let _ = writeln!(out, "    var gpa: std.heap.DebugAllocator(.{{}}) = .init;");
371        let _ = writeln!(out, "    defer _ = gpa.deinit();");
372        let _ = writeln!(out, "    const allocator = gpa.allocator();");
373
374        let _ = writeln!(out, "    var url_buf: [512]u8 = undefined;");
375        let _ = writeln!(
376            out,
377            "    const url = try std.fmt.bufPrint(&url_buf, \"{{s}}/fixtures/{fixture_id}\", .{{if (std.c.getenv(\"MOCK_SERVER_URL\")) |v| std.mem.span(v) else \"http://localhost:8080\"}});"
378        );
379
380        // Headers
381        if !ctx.headers.is_empty() {
382            let mut header_pairs: Vec<(&String, &String)> = ctx.headers.iter().collect();
383            header_pairs.sort_by_key(|(k, _)| k.as_str());
384            let _ = writeln!(out, "    const headers = [_]std.http.Header{{");
385            for (k, v) in &header_pairs {
386                let ek = escape_zig(k);
387                let ev = escape_zig(v);
388                let _ = writeln!(out, "        .{{ .name = \"{ek}\", .value = \"{ev}\" }},");
389            }
390            let _ = writeln!(out, "    }};");
391        }
392
393        // Body
394        if let Some(body) = ctx.body {
395            let json_str = serde_json::to_string(body).unwrap_or_default();
396            let escaped = escape_zig(&json_str);
397            let _ = writeln!(out, "    const body_bytes: []const u8 = \"{escaped}\";");
398        }
399
400        let headers_arg = if ctx.headers.is_empty() { "&.{}" } else { "&headers" };
401        let has_body = ctx.body.is_some();
402
403        let _ = writeln!(
404            out,
405            "    var http_client = std.http.Client{{ .allocator = allocator }};"
406        );
407        let _ = writeln!(out, "    defer http_client.deinit();");
408        let _ = writeln!(out, "    var response_body = std.ArrayList(u8).init(allocator);");
409        let _ = writeln!(out, "    defer response_body.deinit();");
410
411        let method_zig = match method.as_str() {
412            "GET" => ".GET",
413            "POST" => ".POST",
414            "PUT" => ".PUT",
415            "DELETE" => ".DELETE",
416            "PATCH" => ".PATCH",
417            "HEAD" => ".HEAD",
418            "OPTIONS" => ".OPTIONS",
419            _ => ".GET",
420        };
421
422        let payload_field = if has_body { ", .payload = body_bytes" } else { "" };
423        let _ = writeln!(
424            out,
425            "    const {rv} = try http_client.fetch(.{{ .location = .{{ .url = url }}, .method = {method_zig}, .extra_headers = {headers_arg}{payload_field}, .response_storage = .{{ .dynamic = &response_body }} }});",
426            rv = ctx.response_var,
427        );
428    }
429
430    fn render_assert_status(&self, out: &mut String, response_var: &str, status: u16) {
431        let _ = writeln!(
432            out,
433            "    try testing.expectEqual(@as(u10, {status}), @intFromEnum({response_var}.status));"
434        );
435    }
436
437    fn render_assert_header(&self, out: &mut String, _response_var: &str, name: &str, expected: &str) {
438        let ename = escape_zig(&name.to_lowercase());
439        match expected {
440            "<<present>>" => {
441                let _ = writeln!(
442                    out,
443                    "    // assert header '{ename}' is present (header inspection not yet implemented)"
444                );
445            }
446            "<<absent>>" => {
447                let _ = writeln!(
448                    out,
449                    "    // assert header '{ename}' is absent (header inspection not yet implemented)"
450                );
451            }
452            "<<uuid>>" => {
453                let _ = writeln!(
454                    out,
455                    "    // assert header '{ename}' matches UUID pattern (header inspection not yet implemented)"
456                );
457            }
458            exact => {
459                let evalue = escape_zig(exact);
460                let _ = writeln!(
461                    out,
462                    "    // assert header '{ename}' == \"{evalue}\" (header inspection not yet implemented)"
463                );
464            }
465        }
466    }
467
468    fn render_assert_json_body(&self, out: &mut String, _response_var: &str, expected: &serde_json::Value) {
469        let json_str = serde_json::to_string(expected).unwrap_or_default();
470        let escaped = escape_zig(&json_str);
471        let _ = writeln!(
472            out,
473            "    try testing.expectEqualStrings(\"{escaped}\", response_body.items);"
474        );
475    }
476
477    fn render_assert_partial_body(&self, out: &mut String, _response_var: &str, expected: &serde_json::Value) {
478        if let Some(obj) = expected.as_object() {
479            for (key, val) in obj {
480                let ekey = escape_zig(key);
481                let eval = escape_zig(&serde_json::to_string(val).unwrap_or_default());
482                let _ = writeln!(
483                    out,
484                    "    // assert body contains field \"{ekey}\" = \"{eval}\" (partial JSON not yet implemented)"
485                );
486            }
487        }
488    }
489
490    fn render_assert_validation_errors(
491        &self,
492        out: &mut String,
493        _response_var: &str,
494        errors: &[crate::fixture::ValidationErrorExpectation],
495    ) {
496        for ve in errors {
497            let loc = ve.loc.join(".");
498            let escaped_loc = escape_zig(&loc);
499            let escaped_msg = escape_zig(&ve.msg);
500            let _ = writeln!(
501                out,
502                "    // assert validation error at \"{escaped_loc}\": \"{escaped_msg}\" (not yet implemented)"
503            );
504        }
505    }
506}
507
508/// Render a Zig `test "..." { ... }` block for an HTTP server fixture.
509///
510/// Delegates to the shared [`client::http_call::render_http_test`] driver via
511/// [`ZigTestClientRenderer`].
512fn render_http_test_case(out: &mut String, fixture: &Fixture) {
513    client::http_call::render_http_test(out, &ZigTestClientRenderer, fixture);
514}
515
516// ---------------------------------------------------------------------------
517// Function-call test rendering
518// ---------------------------------------------------------------------------
519
520#[allow(clippy::too_many_arguments)]
521fn render_test_file(
522    category: &str,
523    fixtures: &[&Fixture],
524    e2e_config: &E2eConfig,
525    function_name: &str,
526    result_var: &str,
527    args: &[crate::config::ArgMapping],
528    field_resolver: &FieldResolver,
529    enum_fields: &HashSet<String>,
530    module_name: &str,
531    ffi_prefix: &str,
532) -> String {
533    let mut out = String::new();
534    out.push_str(&hash::header(CommentStyle::DoubleSlash));
535    let _ = writeln!(out, "const std = @import(\"std\");");
536    let _ = writeln!(out, "const testing = std.testing;");
537    let _ = writeln!(out, "const {module_name} = @import(\"{module_name}\");");
538    let _ = writeln!(out);
539
540    let _ = writeln!(out, "// E2e tests for category: {category}");
541    let _ = writeln!(out);
542
543    for fixture in fixtures {
544        if fixture.http.is_some() {
545            render_http_test_case(&mut out, fixture);
546        } else {
547            render_test_fn(
548                &mut out,
549                fixture,
550                e2e_config,
551                function_name,
552                result_var,
553                args,
554                field_resolver,
555                enum_fields,
556                module_name,
557                ffi_prefix,
558            );
559        }
560        let _ = writeln!(out);
561    }
562
563    out
564}
565
566#[allow(clippy::too_many_arguments)]
567fn render_test_fn(
568    out: &mut String,
569    fixture: &Fixture,
570    e2e_config: &E2eConfig,
571    _function_name: &str,
572    _result_var: &str,
573    _args: &[crate::config::ArgMapping],
574    field_resolver: &FieldResolver,
575    enum_fields: &HashSet<String>,
576    module_name: &str,
577    ffi_prefix: &str,
578) {
579    // Resolve per-fixture call config.
580    let call_config = e2e_config.resolve_call_for_fixture(fixture.call.as_deref(), &fixture.input);
581    let lang = "zig";
582    let call_overrides = call_config.overrides.get(lang);
583    let function_name = call_overrides
584        .and_then(|o| o.function.as_ref())
585        .cloned()
586        .unwrap_or_else(|| call_config.function.clone());
587    let result_var = &call_config.result_var;
588    let args = &call_config.args;
589    // Client factory: when set, the test instantiates a client object via
590    // `module.factory_fn(...)` and calls methods on the instance rather than
591    // calling top-level package functions directly.
592    // Mirrors the go codegen pattern (go.rs:981-1028 / CallOverride.client_factory).
593    let client_factory = call_overrides.and_then(|o| o.client_factory.as_deref()).or_else(|| {
594        e2e_config
595            .call
596            .overrides
597            .get(lang)
598            .and_then(|o| o.client_factory.as_deref())
599    });
600
601    // When `result_is_json_struct = true`, the Zig function returns `[]u8` JSON.
602    // The test parses it with `std.json.parseFromSlice(std.json.Value, ...)` and
603    // traverses the dynamic JSON object for field assertions.
604    //
605    // Client-factory methods on opaque handles always return JSON `[]u8` because
606    // the zig backend serializes struct results via the FFI's `*_to_json` helper
607    // (see alef-backend-zig/src/gen_bindings/opaque_handles.rs). Force the flag
608    // on whenever a client_factory is in play so the test path parses the JSON
609    // result rather than attempting direct field access on `[]u8`.
610    //
611    // Exception: when the call returns raw bytes (e.g. speech/file_content use the
612    // FFI byte-buffer out-pointer shape and return `[]u8` audio/file bytes rather
613    // than a serialised struct). Detect this by checking the call-level flag first
614    // and then falling back to any per-language override that declares `result_is_bytes`.
615    // The zig and C bindings share the same byte-buffer convention, so a C override
616    // of `result_is_bytes = true` is a reliable proxy when no zig override exists.
617    let call_result_is_bytes = call_config.result_is_bytes || call_config.overrides.values().any(|o| o.result_is_bytes);
618    let result_is_json_struct =
619        !call_result_is_bytes && (call_overrides.is_some_and(|o| o.result_is_json_struct) || client_factory.is_some());
620
621    // Whether the bare wrapper return type is `?T` (Optional). The zig backend
622    // emits `?[]u8` for nullable JSON results and `?<Primitive>` for nullable
623    // primitives, so assertions on the bare result must use null-checks rather
624    // than `.len`.
625    let result_is_option = call_overrides.is_some_and(|o| o.result_is_option) || call_config.result_is_option;
626
627    let test_name = fixture.id.to_snake_case();
628    let description = &fixture.description;
629    let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
630
631    let (setup_lines, args_str, setup_needs_gpa) = build_args_and_setup(&fixture.input, args, &fixture.id, module_name);
632    // Append per-call zig extra_args (e.g. `["null"]` for the trailing
633    // optional `query` parameter on `list_files` / `list_batches`). Mirrors
634    // the same mechanism used by go/python/swift codegen — zig's method
635    // signatures require every optional positional argument to be supplied
636    // explicitly, so the e2e config carries a per-language extras list.
637    let extra_args: Vec<String> = call_overrides.map(|o| o.extra_args.clone()).unwrap_or_default();
638    let args_str = if extra_args.is_empty() {
639        args_str
640    } else if args_str.is_empty() {
641        extra_args.join(", ")
642    } else {
643        format!("{args_str}, {}", extra_args.join(", "))
644    };
645
646    // Pre-compute whether any assertion will emit code that references `result` /
647    // `allocator`. Used to decide whether to emit the GPA allocator binding.
648    let any_happy_emits_code = fixture
649        .assertions
650        .iter()
651        .any(|a| assertion_emits_code(a, field_resolver));
652    let any_non_error_emits_code = fixture
653        .assertions
654        .iter()
655        .filter(|a| a.assertion_type != "error")
656        .any(|a| assertion_emits_code(a, field_resolver));
657
658    // Pre-compute streaming-virtual path conditions.
659    let has_streaming_virtual_assertions = fixture.assertions.iter().any(|a| {
660        a.field
661            .as_ref()
662            .is_some_and(|f| !f.is_empty() && is_streaming_virtual_field(f))
663    });
664    let is_stream_fn = function_name.contains("stream");
665    let uses_streaming_virtual_path =
666        result_is_json_struct && has_streaming_virtual_assertions && is_stream_fn && client_factory.is_some();
667    // Whether the streaming-virtual path also parses JSON (for non-streaming assertions).
668    let streaming_path_has_non_streaming = uses_streaming_virtual_path
669        && fixture.assertions.iter().any(|a| {
670            !a.field
671                .as_ref()
672                .is_some_and(|f| !f.is_empty() && is_streaming_virtual_field(f))
673                && !matches!(a.assertion_type.as_str(), "not_error" | "error")
674                && a.field
675                    .as_ref()
676                    .is_some_and(|f| !f.is_empty() && field_resolver.is_valid_for_result(f))
677        });
678
679    let _ = writeln!(out, "test \"{test_name}\" {{");
680    let _ = writeln!(out, "    // {description}");
681
682    // Skip visitor fixtures until the zig binding wires up fixture-driven
683    // visitor codegen (the binding exposes a C-vtable Visitor struct via the
684    // FFI bridge, but alef-e2e/zig does not yet emit the per-fixture vtable
685    // population + register call). Matches the dart codegen's pending-skip
686    // behaviour.
687    if fixture.visitor.is_some() {
688        let _ = writeln!(out, "    // skipped: pending zig-binding visitor wiring (alef issue)");
689        let _ = writeln!(out, "    return error.SkipZigTest;");
690        let _ = writeln!(out, "}}");
691        let _ = writeln!(out);
692        return;
693    }
694
695    // Emit GPA allocator only when it will actually be used: setup lines that
696    // need GPA allocation (mock_url), or a JSON-struct result path where the test
697    // will call `std.json.parseFromSlice`. The binding is not needed for
698    // error-only paths or tests with no field assertions.
699    // Note: `bytes` arg setup uses c_allocator directly and does NOT require GPA.
700    // For the streaming-virtual path, `allocator` is only needed if there are also
701    // non-streaming assertions that require JSON parsing via parseFromSlice.
702    let needs_gpa = setup_needs_gpa
703        || streaming_path_has_non_streaming
704        || (!uses_streaming_virtual_path && result_is_json_struct && !expects_error && any_happy_emits_code)
705        || (!uses_streaming_virtual_path && result_is_json_struct && expects_error && any_non_error_emits_code);
706    if needs_gpa {
707        let _ = writeln!(out, "    var gpa: std.heap.DebugAllocator(.{{}}) = .init;");
708        let _ = writeln!(out, "    defer _ = gpa.deinit();");
709        let _ = writeln!(out, "    const allocator = gpa.allocator();");
710        let _ = writeln!(out);
711    }
712
713    for line in &setup_lines {
714        let _ = writeln!(out, "    {line}");
715    }
716
717    // Client factory: when configured, instantiate a client object via the named
718    // constructor function and call the method on the instance.
719    // The client is pointed at MOCK_SERVER_URL/fixtures/<id> (mirrors go.rs:981-1028).
720    // When not configured, fall back to calling the top-level package function directly.
721    let call_prefix = if let Some(factory) = client_factory {
722        let fixture_id = &fixture.id;
723        let _ = writeln!(
724            out,
725            "    const _mock_url = try std.fmt.allocPrintSentinel(std.heap.c_allocator, \"{{s}}/fixtures/{fixture_id}\", .{{if (std.c.getenv(\"MOCK_SERVER_URL\")) |v| std.mem.span(v) else \"http://localhost:8080\"}}, 0);"
726        );
727        let _ = writeln!(out, "    defer std.heap.c_allocator.free(_mock_url);");
728        let _ = writeln!(
729            out,
730            "    var _client = try {module_name}.{factory}(\"test-key\", _mock_url, null, null, null);"
731        );
732        let _ = writeln!(out, "    defer _client.free();");
733        "_client".to_string()
734    } else {
735        module_name.to_string()
736    };
737
738    if expects_error {
739        // Error-path test: use error union syntax `!T` and try-catch.
740        // Async functions execute via tokio::runtime::block_on in the FFI shim,
741        // so the call site is synchronous from Zig's perspective.
742        if result_is_json_struct {
743            let _ = writeln!(
744                out,
745                "    const _result_json = {call_prefix}.{function_name}({args_str}) catch {{"
746            );
747        } else {
748            let _ = writeln!(
749                out,
750                "    const result = {call_prefix}.{function_name}({args_str}) catch {{"
751            );
752        }
753        let _ = writeln!(out, "        try testing.expect(true); // Error occurred as expected");
754        let _ = writeln!(out, "        return;");
755        let _ = writeln!(out, "    }};");
756        // Whether any non-error assertion will emit code that references `result`.
757        // If not, we must explicitly discard `result` to satisfy Zig's
758        // strict-unused-locals rule.
759        let any_emits_code = fixture
760            .assertions
761            .iter()
762            .filter(|a| a.assertion_type != "error")
763            .any(|a| assertion_emits_code(a, field_resolver));
764        if result_is_json_struct && any_emits_code {
765            let _ = writeln!(out, "    defer std.heap.c_allocator.free(_result_json);");
766            let _ = writeln!(
767                out,
768                "    var _parsed = try std.json.parseFromSlice(std.json.Value, allocator, _result_json, .{{}});"
769            );
770            let _ = writeln!(out, "    defer _parsed.deinit();");
771            let _ = writeln!(out, "    const {result_var} = &_parsed.value;");
772            let _ = writeln!(out, "    // Perform success assertions if any");
773            for assertion in &fixture.assertions {
774                if assertion.assertion_type != "error" {
775                    render_json_assertion(out, assertion, result_var, field_resolver);
776                }
777            }
778        } else if result_is_json_struct {
779            let _ = writeln!(out, "    _ = _result_json;");
780        } else if any_emits_code {
781            let _ = writeln!(out, "    // Perform success assertions if any");
782            for assertion in &fixture.assertions {
783                if assertion.assertion_type != "error" {
784                    render_assertion(
785                        out,
786                        assertion,
787                        result_var,
788                        field_resolver,
789                        enum_fields,
790                        result_is_option,
791                    );
792                }
793            }
794        } else {
795            let _ = writeln!(out, "    _ = result;");
796        }
797    } else if fixture.assertions.is_empty() {
798        // No assertions: emit a call to verify compilation.
799        if result_is_json_struct {
800            let _ = writeln!(
801                out,
802                "    const _result_json = try {call_prefix}.{function_name}({args_str});"
803            );
804            let _ = writeln!(out, "    defer std.heap.c_allocator.free(_result_json);");
805        } else {
806            let _ = writeln!(out, "    _ = try {call_prefix}.{function_name}({args_str});");
807        }
808    } else {
809        // Happy path: call and assert. Detect whether any assertion actually
810        // emits code that references `result` (some — like `not_error` — emit
811        // nothing) so we don't leave an unused local, which Zig 0.16 rejects.
812        let any_emits_code = fixture
813            .assertions
814            .iter()
815            .any(|a| assertion_emits_code(a, field_resolver));
816        if call_result_is_bytes && client_factory.is_some() {
817            // Bytes path: the function returns raw `[]u8` (audio/file bytes), not
818            // a JSON struct. Call, defer-free, then check len for not_empty/is_empty.
819            let _ = writeln!(
820                out,
821                "    const _result_json = try {call_prefix}.{function_name}({args_str});"
822            );
823            let _ = writeln!(out, "    defer std.heap.c_allocator.free(_result_json);");
824            let has_bytes_assertions = fixture
825                .assertions
826                .iter()
827                .any(|a| matches!(a.assertion_type.as_str(), "not_empty" | "is_empty"));
828            if has_bytes_assertions {
829                for assertion in &fixture.assertions {
830                    match assertion.assertion_type.as_str() {
831                        "not_empty" => {
832                            let _ = writeln!(out, "    try testing.expect(_result_json.len > 0);");
833                        }
834                        "is_empty" => {
835                            let _ = writeln!(out, "    try testing.expectEqual(@as(usize, 0), _result_json.len);");
836                        }
837                        "not_error" | "error" => {}
838                        _ => {
839                            let atype = &assertion.assertion_type;
840                            let _ = writeln!(
841                                out,
842                                "    // bytes result: assertion '{atype}' not implemented for zig bytes"
843                            );
844                        }
845                    }
846                }
847            }
848        } else if result_is_json_struct {
849            // When streaming-virtual field assertions are present (pre-computed above),
850            // emit raw FFI code to collect all chunks instead of calling
851            // `chat_stream` (which only returns the last chunk's JSON).
852            if uses_streaming_virtual_path {
853                let request_from_json = format!("{ffi_prefix}_chat_completion_request_from_json");
854                let request_free = format!("{ffi_prefix}_chat_completion_request_free");
855                let stream_start = format!("{ffi_prefix}_default_client_chat_stream_start");
856                let stream_free = format!("{ffi_prefix}_default_client_chat_stream_free");
857                let client_c_type = format!("{}DefaultClient", ffi_prefix.to_shouty_snake_case());
858
859                // Streaming-virtual path: inline FFI collect.
860                // Build a sentinel-terminated request string.
861                let _ = writeln!(
862                    out,
863                    "    const _req_z = try std.heap.c_allocator.dupeZ(u8, {args_str});"
864                );
865                let _ = writeln!(out, "    defer std.heap.c_allocator.free(_req_z);");
866                let _ = writeln!(
867                    out,
868                    "    const _req_handle = {module_name}.c.{request_from_json}(_req_z.ptr);"
869                );
870                let _ = writeln!(out, "    defer {module_name}.c.{request_free}(_req_handle);");
871                let _ = writeln!(
872                    out,
873                    "    const _stream_handle = {module_name}.c.{stream_start}(@as(*{module_name}.c.{client_c_type}, @ptrCast(_client._handle)), _req_handle);"
874                );
875                let _ = writeln!(out, "    if (_stream_handle == null) return error.StreamStartFailed;");
876                let _ = writeln!(out, "    defer {module_name}.c.{stream_free}(_stream_handle);");
877                // Emit the collect snippet (already has 4-space indentation baked in).
878                let snip =
879                    StreamingFieldResolver::collect_snippet_zig("_stream_handle", "chunks", module_name, ffi_prefix);
880                out.push_str("    ");
881                out.push_str(&snip);
882                out.push('\n');
883                // For non-streaming assertions (e.g. usage), we also need _result_json.
884                // Re-serialize the last chunk in `chunks` to get the JSON.
885                if streaming_path_has_non_streaming {
886                    let _ = writeln!(
887                        out,
888                        "    const _result_json = if (chunks.items.len > 0) chunks.items[chunks.items.len - 1] else &[_]u8{{}};"
889                    );
890                    let _ = writeln!(
891                        out,
892                        "    var _parsed = try std.json.parseFromSlice(std.json.Value, allocator, _result_json, .{{}});"
893                    );
894                    let _ = writeln!(out, "    defer _parsed.deinit();");
895                    let _ = writeln!(out, "    const {result_var} = &_parsed.value;");
896                }
897                for assertion in &fixture.assertions {
898                    render_json_assertion(out, assertion, result_var, field_resolver);
899                }
900            } else {
901                // JSON struct path: parse result JSON and access fields dynamically.
902                let _ = writeln!(
903                    out,
904                    "    const _result_json = try {call_prefix}.{function_name}({args_str});"
905                );
906                let _ = writeln!(out, "    defer std.heap.c_allocator.free(_result_json);");
907                if any_emits_code {
908                    let _ = writeln!(
909                        out,
910                        "    var _parsed = try std.json.parseFromSlice(std.json.Value, allocator, _result_json, .{{}});"
911                    );
912                    let _ = writeln!(out, "    defer _parsed.deinit();");
913                    let _ = writeln!(out, "    const {result_var} = &_parsed.value;");
914                    for assertion in &fixture.assertions {
915                        render_json_assertion(out, assertion, result_var, field_resolver);
916                    }
917                }
918            }
919        } else if any_emits_code {
920            let _ = writeln!(
921                out,
922                "    const {result_var} = try {call_prefix}.{function_name}({args_str});"
923            );
924            for assertion in &fixture.assertions {
925                render_assertion(
926                    out,
927                    assertion,
928                    result_var,
929                    field_resolver,
930                    enum_fields,
931                    result_is_option,
932                );
933            }
934        } else {
935            let _ = writeln!(out, "    _ = try {call_prefix}.{function_name}({args_str});");
936        }
937    }
938
939    let _ = writeln!(out, "}}");
940}
941
942// ---------------------------------------------------------------------------
943// JSON-struct assertion rendering (for result_is_json_struct = true)
944// ---------------------------------------------------------------------------
945
946/// Convert a dot-separated field path into a chain of `std.json.Value` lookups.
947///
948/// Each segment uses `.object.get("key").?` to traverse the JSON object tree.
949/// The final segment stops before the leaf-type accessor so callers can append
950/// the appropriate accessor (`.string`, `.integer`, `.array.items`, etc.).
951///
952/// Returns `(base_expr, last_key)` where `base_expr` already includes all
953/// intermediate `.object.get("…").?` dereferences up to (but not including)
954/// the leaf, and `last_key` is the last path segment.
955/// Variant names of `FormatMetadata` (snake_case, from `#[serde(rename_all = "snake_case")]`).
956/// These appear as typed accessors in fixture paths (e.g. `format.excel.sheet_count`)
957/// but are NOT JSON keys — `FormatMetadata` is internally tagged so variant fields are
958/// flattened directly into the `format` object alongside the `format_type` discriminant.
959const FORMAT_METADATA_VARIANTS: &[&str] = &[
960    "pdf",
961    "docx",
962    "excel",
963    "email",
964    "pptx",
965    "archive",
966    "image",
967    "xml",
968    "text",
969    "html",
970    "ocr",
971    "csv",
972    "bibtex",
973    "citation",
974    "fiction_book",
975    "dbf",
976    "jats",
977    "epub",
978    "pst",
979    "code",
980];
981
982fn json_path_expr(result_var: &str, field_path: &str) -> String {
983    let segments: Vec<&str> = field_path.split('.').collect();
984    let mut expr = result_var.to_string();
985    let mut prev_seg: Option<&str> = None;
986    for seg in &segments {
987        // Skip variant-name accessor segments that follow a `format` key.
988        // FormatMetadata is an internally-tagged enum (`#[serde(tag = "format_type")]`),
989        // so variant fields are flattened directly into the format object — there is no
990        // intermediate JSON key for the variant name.
991        if prev_seg == Some("format") && FORMAT_METADATA_VARIANTS.contains(seg) {
992            prev_seg = Some(seg);
993            continue;
994        }
995        // Handle array accessor notation:
996        //   "links[]"     → access the array, then first element.
997        //   "results[0]"  → access the array, then specific index N.
998        if let Some(key) = seg.strip_suffix("[]") {
999            expr = format!("{expr}.object.get(\"{key}\").?.array.items[0]");
1000        } else if let Some(bracket_pos) = seg.find('[') {
1001            if let Some(end_pos) = seg.find(']') {
1002                if end_pos > bracket_pos + 1 && end_pos == seg.len() - 1 {
1003                    let key = &seg[..bracket_pos];
1004                    let idx = &seg[bracket_pos + 1..end_pos];
1005                    if idx.chars().all(|c| c.is_ascii_digit()) {
1006                        expr = format!("{expr}.object.get(\"{key}\").?.array.items[{idx}]");
1007                        prev_seg = Some(seg);
1008                        continue;
1009                    }
1010                    // Non-numeric bracket: HashMap<String, _> key access. FRB / serde
1011                    // serialize maps as JSON objects, so `field[key]` resolves to
1012                    // `.object.get("field").?.object.get("key").?`. Used by h2m's
1013                    // `metadata.document.open_graph[title]` alias pattern where
1014                    // `open_graph` is a `HashMap<String, String>`.
1015                    expr = format!("{expr}.object.get(\"{key}\").?.object.get(\"{idx}\").?");
1016                    prev_seg = Some(seg);
1017                    continue;
1018                }
1019            }
1020            expr = format!("{expr}.object.get(\"{seg}\").?");
1021        } else {
1022            expr = format!("{expr}.object.get(\"{seg}\").?");
1023        }
1024        prev_seg = Some(seg);
1025    }
1026    expr
1027}
1028
1029/// Render a single assertion for a JSON-struct result (result_is_json_struct = true).
1030///
1031/// The `result_var` variable is `*std.json.Value` (pointer to the parsed root object).
1032/// Field paths are traversed via `.object.get("key").?` chains.
1033fn render_json_assertion(out: &mut String, assertion: &Assertion, result_var: &str, field_resolver: &FieldResolver) {
1034    // Intercept streaming-virtual fields before the result-type validity check.
1035    if let Some(f) = &assertion.field {
1036        if !f.is_empty() && is_streaming_virtual_field(f) {
1037            if let Some(expr) = StreamingFieldResolver::accessor(f, "zig", "chunks") {
1038                match assertion.assertion_type.as_str() {
1039                    "count_min" => {
1040                        if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1041                            let _ = writeln!(out, "    try testing.expect({expr}.len >= {n});");
1042                        }
1043                    }
1044                    "count_equals" => {
1045                        if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1046                            let _ = writeln!(out, "    try testing.expectEqual(@as(usize, {n}), {expr}.len);");
1047                        }
1048                    }
1049                    "equals" => {
1050                        if let Some(serde_json::Value::String(s)) = &assertion.value {
1051                            let escaped = escape_zig(s);
1052                            let _ = writeln!(out, "    try testing.expectEqualStrings(\"{escaped}\", {expr});");
1053                        } else if let Some(v) = &assertion.value {
1054                            let zig_val = json_to_zig(v);
1055                            let _ = writeln!(out, "    try testing.expectEqual({zig_val}, {expr});");
1056                        }
1057                    }
1058                    "not_empty" => {
1059                        let _ = writeln!(out, "    try testing.expect({expr}.len > 0);");
1060                    }
1061                    "is_true" => {
1062                        let _ = writeln!(out, "    try testing.expect({expr});");
1063                    }
1064                    "is_false" => {
1065                        let _ = writeln!(out, "    try testing.expect(!{expr});");
1066                    }
1067                    _ => {
1068                        let atype = &assertion.assertion_type;
1069                        let _ = writeln!(
1070                            out,
1071                            "    // streaming virtual field '{f}' assertion '{atype}' not implemented for zig"
1072                        );
1073                    }
1074                }
1075            }
1076            return;
1077        }
1078    }
1079
1080    // Synthetic `embeddings` field on a JSON-array result (e.g. embed_texts
1081    // returns `Vec<Vec<f32>>` → JSON `[[...],[...]]`). The field name is a
1082    // convention from the fixture schema — the JSON value IS the embeddings
1083    // array. Apply the assertion against `result.array.items` directly. The
1084    // synthetic path is only used when no explicit result_fields configure
1085    // `embeddings` as a real struct field.
1086    if let Some(f) = &assertion.field {
1087        if f == "embeddings" && !field_resolver.has_explicit_field("embeddings") {
1088            match assertion.assertion_type.as_str() {
1089                "count_min" => {
1090                    if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1091                        let _ = writeln!(out, "    try testing.expect({result_var}.array.items.len >= {n});");
1092                    }
1093                    return;
1094                }
1095                "count_equals" => {
1096                    if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1097                        let _ = writeln!(
1098                            out,
1099                            "    try testing.expectEqual(@as(usize, {n}), {result_var}.array.items.len);"
1100                        );
1101                    }
1102                    return;
1103                }
1104                "not_empty" => {
1105                    let _ = writeln!(out, "    try testing.expect({result_var}.array.items.len > 0);");
1106                    return;
1107                }
1108                "is_empty" => {
1109                    let _ = writeln!(
1110                        out,
1111                        "    try testing.expectEqual(@as(usize, 0), {result_var}.array.items.len);"
1112                    );
1113                    return;
1114                }
1115                _ => {}
1116            }
1117        }
1118    }
1119
1120    // Skip assertions on fields that don't exist on the result type.
1121    if let Some(f) = &assertion.field {
1122        if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
1123            let _ = writeln!(out, "    // skipped: field '{f}' not available on result type");
1124            return;
1125        }
1126    }
1127    // error/not_error are handled at the call level, not assertion level.
1128    if matches!(assertion.assertion_type.as_str(), "not_error" | "error") {
1129        return;
1130    }
1131
1132    let raw_field_path = assertion.field.as_deref().unwrap_or("").trim();
1133    let field_path = if raw_field_path.is_empty() {
1134        raw_field_path.to_string()
1135    } else {
1136        field_resolver.resolve(raw_field_path).to_string()
1137    };
1138    let field_path = field_path.trim();
1139
1140    // "{array_field}.length" → strip suffix; use .array.items.len in the template.
1141    let (field_path_for_expr, is_length_access) = if let Some(parent) = field_path.strip_suffix(".length") {
1142        (parent, true)
1143    } else {
1144        (field_path, false)
1145    };
1146
1147    let field_expr = if field_path_for_expr.is_empty() {
1148        result_var.to_string()
1149    } else {
1150        json_path_expr(result_var, field_path_for_expr)
1151    };
1152
1153    // Compute context variables for the template.
1154    let zig_val = match &assertion.value {
1155        Some(serde_json::Value::String(s)) => format!("\"{}\"", escape_zig(s)),
1156        _ => String::new(),
1157    };
1158    let is_string_val = matches!(&assertion.value, Some(serde_json::Value::String(_)));
1159    let is_bool_val = matches!(&assertion.value, Some(serde_json::Value::Bool(_)));
1160    let bool_val = match &assertion.value {
1161        Some(serde_json::Value::Bool(b)) if *b => "true",
1162        _ => "false",
1163    };
1164    let is_null_val = matches!(&assertion.value, Some(serde_json::Value::Null));
1165    let n = assertion.value.as_ref().map(json_to_zig).unwrap_or_default();
1166    let has_n = assertion.value.as_ref().is_some_and(|v| v.is_number() || v.is_u64());
1167    // Distinguish float vs integer JSON values: `std.json.Value` exposes
1168    // `.integer` (i64) and `.float` (f64) as separate variants. Comparing
1169    // `.integer` against a literal with a fractional part (e.g. `0.9`) is a
1170    // Zig compile error, so the template must select the right tag.
1171    let is_float_val = matches!(&assertion.value, Some(serde_json::Value::Number(n)) if !n.is_i64() && !n.is_u64());
1172    let values_list: Vec<String> = assertion
1173        .values
1174        .as_deref()
1175        .unwrap_or_default()
1176        .iter()
1177        .filter_map(|v| {
1178            if let serde_json::Value::String(s) = v {
1179                Some(format!("\"{}\"", escape_zig(s)))
1180            } else {
1181                None
1182            }
1183        })
1184        .collect();
1185
1186    let rendered = crate::template_env::render(
1187        "zig/json_assertion.jinja",
1188        minijinja::context! {
1189            assertion_type => assertion.assertion_type.as_str(),
1190            field_expr => field_expr,
1191            is_length_access => is_length_access,
1192            zig_val => zig_val,
1193            is_string_val => is_string_val,
1194            is_bool_val => is_bool_val,
1195            bool_val => bool_val,
1196            is_null_val => is_null_val,
1197            n => n,
1198            has_n => has_n,
1199            is_float_val => is_float_val,
1200            values_list => values_list,
1201        },
1202    );
1203    out.push_str(&rendered);
1204}
1205
1206/// Predicate matching `render_assertion`: returns true when the assertion
1207/// would emit at least one statement that references the result variable.
1208fn assertion_emits_code(assertion: &Assertion, field_resolver: &FieldResolver) -> bool {
1209    if let Some(f) = &assertion.field {
1210        if !f.is_empty() && is_streaming_virtual_field(f) {
1211            // Streaming virtual fields always emit code — they are handled in a
1212            // dedicated collect path, not skipped.
1213        } else if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
1214            return false;
1215        }
1216    }
1217    matches!(
1218        assertion.assertion_type.as_str(),
1219        "equals"
1220            | "contains"
1221            | "contains_all"
1222            | "not_contains"
1223            | "not_empty"
1224            | "is_empty"
1225            | "starts_with"
1226            | "ends_with"
1227            | "min_length"
1228            | "max_length"
1229            | "count_min"
1230            | "count_equals"
1231            | "is_true"
1232            | "is_false"
1233            | "greater_than"
1234            | "less_than"
1235            | "greater_than_or_equal"
1236            | "less_than_or_equal"
1237            | "contains_any"
1238    )
1239}
1240
1241/// Build setup lines and the argument list for the function call.
1242///
1243/// Returns `(setup_lines, args_str, setup_needs_gpa)` where `setup_needs_gpa`
1244/// is `true` when at least one setup line requires the GPA `allocator` binding.
1245fn build_args_and_setup(
1246    input: &serde_json::Value,
1247    args: &[crate::config::ArgMapping],
1248    fixture_id: &str,
1249    _module_name: &str,
1250) -> (Vec<String>, String, bool) {
1251    if args.is_empty() {
1252        return (Vec::new(), String::new(), false);
1253    }
1254
1255    let mut setup_lines: Vec<String> = Vec::new();
1256    let mut parts: Vec<String> = Vec::new();
1257    let mut setup_needs_gpa = false;
1258
1259    for arg in args {
1260        if arg.arg_type == "mock_url" {
1261            let name = arg.name.clone();
1262            let id_upper = fixture_id.to_uppercase();
1263            setup_lines.push(format!(
1264                "const {name} = if (std.c.getenv(\"MOCK_SERVER_{id_upper}\")) |_pf| try std.fmt.allocPrint(allocator, \"{{s}}\", .{{std.mem.span(_pf)}}) else try std.fmt.allocPrint(allocator, \"{{s}}/fixtures/{fixture_id}\", .{{if (std.c.getenv(\"MOCK_SERVER_URL\")) |v| std.mem.span(v) else \"http://localhost:8080\"}});"
1265            ));
1266            setup_lines.push(format!("defer allocator.free({name});"));
1267            parts.push(name);
1268            setup_needs_gpa = true;
1269            continue;
1270        }
1271
1272        // Handle args (engine handle): serialize config to JSON string literal, or null.
1273        // The Zig binding accepts ?[]const u8 for engine params (creates handle internally).
1274        if arg.arg_type == "handle" {
1275            let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1276            let json_str = match input.get(field) {
1277                Some(serde_json::Value::Null) | None => "null".to_string(),
1278                Some(v) => format!("\"{}\"", escape_zig(&serde_json::to_string(v).unwrap_or_default())),
1279            };
1280            parts.push(json_str);
1281            continue;
1282        }
1283
1284        // The Zig wrapper accepts struct parameters (e.g. `ExtractionConfig`)
1285        // as JSON `[]const u8`, converting them to opaque FFI handles via the
1286        // `<prefix>_<snake>_from_json` helper at the binding layer. Emit the
1287        // fixture's configuration value as a JSON string literal, falling back
1288        // to `"{}"` when the fixture omits a config so callers exercise the
1289        // default path.
1290        if arg.name == "config" && arg.arg_type == "json_object" {
1291            let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1292            let json_str = match input.get(field) {
1293                Some(serde_json::Value::Null) | None => "{}".to_string(),
1294                Some(v) => serde_json::to_string(v).unwrap_or_else(|_| "{}".to_string()),
1295            };
1296            parts.push(format!("\"{}\"", escape_zig(&json_str)));
1297            continue;
1298        }
1299
1300        let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1301        // When `field` is empty or refers to `input` itself (no dotted subfield),
1302        // the entire fixture `input` value is the payload — most commonly for
1303        // `json_object` request bodies (chat/embed/etc.). Without this guard
1304        // `input.get("input")` returns `None` and we fall through to `"{}"`,
1305        // which the FFI rejects as a deserialization error.
1306        let val = if field.is_empty() || field == "input" {
1307            Some(input)
1308        } else {
1309            input.get(field)
1310        };
1311        match val {
1312            None | Some(serde_json::Value::Null) if arg.optional => {
1313                // Zig functions don't have default arguments, so we must
1314                // pass `null` explicitly for every optional parameter.
1315                parts.push("null".to_string());
1316            }
1317            None | Some(serde_json::Value::Null) => {
1318                let default_val = match arg.arg_type.as_str() {
1319                    "string" => "\"\"".to_string(),
1320                    "int" | "integer" => "0".to_string(),
1321                    "float" | "number" => "0.0".to_string(),
1322                    "bool" | "boolean" => "false".to_string(),
1323                    "json_object" => "\"{}\"".to_string(),
1324                    _ => "null".to_string(),
1325                };
1326                parts.push(default_val);
1327            }
1328            Some(v) => {
1329                // For `json_object` arguments other than `config` (handled
1330                // above) the Zig binding accepts a JSON `[]const u8`, so we
1331                // serialize the entire fixture value as a single JSON string
1332                // literal rather than rendering it as a Zig array/struct.
1333                if arg.arg_type == "json_object" {
1334                    let json_str = serde_json::to_string(v).unwrap_or_default();
1335                    parts.push(format!("\"{}\"", escape_zig(&json_str)));
1336                } else if arg.arg_type == "bytes" {
1337                    // `bytes` args are file paths in fixtures — read the file into a
1338                    // local buffer. The cwd is set to test_documents/ at runtime.
1339                    // Zig 0.16 uses std.Io.Dir.cwd() (not std.fs.cwd()) and requires
1340                    // an `io` instance from std.testing.io in test context.
1341                    if let serde_json::Value::String(path) = v {
1342                        let var_name = format!("{}_bytes", arg.name);
1343                        let epath = escape_zig(path);
1344                        setup_lines.push(format!(
1345                            "const {var_name} = try std.Io.Dir.cwd().readFileAlloc(std.testing.io, \"{epath}\", std.heap.c_allocator, .unlimited);"
1346                        ));
1347                        setup_lines.push(format!("defer std.heap.c_allocator.free({var_name});"));
1348                        parts.push(var_name);
1349                    } else {
1350                        parts.push(json_to_zig(v));
1351                    }
1352                } else {
1353                    parts.push(json_to_zig(v));
1354                }
1355            }
1356        }
1357    }
1358
1359    (setup_lines, parts.join(", "), setup_needs_gpa)
1360}
1361
1362fn render_assertion(
1363    out: &mut String,
1364    assertion: &Assertion,
1365    result_var: &str,
1366    field_resolver: &FieldResolver,
1367    enum_fields: &HashSet<String>,
1368    result_is_option: bool,
1369) {
1370    // Bare-result assertions on `?T` (Optional) translate to null-checks instead
1371    // of `.len`. Mirrors the same behaviour in kotlin.rs (bare_result_is_option).
1372    let bare_result_is_option = result_is_option && assertion.field.as_deref().filter(|f| !f.is_empty()).is_none();
1373    if bare_result_is_option {
1374        match assertion.assertion_type.as_str() {
1375            "is_empty" => {
1376                let _ = writeln!(out, "    try testing.expect({result_var} == null);");
1377                return;
1378            }
1379            "not_empty" | "not_error" => {
1380                let _ = writeln!(out, "    try testing.expect({result_var} != null);");
1381                return;
1382            }
1383            _ => {}
1384        }
1385    }
1386    // Synthetic-field 'embeddings' on a JSON-bytes result (e.g. embed_texts
1387    // returns `Vec<Vec<f32>>` serialised as JSON). Parse the JSON array and
1388    // apply count_min/count_equals/not_empty/is_empty against the element count.
1389    if let Some(f) = &assertion.field {
1390        if f == "embeddings" && !field_resolver.is_valid_for_result(f) {
1391            match assertion.assertion_type.as_str() {
1392                "count_min" | "count_equals" | "not_empty" | "is_empty" => {
1393                    let _ = writeln!(out, "    {{");
1394                    let _ = writeln!(
1395                        out,
1396                        "        var _eparse = try std.json.parseFromSlice(std.json.Value, std.heap.c_allocator, {result_var}, .{{}});"
1397                    );
1398                    let _ = writeln!(out, "        defer _eparse.deinit();");
1399                    let _ = writeln!(out, "        const _embeddings_len = _eparse.value.array.items.len;");
1400                    match assertion.assertion_type.as_str() {
1401                        "count_min" => {
1402                            if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1403                                let _ = writeln!(out, "        try testing.expect(_embeddings_len >= {n});");
1404                            }
1405                        }
1406                        "count_equals" => {
1407                            if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1408                                let _ = writeln!(
1409                                    out,
1410                                    "        try testing.expectEqual(@as(usize, {n}), _embeddings_len);"
1411                                );
1412                            }
1413                        }
1414                        "not_empty" => {
1415                            let _ = writeln!(out, "        try testing.expect(_embeddings_len > 0);");
1416                        }
1417                        "is_empty" => {
1418                            let _ = writeln!(out, "        try testing.expectEqual(@as(usize, 0), _embeddings_len);");
1419                        }
1420                        _ => {}
1421                    }
1422                    let _ = writeln!(out, "    }}");
1423                    return;
1424                }
1425                _ => {}
1426            }
1427        }
1428    }
1429
1430    // Skip assertions on fields that don't exist on the result type.
1431    if let Some(f) = &assertion.field {
1432        if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
1433            let _ = writeln!(out, "    // skipped: field '{{f}}' not available on result type");
1434            return;
1435        }
1436    }
1437
1438    // Determine if this field is an enum type.
1439    let _field_is_enum = assertion
1440        .field
1441        .as_deref()
1442        .is_some_and(|f| enum_fields.contains(f) || enum_fields.contains(field_resolver.resolve(f)));
1443
1444    let field_expr = match &assertion.field {
1445        Some(f) if !f.is_empty() => field_resolver.accessor(f, "zig", result_var),
1446        _ => result_var.to_string(),
1447    };
1448
1449    match assertion.assertion_type.as_str() {
1450        "equals" => {
1451            if let Some(expected) = &assertion.value {
1452                let zig_val = json_to_zig(expected);
1453                let _ = writeln!(out, "    try testing.expectEqual({zig_val}, {field_expr});");
1454            }
1455        }
1456        "contains" => {
1457            if let Some(expected) = &assertion.value {
1458                let zig_val = json_to_zig(expected);
1459                let _ = writeln!(
1460                    out,
1461                    "    try testing.expect(std.mem.indexOf(u8, {field_expr}, {zig_val}) != null);"
1462                );
1463            }
1464        }
1465        "contains_all" => {
1466            if let Some(values) = &assertion.values {
1467                for val in values {
1468                    let zig_val = json_to_zig(val);
1469                    let _ = writeln!(
1470                        out,
1471                        "    try testing.expect(std.mem.indexOf(u8, {field_expr}, {zig_val}) != null);"
1472                    );
1473                }
1474            }
1475        }
1476        "not_contains" => {
1477            if let Some(expected) = &assertion.value {
1478                let zig_val = json_to_zig(expected);
1479                let _ = writeln!(
1480                    out,
1481                    "    try testing.expect(std.mem.indexOf(u8, {field_expr}, {zig_val}) == null);"
1482                );
1483            } else if let Some(values) = &assertion.values {
1484                // not_contains with a plural `values` list: assert none of the entries
1485                // appear in the field. Emit one expect line per needle so failures
1486                // pinpoint the offending value.
1487                for val in values {
1488                    let zig_val = json_to_zig(val);
1489                    let _ = writeln!(
1490                        out,
1491                        "    try testing.expect(std.mem.indexOf(u8, {field_expr}, {zig_val}) == null);"
1492                    );
1493                }
1494            }
1495        }
1496        "not_empty" => {
1497            let _ = writeln!(out, "    try testing.expect({field_expr}.len > 0);");
1498        }
1499        "is_empty" => {
1500            let _ = writeln!(out, "    try testing.expect({field_expr}.len == 0);");
1501        }
1502        "starts_with" => {
1503            if let Some(expected) = &assertion.value {
1504                let zig_val = json_to_zig(expected);
1505                let _ = writeln!(
1506                    out,
1507                    "    try testing.expect(std.mem.startsWith(u8, {field_expr}, {zig_val}));"
1508                );
1509            }
1510        }
1511        "ends_with" => {
1512            if let Some(expected) = &assertion.value {
1513                let zig_val = json_to_zig(expected);
1514                let _ = writeln!(
1515                    out,
1516                    "    try testing.expect(std.mem.endsWith(u8, {field_expr}, {zig_val}));"
1517                );
1518            }
1519        }
1520        "min_length" => {
1521            if let Some(val) = &assertion.value {
1522                if let Some(n) = val.as_u64() {
1523                    let _ = writeln!(out, "    try testing.expect({field_expr}.len >= {n});");
1524                }
1525            }
1526        }
1527        "max_length" => {
1528            if let Some(val) = &assertion.value {
1529                if let Some(n) = val.as_u64() {
1530                    let _ = writeln!(out, "    try testing.expect({field_expr}.len <= {n});");
1531                }
1532            }
1533        }
1534        "count_min" => {
1535            if let Some(val) = &assertion.value {
1536                if let Some(n) = val.as_u64() {
1537                    let _ = writeln!(out, "    try testing.expect({field_expr}.len >= {n});");
1538                }
1539            }
1540        }
1541        "count_equals" => {
1542            if let Some(val) = &assertion.value {
1543                if let Some(n) = val.as_u64() {
1544                    // When there is no field (field_expr == result_var), the result
1545                    // is `[]u8` JSON (e.g. batch functions). Parse the JSON array
1546                    // and count its elements; `.len` would give byte count, not item count.
1547                    let has_field = assertion.field.as_deref().is_some_and(|f| !f.is_empty());
1548                    if has_field {
1549                        let _ = writeln!(out, "    try testing.expectEqual({n}, {field_expr}.len);");
1550                    } else {
1551                        let _ = writeln!(out, "    {{");
1552                        let _ = writeln!(
1553                            out,
1554                            "        var _cparse = try std.json.parseFromSlice(std.json.Value, std.heap.c_allocator, {field_expr}, .{{}});"
1555                        );
1556                        let _ = writeln!(out, "        defer _cparse.deinit();");
1557                        let _ = writeln!(
1558                            out,
1559                            "        try testing.expectEqual({n}, _cparse.value.array.items.len);"
1560                        );
1561                        let _ = writeln!(out, "    }}");
1562                    }
1563                }
1564            }
1565        }
1566        "is_true" => {
1567            let _ = writeln!(out, "    try testing.expect({field_expr});");
1568        }
1569        "is_false" => {
1570            let _ = writeln!(out, "    try testing.expect(!{field_expr});");
1571        }
1572        "not_error" => {
1573            // Already handled by the call succeeding.
1574        }
1575        "error" => {
1576            // Handled at the test function level.
1577        }
1578        "greater_than" => {
1579            if let Some(val) = &assertion.value {
1580                let zig_val = json_to_zig(val);
1581                let _ = writeln!(out, "    try testing.expect({field_expr} > {zig_val});");
1582            }
1583        }
1584        "less_than" => {
1585            if let Some(val) = &assertion.value {
1586                let zig_val = json_to_zig(val);
1587                let _ = writeln!(out, "    try testing.expect({field_expr} < {zig_val});");
1588            }
1589        }
1590        "greater_than_or_equal" => {
1591            if let Some(val) = &assertion.value {
1592                let zig_val = json_to_zig(val);
1593                let _ = writeln!(out, "    try testing.expect({field_expr} >= {zig_val});");
1594            }
1595        }
1596        "less_than_or_equal" => {
1597            if let Some(val) = &assertion.value {
1598                let zig_val = json_to_zig(val);
1599                let _ = writeln!(out, "    try testing.expect({field_expr} <= {zig_val});");
1600            }
1601        }
1602        "contains_any" => {
1603            // At least ONE of the values must be found in the field (OR logic).
1604            if let Some(values) = &assertion.values {
1605                let string_values: Vec<String> = values
1606                    .iter()
1607                    .filter_map(|v| {
1608                        if let serde_json::Value::String(s) = v {
1609                            Some(format!(
1610                                "std.mem.indexOf(u8, {field_expr}, \"{}\") != null",
1611                                escape_zig(s)
1612                            ))
1613                        } else {
1614                            None
1615                        }
1616                    })
1617                    .collect();
1618                if !string_values.is_empty() {
1619                    let condition = string_values.join(" or\n        ");
1620                    let _ = writeln!(out, "    try testing.expect(\n        {condition}\n    );");
1621                }
1622            }
1623        }
1624        "matches_regex" => {
1625            let _ = writeln!(out, "    // regex match not yet implemented for Zig");
1626        }
1627        "method_result" => {
1628            let _ = writeln!(out, "    // method_result assertions not yet implemented for Zig");
1629        }
1630        other => {
1631            panic!("Zig e2e generator: unsupported assertion type: {other}");
1632        }
1633    }
1634}
1635
1636/// Convert a `serde_json::Value` to a Zig literal string.
1637fn json_to_zig(value: &serde_json::Value) -> String {
1638    match value {
1639        serde_json::Value::String(s) => format!("\"{}\"", escape_zig(s)),
1640        serde_json::Value::Bool(b) => b.to_string(),
1641        serde_json::Value::Number(n) => n.to_string(),
1642        serde_json::Value::Null => "null".to_string(),
1643        serde_json::Value::Array(arr) => {
1644            let items: Vec<String> = arr.iter().map(json_to_zig).collect();
1645            format!("&.{{{}}}", items.join(", "))
1646        }
1647        serde_json::Value::Object(_) => {
1648            let json_str = serde_json::to_string(value).unwrap_or_default();
1649            format!("\"{}\"", escape_zig(&json_str))
1650        }
1651    }
1652}