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