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    // Emit GPA allocator only when it will actually be used: setup lines that
683    // need GPA allocation (mock_url), or a JSON-struct result path where the test
684    // will call `std.json.parseFromSlice`. The binding is not needed for
685    // error-only paths or tests with no field assertions.
686    // Note: `bytes` arg setup uses c_allocator directly and does NOT require GPA.
687    // For the streaming-virtual path, `allocator` is only needed if there are also
688    // non-streaming assertions that require JSON parsing via parseFromSlice.
689    let needs_gpa = setup_needs_gpa
690        || streaming_path_has_non_streaming
691        || (!uses_streaming_virtual_path && result_is_json_struct && !expects_error && any_happy_emits_code)
692        || (!uses_streaming_virtual_path && result_is_json_struct && expects_error && any_non_error_emits_code);
693    if needs_gpa {
694        let _ = writeln!(out, "    var gpa: std.heap.DebugAllocator(.{{}}) = .init;");
695        let _ = writeln!(out, "    defer _ = gpa.deinit();");
696        let _ = writeln!(out, "    const allocator = gpa.allocator();");
697        let _ = writeln!(out);
698    }
699
700    for line in &setup_lines {
701        let _ = writeln!(out, "    {line}");
702    }
703
704    // Client factory: when configured, instantiate a client object via the named
705    // constructor function and call the method on the instance.
706    // The client is pointed at MOCK_SERVER_URL/fixtures/<id> (mirrors go.rs:981-1028).
707    // When not configured, fall back to calling the top-level package function directly.
708    let call_prefix = if let Some(factory) = client_factory {
709        let fixture_id = &fixture.id;
710        let _ = writeln!(
711            out,
712            "    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);"
713        );
714        let _ = writeln!(out, "    defer std.heap.c_allocator.free(_mock_url);");
715        let _ = writeln!(
716            out,
717            "    var _client = try {module_name}.{factory}(\"test-key\", _mock_url, null, null, null);"
718        );
719        let _ = writeln!(out, "    defer _client.free();");
720        "_client".to_string()
721    } else {
722        module_name.to_string()
723    };
724
725    if expects_error {
726        // Error-path test: use error union syntax `!T` and try-catch.
727        // Async functions execute via tokio::runtime::block_on in the FFI shim,
728        // so the call site is synchronous from Zig's perspective.
729        if result_is_json_struct {
730            let _ = writeln!(
731                out,
732                "    const _result_json = {call_prefix}.{function_name}({args_str}) catch {{"
733            );
734        } else {
735            let _ = writeln!(
736                out,
737                "    const result = {call_prefix}.{function_name}({args_str}) catch {{"
738            );
739        }
740        let _ = writeln!(out, "        try testing.expect(true); // Error occurred as expected");
741        let _ = writeln!(out, "        return;");
742        let _ = writeln!(out, "    }};");
743        // Whether any non-error assertion will emit code that references `result`.
744        // If not, we must explicitly discard `result` to satisfy Zig's
745        // strict-unused-locals rule.
746        let any_emits_code = fixture
747            .assertions
748            .iter()
749            .filter(|a| a.assertion_type != "error")
750            .any(|a| assertion_emits_code(a, field_resolver));
751        if result_is_json_struct && any_emits_code {
752            let _ = writeln!(out, "    defer std.heap.c_allocator.free(_result_json);");
753            let _ = writeln!(
754                out,
755                "    var _parsed = try std.json.parseFromSlice(std.json.Value, allocator, _result_json, .{{}});"
756            );
757            let _ = writeln!(out, "    defer _parsed.deinit();");
758            let _ = writeln!(out, "    const {result_var} = &_parsed.value;");
759            let _ = writeln!(out, "    // Perform success assertions if any");
760            for assertion in &fixture.assertions {
761                if assertion.assertion_type != "error" {
762                    render_json_assertion(out, assertion, result_var, field_resolver);
763                }
764            }
765        } else if result_is_json_struct {
766            let _ = writeln!(out, "    _ = _result_json;");
767        } else if any_emits_code {
768            let _ = writeln!(out, "    // Perform success assertions if any");
769            for assertion in &fixture.assertions {
770                if assertion.assertion_type != "error" {
771                    render_assertion(
772                        out,
773                        assertion,
774                        result_var,
775                        field_resolver,
776                        enum_fields,
777                        result_is_option,
778                    );
779                }
780            }
781        } else {
782            let _ = writeln!(out, "    _ = result;");
783        }
784    } else if fixture.assertions.is_empty() {
785        // No assertions: emit a call to verify compilation.
786        if result_is_json_struct {
787            let _ = writeln!(
788                out,
789                "    const _result_json = try {call_prefix}.{function_name}({args_str});"
790            );
791            let _ = writeln!(out, "    defer std.heap.c_allocator.free(_result_json);");
792        } else {
793            let _ = writeln!(out, "    _ = try {call_prefix}.{function_name}({args_str});");
794        }
795    } else {
796        // Happy path: call and assert. Detect whether any assertion actually
797        // emits code that references `result` (some — like `not_error` — emit
798        // nothing) so we don't leave an unused local, which Zig 0.16 rejects.
799        let any_emits_code = fixture
800            .assertions
801            .iter()
802            .any(|a| assertion_emits_code(a, field_resolver));
803        if call_result_is_bytes && client_factory.is_some() {
804            // Bytes path: the function returns raw `[]u8` (audio/file bytes), not
805            // a JSON struct. Call, defer-free, then check len for not_empty/is_empty.
806            let _ = writeln!(
807                out,
808                "    const _result_json = try {call_prefix}.{function_name}({args_str});"
809            );
810            let _ = writeln!(out, "    defer std.heap.c_allocator.free(_result_json);");
811            let has_bytes_assertions = fixture
812                .assertions
813                .iter()
814                .any(|a| matches!(a.assertion_type.as_str(), "not_empty" | "is_empty"));
815            if has_bytes_assertions {
816                for assertion in &fixture.assertions {
817                    match assertion.assertion_type.as_str() {
818                        "not_empty" => {
819                            let _ = writeln!(out, "    try testing.expect(_result_json.len > 0);");
820                        }
821                        "is_empty" => {
822                            let _ = writeln!(out, "    try testing.expectEqual(@as(usize, 0), _result_json.len);");
823                        }
824                        "not_error" | "error" => {}
825                        _ => {
826                            let atype = &assertion.assertion_type;
827                            let _ = writeln!(
828                                out,
829                                "    // bytes result: assertion '{atype}' not implemented for zig bytes"
830                            );
831                        }
832                    }
833                }
834            }
835        } else if result_is_json_struct {
836            // When streaming-virtual field assertions are present (pre-computed above),
837            // emit raw FFI code to collect all chunks instead of calling
838            // `chat_stream` (which only returns the last chunk's JSON).
839            if uses_streaming_virtual_path {
840                let request_from_json = format!("{ffi_prefix}_chat_completion_request_from_json");
841                let request_free = format!("{ffi_prefix}_chat_completion_request_free");
842                let stream_start = format!("{ffi_prefix}_default_client_chat_stream_start");
843                let stream_free = format!("{ffi_prefix}_default_client_chat_stream_free");
844                let client_c_type = format!("{}DefaultClient", ffi_prefix.to_shouty_snake_case());
845
846                // Streaming-virtual path: inline FFI collect.
847                // Build a sentinel-terminated request string.
848                let _ = writeln!(
849                    out,
850                    "    const _req_z = try std.heap.c_allocator.dupeZ(u8, {args_str});"
851                );
852                let _ = writeln!(out, "    defer std.heap.c_allocator.free(_req_z);");
853                let _ = writeln!(
854                    out,
855                    "    const _req_handle = {module_name}.c.{request_from_json}(_req_z.ptr);"
856                );
857                let _ = writeln!(out, "    defer {module_name}.c.{request_free}(_req_handle);");
858                let _ = writeln!(
859                    out,
860                    "    const _stream_handle = {module_name}.c.{stream_start}(@as(*{module_name}.c.{client_c_type}, @ptrCast(_client._handle)), _req_handle);"
861                );
862                let _ = writeln!(out, "    if (_stream_handle == null) return error.StreamStartFailed;");
863                let _ = writeln!(out, "    defer {module_name}.c.{stream_free}(_stream_handle);");
864                // Emit the collect snippet (already has 4-space indentation baked in).
865                let snip =
866                    StreamingFieldResolver::collect_snippet_zig("_stream_handle", "chunks", module_name, ffi_prefix);
867                out.push_str("    ");
868                out.push_str(&snip);
869                out.push('\n');
870                // For non-streaming assertions (e.g. usage), we also need _result_json.
871                // Re-serialize the last chunk in `chunks` to get the JSON.
872                if streaming_path_has_non_streaming {
873                    let _ = writeln!(
874                        out,
875                        "    const _result_json = if (chunks.items.len > 0) chunks.items[chunks.items.len - 1] else &[_]u8{{}};"
876                    );
877                    let _ = writeln!(
878                        out,
879                        "    var _parsed = try std.json.parseFromSlice(std.json.Value, allocator, _result_json, .{{}});"
880                    );
881                    let _ = writeln!(out, "    defer _parsed.deinit();");
882                    let _ = writeln!(out, "    const {result_var} = &_parsed.value;");
883                }
884                for assertion in &fixture.assertions {
885                    render_json_assertion(out, assertion, result_var, field_resolver);
886                }
887            } else {
888                // JSON struct path: parse result JSON and access fields dynamically.
889                let _ = writeln!(
890                    out,
891                    "    const _result_json = try {call_prefix}.{function_name}({args_str});"
892                );
893                let _ = writeln!(out, "    defer std.heap.c_allocator.free(_result_json);");
894                if any_emits_code {
895                    let _ = writeln!(
896                        out,
897                        "    var _parsed = try std.json.parseFromSlice(std.json.Value, allocator, _result_json, .{{}});"
898                    );
899                    let _ = writeln!(out, "    defer _parsed.deinit();");
900                    let _ = writeln!(out, "    const {result_var} = &_parsed.value;");
901                    for assertion in &fixture.assertions {
902                        render_json_assertion(out, assertion, result_var, field_resolver);
903                    }
904                }
905            }
906        } else if any_emits_code {
907            let _ = writeln!(
908                out,
909                "    const {result_var} = try {call_prefix}.{function_name}({args_str});"
910            );
911            for assertion in &fixture.assertions {
912                render_assertion(
913                    out,
914                    assertion,
915                    result_var,
916                    field_resolver,
917                    enum_fields,
918                    result_is_option,
919                );
920            }
921        } else {
922            let _ = writeln!(out, "    _ = try {call_prefix}.{function_name}({args_str});");
923        }
924    }
925
926    let _ = writeln!(out, "}}");
927}
928
929// ---------------------------------------------------------------------------
930// JSON-struct assertion rendering (for result_is_json_struct = true)
931// ---------------------------------------------------------------------------
932
933/// Convert a dot-separated field path into a chain of `std.json.Value` lookups.
934///
935/// Each segment uses `.object.get("key").?` to traverse the JSON object tree.
936/// The final segment stops before the leaf-type accessor so callers can append
937/// the appropriate accessor (`.string`, `.integer`, `.array.items`, etc.).
938///
939/// Returns `(base_expr, last_key)` where `base_expr` already includes all
940/// intermediate `.object.get("…").?` dereferences up to (but not including)
941/// the leaf, and `last_key` is the last path segment.
942/// Variant names of `FormatMetadata` (snake_case, from `#[serde(rename_all = "snake_case")]`).
943/// These appear as typed accessors in fixture paths (e.g. `format.excel.sheet_count`)
944/// but are NOT JSON keys — `FormatMetadata` is internally tagged so variant fields are
945/// flattened directly into the `format` object alongside the `format_type` discriminant.
946const FORMAT_METADATA_VARIANTS: &[&str] = &[
947    "pdf",
948    "docx",
949    "excel",
950    "email",
951    "pptx",
952    "archive",
953    "image",
954    "xml",
955    "text",
956    "html",
957    "ocr",
958    "csv",
959    "bibtex",
960    "citation",
961    "fiction_book",
962    "dbf",
963    "jats",
964    "epub",
965    "pst",
966    "code",
967];
968
969fn json_path_expr(result_var: &str, field_path: &str) -> String {
970    let segments: Vec<&str> = field_path.split('.').collect();
971    let mut expr = result_var.to_string();
972    let mut prev_seg: Option<&str> = None;
973    for seg in &segments {
974        // Skip variant-name accessor segments that follow a `format` key.
975        // FormatMetadata is an internally-tagged enum (`#[serde(tag = "format_type")]`),
976        // so variant fields are flattened directly into the format object — there is no
977        // intermediate JSON key for the variant name.
978        if prev_seg == Some("format") && FORMAT_METADATA_VARIANTS.contains(seg) {
979            prev_seg = Some(seg);
980            continue;
981        }
982        // Handle array accessor notation:
983        //   "links[]"     → access the array, then first element.
984        //   "results[0]"  → access the array, then specific index N.
985        if let Some(key) = seg.strip_suffix("[]") {
986            expr = format!("{expr}.object.get(\"{key}\").?.array.items[0]");
987        } else if let Some(bracket_pos) = seg.find('[') {
988            if let Some(end_pos) = seg.find(']') {
989                if end_pos > bracket_pos + 1 && end_pos == seg.len() - 1 {
990                    let key = &seg[..bracket_pos];
991                    let idx = &seg[bracket_pos + 1..end_pos];
992                    if idx.chars().all(|c| c.is_ascii_digit()) {
993                        expr = format!("{expr}.object.get(\"{key}\").?.array.items[{idx}]");
994                        prev_seg = Some(seg);
995                        continue;
996                    }
997                }
998            }
999            expr = format!("{expr}.object.get(\"{seg}\").?");
1000        } else {
1001            expr = format!("{expr}.object.get(\"{seg}\").?");
1002        }
1003        prev_seg = Some(seg);
1004    }
1005    expr
1006}
1007
1008/// Render a single assertion for a JSON-struct result (result_is_json_struct = true).
1009///
1010/// The `result_var` variable is `*std.json.Value` (pointer to the parsed root object).
1011/// Field paths are traversed via `.object.get("key").?` chains.
1012fn render_json_assertion(out: &mut String, assertion: &Assertion, result_var: &str, field_resolver: &FieldResolver) {
1013    // Intercept streaming-virtual fields before the result-type validity check.
1014    if let Some(f) = &assertion.field {
1015        if !f.is_empty() && is_streaming_virtual_field(f) {
1016            if let Some(expr) = StreamingFieldResolver::accessor(f, "zig", "chunks") {
1017                match assertion.assertion_type.as_str() {
1018                    "count_min" => {
1019                        if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1020                            let _ = writeln!(out, "    try testing.expect({expr}.len >= {n});");
1021                        }
1022                    }
1023                    "count_equals" => {
1024                        if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1025                            let _ = writeln!(out, "    try testing.expectEqual(@as(usize, {n}), {expr}.len);");
1026                        }
1027                    }
1028                    "equals" => {
1029                        if let Some(serde_json::Value::String(s)) = &assertion.value {
1030                            let escaped = escape_zig(s);
1031                            let _ = writeln!(out, "    try testing.expectEqualStrings(\"{escaped}\", {expr});");
1032                        } else if let Some(v) = &assertion.value {
1033                            let zig_val = json_to_zig(v);
1034                            let _ = writeln!(out, "    try testing.expectEqual({zig_val}, {expr});");
1035                        }
1036                    }
1037                    "not_empty" => {
1038                        let _ = writeln!(out, "    try testing.expect({expr}.len > 0);");
1039                    }
1040                    "is_true" => {
1041                        let _ = writeln!(out, "    try testing.expect({expr});");
1042                    }
1043                    "is_false" => {
1044                        let _ = writeln!(out, "    try testing.expect(!{expr});");
1045                    }
1046                    _ => {
1047                        let atype = &assertion.assertion_type;
1048                        let _ = writeln!(
1049                            out,
1050                            "    // streaming virtual field '{f}' assertion '{atype}' not implemented for zig"
1051                        );
1052                    }
1053                }
1054            }
1055            return;
1056        }
1057    }
1058
1059    // Synthetic `embeddings` field on a JSON-array result (e.g. embed_texts
1060    // returns `Vec<Vec<f32>>` → JSON `[[...],[...]]`). The field name is a
1061    // convention from the fixture schema — the JSON value IS the embeddings
1062    // array. Apply the assertion against `result.array.items` directly. The
1063    // synthetic path is only used when no explicit result_fields configure
1064    // `embeddings` as a real struct field.
1065    if let Some(f) = &assertion.field {
1066        if f == "embeddings" && !field_resolver.has_explicit_field("embeddings") {
1067            match assertion.assertion_type.as_str() {
1068                "count_min" => {
1069                    if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1070                        let _ = writeln!(out, "    try testing.expect({result_var}.array.items.len >= {n});");
1071                    }
1072                    return;
1073                }
1074                "count_equals" => {
1075                    if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1076                        let _ = writeln!(
1077                            out,
1078                            "    try testing.expectEqual(@as(usize, {n}), {result_var}.array.items.len);"
1079                        );
1080                    }
1081                    return;
1082                }
1083                "not_empty" => {
1084                    let _ = writeln!(out, "    try testing.expect({result_var}.array.items.len > 0);");
1085                    return;
1086                }
1087                "is_empty" => {
1088                    let _ = writeln!(
1089                        out,
1090                        "    try testing.expectEqual(@as(usize, 0), {result_var}.array.items.len);"
1091                    );
1092                    return;
1093                }
1094                _ => {}
1095            }
1096        }
1097    }
1098
1099    // Skip assertions on fields that don't exist on the result type.
1100    if let Some(f) = &assertion.field {
1101        if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
1102            let _ = writeln!(out, "    // skipped: field '{f}' not available on result type");
1103            return;
1104        }
1105    }
1106    // error/not_error are handled at the call level, not assertion level.
1107    if matches!(assertion.assertion_type.as_str(), "not_error" | "error") {
1108        return;
1109    }
1110
1111    let raw_field_path = assertion.field.as_deref().unwrap_or("").trim();
1112    let field_path = if raw_field_path.is_empty() {
1113        raw_field_path.to_string()
1114    } else {
1115        field_resolver.resolve(raw_field_path).to_string()
1116    };
1117    let field_path = field_path.trim();
1118
1119    // "{array_field}.length" → strip suffix; use .array.items.len in the template.
1120    let (field_path_for_expr, is_length_access) = if let Some(parent) = field_path.strip_suffix(".length") {
1121        (parent, true)
1122    } else {
1123        (field_path, false)
1124    };
1125
1126    let field_expr = if field_path_for_expr.is_empty() {
1127        result_var.to_string()
1128    } else {
1129        json_path_expr(result_var, field_path_for_expr)
1130    };
1131
1132    // Compute context variables for the template.
1133    let zig_val = match &assertion.value {
1134        Some(serde_json::Value::String(s)) => format!("\"{}\"", escape_zig(s)),
1135        _ => String::new(),
1136    };
1137    let is_string_val = matches!(&assertion.value, Some(serde_json::Value::String(_)));
1138    let is_bool_val = matches!(&assertion.value, Some(serde_json::Value::Bool(_)));
1139    let bool_val = match &assertion.value {
1140        Some(serde_json::Value::Bool(b)) if *b => "true",
1141        _ => "false",
1142    };
1143    let is_null_val = matches!(&assertion.value, Some(serde_json::Value::Null));
1144    let n = assertion.value.as_ref().map(json_to_zig).unwrap_or_default();
1145    let has_n = assertion.value.as_ref().is_some_and(|v| v.is_number() || v.is_u64());
1146    // Distinguish float vs integer JSON values: `std.json.Value` exposes
1147    // `.integer` (i64) and `.float` (f64) as separate variants. Comparing
1148    // `.integer` against a literal with a fractional part (e.g. `0.9`) is a
1149    // Zig compile error, so the template must select the right tag.
1150    let is_float_val = matches!(&assertion.value, Some(serde_json::Value::Number(n)) if !n.is_i64() && !n.is_u64());
1151    let values_list: Vec<String> = assertion
1152        .values
1153        .as_deref()
1154        .unwrap_or_default()
1155        .iter()
1156        .filter_map(|v| {
1157            if let serde_json::Value::String(s) = v {
1158                Some(format!("\"{}\"", escape_zig(s)))
1159            } else {
1160                None
1161            }
1162        })
1163        .collect();
1164
1165    let rendered = crate::template_env::render(
1166        "zig/json_assertion.jinja",
1167        minijinja::context! {
1168            assertion_type => assertion.assertion_type.as_str(),
1169            field_expr => field_expr,
1170            is_length_access => is_length_access,
1171            zig_val => zig_val,
1172            is_string_val => is_string_val,
1173            is_bool_val => is_bool_val,
1174            bool_val => bool_val,
1175            is_null_val => is_null_val,
1176            n => n,
1177            has_n => has_n,
1178            is_float_val => is_float_val,
1179            values_list => values_list,
1180        },
1181    );
1182    out.push_str(&rendered);
1183}
1184
1185/// Predicate matching `render_assertion`: returns true when the assertion
1186/// would emit at least one statement that references the result variable.
1187fn assertion_emits_code(assertion: &Assertion, field_resolver: &FieldResolver) -> bool {
1188    if let Some(f) = &assertion.field {
1189        if !f.is_empty() && is_streaming_virtual_field(f) {
1190            // Streaming virtual fields always emit code — they are handled in a
1191            // dedicated collect path, not skipped.
1192        } else if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
1193            return false;
1194        }
1195    }
1196    matches!(
1197        assertion.assertion_type.as_str(),
1198        "equals"
1199            | "contains"
1200            | "contains_all"
1201            | "not_contains"
1202            | "not_empty"
1203            | "is_empty"
1204            | "starts_with"
1205            | "ends_with"
1206            | "min_length"
1207            | "max_length"
1208            | "count_min"
1209            | "count_equals"
1210            | "is_true"
1211            | "is_false"
1212            | "greater_than"
1213            | "less_than"
1214            | "greater_than_or_equal"
1215            | "less_than_or_equal"
1216            | "contains_any"
1217    )
1218}
1219
1220/// Build setup lines and the argument list for the function call.
1221///
1222/// Returns `(setup_lines, args_str, setup_needs_gpa)` where `setup_needs_gpa`
1223/// is `true` when at least one setup line requires the GPA `allocator` binding.
1224fn build_args_and_setup(
1225    input: &serde_json::Value,
1226    args: &[crate::config::ArgMapping],
1227    fixture_id: &str,
1228    _module_name: &str,
1229) -> (Vec<String>, String, bool) {
1230    if args.is_empty() {
1231        return (Vec::new(), String::new(), false);
1232    }
1233
1234    let mut setup_lines: Vec<String> = Vec::new();
1235    let mut parts: Vec<String> = Vec::new();
1236    let mut setup_needs_gpa = false;
1237
1238    for arg in args {
1239        if arg.arg_type == "mock_url" {
1240            let name = arg.name.clone();
1241            let id_upper = fixture_id.to_uppercase();
1242            setup_lines.push(format!(
1243                "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\"}});"
1244            ));
1245            setup_lines.push(format!("defer allocator.free({name});"));
1246            parts.push(name);
1247            setup_needs_gpa = true;
1248            continue;
1249        }
1250
1251        // Handle args (engine handle): serialize config to JSON string literal, or null.
1252        // The Zig binding accepts ?[]const u8 for engine params (creates handle internally).
1253        if arg.arg_type == "handle" {
1254            let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1255            let json_str = match input.get(field) {
1256                Some(serde_json::Value::Null) | None => "null".to_string(),
1257                Some(v) => format!("\"{}\"", escape_zig(&serde_json::to_string(v).unwrap_or_default())),
1258            };
1259            parts.push(json_str);
1260            continue;
1261        }
1262
1263        // The Zig wrapper accepts struct parameters (e.g. `ExtractionConfig`)
1264        // as JSON `[]const u8`, converting them to opaque FFI handles via the
1265        // `<prefix>_<snake>_from_json` helper at the binding layer. Emit the
1266        // fixture's configuration value as a JSON string literal, falling back
1267        // to `"{}"` when the fixture omits a config so callers exercise the
1268        // default path.
1269        if arg.name == "config" && arg.arg_type == "json_object" {
1270            let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1271            let json_str = match input.get(field) {
1272                Some(serde_json::Value::Null) | None => "{}".to_string(),
1273                Some(v) => serde_json::to_string(v).unwrap_or_else(|_| "{}".to_string()),
1274            };
1275            parts.push(format!("\"{}\"", escape_zig(&json_str)));
1276            continue;
1277        }
1278
1279        let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1280        // When `field` is empty or refers to `input` itself (no dotted subfield),
1281        // the entire fixture `input` value is the payload — most commonly for
1282        // `json_object` request bodies (chat/embed/etc.). Without this guard
1283        // `input.get("input")` returns `None` and we fall through to `"{}"`,
1284        // which the FFI rejects as a deserialization error.
1285        let val = if field.is_empty() || field == "input" {
1286            Some(input)
1287        } else {
1288            input.get(field)
1289        };
1290        match val {
1291            None | Some(serde_json::Value::Null) if arg.optional => {
1292                // Zig functions don't have default arguments, so we must
1293                // pass `null` explicitly for every optional parameter.
1294                parts.push("null".to_string());
1295            }
1296            None | Some(serde_json::Value::Null) => {
1297                let default_val = match arg.arg_type.as_str() {
1298                    "string" => "\"\"".to_string(),
1299                    "int" | "integer" => "0".to_string(),
1300                    "float" | "number" => "0.0".to_string(),
1301                    "bool" | "boolean" => "false".to_string(),
1302                    "json_object" => "\"{}\"".to_string(),
1303                    _ => "null".to_string(),
1304                };
1305                parts.push(default_val);
1306            }
1307            Some(v) => {
1308                // For `json_object` arguments other than `config` (handled
1309                // above) the Zig binding accepts a JSON `[]const u8`, so we
1310                // serialize the entire fixture value as a single JSON string
1311                // literal rather than rendering it as a Zig array/struct.
1312                if arg.arg_type == "json_object" {
1313                    let json_str = serde_json::to_string(v).unwrap_or_default();
1314                    parts.push(format!("\"{}\"", escape_zig(&json_str)));
1315                } else if arg.arg_type == "bytes" {
1316                    // `bytes` args are file paths in fixtures — read the file into a
1317                    // local buffer. The cwd is set to test_documents/ at runtime.
1318                    // Zig 0.16 uses std.Io.Dir.cwd() (not std.fs.cwd()) and requires
1319                    // an `io` instance from std.testing.io in test context.
1320                    if let serde_json::Value::String(path) = v {
1321                        let var_name = format!("{}_bytes", arg.name);
1322                        let epath = escape_zig(path);
1323                        setup_lines.push(format!(
1324                            "const {var_name} = try std.Io.Dir.cwd().readFileAlloc(std.testing.io, \"{epath}\", std.heap.c_allocator, .unlimited);"
1325                        ));
1326                        setup_lines.push(format!("defer std.heap.c_allocator.free({var_name});"));
1327                        parts.push(var_name);
1328                    } else {
1329                        parts.push(json_to_zig(v));
1330                    }
1331                } else {
1332                    parts.push(json_to_zig(v));
1333                }
1334            }
1335        }
1336    }
1337
1338    (setup_lines, parts.join(", "), setup_needs_gpa)
1339}
1340
1341fn render_assertion(
1342    out: &mut String,
1343    assertion: &Assertion,
1344    result_var: &str,
1345    field_resolver: &FieldResolver,
1346    enum_fields: &HashSet<String>,
1347    result_is_option: bool,
1348) {
1349    // Bare-result assertions on `?T` (Optional) translate to null-checks instead
1350    // of `.len`. Mirrors the same behaviour in kotlin.rs (bare_result_is_option).
1351    let bare_result_is_option = result_is_option && assertion.field.as_deref().filter(|f| !f.is_empty()).is_none();
1352    if bare_result_is_option {
1353        match assertion.assertion_type.as_str() {
1354            "is_empty" => {
1355                let _ = writeln!(out, "    try testing.expect({result_var} == null);");
1356                return;
1357            }
1358            "not_empty" | "not_error" => {
1359                let _ = writeln!(out, "    try testing.expect({result_var} != null);");
1360                return;
1361            }
1362            _ => {}
1363        }
1364    }
1365    // Synthetic-field 'embeddings' on a JSON-bytes result (e.g. embed_texts
1366    // returns `Vec<Vec<f32>>` serialised as JSON). Parse the JSON array and
1367    // apply count_min/count_equals/not_empty/is_empty against the element count.
1368    if let Some(f) = &assertion.field {
1369        if f == "embeddings" && !field_resolver.is_valid_for_result(f) {
1370            match assertion.assertion_type.as_str() {
1371                "count_min" | "count_equals" | "not_empty" | "is_empty" => {
1372                    let _ = writeln!(out, "    {{");
1373                    let _ = writeln!(
1374                        out,
1375                        "        var _eparse = try std.json.parseFromSlice(std.json.Value, std.heap.c_allocator, {result_var}, .{{}});"
1376                    );
1377                    let _ = writeln!(out, "        defer _eparse.deinit();");
1378                    let _ = writeln!(out, "        const _embeddings_len = _eparse.value.array.items.len;");
1379                    match assertion.assertion_type.as_str() {
1380                        "count_min" => {
1381                            if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1382                                let _ = writeln!(out, "        try testing.expect(_embeddings_len >= {n});");
1383                            }
1384                        }
1385                        "count_equals" => {
1386                            if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1387                                let _ = writeln!(
1388                                    out,
1389                                    "        try testing.expectEqual(@as(usize, {n}), _embeddings_len);"
1390                                );
1391                            }
1392                        }
1393                        "not_empty" => {
1394                            let _ = writeln!(out, "        try testing.expect(_embeddings_len > 0);");
1395                        }
1396                        "is_empty" => {
1397                            let _ = writeln!(out, "        try testing.expectEqual(@as(usize, 0), _embeddings_len);");
1398                        }
1399                        _ => {}
1400                    }
1401                    let _ = writeln!(out, "    }}");
1402                    return;
1403                }
1404                _ => {}
1405            }
1406        }
1407    }
1408
1409    // Skip assertions on fields that don't exist on the result type.
1410    if let Some(f) = &assertion.field {
1411        if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
1412            let _ = writeln!(out, "    // skipped: field '{{f}}' not available on result type");
1413            return;
1414        }
1415    }
1416
1417    // Determine if this field is an enum type.
1418    let _field_is_enum = assertion
1419        .field
1420        .as_deref()
1421        .is_some_and(|f| enum_fields.contains(f) || enum_fields.contains(field_resolver.resolve(f)));
1422
1423    let field_expr = match &assertion.field {
1424        Some(f) if !f.is_empty() => field_resolver.accessor(f, "zig", result_var),
1425        _ => result_var.to_string(),
1426    };
1427
1428    match assertion.assertion_type.as_str() {
1429        "equals" => {
1430            if let Some(expected) = &assertion.value {
1431                let zig_val = json_to_zig(expected);
1432                let _ = writeln!(out, "    try testing.expectEqual({zig_val}, {field_expr});");
1433            }
1434        }
1435        "contains" => {
1436            if let Some(expected) = &assertion.value {
1437                let zig_val = json_to_zig(expected);
1438                let _ = writeln!(
1439                    out,
1440                    "    try testing.expect(std.mem.indexOf(u8, {field_expr}, {zig_val}) != null);"
1441                );
1442            }
1443        }
1444        "contains_all" => {
1445            if let Some(values) = &assertion.values {
1446                for val in values {
1447                    let zig_val = json_to_zig(val);
1448                    let _ = writeln!(
1449                        out,
1450                        "    try testing.expect(std.mem.indexOf(u8, {field_expr}, {zig_val}) != null);"
1451                    );
1452                }
1453            }
1454        }
1455        "not_contains" => {
1456            if let Some(expected) = &assertion.value {
1457                let zig_val = json_to_zig(expected);
1458                let _ = writeln!(
1459                    out,
1460                    "    try testing.expect(std.mem.indexOf(u8, {field_expr}, {zig_val}) == null);"
1461                );
1462            }
1463        }
1464        "not_empty" => {
1465            let _ = writeln!(out, "    try testing.expect({field_expr}.len > 0);");
1466        }
1467        "is_empty" => {
1468            let _ = writeln!(out, "    try testing.expect({field_expr}.len == 0);");
1469        }
1470        "starts_with" => {
1471            if let Some(expected) = &assertion.value {
1472                let zig_val = json_to_zig(expected);
1473                let _ = writeln!(
1474                    out,
1475                    "    try testing.expect(std.mem.startsWith(u8, {field_expr}, {zig_val}));"
1476                );
1477            }
1478        }
1479        "ends_with" => {
1480            if let Some(expected) = &assertion.value {
1481                let zig_val = json_to_zig(expected);
1482                let _ = writeln!(
1483                    out,
1484                    "    try testing.expect(std.mem.endsWith(u8, {field_expr}, {zig_val}));"
1485                );
1486            }
1487        }
1488        "min_length" => {
1489            if let Some(val) = &assertion.value {
1490                if let Some(n) = val.as_u64() {
1491                    let _ = writeln!(out, "    try testing.expect({field_expr}.len >= {n});");
1492                }
1493            }
1494        }
1495        "max_length" => {
1496            if let Some(val) = &assertion.value {
1497                if let Some(n) = val.as_u64() {
1498                    let _ = writeln!(out, "    try testing.expect({field_expr}.len <= {n});");
1499                }
1500            }
1501        }
1502        "count_min" => {
1503            if let Some(val) = &assertion.value {
1504                if let Some(n) = val.as_u64() {
1505                    let _ = writeln!(out, "    try testing.expect({field_expr}.len >= {n});");
1506                }
1507            }
1508        }
1509        "count_equals" => {
1510            if let Some(val) = &assertion.value {
1511                if let Some(n) = val.as_u64() {
1512                    // When there is no field (field_expr == result_var), the result
1513                    // is `[]u8` JSON (e.g. batch functions). Parse the JSON array
1514                    // and count its elements; `.len` would give byte count, not item count.
1515                    let has_field = assertion.field.as_deref().is_some_and(|f| !f.is_empty());
1516                    if has_field {
1517                        let _ = writeln!(out, "    try testing.expectEqual({n}, {field_expr}.len);");
1518                    } else {
1519                        let _ = writeln!(out, "    {{");
1520                        let _ = writeln!(
1521                            out,
1522                            "        var _cparse = try std.json.parseFromSlice(std.json.Value, std.heap.c_allocator, {field_expr}, .{{}});"
1523                        );
1524                        let _ = writeln!(out, "        defer _cparse.deinit();");
1525                        let _ = writeln!(
1526                            out,
1527                            "        try testing.expectEqual({n}, _cparse.value.array.items.len);"
1528                        );
1529                        let _ = writeln!(out, "    }}");
1530                    }
1531                }
1532            }
1533        }
1534        "is_true" => {
1535            let _ = writeln!(out, "    try testing.expect({field_expr});");
1536        }
1537        "is_false" => {
1538            let _ = writeln!(out, "    try testing.expect(!{field_expr});");
1539        }
1540        "not_error" => {
1541            // Already handled by the call succeeding.
1542        }
1543        "error" => {
1544            // Handled at the test function level.
1545        }
1546        "greater_than" => {
1547            if let Some(val) = &assertion.value {
1548                let zig_val = json_to_zig(val);
1549                let _ = writeln!(out, "    try testing.expect({field_expr} > {zig_val});");
1550            }
1551        }
1552        "less_than" => {
1553            if let Some(val) = &assertion.value {
1554                let zig_val = json_to_zig(val);
1555                let _ = writeln!(out, "    try testing.expect({field_expr} < {zig_val});");
1556            }
1557        }
1558        "greater_than_or_equal" => {
1559            if let Some(val) = &assertion.value {
1560                let zig_val = json_to_zig(val);
1561                let _ = writeln!(out, "    try testing.expect({field_expr} >= {zig_val});");
1562            }
1563        }
1564        "less_than_or_equal" => {
1565            if let Some(val) = &assertion.value {
1566                let zig_val = json_to_zig(val);
1567                let _ = writeln!(out, "    try testing.expect({field_expr} <= {zig_val});");
1568            }
1569        }
1570        "contains_any" => {
1571            // At least ONE of the values must be found in the field (OR logic).
1572            if let Some(values) = &assertion.values {
1573                let string_values: Vec<String> = values
1574                    .iter()
1575                    .filter_map(|v| {
1576                        if let serde_json::Value::String(s) = v {
1577                            Some(format!(
1578                                "std.mem.indexOf(u8, {field_expr}, \"{}\") != null",
1579                                escape_zig(s)
1580                            ))
1581                        } else {
1582                            None
1583                        }
1584                    })
1585                    .collect();
1586                if !string_values.is_empty() {
1587                    let condition = string_values.join(" or\n        ");
1588                    let _ = writeln!(out, "    try testing.expect(\n        {condition}\n    );");
1589                }
1590            }
1591        }
1592        "matches_regex" => {
1593            let _ = writeln!(out, "    // regex match not yet implemented for Zig");
1594        }
1595        "method_result" => {
1596            let _ = writeln!(out, "    // method_result assertions not yet implemented for Zig");
1597        }
1598        other => {
1599            panic!("Zig e2e generator: unsupported assertion type: {other}");
1600        }
1601    }
1602}
1603
1604/// Convert a `serde_json::Value` to a Zig literal string.
1605fn json_to_zig(value: &serde_json::Value) -> String {
1606    match value {
1607        serde_json::Value::String(s) => format!("\"{}\"", escape_zig(s)),
1608        serde_json::Value::Bool(b) => b.to_string(),
1609        serde_json::Value::Number(n) => n.to_string(),
1610        serde_json::Value::Null => "null".to_string(),
1611        serde_json::Value::Array(arr) => {
1612            let items: Vec<String> = arr.iter().map(json_to_zig).collect();
1613            format!("&.{{{}}}", items.join(", "))
1614        }
1615        serde_json::Value::Object(_) => {
1616            let json_str = serde_json::to_string(value).unwrap_or_default();
1617            format!("\"{}\"", escape_zig(&json_str))
1618        }
1619    }
1620}