Skip to main content

alef_e2e/codegen/
rust.rs

1//! Rust e2e test code generator.
2//!
3//! Generates `e2e/rust/Cargo.toml` and `tests/{category}_test.rs` files from
4//! JSON fixtures, driven entirely by `E2eConfig` and `CallConfig`.
5
6use crate::codegen::resolve_field;
7use crate::config::E2eConfig;
8use crate::escape::{escape_rust, rust_raw_string, sanitize_filename, sanitize_ident};
9use crate::field_access::FieldResolver;
10use crate::fixture::{Assertion, CallbackAction, Fixture, FixtureGroup};
11use alef_core::backend::GeneratedFile;
12use alef_core::config::AlefConfig;
13use alef_core::hash::{self, CommentStyle};
14use alef_core::template_versions as tv;
15use anyhow::Result;
16use std::fmt::Write as FmtWrite;
17use std::path::PathBuf;
18
19/// Rust e2e test code generator.
20pub struct RustE2eCodegen;
21
22impl super::E2eCodegen for RustE2eCodegen {
23    fn generate(
24        &self,
25        groups: &[FixtureGroup],
26        e2e_config: &E2eConfig,
27        alef_config: &AlefConfig,
28    ) -> Result<Vec<GeneratedFile>> {
29        let mut files = Vec::new();
30        let output_base = PathBuf::from(e2e_config.effective_output()).join("rust");
31
32        // Resolve crate name and path from config.
33        let crate_name = resolve_crate_name(e2e_config, alef_config);
34        let crate_path = resolve_crate_path(e2e_config, &crate_name);
35        let dep_name = crate_name.replace('-', "_");
36
37        // Cargo.toml
38        // Check if any call config (default or named) uses json_object/handle args (needs serde_json dep).
39        let all_call_configs = std::iter::once(&e2e_config.call).chain(e2e_config.calls.values());
40        let needs_serde_json = all_call_configs
41            .flat_map(|c| c.args.iter())
42            .any(|a| a.arg_type == "json_object" || a.arg_type == "handle");
43
44        // Check if any fixture in any group requires a mock HTTP server.
45        // This includes both liter-llm mock_response fixtures and spikard http fixtures.
46        let needs_mock_server = groups
47            .iter()
48            .flat_map(|g| g.fixtures.iter())
49            .any(|f| !is_skipped(f, "rust") && f.needs_mock_server());
50
51        // Tokio is needed when any test is async (mock server or async call config).
52        let any_async_call = std::iter::once(&e2e_config.call)
53            .chain(e2e_config.calls.values())
54            .any(|c| c.r#async);
55        let needs_tokio = needs_mock_server || any_async_call;
56
57        let crate_version = resolve_crate_version(e2e_config);
58        files.push(GeneratedFile {
59            path: output_base.join("Cargo.toml"),
60            content: render_cargo_toml(
61                &crate_name,
62                &dep_name,
63                &crate_path,
64                needs_serde_json,
65                needs_mock_server,
66                needs_tokio,
67                e2e_config.dep_mode,
68                crate_version.as_deref(),
69                &alef_config.crate_config.features,
70            ),
71            generated_header: true,
72        });
73
74        // Generate mock_server.rs when at least one fixture uses mock_response.
75        if needs_mock_server {
76            files.push(GeneratedFile {
77                path: output_base.join("tests").join("mock_server.rs"),
78                content: render_mock_server_module(),
79                generated_header: true,
80            });
81            // Generate standalone mock-server binary for cross-language e2e suites.
82            files.push(GeneratedFile {
83                path: output_base.join("src").join("main.rs"),
84                content: render_mock_server_binary(),
85                generated_header: true,
86            });
87        }
88
89        // Per-category test files.
90        for group in groups {
91            let fixtures: Vec<&Fixture> = group.fixtures.iter().filter(|f| !is_skipped(f, "rust")).collect();
92
93            if fixtures.is_empty() {
94                continue;
95            }
96
97            let filename = format!("{}_test.rs", sanitize_filename(&group.category));
98            let content = render_test_file(&group.category, &fixtures, e2e_config, &dep_name, needs_mock_server);
99
100            files.push(GeneratedFile {
101                path: output_base.join("tests").join(filename),
102                content,
103                generated_header: true,
104            });
105        }
106
107        Ok(files)
108    }
109
110    fn language_name(&self) -> &'static str {
111        "rust"
112    }
113}
114
115// ---------------------------------------------------------------------------
116// Config resolution helpers
117// ---------------------------------------------------------------------------
118
119fn resolve_crate_name(_e2e_config: &E2eConfig, alef_config: &AlefConfig) -> String {
120    // Always use the Cargo package name (with hyphens) from alef.toml [crate].
121    // The `crate_name` override in [e2e.call.overrides.rust] is for the Rust
122    // import identifier, not the Cargo package name.
123    alef_config.crate_config.name.clone()
124}
125
126fn resolve_crate_path(e2e_config: &E2eConfig, crate_name: &str) -> String {
127    e2e_config
128        .resolve_package("rust")
129        .and_then(|p| p.path.clone())
130        .unwrap_or_else(|| format!("../../crates/{crate_name}"))
131}
132
133fn resolve_crate_version(e2e_config: &E2eConfig) -> Option<String> {
134    e2e_config.resolve_package("rust").and_then(|p| p.version.clone())
135}
136
137fn resolve_function_name_for_call(call_config: &crate::config::CallConfig) -> String {
138    call_config
139        .overrides
140        .get("rust")
141        .and_then(|o| o.function.clone())
142        .unwrap_or_else(|| call_config.function.clone())
143}
144
145fn resolve_module(e2e_config: &E2eConfig, dep_name: &str) -> String {
146    resolve_module_for_call(&e2e_config.call, dep_name)
147}
148
149fn resolve_module_for_call(call_config: &crate::config::CallConfig, dep_name: &str) -> String {
150    // For Rust, the module name is the crate identifier (underscores).
151    // Priority: override.crate_name > override.module > dep_name
152    let overrides = call_config.overrides.get("rust");
153    overrides
154        .and_then(|o| o.crate_name.clone())
155        .or_else(|| overrides.and_then(|o| o.module.clone()))
156        .unwrap_or_else(|| dep_name.to_string())
157}
158
159fn is_skipped(fixture: &Fixture, language: &str) -> bool {
160    fixture.skip.as_ref().is_some_and(|s| s.should_skip(language))
161}
162
163// ---------------------------------------------------------------------------
164// Rendering
165// ---------------------------------------------------------------------------
166
167#[allow(clippy::too_many_arguments)]
168pub fn render_cargo_toml(
169    crate_name: &str,
170    dep_name: &str,
171    crate_path: &str,
172    needs_serde_json: bool,
173    needs_mock_server: bool,
174    needs_tokio: bool,
175    dep_mode: crate::config::DependencyMode,
176    version: Option<&str>,
177    features: &[String],
178) -> String {
179    let e2e_name = format!("{dep_name}-e2e-rust");
180    // Use only the features explicitly configured in alef.toml.
181    // Do NOT auto-add "serde" — the target crate may not have that feature.
182    // serde_json is added as a separate dependency when needed.
183    let effective_features: Vec<&str> = features.iter().map(|s| s.as_str()).collect();
184    let features_str = if effective_features.is_empty() {
185        String::new()
186    } else {
187        format!(", default-features = false, features = {:?}", effective_features)
188    };
189    let dep_spec = match dep_mode {
190        crate::config::DependencyMode::Registry => {
191            let ver = version.unwrap_or("0.1.0");
192            if crate_name != dep_name {
193                format!("{dep_name} = {{ package = \"{crate_name}\", version = \"{ver}\"{features_str} }}")
194            } else if effective_features.is_empty() {
195                format!("{dep_name} = \"{ver}\"")
196            } else {
197                format!("{dep_name} = {{ version = \"{ver}\"{features_str} }}")
198            }
199        }
200        crate::config::DependencyMode::Local => {
201            if crate_name != dep_name {
202                format!("{dep_name} = {{ package = \"{crate_name}\", path = \"{crate_path}\"{features_str} }}")
203            } else if effective_features.is_empty() {
204                format!("{dep_name} = {{ path = \"{crate_path}\" }}")
205            } else {
206                format!("{dep_name} = {{ path = \"{crate_path}\"{features_str} }}")
207            }
208        }
209    };
210    // serde_json is needed either when args use json_object/handle, or when the
211    // mock server binary is present (it uses serde_json::Value for fixture bodies).
212    let effective_needs_serde_json = needs_serde_json || needs_mock_server;
213    let serde_line = if effective_needs_serde_json {
214        "\nserde_json = \"1\""
215    } else {
216        ""
217    };
218    // An empty `[workspace]` table makes the e2e crate its own workspace root, so
219    // it never gets pulled into a parent crate's workspace. This means consumers
220    // don't have to remember to add `e2e/rust` to `workspace.exclude`, and
221    // `cargo fmt`/`cargo build` work the same whether the parent has a
222    // workspace or not.
223    // Mock server requires axum (HTTP router) and tokio-stream (SSE streaming).
224    // The standalone binary additionally needs serde (derive) and walkdir.
225    let mock_lines = if needs_mock_server {
226        format!(
227            "\naxum = \"{axum}\"\ntokio-stream = \"{tokio_stream}\"\nserde = {{ version = \"1\", features = [\"derive\"] }}\nwalkdir = \"{walkdir}\"",
228            axum = tv::cargo::AXUM,
229            tokio_stream = tv::cargo::TOKIO_STREAM,
230            walkdir = tv::cargo::WALKDIR,
231        )
232    } else {
233        String::new()
234    };
235    let mut machete_ignored: Vec<&str> = Vec::new();
236    if effective_needs_serde_json {
237        machete_ignored.push("\"serde_json\"");
238    }
239    if needs_mock_server {
240        machete_ignored.push("\"axum\"");
241        machete_ignored.push("\"tokio-stream\"");
242        machete_ignored.push("\"serde\"");
243        machete_ignored.push("\"walkdir\"");
244    }
245    let machete_section = if machete_ignored.is_empty() {
246        String::new()
247    } else {
248        format!(
249            "\n[package.metadata.cargo-machete]\nignored = [{}]\n",
250            machete_ignored.join(", ")
251        )
252    };
253    let tokio_line = if needs_tokio {
254        "\ntokio = { version = \"1\", features = [\"full\"] }"
255    } else {
256        ""
257    };
258    let bin_section = if needs_mock_server {
259        "\n[[bin]]\nname = \"mock-server\"\npath = \"src/main.rs\"\n"
260    } else {
261        ""
262    };
263    let header = hash::header(CommentStyle::Hash);
264    format!(
265        r#"{header}
266[workspace]
267
268[package]
269name = "{e2e_name}"
270version = "0.1.0"
271edition = "2021"
272license = "MIT"
273publish = false
274{bin_section}
275[dependencies]
276{dep_spec}{serde_line}{mock_lines}{tokio_line}
277{machete_section}"#
278    )
279}
280
281fn render_test_file(
282    category: &str,
283    fixtures: &[&Fixture],
284    e2e_config: &E2eConfig,
285    dep_name: &str,
286    needs_mock_server: bool,
287) -> String {
288    let mut out = String::new();
289    out.push_str(&hash::header(CommentStyle::DoubleSlash));
290    let _ = writeln!(out, "//! E2e tests for category: {category}");
291    let _ = writeln!(out);
292
293    let module = resolve_module(e2e_config, dep_name);
294    let field_resolver = FieldResolver::new(
295        &e2e_config.fields,
296        &e2e_config.fields_optional,
297        &e2e_config.result_fields,
298        &e2e_config.fields_array,
299    );
300
301    // Collect all unique (module, function) pairs needed across all fixtures in this file.
302    // Fixtures that name a specific call may use a different function (and module) than
303    // the default [e2e.call] config.
304    let mut imported: std::collections::BTreeSet<(String, String)> = std::collections::BTreeSet::new();
305    for fixture in fixtures.iter() {
306        let call_config = e2e_config.resolve_call(fixture.call.as_deref());
307        let fn_name = resolve_function_name_for_call(call_config);
308        let mod_name = resolve_module_for_call(call_config, dep_name);
309        imported.insert((mod_name, fn_name));
310    }
311    // Emit use statements, grouping by module when possible.
312    let mut by_module: std::collections::BTreeMap<String, Vec<String>> = std::collections::BTreeMap::new();
313    for (mod_name, fn_name) in &imported {
314        by_module.entry(mod_name.clone()).or_default().push(fn_name.clone());
315    }
316    for (mod_name, fns) in &by_module {
317        if fns.len() == 1 {
318            let _ = writeln!(out, "use {mod_name}::{};", fns[0]);
319        } else {
320            let joined = fns.join(", ");
321            let _ = writeln!(out, "use {mod_name}::{{{joined}}};");
322        }
323    }
324
325    // Import handle constructor functions and the config type they use.
326    let has_handle_args = e2e_config.call.args.iter().any(|a| a.arg_type == "handle");
327    if has_handle_args {
328        let _ = writeln!(out, "use {module}::CrawlConfig;");
329    }
330    for arg in &e2e_config.call.args {
331        if arg.arg_type == "handle" {
332            use heck::ToSnakeCase;
333            let constructor_name = format!("create_{}", arg.name.to_snake_case());
334            let _ = writeln!(out, "use {module}::{constructor_name};");
335        }
336    }
337
338    // Import mock_server module when any fixture in this file uses mock_response.
339    let file_needs_mock = needs_mock_server && fixtures.iter().any(|f| f.needs_mock_server());
340    if file_needs_mock {
341        let _ = writeln!(out, "mod mock_server;");
342        let _ = writeln!(out, "use mock_server::{{MockRoute, MockServer}};");
343    }
344
345    // Import the visitor trait, result enum, and node context when any fixture
346    // in this file declares a `visitor` block. Without these, the inline
347    // `impl HtmlVisitor for _TestVisitor` block fails to resolve.
348    let file_needs_visitor = fixtures.iter().any(|f| f.visitor.is_some());
349    if file_needs_visitor {
350        let visitor_trait = resolve_visitor_trait(&module);
351        let _ = writeln!(out, "use {module}::{{{visitor_trait}, NodeContext, VisitResult}};");
352    }
353
354    let _ = writeln!(out);
355
356    for fixture in fixtures {
357        render_test_function(&mut out, fixture, e2e_config, dep_name, &field_resolver);
358        let _ = writeln!(out);
359    }
360
361    if !out.ends_with('\n') {
362        out.push('\n');
363    }
364    out
365}
366
367fn render_test_function(
368    out: &mut String,
369    fixture: &Fixture,
370    e2e_config: &E2eConfig,
371    dep_name: &str,
372    field_resolver: &FieldResolver,
373) {
374    let fn_name = sanitize_ident(&fixture.id);
375    let description = &fixture.description;
376    let call_config = e2e_config.resolve_call(fixture.call.as_deref());
377    let function_name = resolve_function_name_for_call(call_config);
378    let module = resolve_module_for_call(call_config, dep_name);
379    let result_var = &call_config.result_var;
380    let has_mock = fixture.needs_mock_server();
381
382    // Tests with a mock server are always async (Axum requires a Tokio runtime).
383    let is_async = call_config.r#async || has_mock;
384    if is_async {
385        let _ = writeln!(out, "#[tokio::test]");
386        let _ = writeln!(out, "async fn test_{fn_name}() {{");
387    } else {
388        let _ = writeln!(out, "#[test]");
389        let _ = writeln!(out, "fn test_{fn_name}() {{");
390    }
391    let _ = writeln!(out, "    // {description}");
392
393    // Emit mock server setup before building arguments so arg expressions can
394    // reference `mock_server.url` when needed.
395    if has_mock {
396        render_mock_server_setup(out, fixture, e2e_config);
397    }
398
399    // Check if any assertion is an error assertion.
400    let has_error_assertion = fixture.assertions.iter().any(|a| a.assertion_type == "error");
401
402    // Resolve Rust-specific overrides for argument shaping.
403    let rust_overrides = call_config.overrides.get("rust");
404    let wrap_options_in_some = rust_overrides.is_some_and(|o| o.wrap_options_in_some);
405    let extra_args: Vec<String> = rust_overrides.map(|o| o.extra_args.clone()).unwrap_or_default();
406
407    // Emit input variable bindings from args config.
408    let mut arg_exprs: Vec<String> = Vec::new();
409    for arg in &call_config.args {
410        let value = resolve_field(&fixture.input, &arg.field);
411        let var_name = &arg.name;
412        let (bindings, expr) = render_rust_arg(
413            var_name,
414            value,
415            &arg.arg_type,
416            arg.optional,
417            &module,
418            &fixture.id,
419            if has_mock {
420                Some("mock_server.url.as_str()")
421            } else {
422                None
423            },
424            arg.owned,
425            arg.element_type.as_deref(),
426        );
427        for binding in &bindings {
428            let _ = writeln!(out, "    {binding}");
429        }
430        // For functions whose options slot is owned `Option<T>` rather than `&T`,
431        // wrap the json_object expression in `Some(...).clone()` so it matches
432        // the parameter shape. Other arg types pass through unchanged.
433        let final_expr = if wrap_options_in_some && arg.arg_type == "json_object" {
434            if let Some(rest) = expr.strip_prefix('&') {
435                format!("Some({rest}.clone())")
436            } else {
437                format!("Some({expr})")
438            }
439        } else {
440            expr
441        };
442        arg_exprs.push(final_expr);
443    }
444
445    // Emit visitor if present in fixture.
446    if let Some(visitor_spec) = &fixture.visitor {
447        let _ = writeln!(out, "    struct _TestVisitor;");
448        let _ = writeln!(out, "    impl {} for _TestVisitor {{", resolve_visitor_trait(&module));
449        for (method_name, action) in &visitor_spec.callbacks {
450            emit_rust_visitor_method(out, method_name, action);
451        }
452        let _ = writeln!(out, "    }}");
453        let _ = writeln!(
454            out,
455            "    let visitor = std::rc::Rc::new(std::cell::RefCell::new(_TestVisitor));"
456        );
457        arg_exprs.push("Some(visitor)".to_string());
458    } else {
459        // No fixture-supplied visitor: append any extra positional args declared in
460        // the rust override (e.g. trailing `None` for an Option<VisitorParam> slot).
461        arg_exprs.extend(extra_args);
462    }
463
464    let args_str = arg_exprs.join(", ");
465
466    let await_suffix = if is_async { ".await" } else { "" };
467
468    let result_is_tree = call_config.result_var == "tree";
469    // When the rust override sets result_is_simple, the function returns a plain type
470    // (String, Vec<T>, etc.) — field-access assertions use the result var directly.
471    let result_is_simple = rust_overrides.is_some_and(|o| o.result_is_simple);
472    // When result_is_vec is set, the function returns Vec<T>. Field-path assertions
473    // are wrapped in `.iter().all(|r| ...)` so every element is checked.
474    let result_is_vec = rust_overrides.is_some_and(|o| o.result_is_vec);
475    // When result_is_option is set, the function returns Option<T>. Field-path
476    // assertions unwrap first via `.as_ref().expect("Option should be Some")`.
477    let result_is_option = rust_overrides.is_some_and(|o| o.result_is_option);
478
479    if has_error_assertion {
480        let _ = writeln!(out, "    let {result_var} = {function_name}({args_str}){await_suffix};");
481        // Render error assertions.
482        for assertion in &fixture.assertions {
483            render_assertion(
484                out,
485                assertion,
486                result_var,
487                &module,
488                dep_name,
489                true,
490                &[],
491                field_resolver,
492                result_is_tree,
493                result_is_simple,
494                false,
495                false,
496            );
497        }
498        let _ = writeln!(out, "}}");
499        return;
500    }
501
502    // Non-error path: unwrap the result.
503    let has_not_error = fixture.assertions.iter().any(|a| a.assertion_type == "not_error");
504
505    // Check if any assertion actually uses the result variable.
506    // If all assertions are skipped (field not on result type), use `_` to avoid
507    // Rust's "variable never used" warning.
508    let has_usable_assertion = fixture.assertions.iter().any(|a| {
509        if a.assertion_type == "not_error" || a.assertion_type == "error" {
510            return false;
511        }
512        if a.assertion_type == "method_result" {
513            // method_result assertions that would generate only a TODO comment don't use the
514            // result variable. These are: missing `method` field, or unsupported `check` type.
515            let supported_checks = [
516                "equals",
517                "is_true",
518                "is_false",
519                "greater_than_or_equal",
520                "count_min",
521                "is_error",
522                "contains",
523                "not_empty",
524                "is_empty",
525            ];
526            let check = a.check.as_deref().unwrap_or("is_true");
527            if a.method.is_none() || !supported_checks.contains(&check) {
528                return false;
529            }
530        }
531        match &a.field {
532            Some(f) if !f.is_empty() => field_resolver.is_valid_for_result(f),
533            _ => true,
534        }
535    });
536
537    let result_binding = if has_usable_assertion {
538        result_var.to_string()
539    } else {
540        "_".to_string()
541    };
542
543    // Detect Option-returning functions: only skip unwrap when ALL assertions are
544    // pure emptiness/bool checks with NO field access (is_none/is_some on the result itself).
545    // If any assertion accesses a field (e.g. `html`), we need the inner value, so unwrap.
546    let has_field_access = fixture
547        .assertions
548        .iter()
549        .any(|a| a.field.as_ref().is_some_and(|f| !f.is_empty()));
550    let only_emptiness_checks = !has_field_access
551        && fixture.assertions.iter().all(|a| {
552            matches!(
553                a.assertion_type.as_str(),
554                "is_empty" | "is_false" | "not_empty" | "is_true" | "not_error"
555            )
556        });
557
558    // Per-rust override of the call-level `returns_result`. When set, takes
559    // precedence over `CallConfig.returns_result` for the Rust generator only.
560    let returns_result = rust_overrides
561        .and_then(|o| o.returns_result)
562        .unwrap_or(call_config.returns_result);
563
564    let unwrap_suffix = if returns_result {
565        ".expect(\"should succeed\")"
566    } else {
567        ""
568    };
569    if only_emptiness_checks || !returns_result {
570        // Option-returning or non-Result-returning: bind raw value, no unwrap.
571        let _ = writeln!(
572            out,
573            "    let {result_binding} = {function_name}({args_str}){await_suffix};"
574        );
575    } else if has_not_error || !fixture.assertions.is_empty() {
576        let _ = writeln!(
577            out,
578            "    let {result_binding} = {function_name}({args_str}){await_suffix}{unwrap_suffix};"
579        );
580    } else {
581        let _ = writeln!(
582            out,
583            "    let {result_binding} = {function_name}({args_str}){await_suffix};"
584        );
585    }
586
587    // Emit Option field unwrap bindings for any fields accessed in assertions.
588    // Use FieldResolver to handle optional fields, including nested/aliased paths.
589    // Skipped when the call returns Vec<T>: per-element iteration is emitted by
590    // `render_assertion` itself, so the call-site has no single result struct
591    // to unwrap fields off of.
592    let string_assertion_types = [
593        "equals",
594        "contains",
595        "contains_all",
596        "contains_any",
597        "not_contains",
598        "starts_with",
599        "ends_with",
600        "min_length",
601        "max_length",
602        "matches_regex",
603    ];
604    let mut unwrapped_fields: Vec<(String, String)> = Vec::new(); // (fixture_field, local_var)
605    if !result_is_vec {
606        for assertion in &fixture.assertions {
607            if let Some(f) = &assertion.field {
608                if !f.is_empty()
609                    && string_assertion_types.contains(&assertion.assertion_type.as_str())
610                    && !unwrapped_fields.iter().any(|(ff, _)| ff == f)
611                {
612                    // Only unwrap optional string fields — numeric optionals (u64, usize)
613                    // don't support .as_deref() and should be compared directly.
614                    let is_string_assertion = assertion.value.as_ref().is_none_or(|v| v.is_string());
615                    if !is_string_assertion {
616                        continue;
617                    }
618                    if let Some((binding, local_var)) = field_resolver.rust_unwrap_binding(f, result_var) {
619                        let _ = writeln!(out, "    {binding}");
620                        unwrapped_fields.push((f.clone(), local_var));
621                    }
622                }
623            }
624        }
625    }
626
627    // Render assertions.
628    for assertion in &fixture.assertions {
629        if assertion.assertion_type == "not_error" {
630            // Already handled by .expect() above.
631            continue;
632        }
633        render_assertion(
634            out,
635            assertion,
636            result_var,
637            &module,
638            dep_name,
639            false,
640            &unwrapped_fields,
641            field_resolver,
642            result_is_tree,
643            result_is_simple,
644            result_is_vec,
645            result_is_option,
646        );
647    }
648
649    let _ = writeln!(out, "}}");
650}
651
652// ---------------------------------------------------------------------------
653// Argument rendering
654// ---------------------------------------------------------------------------
655
656#[allow(clippy::too_many_arguments)]
657fn render_rust_arg(
658    name: &str,
659    value: &serde_json::Value,
660    arg_type: &str,
661    optional: bool,
662    module: &str,
663    fixture_id: &str,
664    mock_base_url: Option<&str>,
665    owned: bool,
666    element_type: Option<&str>,
667) -> (Vec<String>, String) {
668    if arg_type == "mock_url" {
669        let lines = vec![format!(
670            "let {name} = format!(\"{{}}/fixtures/{{}}\", std::env::var(\"MOCK_SERVER_URL\").expect(\"MOCK_SERVER_URL not set\"), \"{fixture_id}\");"
671        )];
672        return (lines, format!("&{name}"));
673    }
674    // When the arg is a base_url and a mock server is running, use the mock server URL.
675    if arg_type == "base_url" {
676        if let Some(url_expr) = mock_base_url {
677            return (vec![], url_expr.to_string());
678        }
679        // No mock server: fall through to string handling below.
680    }
681    if arg_type == "handle" {
682        // Generate a create_engine (or equivalent) call and pass the config.
683        // If the fixture has input.config, serialize it as a json_object and pass it;
684        // otherwise pass None.
685        use heck::ToSnakeCase;
686        let constructor_name = format!("create_{}", name.to_snake_case());
687        let mut lines = Vec::new();
688        if value.is_null() || value.is_object() && value.as_object().unwrap().is_empty() {
689            lines.push(format!(
690                "let {name} = {constructor_name}(None).expect(\"handle creation should succeed\");"
691            ));
692        } else {
693            // Serialize the config JSON and deserialize at runtime.
694            let json_literal = serde_json::to_string(value).unwrap_or_default();
695            let escaped = json_literal.replace('\\', "\\\\").replace('"', "\\\"");
696            lines.push(format!(
697                "let {name}_config: CrawlConfig = serde_json::from_str(\"{escaped}\").expect(\"config should parse\");"
698            ));
699            lines.push(format!(
700                "let {name} = {constructor_name}(Some({name}_config)).expect(\"handle creation should succeed\");"
701            ));
702        }
703        return (lines, format!("&{name}"));
704    }
705    if arg_type == "json_object" {
706        return render_json_object_arg(name, value, optional, owned, element_type, module);
707    }
708    if value.is_null() && !optional {
709        // Required arg with no fixture value: use a language-appropriate default.
710        let default_val = match arg_type {
711            "string" => "String::new()".to_string(),
712            "int" | "integer" => "0".to_string(),
713            "float" | "number" => "0.0_f64".to_string(),
714            "bool" | "boolean" => "false".to_string(),
715            _ => "Default::default()".to_string(),
716        };
717        // String args are passed by reference in Rust.
718        let expr = if arg_type == "string" {
719            format!("&{name}")
720        } else {
721            name.to_string()
722        };
723        return (vec![format!("let {name} = {default_val};")], expr);
724    }
725    let literal = json_to_rust_literal(value, arg_type);
726    // For non-optional `string` args, the binding is an immediate `&'static str`
727    // literal — pass it directly without an extra `&` (which would yield `&&str`).
728    // Bytes args are strings passed as .as_bytes().
729    let pass_by_ref = arg_type == "bytes";
730    let optional_expr = |n: &str| {
731        if arg_type == "string" {
732            format!("{n}.as_deref()")
733        } else if arg_type == "bytes" {
734            format!("{n}.as_deref().map(|v| v.as_slice())")
735        } else {
736            // Owned numeric / bool / generic: pass the Option<T> by value.
737            // Function signature shape `Option<T>` matches without `.as_ref()`,
738            // which would produce `Option<&T>` and fail to coerce.
739            n.to_string()
740        }
741    };
742    let expr = |n: &str| {
743        if arg_type == "bytes" {
744            format!("{n}.as_bytes()")
745        } else if pass_by_ref {
746            format!("&{n}")
747        } else {
748            n.to_string()
749        }
750    };
751    if optional && value.is_null() {
752        let none_decl = match arg_type {
753            "string" => format!("let {name}: Option<String> = None;"),
754            "bytes" => format!("let {name}: Option<Vec<u8>> = None;"),
755            _ => format!("let {name} = None;"),
756        };
757        (vec![none_decl], optional_expr(name))
758    } else if optional {
759        (vec![format!("let {name} = Some({literal});")], optional_expr(name))
760    } else {
761        (vec![format!("let {name} = {literal};")], expr(name))
762    }
763}
764
765/// Render a `json_object` argument: serialize the fixture JSON as a `serde_json::json!` literal
766/// and deserialize it through serde at runtime. Type inference from the function signature
767/// determines the concrete type, keeping the generator generic.
768///
769/// `owned` — when true the binding is passed by value (no leading `&`); use for `Vec<T>` params.
770/// `element_type` — when set, emits `Vec<element_type>` annotation to satisfy type inference for
771///   `&[T]` parameters where `serde_json::from_value` cannot resolve the unsized slice type.
772fn render_json_object_arg(
773    name: &str,
774    value: &serde_json::Value,
775    optional: bool,
776    owned: bool,
777    element_type: Option<&str>,
778    _module: &str,
779) -> (Vec<String>, String) {
780    // Owned params (Vec<T>) are passed by value; ref params (most configs) use &.
781    let pass_by_ref = !owned;
782
783    if value.is_null() && optional {
784        // Use Default::default() — Rust functions take &T (or T for owned), not Option<T>.
785        let expr = if pass_by_ref {
786            format!("&{name}")
787        } else {
788            name.to_string()
789        };
790        return (vec![format!("let {name} = Default::default();")], expr);
791    }
792
793    // Fixture keys are camelCase; the Rust ConversionOptions type uses snake_case serde.
794    // Normalize keys before building the json! literal so deserialization succeeds.
795    let normalized = super::normalize_json_keys_to_snake_case(value);
796    // Build the json! macro invocation from the fixture object.
797    let json_literal = json_value_to_macro_literal(&normalized);
798    let mut lines = Vec::new();
799    lines.push(format!("let {name}_json = serde_json::json!({json_literal});"));
800
801    // When an explicit element type is given, annotate with Vec<T> so that
802    // serde_json::from_value can infer the element type for &[T] parameters (A4 fix).
803    let deser_expr = if let Some(elem) = element_type {
804        format!("serde_json::from_value::<Vec<{elem}>>({name}_json).unwrap()")
805    } else {
806        format!("serde_json::from_value({name}_json).unwrap()")
807    };
808
809    // A1 fix: always deser as T (never wrap in Some()); optional non-null args target
810    // &T not &Option<T>. Pass as &T (ref) or T (owned) depending on the `owned` flag.
811    lines.push(format!("let {name} = {deser_expr};"));
812    let expr = if pass_by_ref {
813        format!("&{name}")
814    } else {
815        name.to_string()
816    };
817    (lines, expr)
818}
819
820/// Convert a `serde_json::Value` into a string suitable for the `serde_json::json!()` macro.
821fn json_value_to_macro_literal(value: &serde_json::Value) -> String {
822    match value {
823        serde_json::Value::Null => "null".to_string(),
824        serde_json::Value::Bool(b) => format!("{b}"),
825        serde_json::Value::Number(n) => n.to_string(),
826        serde_json::Value::String(s) => {
827            let escaped = s.replace('\\', "\\\\").replace('"', "\\\"");
828            format!("\"{escaped}\"")
829        }
830        serde_json::Value::Array(arr) => {
831            let items: Vec<String> = arr.iter().map(json_value_to_macro_literal).collect();
832            format!("[{}]", items.join(", "))
833        }
834        serde_json::Value::Object(obj) => {
835            let entries: Vec<String> = obj
836                .iter()
837                .map(|(k, v)| {
838                    let escaped_key = k.replace('\\', "\\\\").replace('"', "\\\"");
839                    format!("\"{escaped_key}\": {}", json_value_to_macro_literal(v))
840                })
841                .collect();
842            format!("{{{}}}", entries.join(", "))
843        }
844    }
845}
846
847fn json_to_rust_literal(value: &serde_json::Value, arg_type: &str) -> String {
848    match value {
849        serde_json::Value::Null => "None".to_string(),
850        serde_json::Value::Bool(b) => format!("{b}"),
851        serde_json::Value::Number(n) => {
852            if arg_type.contains("float") || arg_type.contains("f64") || arg_type.contains("f32") {
853                if let Some(f) = n.as_f64() {
854                    return format!("{f}_f64");
855                }
856            }
857            n.to_string()
858        }
859        serde_json::Value::String(s) => rust_raw_string(s),
860        serde_json::Value::Array(_) | serde_json::Value::Object(_) => {
861            let json_str = serde_json::to_string(value).unwrap_or_default();
862            let literal = rust_raw_string(&json_str);
863            format!("serde_json::from_str({literal}).unwrap()")
864        }
865    }
866}
867
868// ---------------------------------------------------------------------------
869// Mock server helpers
870// ---------------------------------------------------------------------------
871
872/// Emit mock server setup lines into a test function body.
873///
874/// Builds `MockRoute` objects from the fixture's `mock_response` and starts
875/// the server.  The resulting `mock_server` variable is in scope for the rest
876/// of the test function.
877fn render_mock_server_setup(out: &mut String, fixture: &Fixture, e2e_config: &E2eConfig) {
878    let mock = match fixture.mock_response.as_ref() {
879        Some(m) => m,
880        None => return,
881    };
882
883    // Resolve the HTTP path and method from the call config.
884    let call_config = e2e_config.resolve_call(fixture.call.as_deref());
885    let path = call_config.path.as_deref().unwrap_or("/");
886    let method = call_config.method.as_deref().unwrap_or("POST");
887
888    let status = mock.status;
889
890    // Render headers map as a Vec<(String, String)> literal for stable iteration order.
891    let mut header_entries: Vec<(&String, &String)> = mock.headers.iter().collect();
892    header_entries.sort_by(|a, b| a.0.cmp(b.0));
893    let render_headers = |out: &mut String| {
894        let _ = writeln!(out, "        headers: vec![");
895        for (name, value) in &header_entries {
896            let n = rust_raw_string(name);
897            let v = rust_raw_string(value);
898            let _ = writeln!(out, "            ({n}.to_string(), {v}.to_string()),");
899        }
900        let _ = writeln!(out, "        ],");
901    };
902
903    if let Some(chunks) = &mock.stream_chunks {
904        // Streaming SSE response.
905        let _ = writeln!(out, "    let mock_route = MockRoute {{");
906        let _ = writeln!(out, "        path: \"{path}\",");
907        let _ = writeln!(out, "        method: \"{method}\",");
908        let _ = writeln!(out, "        status: {status},");
909        let _ = writeln!(out, "        body: String::new(),");
910        let _ = writeln!(out, "        stream_chunks: vec![");
911        for chunk in chunks {
912            let chunk_str = match chunk {
913                serde_json::Value::String(s) => rust_raw_string(s),
914                other => {
915                    let s = serde_json::to_string(other).unwrap_or_default();
916                    rust_raw_string(&s)
917                }
918            };
919            let _ = writeln!(out, "            {chunk_str}.to_string(),");
920        }
921        let _ = writeln!(out, "        ],");
922        render_headers(out);
923        let _ = writeln!(out, "    }};");
924    } else {
925        // Non-streaming JSON response.
926        let body_str = match &mock.body {
927            Some(b) => {
928                let s = serde_json::to_string(b).unwrap_or_default();
929                rust_raw_string(&s)
930            }
931            None => rust_raw_string("{}"),
932        };
933        let _ = writeln!(out, "    let mock_route = MockRoute {{");
934        let _ = writeln!(out, "        path: \"{path}\",");
935        let _ = writeln!(out, "        method: \"{method}\",");
936        let _ = writeln!(out, "        status: {status},");
937        let _ = writeln!(out, "        body: {body_str}.to_string(),");
938        let _ = writeln!(out, "        stream_chunks: vec![],");
939        render_headers(out);
940        let _ = writeln!(out, "    }};");
941    }
942
943    let _ = writeln!(out, "    let mock_server = MockServer::start(vec![mock_route]).await;");
944}
945
946/// Generate the complete `mock_server.rs` module source.
947pub fn render_mock_server_module() -> String {
948    // This is parameterized Axum mock server code identical in structure to
949    // liter-llm's mock_server.rs but without any project-specific imports.
950    hash::header(CommentStyle::DoubleSlash)
951        + r#"//
952// Minimal axum-based mock HTTP server for e2e tests.
953
954use std::net::SocketAddr;
955use std::sync::Arc;
956
957use axum::Router;
958use axum::body::Body;
959use axum::extract::State;
960use axum::http::{Request, StatusCode};
961use axum::response::{IntoResponse, Response};
962use tokio::net::TcpListener;
963
964/// A single mock route: match by path + method, return a configured response.
965#[derive(Clone, Debug)]
966pub struct MockRoute {
967    /// URL path to match, e.g. `"/v1/chat/completions"`.
968    pub path: &'static str,
969    /// HTTP method to match, e.g. `"POST"` or `"GET"`.
970    pub method: &'static str,
971    /// HTTP status code to return.
972    pub status: u16,
973    /// Response body JSON string (used when `stream_chunks` is empty).
974    pub body: String,
975    /// Ordered SSE data payloads for streaming responses.
976    /// Each entry becomes `data: <chunk>\n\n` in the response.
977    /// A final `data: [DONE]\n\n` is always appended.
978    pub stream_chunks: Vec<String>,
979    /// Response headers to apply (name, value) pairs.
980    /// Multiple entries with the same name produce multiple header lines.
981    pub headers: Vec<(String, String)>,
982}
983
984struct ServerState {
985    routes: Vec<MockRoute>,
986}
987
988pub struct MockServer {
989    /// Base URL of the mock server, e.g. `"http://127.0.0.1:54321"`.
990    pub url: String,
991    handle: tokio::task::JoinHandle<()>,
992}
993
994impl MockServer {
995    /// Start a mock server with the given routes.  Binds to a random port on
996    /// localhost and returns immediately once the server is listening.
997    pub async fn start(routes: Vec<MockRoute>) -> Self {
998        let state = Arc::new(ServerState { routes });
999
1000        let app = Router::new().fallback(handle_request).with_state(state);
1001
1002        let listener = TcpListener::bind("127.0.0.1:0")
1003            .await
1004            .expect("Failed to bind mock server port");
1005        let addr: SocketAddr = listener.local_addr().expect("Failed to get local addr");
1006        let url = format!("http://{addr}");
1007
1008        let handle = tokio::spawn(async move {
1009            axum::serve(listener, app).await.expect("Mock server failed");
1010        });
1011
1012        MockServer { url, handle }
1013    }
1014
1015    /// Stop the mock server.
1016    pub fn shutdown(self) {
1017        self.handle.abort();
1018    }
1019}
1020
1021impl Drop for MockServer {
1022    fn drop(&mut self) {
1023        self.handle.abort();
1024    }
1025}
1026
1027async fn handle_request(State(state): State<Arc<ServerState>>, req: Request<Body>) -> Response {
1028    let path = req.uri().path().to_owned();
1029    let method = req.method().as_str().to_uppercase();
1030
1031    for route in &state.routes {
1032        if route.path == path && route.method.to_uppercase() == method {
1033            let status =
1034                StatusCode::from_u16(route.status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
1035
1036            if !route.stream_chunks.is_empty() {
1037                // Build SSE body: data: <chunk>\n\n ... data: [DONE]\n\n
1038                let mut sse = String::new();
1039                for chunk in &route.stream_chunks {
1040                    sse.push_str("data: ");
1041                    sse.push_str(chunk);
1042                    sse.push_str("\n\n");
1043                }
1044                sse.push_str("data: [DONE]\n\n");
1045
1046                let mut builder = Response::builder()
1047                    .status(status)
1048                    .header("content-type", "text/event-stream")
1049                    .header("cache-control", "no-cache");
1050                for (name, value) in &route.headers {
1051                    builder = builder.header(name, value);
1052                }
1053                return builder.body(Body::from(sse)).unwrap().into_response();
1054            }
1055
1056            let mut builder =
1057                Response::builder().status(status).header("content-type", "application/json");
1058            for (name, value) in &route.headers {
1059                builder = builder.header(name, value);
1060            }
1061            return builder.body(Body::from(route.body.clone())).unwrap().into_response();
1062        }
1063    }
1064
1065    // No matching route → 404.
1066    Response::builder()
1067        .status(StatusCode::NOT_FOUND)
1068        .body(Body::from(format!("No mock route for {method} {path}")))
1069        .unwrap()
1070        .into_response()
1071}
1072"#
1073}
1074
1075/// Generate the `src/main.rs` for the standalone mock server binary.
1076///
1077/// The binary:
1078/// - Reads all `*.json` fixture files from a fixtures directory (default `../../fixtures`).
1079/// - For each fixture that has a `mock_response` field, registers a route at
1080///   `/fixtures/{fixture_id}` returning the configured status/body/SSE chunks.
1081/// - Binds to `127.0.0.1:0` (random port), prints `MOCK_SERVER_URL=http://...`
1082///   to stdout, then waits until stdin is closed for clean teardown.
1083///
1084/// This binary is intended for cross-language e2e suites (WASM, Node) that
1085/// spawn it as a child process and read the URL from its stdout.
1086pub fn render_mock_server_binary() -> String {
1087    hash::header(CommentStyle::DoubleSlash)
1088        + r#"//
1089// Standalone mock HTTP server binary for cross-language e2e tests.
1090// Reads fixture JSON files and serves mock responses on /fixtures/{fixture_id}.
1091//
1092// Usage: mock-server [fixtures-dir]
1093//   fixtures-dir defaults to "../../fixtures"
1094//
1095// Prints `MOCK_SERVER_URL=http://127.0.0.1:<port>` to stdout once listening,
1096// then blocks until stdin is closed (parent process exit triggers cleanup).
1097
1098use std::collections::HashMap;
1099use std::io::{self, BufRead};
1100use std::net::SocketAddr;
1101use std::path::Path;
1102use std::sync::Arc;
1103
1104use axum::Router;
1105use axum::body::Body;
1106use axum::extract::State;
1107use axum::http::{Request, StatusCode};
1108use axum::response::{IntoResponse, Response};
1109use serde::Deserialize;
1110use tokio::net::TcpListener;
1111
1112// ---------------------------------------------------------------------------
1113// Fixture types (mirrors alef-e2e's fixture.rs for runtime deserialization)
1114// Supports both schemas:
1115//   liter-llm: mock_response: { status, body, stream_chunks }
1116//   spikard:   http.expected_response: { status_code, body, headers }
1117// ---------------------------------------------------------------------------
1118
1119#[derive(Debug, Deserialize)]
1120struct MockResponse {
1121    status: u16,
1122    #[serde(default)]
1123    body: Option<serde_json::Value>,
1124    #[serde(default)]
1125    stream_chunks: Option<Vec<serde_json::Value>>,
1126    #[serde(default)]
1127    headers: HashMap<String, String>,
1128}
1129
1130#[derive(Debug, Deserialize)]
1131struct HttpExpectedResponse {
1132    status_code: u16,
1133    #[serde(default)]
1134    body: Option<serde_json::Value>,
1135    #[serde(default)]
1136    headers: HashMap<String, String>,
1137}
1138
1139#[derive(Debug, Deserialize)]
1140struct HttpFixture {
1141    expected_response: HttpExpectedResponse,
1142}
1143
1144#[derive(Debug, Deserialize)]
1145struct Fixture {
1146    id: String,
1147    #[serde(default)]
1148    mock_response: Option<MockResponse>,
1149    #[serde(default)]
1150    http: Option<HttpFixture>,
1151}
1152
1153impl Fixture {
1154    /// Bridge both schemas into a unified MockResponse.
1155    fn as_mock_response(&self) -> Option<MockResponse> {
1156        if let Some(mock) = &self.mock_response {
1157            return Some(MockResponse {
1158                status: mock.status,
1159                body: mock.body.clone(),
1160                stream_chunks: mock.stream_chunks.clone(),
1161                headers: mock.headers.clone(),
1162            });
1163        }
1164        if let Some(http) = &self.http {
1165            return Some(MockResponse {
1166                status: http.expected_response.status_code,
1167                body: http.expected_response.body.clone(),
1168                stream_chunks: None,
1169                headers: http.expected_response.headers.clone(),
1170            });
1171        }
1172        None
1173    }
1174}
1175
1176// ---------------------------------------------------------------------------
1177// Route table
1178// ---------------------------------------------------------------------------
1179
1180#[derive(Clone, Debug)]
1181struct MockRoute {
1182    status: u16,
1183    body: String,
1184    stream_chunks: Vec<String>,
1185    headers: Vec<(String, String)>,
1186}
1187
1188type RouteTable = Arc<HashMap<String, MockRoute>>;
1189
1190// ---------------------------------------------------------------------------
1191// Axum handler
1192// ---------------------------------------------------------------------------
1193
1194async fn handle_request(State(routes): State<RouteTable>, req: Request<Body>) -> Response {
1195    let path = req.uri().path().to_owned();
1196
1197    // Try exact match first
1198    if let Some(route) = routes.get(&path) {
1199        return serve_route(route);
1200    }
1201
1202    // Try prefix match: find a route that is a prefix of the request path
1203    // This allows /fixtures/basic_chat/v1/chat/completions to match /fixtures/basic_chat
1204    for (route_path, route) in routes.iter() {
1205        if path.starts_with(route_path) && (path.len() == route_path.len() || path.as_bytes()[route_path.len()] == b'/') {
1206            return serve_route(route);
1207        }
1208    }
1209
1210    Response::builder()
1211        .status(StatusCode::NOT_FOUND)
1212        .body(Body::from(format!("No mock route for {path}")))
1213        .unwrap()
1214        .into_response()
1215}
1216
1217fn serve_route(route: &MockRoute) -> Response {
1218    let status = StatusCode::from_u16(route.status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
1219
1220    if !route.stream_chunks.is_empty() {
1221        let mut sse = String::new();
1222        for chunk in &route.stream_chunks {
1223            sse.push_str("data: ");
1224            sse.push_str(chunk);
1225            sse.push_str("\n\n");
1226        }
1227        sse.push_str("data: [DONE]\n\n");
1228
1229        let mut builder = Response::builder()
1230            .status(status)
1231            .header("content-type", "text/event-stream")
1232            .header("cache-control", "no-cache");
1233        for (name, value) in &route.headers {
1234            builder = builder.header(name, value);
1235        }
1236        return builder.body(Body::from(sse)).unwrap().into_response();
1237    }
1238
1239    let mut builder = Response::builder().status(status).header("content-type", "application/json");
1240    for (name, value) in &route.headers {
1241        builder = builder.header(name, value);
1242    }
1243    builder.body(Body::from(route.body.clone())).unwrap().into_response()
1244}
1245
1246// ---------------------------------------------------------------------------
1247// Fixture loading
1248// ---------------------------------------------------------------------------
1249
1250fn load_routes(fixtures_dir: &Path) -> HashMap<String, MockRoute> {
1251    let mut routes = HashMap::new();
1252    load_routes_recursive(fixtures_dir, &mut routes);
1253    routes
1254}
1255
1256fn load_routes_recursive(dir: &Path, routes: &mut HashMap<String, MockRoute>) {
1257    let entries = match std::fs::read_dir(dir) {
1258        Ok(e) => e,
1259        Err(err) => {
1260            eprintln!("warning: cannot read directory {}: {err}", dir.display());
1261            return;
1262        }
1263    };
1264
1265    let mut paths: Vec<_> = entries.filter_map(|e| e.ok()).map(|e| e.path()).collect();
1266    paths.sort();
1267
1268    for path in paths {
1269        if path.is_dir() {
1270            load_routes_recursive(&path, routes);
1271        } else if path.extension().is_some_and(|ext| ext == "json") {
1272            let filename = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
1273            if filename == "schema.json" || filename.starts_with('_') {
1274                continue;
1275            }
1276            let content = match std::fs::read_to_string(&path) {
1277                Ok(c) => c,
1278                Err(err) => {
1279                    eprintln!("warning: cannot read {}: {err}", path.display());
1280                    continue;
1281                }
1282            };
1283            let fixtures: Vec<Fixture> = if content.trim_start().starts_with('[') {
1284                match serde_json::from_str(&content) {
1285                    Ok(v) => v,
1286                    Err(err) => {
1287                        eprintln!("warning: cannot parse {}: {err}", path.display());
1288                        continue;
1289                    }
1290                }
1291            } else {
1292                match serde_json::from_str::<Fixture>(&content) {
1293                    Ok(f) => vec![f],
1294                    Err(err) => {
1295                        eprintln!("warning: cannot parse {}: {err}", path.display());
1296                        continue;
1297                    }
1298                }
1299            };
1300
1301            for fixture in fixtures {
1302                if let Some(mock) = fixture.as_mock_response() {
1303                    let route_path = format!("/fixtures/{}", fixture.id);
1304                    let body = mock
1305                        .body
1306                        .as_ref()
1307                        .map(|b| serde_json::to_string(b).unwrap_or_default())
1308                        .unwrap_or_default();
1309                    let stream_chunks = mock
1310                        .stream_chunks
1311                        .unwrap_or_default()
1312                        .into_iter()
1313                        .map(|c| match c {
1314                            serde_json::Value::String(s) => s,
1315                            other => serde_json::to_string(&other).unwrap_or_default(),
1316                        })
1317                        .collect();
1318                    let mut headers: Vec<(String, String)> =
1319                        mock.headers.into_iter().collect();
1320                    headers.sort_by(|a, b| a.0.cmp(&b.0));
1321                    routes.insert(route_path, MockRoute { status: mock.status, body, stream_chunks, headers });
1322                }
1323            }
1324        }
1325    }
1326}
1327
1328// ---------------------------------------------------------------------------
1329// Entry point
1330// ---------------------------------------------------------------------------
1331
1332#[tokio::main]
1333async fn main() {
1334    let fixtures_dir_arg = std::env::args().nth(1).unwrap_or_else(|| "../../fixtures".to_string());
1335    let fixtures_dir = Path::new(&fixtures_dir_arg);
1336
1337    let routes = load_routes(fixtures_dir);
1338    eprintln!("mock-server: loaded {} routes from {}", routes.len(), fixtures_dir.display());
1339
1340    let route_table: RouteTable = Arc::new(routes);
1341    let app = Router::new().fallback(handle_request).with_state(route_table);
1342
1343    let listener = TcpListener::bind("127.0.0.1:0")
1344        .await
1345        .expect("mock-server: failed to bind port");
1346    let addr: SocketAddr = listener.local_addr().expect("mock-server: failed to get local addr");
1347
1348    // Print the URL so the parent process can read it.
1349    println!("MOCK_SERVER_URL=http://{addr}");
1350    // Flush stdout explicitly so the parent does not block waiting.
1351    use std::io::Write;
1352    std::io::stdout().flush().expect("mock-server: failed to flush stdout");
1353
1354    // Spawn the server in the background.
1355    tokio::spawn(async move {
1356        axum::serve(listener, app).await.expect("mock-server: server error");
1357    });
1358
1359    // Block until stdin is closed — the parent process controls lifetime.
1360    let stdin = io::stdin();
1361    let mut lines = stdin.lock().lines();
1362    while lines.next().is_some() {}
1363}
1364"#
1365}
1366
1367// ---------------------------------------------------------------------------
1368// Assertion rendering
1369// ---------------------------------------------------------------------------
1370
1371#[allow(clippy::too_many_arguments)]
1372fn render_assertion(
1373    out: &mut String,
1374    assertion: &Assertion,
1375    result_var: &str,
1376    module: &str,
1377    dep_name: &str,
1378    is_error_context: bool,
1379    unwrapped_fields: &[(String, String)], // (fixture_field, local_var)
1380    field_resolver: &FieldResolver,
1381    result_is_tree: bool,
1382    result_is_simple: bool,
1383    result_is_vec: bool,
1384    result_is_option: bool,
1385) {
1386    // Vec<T> result: iterate per-element so each assertion checks every element.
1387    // Field-path assertions become `for r in &{result} { <assert using r> }`.
1388    // Length-style assertions on the Vec itself (no field path) operate on the
1389    // Vec directly.
1390    let has_field = assertion.field.as_ref().is_some_and(|f| !f.is_empty());
1391    if result_is_vec && has_field && !is_error_context {
1392        let _ = writeln!(out, "    for r in &{result_var} {{");
1393        render_assertion(
1394            out,
1395            assertion,
1396            "r",
1397            module,
1398            dep_name,
1399            is_error_context,
1400            unwrapped_fields,
1401            field_resolver,
1402            result_is_tree,
1403            result_is_simple,
1404            false, // already inside loop
1405            result_is_option,
1406        );
1407        let _ = writeln!(out, "    }}");
1408        return;
1409    }
1410    // Option<T> result: map `is_empty`/`not_empty` to `is_none()`/`is_some()`,
1411    // and unwrap the inner value before any other assertion runs.
1412    if result_is_option && !is_error_context {
1413        let assertion_type = assertion.assertion_type.as_str();
1414        if !has_field && (assertion_type == "is_empty" || assertion_type == "not_empty") {
1415            let check = if assertion_type == "is_empty" {
1416                "is_none"
1417            } else {
1418                "is_some"
1419            };
1420            let _ = writeln!(
1421                out,
1422                "    assert!({result_var}.{check}(), \"expected Option to be {check}\");"
1423            );
1424            return;
1425        }
1426        // For any other assertion shape, unwrap the Option and recurse with a
1427        // bare reference variable so the rest of the renderer treats the inner
1428        // value as the result.
1429        let _ = writeln!(
1430            out,
1431            "    let r = {result_var}.as_ref().expect(\"Option<T> should be Some\");"
1432        );
1433        render_assertion(
1434            out,
1435            assertion,
1436            "r",
1437            module,
1438            dep_name,
1439            is_error_context,
1440            unwrapped_fields,
1441            field_resolver,
1442            result_is_tree,
1443            result_is_simple,
1444            result_is_vec,
1445            false, // already unwrapped
1446        );
1447        return;
1448    }
1449    let _ = dep_name;
1450    // Handle synthetic fields like chunks_have_content (derived assertions)
1451    if let Some(f) = &assertion.field {
1452        if f == "chunks_have_content" {
1453            match assertion.assertion_type.as_str() {
1454                "is_true" => {
1455                    let _ = writeln!(
1456                        out,
1457                        "    assert!({result_var}.chunks.as_ref().is_some_and(|chunks| !chunks.is_empty() && chunks.iter().all(|c| !c.content.is_empty())), \"expected all chunks to have content\");"
1458                    );
1459                }
1460                "is_false" => {
1461                    let _ = writeln!(
1462                        out,
1463                        "    assert!({result_var}.chunks.as_ref().is_none() || {result_var}.chunks.as_ref().unwrap().iter().any(|c| c.content.is_empty()), \"expected some chunks to be empty\");"
1464                    );
1465                }
1466                _ => {
1467                    let _ = writeln!(
1468                        out,
1469                        "    // unsupported assertion type on synthetic field chunks_have_content"
1470                    );
1471                }
1472            }
1473            return;
1474        }
1475    }
1476
1477    // Skip assertions on fields that don't exist on the result type.
1478    if let Some(f) = &assertion.field {
1479        if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
1480            let _ = writeln!(out, "    // skipped: field '{f}' not available on result type");
1481            return;
1482        }
1483    }
1484
1485    // Determine field access expression:
1486    // 1. If the field was unwrapped to a local var, use that local var name.
1487    // 2. When result_is_simple, the function returns a plain type (String etc.) — use result_var.
1488    // 3. When the result is a Tree, map pseudo-field names to correct Rust expressions.
1489    // 4. Otherwise, use the field resolver to generate the accessor.
1490    let field_access = match &assertion.field {
1491        Some(f) if !f.is_empty() => {
1492            if let Some((_, local_var)) = unwrapped_fields.iter().find(|(ff, _)| ff == f) {
1493                local_var.clone()
1494            } else if result_is_simple {
1495                // Plain return type (String, Vec<T>, etc.) has no struct fields.
1496                // Use the result variable directly so assertions operate on the value itself.
1497                result_var.to_string()
1498            } else if result_is_tree {
1499                // Tree is an opaque type — its "fields" are accessed via root_node() or
1500                // free functions. Map known pseudo-field names to correct Rust expressions.
1501                tree_field_access_expr(f, result_var, module)
1502            } else {
1503                field_resolver.accessor(f, "rust", result_var)
1504            }
1505        }
1506        _ => result_var.to_string(),
1507    };
1508
1509    // Check if this field was unwrapped (i.e., it is optional and was bound to a local).
1510    let is_unwrapped = assertion
1511        .field
1512        .as_ref()
1513        .is_some_and(|f| unwrapped_fields.iter().any(|(ff, _)| ff == f));
1514
1515    match assertion.assertion_type.as_str() {
1516        "error" => {
1517            let _ = writeln!(out, "    assert!({result_var}.is_err(), \"expected call to fail\");");
1518            if let Some(serde_json::Value::String(msg)) = &assertion.value {
1519                let escaped = escape_rust(msg);
1520                let _ = writeln!(
1521                    out,
1522                    "    assert!({result_var}.as_ref().unwrap_err().to_string().contains(\"{escaped}\"), \"error message mismatch\");"
1523                );
1524            }
1525        }
1526        "not_error" => {
1527            // Handled at call site; nothing extra needed here.
1528        }
1529        "equals" => {
1530            if let Some(val) = &assertion.value {
1531                let expected = value_to_rust_string(val);
1532                if is_error_context {
1533                    return;
1534                }
1535                // For string equality, trim trailing whitespace to handle trailing newlines
1536                // from the converter.
1537                if val.is_string() {
1538                    let _ = writeln!(
1539                        out,
1540                        "    assert_eq!({field_access}.trim(), {expected}, \"equals assertion failed\");"
1541                    );
1542                } else if val.is_boolean() {
1543                    // Use assert!/assert!(!...) for booleans — clippy prefers this over assert_eq!(_, true/false).
1544                    if val.as_bool() == Some(true) {
1545                        let _ = writeln!(out, "    assert!({field_access}, \"equals assertion failed\");");
1546                    } else {
1547                        let _ = writeln!(out, "    assert!(!{field_access}, \"equals assertion failed\");");
1548                    }
1549                } else {
1550                    // Wrap expected value in Some() for optional fields.
1551                    let is_opt = assertion.field.as_ref().is_some_and(|f| {
1552                        let resolved = field_resolver.resolve(f);
1553                        field_resolver.is_optional(resolved)
1554                    });
1555                    if is_opt
1556                        && !unwrapped_fields
1557                            .iter()
1558                            .any(|(ff, _)| assertion.field.as_ref() == Some(ff))
1559                    {
1560                        let _ = writeln!(
1561                            out,
1562                            "    assert_eq!({field_access}, Some({expected}), \"equals assertion failed\");"
1563                        );
1564                    } else {
1565                        let _ = writeln!(
1566                            out,
1567                            "    assert_eq!({field_access}, {expected}, \"equals assertion failed\");"
1568                        );
1569                    }
1570                }
1571            }
1572        }
1573        "contains" => {
1574            if let Some(val) = &assertion.value {
1575                let expected = value_to_rust_string(val);
1576                let line = format!(
1577                    "    assert!(format!(\"{{:?}}\", {field_access}).contains({expected}), \"expected to contain: {{}}\", {expected});"
1578                );
1579                let _ = writeln!(out, "{line}");
1580            }
1581        }
1582        "contains_all" => {
1583            if let Some(values) = &assertion.values {
1584                for val in values {
1585                    let expected = value_to_rust_string(val);
1586                    let line = format!(
1587                        "    assert!(format!(\"{{:?}}\", {field_access}).contains({expected}), \"expected to contain: {{}}\", {expected});"
1588                    );
1589                    let _ = writeln!(out, "{line}");
1590                }
1591            }
1592        }
1593        "not_contains" => {
1594            if let Some(val) = &assertion.value {
1595                let expected = value_to_rust_string(val);
1596                let line = format!(
1597                    "    assert!(!format!(\"{{:?}}\", {field_access}).contains({expected}), \"expected NOT to contain: {{}}\", {expected});"
1598                );
1599                let _ = writeln!(out, "{line}");
1600            }
1601        }
1602        "not_empty" => {
1603            if let Some(f) = &assertion.field {
1604                let resolved = field_resolver.resolve(f);
1605                let is_opt = !is_unwrapped && field_resolver.is_optional(resolved);
1606                let is_arr = field_resolver.is_array(resolved);
1607                if is_opt && is_arr {
1608                    // Option<Vec<T>>: must be Some AND inner non-empty.
1609                    let accessor = field_resolver.accessor(f, "rust", result_var);
1610                    let _ = writeln!(
1611                        out,
1612                        "    assert!({accessor}.as_ref().is_some_and(|v| !v.is_empty()), \"expected {f} to be present and non-empty\");"
1613                    );
1614                } else if is_opt {
1615                    // Non-collection optional field (e.g., Option<Struct>): use is_some().
1616                    let accessor = field_resolver.accessor(f, "rust", result_var);
1617                    let _ = writeln!(
1618                        out,
1619                        "    assert!({accessor}.is_some(), \"expected {f} to be present\");"
1620                    );
1621                } else {
1622                    let _ = writeln!(
1623                        out,
1624                        "    assert!(!{field_access}.is_empty(), \"expected non-empty value\");"
1625                    );
1626                }
1627            } else if result_is_option {
1628                // Bare result is Option<T>: not_empty == is_some().
1629                let _ = writeln!(
1630                    out,
1631                    "    assert!({field_access}.is_some(), \"expected non-empty value\");"
1632                );
1633            } else {
1634                // Bare result is a struct/string/collection — non-empty via is_empty().
1635                let _ = writeln!(
1636                    out,
1637                    "    assert!(!{field_access}.is_empty(), \"expected non-empty value\");"
1638                );
1639            }
1640        }
1641        "is_empty" => {
1642            if let Some(f) = &assertion.field {
1643                let resolved = field_resolver.resolve(f);
1644                let is_opt = !is_unwrapped && field_resolver.is_optional(resolved);
1645                let is_arr = field_resolver.is_array(resolved);
1646                if is_opt && is_arr {
1647                    // Option<Vec<T>>: empty means None or empty vec.
1648                    let accessor = field_resolver.accessor(f, "rust", result_var);
1649                    let _ = writeln!(
1650                        out,
1651                        "    assert!({accessor}.as_ref().is_none_or(|v| v.is_empty()), \"expected {f} to be empty or absent\");"
1652                    );
1653                } else if is_opt {
1654                    let accessor = field_resolver.accessor(f, "rust", result_var);
1655                    let _ = writeln!(out, "    assert!({accessor}.is_none(), \"expected {f} to be absent\");");
1656                } else {
1657                    let _ = writeln!(out, "    assert!({field_access}.is_empty(), \"expected empty value\");");
1658                }
1659            } else {
1660                let _ = writeln!(out, "    assert!({field_access}.is_none(), \"expected empty value\");");
1661            }
1662        }
1663        "contains_any" => {
1664            if let Some(values) = &assertion.values {
1665                let checks: Vec<String> = values
1666                    .iter()
1667                    .map(|v| {
1668                        let expected = value_to_rust_string(v);
1669                        format!("{field_access}.contains({expected})")
1670                    })
1671                    .collect();
1672                let joined = checks.join(" || ");
1673                let _ = writeln!(
1674                    out,
1675                    "    assert!({joined}, \"expected to contain at least one of the specified values\");"
1676                );
1677            }
1678        }
1679        "greater_than" => {
1680            if let Some(val) = &assertion.value {
1681                // Skip comparisons with negative values against unsigned types (.len() etc.)
1682                if val.as_f64().is_some_and(|n| n < 0.0) {
1683                    let _ = writeln!(
1684                        out,
1685                        "    // skipped: greater_than with negative value is always true for unsigned types"
1686                    );
1687                } else if val.as_u64() == Some(0) {
1688                    // Clippy prefers !is_empty() over len() > 0
1689                    let base = field_access.strip_suffix(".len()").unwrap_or(&field_access);
1690                    let _ = writeln!(out, "    assert!(!{base}.is_empty(), \"expected > 0\");");
1691                } else {
1692                    let lit = numeric_literal(val);
1693                    let _ = writeln!(out, "    assert!({field_access} > {lit}, \"expected > {lit}\");");
1694                }
1695            }
1696        }
1697        "less_than" => {
1698            if let Some(val) = &assertion.value {
1699                let lit = numeric_literal(val);
1700                let _ = writeln!(out, "    assert!({field_access} < {lit}, \"expected < {lit}\");");
1701            }
1702        }
1703        "greater_than_or_equal" => {
1704            if let Some(val) = &assertion.value {
1705                let lit = numeric_literal(val);
1706                if val.as_u64() == Some(1) && field_access.ends_with(".len()") {
1707                    // Clippy prefers !is_empty() over len() >= 1 for collections.
1708                    // Only apply when the expression is already a `.len()` call so we
1709                    // don't mistakenly call `.is_empty()` on numeric (usize) fields.
1710                    let base = field_access.strip_suffix(".len()").unwrap_or(&field_access);
1711                    let _ = writeln!(out, "    assert!(!{base}.is_empty(), \"expected >= 1\");");
1712                } else {
1713                    let _ = writeln!(out, "    assert!({field_access} >= {lit}, \"expected >= {lit}\");");
1714                }
1715            }
1716        }
1717        "less_than_or_equal" => {
1718            if let Some(val) = &assertion.value {
1719                let lit = numeric_literal(val);
1720                let _ = writeln!(out, "    assert!({field_access} <= {lit}, \"expected <= {lit}\");");
1721            }
1722        }
1723        "starts_with" => {
1724            if let Some(val) = &assertion.value {
1725                let expected = value_to_rust_string(val);
1726                let _ = writeln!(
1727                    out,
1728                    "    assert!({field_access}.starts_with({expected}), \"expected to start with: {{}}\", {expected});"
1729                );
1730            }
1731        }
1732        "ends_with" => {
1733            if let Some(val) = &assertion.value {
1734                let expected = value_to_rust_string(val);
1735                let _ = writeln!(
1736                    out,
1737                    "    assert!({field_access}.ends_with({expected}), \"expected to end with: {{}}\", {expected});"
1738                );
1739            }
1740        }
1741        "min_length" => {
1742            if let Some(val) = &assertion.value {
1743                if let Some(n) = val.as_u64() {
1744                    let _ = writeln!(
1745                        out,
1746                        "    assert!({field_access}.len() >= {n}, \"expected length >= {n}, got {{}}\", {field_access}.len());"
1747                    );
1748                }
1749            }
1750        }
1751        "max_length" => {
1752            if let Some(val) = &assertion.value {
1753                if let Some(n) = val.as_u64() {
1754                    let _ = writeln!(
1755                        out,
1756                        "    assert!({field_access}.len() <= {n}, \"expected length <= {n}, got {{}}\", {field_access}.len());"
1757                    );
1758                }
1759            }
1760        }
1761        "count_min" => {
1762            if let Some(val) = &assertion.value {
1763                if let Some(n) = val.as_u64() {
1764                    let opt_arr_field = assertion.field.as_ref().is_some_and(|f| {
1765                        let resolved = field_resolver.resolve(f);
1766                        let is_opt = !is_unwrapped && field_resolver.is_optional(resolved);
1767                        let is_arr = field_resolver.is_array(resolved);
1768                        is_opt && is_arr
1769                    });
1770                    let base = field_access.strip_suffix(".len()").unwrap_or(&field_access);
1771                    if opt_arr_field {
1772                        // Option<Vec<T>>: must be Some AND inner len >= n.
1773                        if n <= 1 {
1774                            let _ = writeln!(
1775                                out,
1776                                "    assert!({base}.as_ref().is_some_and(|v| !v.is_empty()), \"expected >= {n}\");"
1777                            );
1778                        } else {
1779                            let _ = writeln!(
1780                                out,
1781                                "    assert!({base}.as_ref().is_some_and(|v| v.len() >= {n}), \"expected at least {n} elements\");"
1782                            );
1783                        }
1784                    } else if n <= 1 {
1785                        let _ = writeln!(out, "    assert!(!{base}.is_empty(), \"expected >= {n}\");");
1786                    } else {
1787                        let _ = writeln!(
1788                            out,
1789                            "    assert!({field_access}.len() >= {n}, \"expected at least {n} elements, got {{}}\", {field_access}.len());"
1790                        );
1791                    }
1792                }
1793            }
1794        }
1795        "count_equals" => {
1796            if let Some(val) = &assertion.value {
1797                if let Some(n) = val.as_u64() {
1798                    let opt_arr_field = assertion.field.as_ref().is_some_and(|f| {
1799                        let resolved = field_resolver.resolve(f);
1800                        let is_opt = !is_unwrapped && field_resolver.is_optional(resolved);
1801                        let is_arr = field_resolver.is_array(resolved);
1802                        is_opt && is_arr
1803                    });
1804                    let base = field_access.strip_suffix(".len()").unwrap_or(&field_access);
1805                    if opt_arr_field {
1806                        let _ = writeln!(
1807                            out,
1808                            "    assert!({base}.as_ref().is_some_and(|v| v.len() == {n}), \"expected exactly {n} elements\");"
1809                        );
1810                    } else {
1811                        let _ = writeln!(
1812                            out,
1813                            "    assert_eq!({field_access}.len(), {n}, \"expected exactly {n} elements, got {{}}\", {field_access}.len());"
1814                        );
1815                    }
1816                }
1817            }
1818        }
1819        "is_true" => {
1820            let _ = writeln!(out, "    assert!({field_access}, \"expected true\");");
1821        }
1822        "is_false" => {
1823            let _ = writeln!(out, "    assert!(!{field_access}, \"expected false\");");
1824        }
1825        "method_result" => {
1826            if let Some(method_name) = &assertion.method {
1827                // Build the call expression. When the result is a tree-sitter Tree (an opaque
1828                // type), methods like `root_child_count` do not exist on `Tree` directly —
1829                // they are free functions in the crate or are accessed via `root_node()`.
1830                let call_expr = if result_is_tree {
1831                    build_tree_call_expr(field_access.as_str(), method_name, assertion.args.as_ref(), module)
1832                } else if let Some(args) = &assertion.args {
1833                    let arg_lit = json_to_rust_literal(args, "");
1834                    format!("{field_access}.{method_name}({arg_lit})")
1835                } else {
1836                    format!("{field_access}.{method_name}()")
1837                };
1838
1839                // Determine whether the call expression returns a numeric type so we can
1840                // choose the right comparison strategy for `greater_than_or_equal`.
1841                let returns_numeric = result_is_tree && is_tree_numeric_method(method_name);
1842
1843                let check = assertion.check.as_deref().unwrap_or("is_true");
1844                match check {
1845                    "equals" => {
1846                        if let Some(val) = &assertion.value {
1847                            if val.is_boolean() {
1848                                if val.as_bool() == Some(true) {
1849                                    let _ = writeln!(
1850                                        out,
1851                                        "    assert!({call_expr}, \"method_result equals assertion failed\");"
1852                                    );
1853                                } else {
1854                                    let _ = writeln!(
1855                                        out,
1856                                        "    assert!(!{call_expr}, \"method_result equals assertion failed\");"
1857                                    );
1858                                }
1859                            } else {
1860                                let expected = value_to_rust_string(val);
1861                                let _ = writeln!(
1862                                    out,
1863                                    "    assert_eq!({call_expr}, {expected}, \"method_result equals assertion failed\");"
1864                                );
1865                            }
1866                        }
1867                    }
1868                    "is_true" => {
1869                        let _ = writeln!(
1870                            out,
1871                            "    assert!({call_expr}, \"method_result is_true assertion failed\");"
1872                        );
1873                    }
1874                    "is_false" => {
1875                        let _ = writeln!(
1876                            out,
1877                            "    assert!(!{call_expr}, \"method_result is_false assertion failed\");"
1878                        );
1879                    }
1880                    "greater_than_or_equal" => {
1881                        if let Some(val) = &assertion.value {
1882                            let lit = numeric_literal(val);
1883                            if returns_numeric {
1884                                // Numeric return (e.g., child_count()) — always use >= comparison.
1885                                let _ = writeln!(out, "    assert!({call_expr} >= {lit}, \"expected >= {lit}\");");
1886                            } else if val.as_u64() == Some(1) {
1887                                // Clippy prefers !is_empty() over len() >= 1 for collections.
1888                                let _ = writeln!(out, "    assert!(!{call_expr}.is_empty(), \"expected >= 1\");");
1889                            } else {
1890                                let _ = writeln!(out, "    assert!({call_expr} >= {lit}, \"expected >= {lit}\");");
1891                            }
1892                        }
1893                    }
1894                    "count_min" => {
1895                        if let Some(val) = &assertion.value {
1896                            let n = val.as_u64().unwrap_or(0);
1897                            if n <= 1 {
1898                                let _ = writeln!(out, "    assert!(!{call_expr}.is_empty(), \"expected >= {n}\");");
1899                            } else {
1900                                let _ = writeln!(
1901                                    out,
1902                                    "    assert!({call_expr}.len() >= {n}, \"expected at least {n} elements, got {{}}\", {call_expr}.len());"
1903                                );
1904                            }
1905                        }
1906                    }
1907                    "is_error" => {
1908                        // For is_error we need the raw Result without .unwrap().
1909                        let raw_call = call_expr.strip_suffix(".unwrap()").unwrap_or(&call_expr);
1910                        let _ = writeln!(
1911                            out,
1912                            "    assert!({raw_call}.is_err(), \"expected method to return error\");"
1913                        );
1914                    }
1915                    "contains" => {
1916                        if let Some(val) = &assertion.value {
1917                            let expected = value_to_rust_string(val);
1918                            let _ = writeln!(
1919                                out,
1920                                "    assert!({call_expr}.contains({expected}), \"expected result to contain {{}}\", {expected});"
1921                            );
1922                        }
1923                    }
1924                    "not_empty" => {
1925                        let _ = writeln!(
1926                            out,
1927                            "    assert!(!{call_expr}.is_empty(), \"expected non-empty result\");"
1928                        );
1929                    }
1930                    "is_empty" => {
1931                        let _ = writeln!(out, "    assert!({call_expr}.is_empty(), \"expected empty result\");");
1932                    }
1933                    other_check => {
1934                        panic!("Rust e2e generator: unsupported method_result check type: {other_check}");
1935                    }
1936                }
1937            } else {
1938                panic!("Rust e2e generator: method_result assertion missing 'method' field");
1939            }
1940        }
1941        other => {
1942            panic!("Rust e2e generator: unsupported assertion type: {other}");
1943        }
1944    }
1945}
1946
1947/// Translate a fixture pseudo-field name on a `tree_sitter::Tree` into the
1948/// correct Rust accessor expression.
1949///
1950/// When an assertion uses `field: "root_child_count"` on a tree result, the
1951/// field resolver would naively emit `tree.root_child_count` — which is invalid
1952/// because `Tree` is an opaque type with no such field.  This function maps the
1953/// pseudo-field to the correct Rust expression instead.
1954fn tree_field_access_expr(field: &str, result_var: &str, module: &str) -> String {
1955    match field {
1956        "root_child_count" => format!("{result_var}.root_node().child_count()"),
1957        "root_node_type" => format!("{result_var}.root_node().kind()"),
1958        "named_children_count" => format!("{result_var}.root_node().named_child_count()"),
1959        "has_error_nodes" => format!("{module}::tree_has_error_nodes(&{result_var})"),
1960        "error_count" | "tree_error_count" => format!("{module}::tree_error_count(&{result_var})"),
1961        "tree_to_sexp" => format!("{module}::tree_to_sexp(&{result_var})"),
1962        // Unknown pseudo-field: fall back to direct field access (will likely fail to compile,
1963        // but gives the developer a useful error pointing to the fixture).
1964        other => format!("{result_var}.{other}"),
1965    }
1966}
1967
1968/// Build a Rust call expression for a logical "method" on a `tree_sitter::Tree`.
1969///
1970/// `Tree` is an opaque type — it does not expose methods like `root_child_count`.
1971/// Instead, these are either free functions in the crate or are accessed via
1972/// `tree.root_node().<method>()`. This function translates the fixture-level
1973/// method name into the correct Rust expression.
1974fn build_tree_call_expr(
1975    field_access: &str,
1976    method_name: &str,
1977    args: Option<&serde_json::Value>,
1978    module: &str,
1979) -> String {
1980    match method_name {
1981        "root_child_count" => format!("{field_access}.root_node().child_count()"),
1982        "root_node_type" => format!("{field_access}.root_node().kind()"),
1983        "named_children_count" => format!("{field_access}.root_node().named_child_count()"),
1984        "has_error_nodes" => format!("{module}::tree_has_error_nodes(&{field_access})"),
1985        "error_count" | "tree_error_count" => format!("{module}::tree_error_count(&{field_access})"),
1986        "tree_to_sexp" => format!("{module}::tree_to_sexp(&{field_access})"),
1987        "contains_node_type" => {
1988            let node_type = args
1989                .and_then(|a| a.get("node_type"))
1990                .and_then(|v| v.as_str())
1991                .unwrap_or("");
1992            format!("{module}::tree_contains_node_type(&{field_access}, \"{node_type}\")")
1993        }
1994        "find_nodes_by_type" => {
1995            let node_type = args
1996                .and_then(|a| a.get("node_type"))
1997                .and_then(|v| v.as_str())
1998                .unwrap_or("");
1999            format!("{module}::find_nodes_by_type(&{field_access}, \"{node_type}\")")
2000        }
2001        "run_query" => {
2002            let query_source = args
2003                .and_then(|a| a.get("query_source"))
2004                .and_then(|v| v.as_str())
2005                .unwrap_or("");
2006            let language = args
2007                .and_then(|a| a.get("language"))
2008                .and_then(|v| v.as_str())
2009                .unwrap_or("");
2010            // Use a raw string for the query to avoid escaping issues.
2011            // run_query returns Result — unwrap it for assertion access.
2012            format!(
2013                "{module}::run_query(&{field_access}, \"{language}\", r#\"{query_source}\"#, source.as_bytes()).unwrap()"
2014            )
2015        }
2016        // Fallback: try as a plain method call.
2017        _ => {
2018            if let Some(args) = args {
2019                let arg_lit = json_to_rust_literal(args, "");
2020                format!("{field_access}.{method_name}({arg_lit})")
2021            } else {
2022                format!("{field_access}.{method_name}()")
2023            }
2024        }
2025    }
2026}
2027
2028/// Returns `true` when the tree method name produces a numeric result (usize/u64),
2029/// meaning `>= N` comparisons should use direct numeric comparison rather than
2030/// `.is_empty()` (which only works for collections).
2031fn is_tree_numeric_method(method_name: &str) -> bool {
2032    matches!(
2033        method_name,
2034        "root_child_count" | "named_children_count" | "error_count" | "tree_error_count"
2035    )
2036}
2037
2038/// Convert a JSON numeric value to a Rust literal suitable for comparisons.
2039///
2040/// Whole numbers (no fractional part) are emitted as bare integer literals so
2041/// they are compatible with `usize`, `u64`, etc. (e.g., `.len()` results).
2042/// Numbers with a fractional component get the `_f64` suffix.
2043fn numeric_literal(value: &serde_json::Value) -> String {
2044    if let Some(n) = value.as_f64() {
2045        if n.fract() == 0.0 {
2046            // Whole number — emit without a type suffix so Rust can infer the
2047            // correct integer type from context (usize, u64, i64, …).
2048            return format!("{}", n as i64);
2049        }
2050        return format!("{n}_f64");
2051    }
2052    // Fallback: use the raw JSON representation.
2053    value.to_string()
2054}
2055
2056fn value_to_rust_string(value: &serde_json::Value) -> String {
2057    match value {
2058        serde_json::Value::String(s) => rust_raw_string(s),
2059        serde_json::Value::Bool(b) => format!("{b}"),
2060        serde_json::Value::Number(n) => n.to_string(),
2061        other => {
2062            let s = other.to_string();
2063            format!("\"{s}\"")
2064        }
2065    }
2066}
2067
2068// ---------------------------------------------------------------------------
2069// Visitor generation
2070// ---------------------------------------------------------------------------
2071
2072/// Resolve the visitor trait name based on module.
2073fn resolve_visitor_trait(module: &str) -> String {
2074    // For html_to_markdown modules, use HtmlVisitor
2075    if module.contains("html_to_markdown") {
2076        "HtmlVisitor".to_string()
2077    } else {
2078        // Default fallback for other modules
2079        "Visitor".to_string()
2080    }
2081}
2082
2083/// Emit a Rust visitor method for a callback action.
2084///
2085/// The parameter type list mirrors the `HtmlVisitor` trait in
2086/// `kreuzberg-dev/html-to-markdown`. Param names are bound to `_` because the
2087/// generated visitor body never references them — the body always returns a
2088/// fixed `VisitResult` variant — so we'd otherwise hit `unused_variables`
2089/// warnings that fail prek's `cargo clippy -D warnings` hook.
2090fn emit_rust_visitor_method(out: &mut String, method_name: &str, action: &CallbackAction) {
2091    // Each entry: parameters typed exactly as `HtmlVisitor` expects them,
2092    // bound to `_` patterns so the generated body needn't introduce unused
2093    // bindings. Receiver is `&mut self` to match the trait.
2094    let params = match method_name {
2095        "visit_link" => "_: &NodeContext, _: &str, _: &str, _: &str",
2096        "visit_image" => "_: &NodeContext, _: &str, _: &str, _: &str",
2097        "visit_heading" => "_: &NodeContext, _: u8, _: &str, _: Option<&str>",
2098        "visit_code_block" => "_: &NodeContext, _: Option<&str>, _: &str",
2099        "visit_code_inline"
2100        | "visit_strong"
2101        | "visit_emphasis"
2102        | "visit_strikethrough"
2103        | "visit_underline"
2104        | "visit_subscript"
2105        | "visit_superscript"
2106        | "visit_mark"
2107        | "visit_button"
2108        | "visit_summary"
2109        | "visit_figcaption"
2110        | "visit_definition_term"
2111        | "visit_definition_description" => "_: &NodeContext, _: &str",
2112        "visit_text" => "_: &NodeContext, _: &str",
2113        "visit_list_item" => "_: &NodeContext, _: bool, _: &str, _: &str",
2114        "visit_blockquote" => "_: &NodeContext, _: &str, _: u32",
2115        "visit_table_row" => "_: &NodeContext, _: &[String], _: bool",
2116        "visit_custom_element" => "_: &NodeContext, _: &str, _: &str",
2117        "visit_form" => "_: &NodeContext, _: &str, _: &str",
2118        "visit_input" => "_: &NodeContext, _: &str, _: &str, _: &str",
2119        "visit_audio" | "visit_video" | "visit_iframe" => "_: &NodeContext, _: &str",
2120        "visit_details" => "_: &NodeContext, _: bool",
2121        "visit_element_end" | "visit_table_end" | "visit_definition_list_end" | "visit_figure_end" => {
2122            "_: &NodeContext, _: &str"
2123        }
2124        "visit_list_start" => "_: &NodeContext, _: bool",
2125        "visit_list_end" => "_: &NodeContext, _: bool, _: &str",
2126        _ => "_: &NodeContext",
2127    };
2128
2129    let _ = writeln!(out, "        fn {method_name}(&mut self, {params}) -> VisitResult {{");
2130    match action {
2131        CallbackAction::Skip => {
2132            let _ = writeln!(out, "            VisitResult::Skip");
2133        }
2134        CallbackAction::Continue => {
2135            let _ = writeln!(out, "            VisitResult::Continue");
2136        }
2137        CallbackAction::PreserveHtml => {
2138            let _ = writeln!(out, "            VisitResult::PreserveHtml");
2139        }
2140        CallbackAction::Custom { output } => {
2141            let escaped = escape_rust(output);
2142            let _ = writeln!(out, "            VisitResult::Custom(\"{escaped}\".to_string())");
2143        }
2144        CallbackAction::CustomTemplate { template } => {
2145            let escaped = escape_rust(template);
2146            let _ = writeln!(out, "            VisitResult::Custom(format!(\"{escaped}\"))");
2147        }
2148    }
2149    let _ = writeln!(out, "        }}");
2150}