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 expr = |n: &str| {
665        if arg_type == "bytes" {
666            format!("{n}.as_bytes()")
667        } else if pass_by_ref {
668            format!("&{n}")
669        } else {
670            n.to_string()
671        }
672    };
673    if optional && value.is_null() {
674        (vec![format!("let {name} = None;")], expr(name))
675    } else if optional {
676        (vec![format!("let {name} = Some({literal});")], expr(name))
677    } else {
678        (vec![format!("let {name} = {literal};")], expr(name))
679    }
680}
681
682/// Render a `json_object` argument: serialize the fixture JSON as a `serde_json::json!` literal
683/// and deserialize it through serde at runtime. Type inference from the function signature
684/// determines the concrete type, keeping the generator generic.
685fn render_json_object_arg(
686    name: &str,
687    value: &serde_json::Value,
688    optional: bool,
689    _module: &str,
690) -> (Vec<String>, String) {
691    if value.is_null() && optional {
692        // Use Default::default() and pass by reference — Rust functions typically
693        // take &T not Option<T> for config params.
694        return (vec![format!("let {name} = Default::default();")], format!("&{name}"));
695    }
696
697    // Fixture keys are camelCase; the Rust ConversionOptions type uses snake_case serde.
698    // Normalize keys before building the json! literal so deserialization succeeds.
699    let normalized = super::normalize_json_keys_to_snake_case(value);
700    // Build the json! macro invocation from the fixture object.
701    let json_literal = json_value_to_macro_literal(&normalized);
702    let mut lines = Vec::new();
703    lines.push(format!("let {name}_json = serde_json::json!({json_literal});"));
704    // Deserialize to a concrete type inferred from the function signature.
705    let deser_expr = format!("serde_json::from_value({name}_json).unwrap()");
706    if optional {
707        lines.push(format!("let {name} = Some({deser_expr});"));
708        (lines, format!("&{name}"))
709    } else {
710        lines.push(format!("let {name} = {deser_expr};"));
711        (lines, format!("&{name}"))
712    }
713}
714
715/// Convert a `serde_json::Value` into a string suitable for the `serde_json::json!()` macro.
716fn json_value_to_macro_literal(value: &serde_json::Value) -> String {
717    match value {
718        serde_json::Value::Null => "null".to_string(),
719        serde_json::Value::Bool(b) => format!("{b}"),
720        serde_json::Value::Number(n) => n.to_string(),
721        serde_json::Value::String(s) => {
722            let escaped = s.replace('\\', "\\\\").replace('"', "\\\"");
723            format!("\"{escaped}\"")
724        }
725        serde_json::Value::Array(arr) => {
726            let items: Vec<String> = arr.iter().map(json_value_to_macro_literal).collect();
727            format!("[{}]", items.join(", "))
728        }
729        serde_json::Value::Object(obj) => {
730            let entries: Vec<String> = obj
731                .iter()
732                .map(|(k, v)| {
733                    let escaped_key = k.replace('\\', "\\\\").replace('"', "\\\"");
734                    format!("\"{escaped_key}\": {}", json_value_to_macro_literal(v))
735                })
736                .collect();
737            format!("{{{}}}", entries.join(", "))
738        }
739    }
740}
741
742fn json_to_rust_literal(value: &serde_json::Value, arg_type: &str) -> String {
743    match value {
744        serde_json::Value::Null => "None".to_string(),
745        serde_json::Value::Bool(b) => format!("{b}"),
746        serde_json::Value::Number(n) => {
747            if arg_type.contains("float") || arg_type.contains("f64") || arg_type.contains("f32") {
748                if let Some(f) = n.as_f64() {
749                    return format!("{f}_f64");
750                }
751            }
752            n.to_string()
753        }
754        serde_json::Value::String(s) => rust_raw_string(s),
755        serde_json::Value::Array(_) | serde_json::Value::Object(_) => {
756            let json_str = serde_json::to_string(value).unwrap_or_default();
757            let literal = rust_raw_string(&json_str);
758            format!("serde_json::from_str({literal}).unwrap()")
759        }
760    }
761}
762
763// ---------------------------------------------------------------------------
764// Mock server helpers
765// ---------------------------------------------------------------------------
766
767/// Emit mock server setup lines into a test function body.
768///
769/// Builds `MockRoute` objects from the fixture's `mock_response` and starts
770/// the server.  The resulting `mock_server` variable is in scope for the rest
771/// of the test function.
772fn render_mock_server_setup(out: &mut String, fixture: &Fixture, e2e_config: &E2eConfig) {
773    let mock = match fixture.mock_response.as_ref() {
774        Some(m) => m,
775        None => return,
776    };
777
778    // Resolve the HTTP path and method from the call config.
779    let call_config = e2e_config.resolve_call(fixture.call.as_deref());
780    let path = call_config.path.as_deref().unwrap_or("/");
781    let method = call_config.method.as_deref().unwrap_or("POST");
782
783    let status = mock.status;
784
785    if let Some(chunks) = &mock.stream_chunks {
786        // Streaming SSE response.
787        let _ = writeln!(out, "    let mock_route = MockRoute {{");
788        let _ = writeln!(out, "        path: \"{path}\",");
789        let _ = writeln!(out, "        method: \"{method}\",");
790        let _ = writeln!(out, "        status: {status},");
791        let _ = writeln!(out, "        body: String::new(),");
792        let _ = writeln!(out, "        stream_chunks: vec![");
793        for chunk in chunks {
794            let chunk_str = match chunk {
795                serde_json::Value::String(s) => rust_raw_string(s),
796                other => {
797                    let s = serde_json::to_string(other).unwrap_or_default();
798                    rust_raw_string(&s)
799                }
800            };
801            let _ = writeln!(out, "            {chunk_str}.to_string(),");
802        }
803        let _ = writeln!(out, "        ],");
804        let _ = writeln!(out, "    }};");
805    } else {
806        // Non-streaming JSON response.
807        let body_str = match &mock.body {
808            Some(b) => {
809                let s = serde_json::to_string(b).unwrap_or_default();
810                rust_raw_string(&s)
811            }
812            None => rust_raw_string("{}"),
813        };
814        let _ = writeln!(out, "    let mock_route = MockRoute {{");
815        let _ = writeln!(out, "        path: \"{path}\",");
816        let _ = writeln!(out, "        method: \"{method}\",");
817        let _ = writeln!(out, "        status: {status},");
818        let _ = writeln!(out, "        body: {body_str}.to_string(),");
819        let _ = writeln!(out, "        stream_chunks: vec![],");
820        let _ = writeln!(out, "    }};");
821    }
822
823    let _ = writeln!(out, "    let mock_server = MockServer::start(vec![mock_route]).await;");
824}
825
826/// Generate the complete `mock_server.rs` module source.
827fn render_mock_server_module() -> String {
828    // This is parameterized Axum mock server code identical in structure to
829    // liter-llm's mock_server.rs but without any project-specific imports.
830    hash::header(CommentStyle::DoubleSlash)
831        + r#"//
832// Minimal axum-based mock HTTP server for e2e tests.
833
834use std::net::SocketAddr;
835use std::sync::Arc;
836
837use axum::Router;
838use axum::body::Body;
839use axum::extract::State;
840use axum::http::{Request, StatusCode};
841use axum::response::{IntoResponse, Response};
842use tokio::net::TcpListener;
843
844/// A single mock route: match by path + method, return a configured response.
845#[derive(Clone, Debug)]
846pub struct MockRoute {
847    /// URL path to match, e.g. `"/v1/chat/completions"`.
848    pub path: &'static str,
849    /// HTTP method to match, e.g. `"POST"` or `"GET"`.
850    pub method: &'static str,
851    /// HTTP status code to return.
852    pub status: u16,
853    /// Response body JSON string (used when `stream_chunks` is empty).
854    pub body: String,
855    /// Ordered SSE data payloads for streaming responses.
856    /// Each entry becomes `data: <chunk>\n\n` in the response.
857    /// A final `data: [DONE]\n\n` is always appended.
858    pub stream_chunks: Vec<String>,
859}
860
861struct ServerState {
862    routes: Vec<MockRoute>,
863}
864
865pub struct MockServer {
866    /// Base URL of the mock server, e.g. `"http://127.0.0.1:54321"`.
867    pub url: String,
868    handle: tokio::task::JoinHandle<()>,
869}
870
871impl MockServer {
872    /// Start a mock server with the given routes.  Binds to a random port on
873    /// localhost and returns immediately once the server is listening.
874    pub async fn start(routes: Vec<MockRoute>) -> Self {
875        let state = Arc::new(ServerState { routes });
876
877        let app = Router::new().fallback(handle_request).with_state(state);
878
879        let listener = TcpListener::bind("127.0.0.1:0")
880            .await
881            .expect("Failed to bind mock server port");
882        let addr: SocketAddr = listener.local_addr().expect("Failed to get local addr");
883        let url = format!("http://{addr}");
884
885        let handle = tokio::spawn(async move {
886            axum::serve(listener, app).await.expect("Mock server failed");
887        });
888
889        MockServer { url, handle }
890    }
891
892    /// Stop the mock server.
893    pub fn shutdown(self) {
894        self.handle.abort();
895    }
896}
897
898impl Drop for MockServer {
899    fn drop(&mut self) {
900        self.handle.abort();
901    }
902}
903
904async fn handle_request(State(state): State<Arc<ServerState>>, req: Request<Body>) -> Response {
905    let path = req.uri().path().to_owned();
906    let method = req.method().as_str().to_uppercase();
907
908    for route in &state.routes {
909        if route.path == path && route.method.to_uppercase() == method {
910            let status =
911                StatusCode::from_u16(route.status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
912
913            if !route.stream_chunks.is_empty() {
914                // Build SSE body: data: <chunk>\n\n ... data: [DONE]\n\n
915                let mut sse = String::new();
916                for chunk in &route.stream_chunks {
917                    sse.push_str("data: ");
918                    sse.push_str(chunk);
919                    sse.push_str("\n\n");
920                }
921                sse.push_str("data: [DONE]\n\n");
922
923                return Response::builder()
924                    .status(status)
925                    .header("content-type", "text/event-stream")
926                    .header("cache-control", "no-cache")
927                    .body(Body::from(sse))
928                    .unwrap()
929                    .into_response();
930            }
931
932            return Response::builder()
933                .status(status)
934                .header("content-type", "application/json")
935                .body(Body::from(route.body.clone()))
936                .unwrap()
937                .into_response();
938        }
939    }
940
941    // No matching route → 404.
942    Response::builder()
943        .status(StatusCode::NOT_FOUND)
944        .body(Body::from(format!("No mock route for {method} {path}")))
945        .unwrap()
946        .into_response()
947}
948"#
949}
950
951/// Generate the `src/main.rs` for the standalone mock server binary.
952///
953/// The binary:
954/// - Reads all `*.json` fixture files from a fixtures directory (default `../../fixtures`).
955/// - For each fixture that has a `mock_response` field, registers a route at
956///   `/fixtures/{fixture_id}` returning the configured status/body/SSE chunks.
957/// - Binds to `127.0.0.1:0` (random port), prints `MOCK_SERVER_URL=http://...`
958///   to stdout, then waits until stdin is closed for clean teardown.
959///
960/// This binary is intended for cross-language e2e suites (WASM, Node) that
961/// spawn it as a child process and read the URL from its stdout.
962fn render_mock_server_binary() -> String {
963    hash::header(CommentStyle::DoubleSlash)
964        + r#"//
965// Standalone mock HTTP server binary for cross-language e2e tests.
966// Reads fixture JSON files and serves mock responses on /fixtures/{fixture_id}.
967//
968// Usage: mock-server [fixtures-dir]
969//   fixtures-dir defaults to "../../fixtures"
970//
971// Prints `MOCK_SERVER_URL=http://127.0.0.1:<port>` to stdout once listening,
972// then blocks until stdin is closed (parent process exit triggers cleanup).
973
974use std::collections::HashMap;
975use std::io::{self, BufRead};
976use std::net::SocketAddr;
977use std::path::Path;
978use std::sync::Arc;
979
980use axum::Router;
981use axum::body::Body;
982use axum::extract::State;
983use axum::http::{Request, StatusCode};
984use axum::response::{IntoResponse, Response};
985use serde::Deserialize;
986use tokio::net::TcpListener;
987
988// ---------------------------------------------------------------------------
989// Fixture types (mirrors alef-e2e's fixture.rs for runtime deserialization)
990// ---------------------------------------------------------------------------
991
992#[derive(Debug, Deserialize)]
993struct MockResponse {
994    status: u16,
995    #[serde(default)]
996    body: Option<serde_json::Value>,
997    #[serde(default)]
998    stream_chunks: Option<Vec<serde_json::Value>>,
999}
1000
1001#[derive(Debug, Deserialize)]
1002struct Fixture {
1003    id: String,
1004    #[serde(default)]
1005    mock_response: Option<MockResponse>,
1006}
1007
1008// ---------------------------------------------------------------------------
1009// Route table
1010// ---------------------------------------------------------------------------
1011
1012#[derive(Clone, Debug)]
1013struct MockRoute {
1014    status: u16,
1015    body: String,
1016    stream_chunks: Vec<String>,
1017}
1018
1019type RouteTable = Arc<HashMap<String, MockRoute>>;
1020
1021// ---------------------------------------------------------------------------
1022// Axum handler
1023// ---------------------------------------------------------------------------
1024
1025async fn handle_request(State(routes): State<RouteTable>, req: Request<Body>) -> Response {
1026    let path = req.uri().path().to_owned();
1027
1028    // Try exact match first
1029    if let Some(route) = routes.get(&path) {
1030        return serve_route(route);
1031    }
1032
1033    // Try prefix match: find a route that is a prefix of the request path
1034    // This allows /fixtures/basic_chat/v1/chat/completions to match /fixtures/basic_chat
1035    for (route_path, route) in routes.iter() {
1036        if path.starts_with(route_path) && (path.len() == route_path.len() || path.as_bytes()[route_path.len()] == b'/') {
1037            return serve_route(route);
1038        }
1039    }
1040
1041    Response::builder()
1042        .status(StatusCode::NOT_FOUND)
1043        .body(Body::from(format!("No mock route for {path}")))
1044        .unwrap()
1045        .into_response()
1046}
1047
1048fn serve_route(route: &MockRoute) -> Response {
1049    let status = StatusCode::from_u16(route.status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
1050
1051    if !route.stream_chunks.is_empty() {
1052        let mut sse = String::new();
1053        for chunk in &route.stream_chunks {
1054            sse.push_str("data: ");
1055            sse.push_str(chunk);
1056            sse.push_str("\n\n");
1057        }
1058        sse.push_str("data: [DONE]\n\n");
1059
1060        return Response::builder()
1061            .status(status)
1062            .header("content-type", "text/event-stream")
1063            .header("cache-control", "no-cache")
1064            .body(Body::from(sse))
1065            .unwrap()
1066            .into_response();
1067    }
1068
1069    Response::builder()
1070        .status(status)
1071        .header("content-type", "application/json")
1072        .body(Body::from(route.body.clone()))
1073        .unwrap()
1074        .into_response()
1075}
1076
1077// ---------------------------------------------------------------------------
1078// Fixture loading
1079// ---------------------------------------------------------------------------
1080
1081fn load_routes(fixtures_dir: &Path) -> HashMap<String, MockRoute> {
1082    let mut routes = HashMap::new();
1083    load_routes_recursive(fixtures_dir, &mut routes);
1084    routes
1085}
1086
1087fn load_routes_recursive(dir: &Path, routes: &mut HashMap<String, MockRoute>) {
1088    let entries = match std::fs::read_dir(dir) {
1089        Ok(e) => e,
1090        Err(err) => {
1091            eprintln!("warning: cannot read directory {}: {err}", dir.display());
1092            return;
1093        }
1094    };
1095
1096    let mut paths: Vec<_> = entries.filter_map(|e| e.ok()).map(|e| e.path()).collect();
1097    paths.sort();
1098
1099    for path in paths {
1100        if path.is_dir() {
1101            load_routes_recursive(&path, routes);
1102        } else if path.extension().is_some_and(|ext| ext == "json") {
1103            let filename = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
1104            if filename == "schema.json" || filename.starts_with('_') {
1105                continue;
1106            }
1107            let content = match std::fs::read_to_string(&path) {
1108                Ok(c) => c,
1109                Err(err) => {
1110                    eprintln!("warning: cannot read {}: {err}", path.display());
1111                    continue;
1112                }
1113            };
1114            let fixtures: Vec<Fixture> = if content.trim_start().starts_with('[') {
1115                match serde_json::from_str(&content) {
1116                    Ok(v) => v,
1117                    Err(err) => {
1118                        eprintln!("warning: cannot parse {}: {err}", path.display());
1119                        continue;
1120                    }
1121                }
1122            } else {
1123                match serde_json::from_str::<Fixture>(&content) {
1124                    Ok(f) => vec![f],
1125                    Err(err) => {
1126                        eprintln!("warning: cannot parse {}: {err}", path.display());
1127                        continue;
1128                    }
1129                }
1130            };
1131
1132            for fixture in fixtures {
1133                if let Some(mock) = fixture.mock_response {
1134                    let route_path = format!("/fixtures/{}", fixture.id);
1135                    let body = mock
1136                        .body
1137                        .as_ref()
1138                        .map(|b| serde_json::to_string(b).unwrap_or_default())
1139                        .unwrap_or_default();
1140                    let stream_chunks = mock
1141                        .stream_chunks
1142                        .unwrap_or_default()
1143                        .into_iter()
1144                        .map(|c| match c {
1145                            serde_json::Value::String(s) => s,
1146                            other => serde_json::to_string(&other).unwrap_or_default(),
1147                        })
1148                        .collect();
1149                    routes.insert(route_path, MockRoute { status: mock.status, body, stream_chunks });
1150                }
1151            }
1152        }
1153    }
1154}
1155
1156// ---------------------------------------------------------------------------
1157// Entry point
1158// ---------------------------------------------------------------------------
1159
1160#[tokio::main]
1161async fn main() {
1162    let fixtures_dir_arg = std::env::args().nth(1).unwrap_or_else(|| "../../fixtures".to_string());
1163    let fixtures_dir = Path::new(&fixtures_dir_arg);
1164
1165    let routes = load_routes(fixtures_dir);
1166    eprintln!("mock-server: loaded {} routes from {}", routes.len(), fixtures_dir.display());
1167
1168    let route_table: RouteTable = Arc::new(routes);
1169    let app = Router::new().fallback(handle_request).with_state(route_table);
1170
1171    let listener = TcpListener::bind("127.0.0.1:0")
1172        .await
1173        .expect("mock-server: failed to bind port");
1174    let addr: SocketAddr = listener.local_addr().expect("mock-server: failed to get local addr");
1175
1176    // Print the URL so the parent process can read it.
1177    println!("MOCK_SERVER_URL=http://{addr}");
1178    // Flush stdout explicitly so the parent does not block waiting.
1179    use std::io::Write;
1180    std::io::stdout().flush().expect("mock-server: failed to flush stdout");
1181
1182    // Spawn the server in the background.
1183    tokio::spawn(async move {
1184        axum::serve(listener, app).await.expect("mock-server: server error");
1185    });
1186
1187    // Block until stdin is closed — the parent process controls lifetime.
1188    let stdin = io::stdin();
1189    let mut lines = stdin.lock().lines();
1190    while lines.next().is_some() {}
1191}
1192"#
1193}
1194
1195// ---------------------------------------------------------------------------
1196// Assertion rendering
1197// ---------------------------------------------------------------------------
1198
1199#[allow(clippy::too_many_arguments)]
1200fn render_assertion(
1201    out: &mut String,
1202    assertion: &Assertion,
1203    result_var: &str,
1204    module: &str,
1205    _dep_name: &str,
1206    is_error_context: bool,
1207    unwrapped_fields: &[(String, String)], // (fixture_field, local_var)
1208    field_resolver: &FieldResolver,
1209    result_is_tree: bool,
1210) {
1211    // Skip assertions on fields that don't exist on the result type.
1212    if let Some(f) = &assertion.field {
1213        if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
1214            let _ = writeln!(out, "    // skipped: field '{f}' not available on result type");
1215            return;
1216        }
1217    }
1218
1219    // Determine field access expression:
1220    // 1. If the field was unwrapped to a local var, use that local var name.
1221    // 2. When the result is a Tree, map pseudo-field names to correct Rust expressions.
1222    // 3. Otherwise, use the field resolver to generate the accessor.
1223    let field_access = match &assertion.field {
1224        Some(f) if !f.is_empty() => {
1225            if let Some((_, local_var)) = unwrapped_fields.iter().find(|(ff, _)| ff == f) {
1226                local_var.clone()
1227            } else if result_is_tree {
1228                // Tree is an opaque type — its "fields" are accessed via root_node() or
1229                // free functions. Map known pseudo-field names to correct Rust expressions.
1230                tree_field_access_expr(f, result_var, module)
1231            } else {
1232                field_resolver.accessor(f, "rust", result_var)
1233            }
1234        }
1235        _ => result_var.to_string(),
1236    };
1237
1238    // Check if this field was unwrapped (i.e., it is optional and was bound to a local).
1239    let is_unwrapped = assertion
1240        .field
1241        .as_ref()
1242        .is_some_and(|f| unwrapped_fields.iter().any(|(ff, _)| ff == f));
1243
1244    match assertion.assertion_type.as_str() {
1245        "error" => {
1246            let _ = writeln!(out, "    assert!({result_var}.is_err(), \"expected call to fail\");");
1247            if let Some(serde_json::Value::String(msg)) = &assertion.value {
1248                let escaped = escape_rust(msg);
1249                let _ = writeln!(
1250                    out,
1251                    "    assert!({result_var}.as_ref().unwrap_err().to_string().contains(\"{escaped}\"), \"error message mismatch\");"
1252                );
1253            }
1254        }
1255        "not_error" => {
1256            // Handled at call site; nothing extra needed here.
1257        }
1258        "equals" => {
1259            if let Some(val) = &assertion.value {
1260                let expected = value_to_rust_string(val);
1261                if is_error_context {
1262                    return;
1263                }
1264                // For string equality, trim trailing whitespace to handle trailing newlines
1265                // from the converter.
1266                if val.is_string() {
1267                    let _ = writeln!(
1268                        out,
1269                        "    assert_eq!({field_access}.trim(), {expected}, \"equals assertion failed\");"
1270                    );
1271                } else if val.is_boolean() {
1272                    // Use assert!/assert!(!...) for booleans — clippy prefers this over assert_eq!(_, true/false).
1273                    if val.as_bool() == Some(true) {
1274                        let _ = writeln!(out, "    assert!({field_access}, \"equals assertion failed\");");
1275                    } else {
1276                        let _ = writeln!(out, "    assert!(!{field_access}, \"equals assertion failed\");");
1277                    }
1278                } else {
1279                    // Wrap expected value in Some() for optional fields.
1280                    let is_opt = assertion.field.as_ref().is_some_and(|f| {
1281                        let resolved = field_resolver.resolve(f);
1282                        field_resolver.is_optional(resolved)
1283                    });
1284                    if is_opt
1285                        && !unwrapped_fields
1286                            .iter()
1287                            .any(|(ff, _)| assertion.field.as_ref() == Some(ff))
1288                    {
1289                        let _ = writeln!(
1290                            out,
1291                            "    assert_eq!({field_access}, Some({expected}), \"equals assertion failed\");"
1292                        );
1293                    } else {
1294                        let _ = writeln!(
1295                            out,
1296                            "    assert_eq!({field_access}, {expected}, \"equals assertion failed\");"
1297                        );
1298                    }
1299                }
1300            }
1301        }
1302        "contains" => {
1303            if let Some(val) = &assertion.value {
1304                let expected = value_to_rust_string(val);
1305                let line = format!(
1306                    "    assert!(format!(\"{{:?}}\", {field_access}).contains({expected}), \"expected to contain: {{}}\", {expected});"
1307                );
1308                let _ = writeln!(out, "{line}");
1309            }
1310        }
1311        "contains_all" => {
1312            if let Some(values) = &assertion.values {
1313                for val in values {
1314                    let expected = value_to_rust_string(val);
1315                    let line = format!(
1316                        "    assert!(format!(\"{{:?}}\", {field_access}).contains({expected}), \"expected to contain: {{}}\", {expected});"
1317                    );
1318                    let _ = writeln!(out, "{line}");
1319                }
1320            }
1321        }
1322        "not_contains" => {
1323            if let Some(val) = &assertion.value {
1324                let expected = value_to_rust_string(val);
1325                let line = format!(
1326                    "    assert!(!format!(\"{{:?}}\", {field_access}).contains({expected}), \"expected NOT to contain: {{}}\", {expected});"
1327                );
1328                let _ = writeln!(out, "{line}");
1329            }
1330        }
1331        "not_empty" => {
1332            if let Some(f) = &assertion.field {
1333                let resolved = field_resolver.resolve(f);
1334                if !is_unwrapped && field_resolver.is_optional(resolved) {
1335                    // Non-string optional field (e.g., Option<Struct>): use is_some()
1336                    let accessor = field_resolver.accessor(f, "rust", result_var);
1337                    let _ = writeln!(
1338                        out,
1339                        "    assert!({accessor}.is_some(), \"expected {f} to be present\");"
1340                    );
1341                } else {
1342                    let _ = writeln!(
1343                        out,
1344                        "    assert!(!{field_access}.is_empty(), \"expected non-empty value\");"
1345                    );
1346                }
1347            } else {
1348                // No field: assertion on the result itself. Use is_some() for Option types.
1349                let _ = writeln!(
1350                    out,
1351                    "    assert!({field_access}.is_some(), \"expected non-empty value\");"
1352                );
1353            }
1354        }
1355        "is_empty" => {
1356            if let Some(f) = &assertion.field {
1357                let resolved = field_resolver.resolve(f);
1358                if !is_unwrapped && field_resolver.is_optional(resolved) {
1359                    let accessor = field_resolver.accessor(f, "rust", result_var);
1360                    let _ = writeln!(out, "    assert!({accessor}.is_none(), \"expected {f} to be absent\");");
1361                } else {
1362                    let _ = writeln!(out, "    assert!({field_access}.is_empty(), \"expected empty value\");");
1363                }
1364            } else {
1365                // No field: assertion on the result itself. Use is_none() for Option types.
1366                let _ = writeln!(out, "    assert!({field_access}.is_none(), \"expected empty value\");");
1367            }
1368        }
1369        "contains_any" => {
1370            if let Some(values) = &assertion.values {
1371                let checks: Vec<String> = values
1372                    .iter()
1373                    .map(|v| {
1374                        let expected = value_to_rust_string(v);
1375                        format!("{field_access}.contains({expected})")
1376                    })
1377                    .collect();
1378                let joined = checks.join(" || ");
1379                let _ = writeln!(
1380                    out,
1381                    "    assert!({joined}, \"expected to contain at least one of the specified values\");"
1382                );
1383            }
1384        }
1385        "greater_than" => {
1386            if let Some(val) = &assertion.value {
1387                // Skip comparisons with negative values against unsigned types (.len() etc.)
1388                if val.as_f64().is_some_and(|n| n < 0.0) {
1389                    let _ = writeln!(
1390                        out,
1391                        "    // skipped: greater_than with negative value is always true for unsigned types"
1392                    );
1393                } else if val.as_u64() == Some(0) {
1394                    // Clippy prefers !is_empty() over len() > 0
1395                    let base = field_access.strip_suffix(".len()").unwrap_or(&field_access);
1396                    let _ = writeln!(out, "    assert!(!{base}.is_empty(), \"expected > 0\");");
1397                } else {
1398                    let lit = numeric_literal(val);
1399                    let _ = writeln!(out, "    assert!({field_access} > {lit}, \"expected > {lit}\");");
1400                }
1401            }
1402        }
1403        "less_than" => {
1404            if let Some(val) = &assertion.value {
1405                let lit = numeric_literal(val);
1406                let _ = writeln!(out, "    assert!({field_access} < {lit}, \"expected < {lit}\");");
1407            }
1408        }
1409        "greater_than_or_equal" => {
1410            if let Some(val) = &assertion.value {
1411                let lit = numeric_literal(val);
1412                if val.as_u64() == Some(1) && field_access.ends_with(".len()") {
1413                    // Clippy prefers !is_empty() over len() >= 1 for collections.
1414                    // Only apply when the expression is already a `.len()` call so we
1415                    // don't mistakenly call `.is_empty()` on numeric (usize) fields.
1416                    let base = field_access.strip_suffix(".len()").unwrap_or(&field_access);
1417                    let _ = writeln!(out, "    assert!(!{base}.is_empty(), \"expected >= 1\");");
1418                } else {
1419                    let _ = writeln!(out, "    assert!({field_access} >= {lit}, \"expected >= {lit}\");");
1420                }
1421            }
1422        }
1423        "less_than_or_equal" => {
1424            if let Some(val) = &assertion.value {
1425                let lit = numeric_literal(val);
1426                let _ = writeln!(out, "    assert!({field_access} <= {lit}, \"expected <= {lit}\");");
1427            }
1428        }
1429        "starts_with" => {
1430            if let Some(val) = &assertion.value {
1431                let expected = value_to_rust_string(val);
1432                let _ = writeln!(
1433                    out,
1434                    "    assert!({field_access}.starts_with({expected}), \"expected to start with: {{}}\", {expected});"
1435                );
1436            }
1437        }
1438        "ends_with" => {
1439            if let Some(val) = &assertion.value {
1440                let expected = value_to_rust_string(val);
1441                let _ = writeln!(
1442                    out,
1443                    "    assert!({field_access}.ends_with({expected}), \"expected to end with: {{}}\", {expected});"
1444                );
1445            }
1446        }
1447        "min_length" => {
1448            if let Some(val) = &assertion.value {
1449                if let Some(n) = val.as_u64() {
1450                    let _ = writeln!(
1451                        out,
1452                        "    assert!({field_access}.len() >= {n}, \"expected length >= {n}, got {{}}\", {field_access}.len());"
1453                    );
1454                }
1455            }
1456        }
1457        "max_length" => {
1458            if let Some(val) = &assertion.value {
1459                if let Some(n) = val.as_u64() {
1460                    let _ = writeln!(
1461                        out,
1462                        "    assert!({field_access}.len() <= {n}, \"expected length <= {n}, got {{}}\", {field_access}.len());"
1463                    );
1464                }
1465            }
1466        }
1467        "count_min" => {
1468            if let Some(val) = &assertion.value {
1469                if let Some(n) = val.as_u64() {
1470                    if n <= 1 {
1471                        // Clippy prefers !is_empty() over len() >= 1
1472                        let base = field_access.strip_suffix(".len()").unwrap_or(&field_access);
1473                        let _ = writeln!(out, "    assert!(!{base}.is_empty(), \"expected >= {n}\");");
1474                    } else {
1475                        let _ = writeln!(
1476                            out,
1477                            "    assert!({field_access}.len() >= {n}, \"expected at least {n} elements, got {{}}\", {field_access}.len());"
1478                        );
1479                    }
1480                }
1481            }
1482        }
1483        "count_equals" => {
1484            if let Some(val) = &assertion.value {
1485                if let Some(n) = val.as_u64() {
1486                    let _ = writeln!(
1487                        out,
1488                        "    assert_eq!({field_access}.len(), {n}, \"expected exactly {n} elements, got {{}}\", {field_access}.len());"
1489                    );
1490                }
1491            }
1492        }
1493        "is_true" => {
1494            let _ = writeln!(out, "    assert!({field_access}, \"expected true\");");
1495        }
1496        "is_false" => {
1497            let _ = writeln!(out, "    assert!(!{field_access}, \"expected false\");");
1498        }
1499        "method_result" => {
1500            if let Some(method_name) = &assertion.method {
1501                // Build the call expression. When the result is a tree-sitter Tree (an opaque
1502                // type), methods like `root_child_count` do not exist on `Tree` directly —
1503                // they are free functions in the crate or are accessed via `root_node()`.
1504                let call_expr = if result_is_tree {
1505                    build_tree_call_expr(field_access.as_str(), method_name, assertion.args.as_ref(), module)
1506                } else if let Some(args) = &assertion.args {
1507                    let arg_lit = json_to_rust_literal(args, "");
1508                    format!("{field_access}.{method_name}({arg_lit})")
1509                } else {
1510                    format!("{field_access}.{method_name}()")
1511                };
1512
1513                // Determine whether the call expression returns a numeric type so we can
1514                // choose the right comparison strategy for `greater_than_or_equal`.
1515                let returns_numeric = result_is_tree && is_tree_numeric_method(method_name);
1516
1517                let check = assertion.check.as_deref().unwrap_or("is_true");
1518                match check {
1519                    "equals" => {
1520                        if let Some(val) = &assertion.value {
1521                            if val.is_boolean() {
1522                                if val.as_bool() == Some(true) {
1523                                    let _ = writeln!(
1524                                        out,
1525                                        "    assert!({call_expr}, \"method_result equals assertion failed\");"
1526                                    );
1527                                } else {
1528                                    let _ = writeln!(
1529                                        out,
1530                                        "    assert!(!{call_expr}, \"method_result equals assertion failed\");"
1531                                    );
1532                                }
1533                            } else {
1534                                let expected = value_to_rust_string(val);
1535                                let _ = writeln!(
1536                                    out,
1537                                    "    assert_eq!({call_expr}, {expected}, \"method_result equals assertion failed\");"
1538                                );
1539                            }
1540                        }
1541                    }
1542                    "is_true" => {
1543                        let _ = writeln!(
1544                            out,
1545                            "    assert!({call_expr}, \"method_result is_true assertion failed\");"
1546                        );
1547                    }
1548                    "is_false" => {
1549                        let _ = writeln!(
1550                            out,
1551                            "    assert!(!{call_expr}, \"method_result is_false assertion failed\");"
1552                        );
1553                    }
1554                    "greater_than_or_equal" => {
1555                        if let Some(val) = &assertion.value {
1556                            let lit = numeric_literal(val);
1557                            if returns_numeric {
1558                                // Numeric return (e.g., child_count()) — always use >= comparison.
1559                                let _ = writeln!(out, "    assert!({call_expr} >= {lit}, \"expected >= {lit}\");");
1560                            } else if val.as_u64() == Some(1) {
1561                                // Clippy prefers !is_empty() over len() >= 1 for collections.
1562                                let _ = writeln!(out, "    assert!(!{call_expr}.is_empty(), \"expected >= 1\");");
1563                            } else {
1564                                let _ = writeln!(out, "    assert!({call_expr} >= {lit}, \"expected >= {lit}\");");
1565                            }
1566                        }
1567                    }
1568                    "count_min" => {
1569                        if let Some(val) = &assertion.value {
1570                            let n = val.as_u64().unwrap_or(0);
1571                            if n <= 1 {
1572                                let _ = writeln!(out, "    assert!(!{call_expr}.is_empty(), \"expected >= {n}\");");
1573                            } else {
1574                                let _ = writeln!(
1575                                    out,
1576                                    "    assert!({call_expr}.len() >= {n}, \"expected at least {n} elements, got {{}}\", {call_expr}.len());"
1577                                );
1578                            }
1579                        }
1580                    }
1581                    "is_error" => {
1582                        // For is_error we need the raw Result without .unwrap().
1583                        let raw_call = call_expr.strip_suffix(".unwrap()").unwrap_or(&call_expr);
1584                        let _ = writeln!(
1585                            out,
1586                            "    assert!({raw_call}.is_err(), \"expected method to return error\");"
1587                        );
1588                    }
1589                    "contains" => {
1590                        if let Some(val) = &assertion.value {
1591                            let expected = value_to_rust_string(val);
1592                            let _ = writeln!(
1593                                out,
1594                                "    assert!({call_expr}.contains({expected}), \"expected result to contain {{}}\", {expected});"
1595                            );
1596                        }
1597                    }
1598                    "not_empty" => {
1599                        let _ = writeln!(
1600                            out,
1601                            "    assert!(!{call_expr}.is_empty(), \"expected non-empty result\");"
1602                        );
1603                    }
1604                    "is_empty" => {
1605                        let _ = writeln!(out, "    assert!({call_expr}.is_empty(), \"expected empty result\");");
1606                    }
1607                    other_check => {
1608                        panic!("Rust e2e generator: unsupported method_result check type: {other_check}");
1609                    }
1610                }
1611            } else {
1612                panic!("Rust e2e generator: method_result assertion missing 'method' field");
1613            }
1614        }
1615        other => {
1616            panic!("Rust e2e generator: unsupported assertion type: {other}");
1617        }
1618    }
1619}
1620
1621/// Translate a fixture pseudo-field name on a `tree_sitter::Tree` into the
1622/// correct Rust accessor expression.
1623///
1624/// When an assertion uses `field: "root_child_count"` on a tree result, the
1625/// field resolver would naively emit `tree.root_child_count` — which is invalid
1626/// because `Tree` is an opaque type with no such field.  This function maps the
1627/// pseudo-field to the correct Rust expression instead.
1628fn tree_field_access_expr(field: &str, result_var: &str, module: &str) -> String {
1629    match field {
1630        "root_child_count" => format!("{result_var}.root_node().child_count()"),
1631        "root_node_type" => format!("{result_var}.root_node().kind()"),
1632        "named_children_count" => format!("{result_var}.root_node().named_child_count()"),
1633        "has_error_nodes" => format!("{module}::tree_has_error_nodes(&{result_var})"),
1634        "error_count" | "tree_error_count" => format!("{module}::tree_error_count(&{result_var})"),
1635        "tree_to_sexp" => format!("{module}::tree_to_sexp(&{result_var})"),
1636        // Unknown pseudo-field: fall back to direct field access (will likely fail to compile,
1637        // but gives the developer a useful error pointing to the fixture).
1638        other => format!("{result_var}.{other}"),
1639    }
1640}
1641
1642/// Build a Rust call expression for a logical "method" on a `tree_sitter::Tree`.
1643///
1644/// `Tree` is an opaque type — it does not expose methods like `root_child_count`.
1645/// Instead, these are either free functions in the crate or are accessed via
1646/// `tree.root_node().<method>()`. This function translates the fixture-level
1647/// method name into the correct Rust expression.
1648fn build_tree_call_expr(
1649    field_access: &str,
1650    method_name: &str,
1651    args: Option<&serde_json::Value>,
1652    module: &str,
1653) -> String {
1654    match method_name {
1655        "root_child_count" => format!("{field_access}.root_node().child_count()"),
1656        "root_node_type" => format!("{field_access}.root_node().kind()"),
1657        "named_children_count" => format!("{field_access}.root_node().named_child_count()"),
1658        "has_error_nodes" => format!("{module}::tree_has_error_nodes(&{field_access})"),
1659        "error_count" | "tree_error_count" => format!("{module}::tree_error_count(&{field_access})"),
1660        "tree_to_sexp" => format!("{module}::tree_to_sexp(&{field_access})"),
1661        "contains_node_type" => {
1662            let node_type = args
1663                .and_then(|a| a.get("node_type"))
1664                .and_then(|v| v.as_str())
1665                .unwrap_or("");
1666            format!("{module}::tree_contains_node_type(&{field_access}, \"{node_type}\")")
1667        }
1668        "find_nodes_by_type" => {
1669            let node_type = args
1670                .and_then(|a| a.get("node_type"))
1671                .and_then(|v| v.as_str())
1672                .unwrap_or("");
1673            format!("{module}::find_nodes_by_type(&{field_access}, \"{node_type}\")")
1674        }
1675        "run_query" => {
1676            let query_source = args
1677                .and_then(|a| a.get("query_source"))
1678                .and_then(|v| v.as_str())
1679                .unwrap_or("");
1680            let language = args
1681                .and_then(|a| a.get("language"))
1682                .and_then(|v| v.as_str())
1683                .unwrap_or("");
1684            // Use a raw string for the query to avoid escaping issues.
1685            // run_query returns Result — unwrap it for assertion access.
1686            format!(
1687                "{module}::run_query(&{field_access}, \"{language}\", r#\"{query_source}\"#, source.as_bytes()).unwrap()"
1688            )
1689        }
1690        // Fallback: try as a plain method call.
1691        _ => {
1692            if let Some(args) = args {
1693                let arg_lit = json_to_rust_literal(args, "");
1694                format!("{field_access}.{method_name}({arg_lit})")
1695            } else {
1696                format!("{field_access}.{method_name}()")
1697            }
1698        }
1699    }
1700}
1701
1702/// Returns `true` when the tree method name produces a numeric result (usize/u64),
1703/// meaning `>= N` comparisons should use direct numeric comparison rather than
1704/// `.is_empty()` (which only works for collections).
1705fn is_tree_numeric_method(method_name: &str) -> bool {
1706    matches!(
1707        method_name,
1708        "root_child_count" | "named_children_count" | "error_count" | "tree_error_count"
1709    )
1710}
1711
1712/// Convert a JSON numeric value to a Rust literal suitable for comparisons.
1713///
1714/// Whole numbers (no fractional part) are emitted as bare integer literals so
1715/// they are compatible with `usize`, `u64`, etc. (e.g., `.len()` results).
1716/// Numbers with a fractional component get the `_f64` suffix.
1717fn numeric_literal(value: &serde_json::Value) -> String {
1718    if let Some(n) = value.as_f64() {
1719        if n.fract() == 0.0 {
1720            // Whole number — emit without a type suffix so Rust can infer the
1721            // correct integer type from context (usize, u64, i64, …).
1722            return format!("{}", n as i64);
1723        }
1724        return format!("{n}_f64");
1725    }
1726    // Fallback: use the raw JSON representation.
1727    value.to_string()
1728}
1729
1730fn value_to_rust_string(value: &serde_json::Value) -> String {
1731    match value {
1732        serde_json::Value::String(s) => rust_raw_string(s),
1733        serde_json::Value::Bool(b) => format!("{b}"),
1734        serde_json::Value::Number(n) => n.to_string(),
1735        other => {
1736            let s = other.to_string();
1737            format!("\"{s}\"")
1738        }
1739    }
1740}
1741
1742// ---------------------------------------------------------------------------
1743// Visitor generation
1744// ---------------------------------------------------------------------------
1745
1746/// Resolve the visitor trait name based on module.
1747fn resolve_visitor_trait(module: &str) -> String {
1748    // For html_to_markdown modules, use HtmlVisitor
1749    if module.contains("html_to_markdown") {
1750        "HtmlVisitor".to_string()
1751    } else {
1752        // Default fallback for other modules
1753        "Visitor".to_string()
1754    }
1755}
1756
1757/// Emit a Rust visitor method for a callback action.
1758///
1759/// The parameter type list mirrors the `HtmlVisitor` trait in
1760/// `kreuzberg-dev/html-to-markdown`. Param names are bound to `_` because the
1761/// generated visitor body never references them — the body always returns a
1762/// fixed `VisitResult` variant — so we'd otherwise hit `unused_variables`
1763/// warnings that fail prek's `cargo clippy -D warnings` hook.
1764fn emit_rust_visitor_method(out: &mut String, method_name: &str, action: &CallbackAction) {
1765    // Each entry: parameters typed exactly as `HtmlVisitor` expects them,
1766    // bound to `_` patterns so the generated body needn't introduce unused
1767    // bindings. Receiver is `&mut self` to match the trait.
1768    let params = match method_name {
1769        "visit_link" => "_: &NodeContext, _: &str, _: &str, _: &str",
1770        "visit_image" => "_: &NodeContext, _: &str, _: &str, _: &str",
1771        "visit_heading" => "_: &NodeContext, _: u8, _: &str, _: Option<&str>",
1772        "visit_code_block" => "_: &NodeContext, _: Option<&str>, _: &str",
1773        "visit_code_inline"
1774        | "visit_strong"
1775        | "visit_emphasis"
1776        | "visit_strikethrough"
1777        | "visit_underline"
1778        | "visit_subscript"
1779        | "visit_superscript"
1780        | "visit_mark"
1781        | "visit_button"
1782        | "visit_summary"
1783        | "visit_figcaption"
1784        | "visit_definition_term"
1785        | "visit_definition_description" => "_: &NodeContext, _: &str",
1786        "visit_text" => "_: &NodeContext, _: &str",
1787        "visit_list_item" => "_: &NodeContext, _: bool, _: &str, _: &str",
1788        "visit_blockquote" => "_: &NodeContext, _: &str, _: u32",
1789        "visit_table_row" => "_: &NodeContext, _: &[String], _: bool",
1790        "visit_custom_element" => "_: &NodeContext, _: &str, _: &str",
1791        "visit_form" => "_: &NodeContext, _: &str, _: &str",
1792        "visit_input" => "_: &NodeContext, _: &str, _: &str, _: &str",
1793        "visit_audio" | "visit_video" | "visit_iframe" => "_: &NodeContext, _: &str",
1794        "visit_details" => "_: &NodeContext, _: bool",
1795        "visit_element_end" | "visit_table_end" | "visit_definition_list_end" | "visit_figure_end" => {
1796            "_: &NodeContext, _: &str"
1797        }
1798        "visit_list_start" => "_: &NodeContext, _: bool",
1799        "visit_list_end" => "_: &NodeContext, _: bool, _: &str",
1800        _ => "_: &NodeContext",
1801    };
1802
1803    let _ = writeln!(out, "        fn {method_name}(&mut self, {params}) -> VisitResult {{");
1804    match action {
1805        CallbackAction::Skip => {
1806            let _ = writeln!(out, "            VisitResult::Skip");
1807        }
1808        CallbackAction::Continue => {
1809            let _ = writeln!(out, "            VisitResult::Continue");
1810        }
1811        CallbackAction::PreserveHtml => {
1812            let _ = writeln!(out, "            VisitResult::PreserveHtml");
1813        }
1814        CallbackAction::Custom { output } => {
1815            let escaped = escape_rust(output);
1816            let _ = writeln!(out, "            VisitResult::Custom(\"{escaped}\".to_string())");
1817        }
1818        CallbackAction::CustomTemplate { template } => {
1819            let escaped = escape_rust(template);
1820            let _ = writeln!(out, "            VisitResult::Custom(format!(\"{escaped}\"))");
1821        }
1822    }
1823    let _ = writeln!(out, "        }}");
1824}