Skip to main content

alef_e2e/codegen/
r.rs

1//! R e2e test generator using testthat.
2
3use crate::config::E2eConfig;
4use crate::escape::{escape_r, r_template_to_paste0, sanitize_filename, sanitize_ident};
5use crate::field_access::FieldResolver;
6use crate::fixture::{Assertion, CallbackAction, Fixture, FixtureGroup, TemplateReturnForm};
7use alef_core::backend::GeneratedFile;
8use alef_core::config::ResolvedCrateConfig;
9use alef_core::hash::{self, CommentStyle};
10use anyhow::Result;
11use std::fmt::Write as FmtWrite;
12use std::path::PathBuf;
13
14use super::E2eCodegen;
15
16/// R e2e code generator.
17pub struct RCodegen;
18
19impl E2eCodegen for RCodegen {
20    fn generate(
21        &self,
22        groups: &[FixtureGroup],
23        e2e_config: &E2eConfig,
24        config: &ResolvedCrateConfig,
25        _type_defs: &[alef_core::ir::TypeDef],
26        _enums: &[alef_core::ir::EnumDef],
27    ) -> Result<Vec<GeneratedFile>> {
28        let lang = self.language_name();
29        let output_base = PathBuf::from(e2e_config.effective_output()).join(lang);
30
31        let mut files = Vec::new();
32
33        // Resolve call config with overrides.
34        let call = &e2e_config.call;
35        let overrides = call.overrides.get(lang);
36        let module_path = overrides
37            .and_then(|o| o.module.as_ref())
38            .cloned()
39            .unwrap_or_else(|| call.module.clone());
40        let _function_name = overrides
41            .and_then(|o| o.function.as_ref())
42            .cloned()
43            .unwrap_or_else(|| call.function.clone());
44        let result_is_simple = call.result_is_simple || overrides.is_some_and(|o| o.result_is_simple);
45        let result_is_r_list = overrides.is_some_and(|o| o.result_is_r_list);
46        let _result_var = &call.result_var;
47
48        // Resolve package config.
49        let r_pkg = e2e_config.resolve_package("r");
50        let pkg_name = r_pkg
51            .as_ref()
52            .and_then(|p| p.name.as_ref())
53            .cloned()
54            .unwrap_or_else(|| module_path.clone());
55        let pkg_path = r_pkg
56            .as_ref()
57            .and_then(|p| p.path.as_ref())
58            .cloned()
59            .unwrap_or_else(|| "../../packages/r".to_string());
60        let pkg_version = r_pkg
61            .as_ref()
62            .and_then(|p| p.version.as_ref())
63            .cloned()
64            .or_else(|| config.resolved_version())
65            .unwrap_or_else(|| "0.1.0".to_string());
66
67        // Generate DESCRIPTION file.
68        files.push(GeneratedFile {
69            path: output_base.join("DESCRIPTION"),
70            content: render_description(&pkg_name, &pkg_version, e2e_config.dep_mode),
71            generated_header: false,
72        });
73
74        // Generate test runner script.
75        files.push(GeneratedFile {
76            path: output_base.join("run_tests.R"),
77            content: render_test_runner(&pkg_path, e2e_config.dep_mode),
78            generated_header: true,
79        });
80
81        // setup-fixtures.R — testthat sources `setup-*.R` files in the tests
82        // directory once before any tests run, with the working directory set
83        // to the tests/ folder. We use this hook to chdir into the repo's
84        // shared `test_documents/` directory so that fixture paths like
85        // `pdf/fake_memo.pdf` resolve at extraction time.
86        files.push(GeneratedFile {
87            path: output_base.join("tests").join("setup-fixtures.R"),
88            content: render_setup_fixtures(&e2e_config.test_documents_relative_from(1)),
89            generated_header: true,
90        });
91
92        // Generate test files per category.
93        for group in groups {
94            let active: Vec<&Fixture> = group
95                .fixtures
96                .iter()
97                .filter(|f| super::should_include_fixture(f, lang, e2e_config))
98                .collect();
99
100            if active.is_empty() {
101                continue;
102            }
103
104            let filename = format!("test_{}.R", sanitize_filename(&group.category));
105            let content = render_test_file(&group.category, &active, result_is_simple, result_is_r_list, e2e_config);
106            files.push(GeneratedFile {
107                path: output_base.join("tests").join(filename),
108                content,
109                generated_header: true,
110            });
111        }
112
113        Ok(files)
114    }
115
116    fn language_name(&self) -> &'static str {
117        "r"
118    }
119}
120
121fn render_description(pkg_name: &str, pkg_version: &str, dep_mode: crate::config::DependencyMode) -> String {
122    let dep_line = match dep_mode {
123        crate::config::DependencyMode::Registry => {
124            format!("Imports: {pkg_name} ({pkg_version})\n")
125        }
126        crate::config::DependencyMode::Local => String::new(),
127    };
128    format!(
129        r#"Package: e2e.r
130Title: E2E Tests for {pkg_name}
131Version: 0.1.0
132Description: End-to-end test suite.
133{dep_line}Suggests: testthat (>= 3.0.0)
134Config/testthat/edition: 3
135"#
136    )
137}
138
139fn render_setup_fixtures(test_documents_path: &str) -> String {
140    let mut out = String::new();
141    out.push_str(&hash::header(CommentStyle::Hash));
142    let _ = writeln!(out);
143    let _ = writeln!(
144        out,
145        "# Resolve fixture paths against the repo's `test_documents/` directory."
146    );
147    let _ = writeln!(
148        out,
149        "# testthat sources setup-*.R with the working directory at tests/,"
150    );
151    let _ = writeln!(
152        out,
153        "# so test_documents lives three directories up: tests/ -> e2e/r/ -> e2e/ -> repo root."
154    );
155    let _ = writeln!(
156        out,
157        "# Each `test_that()` block has its working directory reset back to tests/, so"
158    );
159    let _ = writeln!(
160        out,
161        "# fixture lookups must be performed via this helper rather than relying on `setwd`."
162    );
163    let _ = writeln!(
164        out,
165        ".alef_test_documents <- normalizePath(\"{test_documents_path}\", mustWork = FALSE)"
166    );
167    let _ = writeln!(out, ".resolve_fixture <- function(path) {{");
168    let _ = writeln!(out, "  if (dir.exists(.alef_test_documents)) {{");
169    let _ = writeln!(out, "    file.path(.alef_test_documents, path)");
170    let _ = writeln!(out, "  }} else {{");
171    let _ = writeln!(out, "    path");
172    let _ = writeln!(out, "  }}");
173    let _ = writeln!(out, "}}");
174    let _ = writeln!(out);
175    // FormatMetadata is an internally-tagged enum (serde tag = "format_type")
176    // so the JSON shape varies. `simplifyVector = FALSE` hands us a per-variant
177    // list — keyed by the snake_case variant name (`image`, `excel`, ...) — that
178    // points at the inner metadata struct, with all other variants set to NULL.
179    // Collapse both shapes here so terminal `metadata$format` assertions see
180    // the human-readable format string (e.g. "PNG") instead of the wrapper list.
181    let _ = writeln!(
182        out,
183        ".alef_format_value <- function(x) {{
184  if (is.list(x)) {{
185    for (variant in names(x)) {{
186      v <- x[[variant]]
187      if (is.list(v) && !is.null(v[[\"format\"]]) && is.character(v[[\"format\"]])) {{
188        return(v[[\"format\"]])
189      }}
190    }}
191    if (!is.null(x[[\"format\"]]) && is.character(x[[\"format\"]])) {{
192      return(x[[\"format\"]])
193    }}
194    if (!is.null(x[[\"format_type\"]])) {{
195      return(x[[\"format_type\"]])
196    }}
197  }}
198  x
199}}"
200    );
201    out
202}
203
204fn render_test_runner(pkg_path: &str, dep_mode: crate::config::DependencyMode) -> String {
205    let mut out = String::new();
206    out.push_str(&hash::header(CommentStyle::Hash));
207    let _ = writeln!(out, "library(testthat)");
208    match dep_mode {
209        crate::config::DependencyMode::Registry => {
210            // In registry mode, require the installed CRAN package directly.
211            let _ = writeln!(out, "# Package loaded via library() from CRAN install.");
212        }
213        crate::config::DependencyMode::Local => {
214            // Use devtools::load_all() to load the local R package without requiring
215            // a full install, matching the e2e test runner convention.
216            let _ = writeln!(out, "devtools::load_all(\"{pkg_path}\")");
217        }
218    }
219    let _ = writeln!(out);
220    // Surface every failure rather than aborting at the default max_fails=10 —
221    // partial pass counts are essential for triage during e2e bring-up.
222    let _ = writeln!(out, "testthat::set_max_fails(Inf)");
223    // Resolve the tests/ directory relative to this script. testthat reads
224    // setup-*.R from there before each file runs, where path resolution
225    // against test_documents/ is handled by the `.resolve_fixture` helper.
226    let _ = writeln!(
227        out,
228        ".script_dir <- tryCatch(dirname(normalizePath(sys.frame(1)$ofile)), error = function(e) getwd())"
229    );
230    let _ = writeln!(out, "test_dir(file.path(.script_dir, \"tests\"))");
231    out
232}
233
234fn render_test_file(
235    category: &str,
236    fixtures: &[&Fixture],
237    result_is_simple: bool,
238    result_is_r_list: bool,
239    e2e_config: &E2eConfig,
240) -> String {
241    let mut out = String::new();
242    out.push_str(&hash::header(CommentStyle::Hash));
243    let _ = writeln!(out, "# E2e tests for category: {category}");
244    let _ = writeln!(out);
245
246    for (i, fixture) in fixtures.iter().enumerate() {
247        render_test_case(&mut out, fixture, e2e_config, result_is_simple, result_is_r_list);
248        if i + 1 < fixtures.len() {
249            let _ = writeln!(out);
250        }
251    }
252
253    // Clean up trailing newlines.
254    while out.ends_with("\n\n") {
255        out.pop();
256    }
257    if !out.ends_with('\n') {
258        out.push('\n');
259    }
260    out
261}
262
263fn render_test_case(
264    out: &mut String,
265    fixture: &Fixture,
266    e2e_config: &E2eConfig,
267    default_result_is_simple: bool,
268    default_result_is_r_list: bool,
269) {
270    let call_config = e2e_config.resolve_call_for_fixture(
271        fixture.call.as_deref(),
272        &fixture.id,
273        &fixture.resolved_category(),
274        &fixture.tags,
275        &fixture.input,
276    );
277    let call_field_resolver = FieldResolver::new(
278        e2e_config.effective_fields(call_config),
279        e2e_config.effective_fields_optional(call_config),
280        e2e_config.effective_result_fields(call_config),
281        e2e_config.effective_fields_array(call_config),
282        &std::collections::HashSet::new(),
283    );
284    let field_resolver = &call_field_resolver;
285    // Resolve `function` via the R override when present. The default
286    // `call_config.function` can be empty (e.g. trait-bridge calls like
287    // `clear_document_extractors` set `function = ""` at the top level and
288    // expose the real binding name only through per-language overrides);
289    // emitting it verbatim produces invalid `result <- ()` calls.
290    let function_name = call_config
291        .overrides
292        .get("r")
293        .and_then(|o| o.function.as_ref())
294        .cloned()
295        .unwrap_or_else(|| call_config.function.clone());
296    let result_var = &call_config.result_var;
297    // Per-fixture call configs (e.g. `list_document_extractors`) may set
298    // `result_is_simple = true` even when the default `[e2e.call]` does not.
299    // Without this lookup the registry/detection wrappers (which return scalar
300    // strings or character vectors directly) get wrapped in
301    // `jsonlite::fromJSON(...)` and the parser fails on non-JSON output.
302    let r_override = call_config.overrides.get("r");
303    let result_is_simple = if fixture.call.is_some() {
304        call_config.result_is_simple || r_override.is_some_and(|o| o.result_is_simple)
305    } else {
306        default_result_is_simple
307    };
308    // Per-fixture override: when the R binding already returns a native R list
309    // (not a JSON string), suppress `jsonlite::fromJSON` wrapping while still
310    // using field-path (`result$field`) accessors in assertions.
311    let result_is_r_list = if fixture.call.is_some() {
312        r_override.is_some_and(|o| o.result_is_r_list)
313    } else {
314        default_result_is_r_list
315    };
316
317    let test_name = sanitize_ident(&fixture.id);
318    let description = fixture.description.replace('"', "\\\"");
319
320    let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
321
322    // Allow per-call R overrides to remap fixture argument names. Many calls
323    // (e.g. `extract_bytes`, `batch_extract_files`) use language-neutral
324    // fixture field names (`data`, `paths`) that the R extendr binding
325    // exposes under different identifiers (`content`, `items`).
326    let arg_name_map = r_override.map(|o| &o.arg_name_map);
327    // Resolve `options_type` for typed config args. When set (e.g. via the
328    // C#/Java override that pins the `config` arg of `embed_texts` to
329    // `EmbeddingConfig`), we use it instead of the heuristic in
330    // `r_default_for_config_arg` so the extendr binding receives the right
331    // ExternalPtr type rather than a default `ExtractionConfig`.
332    let options_type = r_override.and_then(|o| o.options_type.as_deref()).or_else(|| {
333        // Fall back to any other language's override that pins the type —
334        // R doesn't define its own override list yet for most embed calls,
335        // and the underlying Rust signature is the same regardless of
336        // binding, so reusing csharp/java/go/php options_type is safe.
337        //
338        // Skip `Js`-prefixed types from the Node/wasm bindings: those are
339        // NAPI/wasm-bindgen specific wrapper types, while extendr exposes the
340        // bare Rust type names (e.g. `ExtractionConfig`, not `JsExtractionConfig`).
341        call_config
342            .overrides
343            .values()
344            .filter_map(|o| o.options_type.as_deref())
345            .find(|name| !name.starts_with("Js"))
346    });
347    let args_str = build_args_string(&fixture.input, &call_config.args, arg_name_map, options_type);
348
349    // Per-call R extra_args: positional trailing arguments appended verbatim.
350    // Used when the extendr wrapper has more parameters than the fixture
351    // declares (e.g. `render_pdf_page_to_png(pdf_bytes, page_index, dpi,
352    // password)` where `dpi`/`password` are optional in Rust but extendr
353    // surfaces them as required R parameters with no defaults).
354    let r_extra_args: Vec<String> = r_override.map(|o| o.extra_args.clone()).unwrap_or_default();
355    let args_with_extra = if r_extra_args.is_empty() {
356        args_str
357    } else {
358        let extra = r_extra_args.join(", ");
359        if args_str.is_empty() {
360            extra
361        } else {
362            format!("{args_str}, {extra}")
363        }
364    };
365
366    // Build visitor setup and args if present
367    let mut setup_lines = Vec::new();
368    let final_args = if let Some(visitor_spec) = &fixture.visitor {
369        build_r_visitor(&mut setup_lines, visitor_spec);
370        // R rejects duplicated named arguments ("matched by multiple actual arguments"), so
371        // strip any existing `options = ...` arg before appending the visitor-options list.
372        // Handles `options = NULL` (when no default) and `options = ConversionOptions$default()`
373        // (when build_args_string emits a default placeholder for an optional options arg).
374        let base = strip_options_arg(&args_with_extra);
375        let visitor_opts = "options = list(visitor = visitor)";
376        let trimmed = base.trim_matches([' ', ',']);
377        if trimmed.is_empty() {
378            visitor_opts.to_string()
379        } else {
380            format!("{trimmed}, {visitor_opts}")
381        }
382    } else {
383        args_with_extra
384    };
385
386    if expects_error {
387        let _ = writeln!(out, "test_that(\"{test_name}: {description}\", {{");
388        for line in &setup_lines {
389            let _ = writeln!(out, "  {line}");
390        }
391        let _ = writeln!(out, "  expect_error({function_name}({final_args}))");
392        let _ = writeln!(out, "}})");
393        return;
394    }
395
396    let _ = writeln!(out, "test_that(\"{test_name}: {description}\", {{");
397    for line in &setup_lines {
398        let _ = writeln!(out, "  {line}");
399    }
400    // The extendr extraction wrappers return JSON strings carrying the
401    // serialized core result; parse into an R list so tests can use `$`
402    // accessors. `result_is_simple` calls (e.g. `convert_html_to_markdown`)
403    // already return scalar values and must be passed through verbatim.
404    // `result_is_r_list` signals the binding returns a native R list (Robj),
405    // not a JSON string — skip `jsonlite::fromJSON` but keep `$` accessors.
406    // `returns_void` calls (trait-bridge `clear_*` wrappers that return `()`
407    // in Rust → `NULL` in R) must not bind a `result` variable: the previous
408    // emission of `result <- {function_name}(...)` was already correct when
409    // `function_name` resolved, but parsers flag a stray `result` for void
410    // calls. Use `invisible(...)` to make the void contract explicit.
411    if call_config.returns_void {
412        let _ = writeln!(out, "  invisible({function_name}({final_args}))");
413    } else if result_is_simple || result_is_r_list {
414        let _ = writeln!(out, "  {result_var} <- {function_name}({final_args})");
415    } else {
416        let _ = writeln!(
417            out,
418            "  {result_var} <- jsonlite::fromJSON({function_name}({final_args}), simplifyVector = FALSE)"
419        );
420    }
421
422    let result_is_bytes = call_config.result_is_bytes || r_override.is_some_and(|o| o.result_is_bytes);
423    for assertion in &fixture.assertions {
424        render_assertion(
425            out,
426            assertion,
427            result_var,
428            field_resolver,
429            result_is_simple,
430            result_is_bytes,
431            e2e_config,
432        );
433    }
434
435    let _ = writeln!(out, "}})");
436}
437
438/// Remove the named `options = …` argument (if any) from an R call-args string.
439///
440/// Walks the string while tracking paren/quote depth so a comma inside a nested
441/// expression like `options = list(visitor = visitor)` isn't treated as the
442/// arg terminator. Returns the rebuilt args string with the `options =` arg
443/// dropped; callers append a fresh one.
444fn strip_options_arg(args_str: &str) -> String {
445    let mut parts: Vec<String> = Vec::new();
446    let mut current = String::new();
447    let mut paren_depth: i32 = 0;
448    let mut in_single = false;
449    let mut in_double = false;
450    for c in args_str.chars() {
451        if !in_single && !in_double {
452            match c {
453                '(' | '[' | '{' => paren_depth += 1,
454                ')' | ']' | '}' => paren_depth -= 1,
455                '\'' => in_single = true,
456                '"' => in_double = true,
457                ',' if paren_depth == 0 => {
458                    parts.push(current.trim().to_string());
459                    current.clear();
460                    continue;
461                }
462                _ => {}
463            }
464        } else if in_single && c == '\'' {
465            in_single = false;
466        } else if in_double && c == '"' {
467            in_double = false;
468        }
469        current.push(c);
470    }
471    if !current.trim().is_empty() {
472        parts.push(current.trim().to_string());
473    }
474    parts
475        .into_iter()
476        .filter(|p| !p.starts_with("options ") && !p.starts_with("options="))
477        .collect::<Vec<_>>()
478        .join(", ")
479}
480
481fn build_args_string(
482    input: &serde_json::Value,
483    args: &[crate::config::ArgMapping],
484    arg_name_map: Option<&std::collections::HashMap<String, String>>,
485    options_type: Option<&str>,
486) -> String {
487    if args.is_empty() {
488        // No declared args means the wrapper takes zero parameters. Always
489        // emit an empty arg list — fixtures may carry harness metadata under
490        // `input` (e.g. `setup.lazy_init_required` for Go's eager-init shim)
491        // that must not leak into the R call site as a positional `list(...)`.
492        return String::new();
493    }
494
495    let parts: Vec<String> = args
496        .iter()
497        .filter_map(|arg| {
498            // Apply per-language argument renames before emitting the call.
499            let arg_name: &str = arg_name_map
500                .and_then(|m| m.get(&arg.name).map(String::as_str))
501                .unwrap_or(&arg.name);
502
503            let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
504            let val = input.get(field);
505            // R extendr-generated wrappers do not preserve Option<T> defaults from
506            // the Rust signature — every parameter is positional and required at
507            // the R level. To keep generated calls valid we must pass a placeholder
508            // (`NULL` for `Option<T>`, `ExtractionConfig$default()` for typed
509            // configs) whenever the fixture omits an optional value.
510            let val = match val {
511                Some(v) if !(v.is_null() && arg.optional) => v,
512                _ => {
513                    if !arg.optional {
514                        return None;
515                    }
516                    if arg.arg_type == "json_object" {
517                        let r_value = r_default_for_config_arg(arg_name, options_type);
518                        return Some(format!("{arg_name} = {r_value}"));
519                    }
520                    return Some(format!("{arg_name} = NULL"));
521                }
522            };
523            // The extendr bindings expect owned PORs (ExternalPtr) for typed
524            // config arguments — passing an R `list()` raises
525            // `Expected ExternalPtr got List`. The fixtures don't carry the
526            // option fields needed to round-trip through ExtractionConfig$new,
527            // so emit `ExtractionConfig$default()` whenever a `json_object` arg
528            // resolves to an empty / object-shaped JSON value.
529            if arg.arg_type == "json_object" && (val.is_null() || val.as_object().is_some_and(|m| m.is_empty())) {
530                let r_value = r_default_for_config_arg(arg_name, options_type);
531                return Some(format!("{arg_name} = {r_value}"));
532            }
533            // Non-empty json_object for typed config args (those whose default is a
534            // `$default()` constructor): use `TypeName$from_json(jsonlite::toJSON(...))`
535            // so the Rust function receives a proper ExternalPtr, not a list.
536            // For `options`-style args (default = NULL) emit as a plain R list.
537            if arg.arg_type == "json_object" && val.is_object() {
538                let default_expr = r_default_for_config_arg(arg_name, options_type);
539                if default_expr.ends_with("$default()") {
540                    // Extract the type name from "TypeName$default()"
541                    let type_name = default_expr.trim_end_matches("$default()");
542                    // Use the `I(...)` (AsIs) wrapper for array-valued fields so
543                    // `jsonlite::toJSON(..., auto_unbox = TRUE)` preserves them as
544                    // JSON arrays. Without this, single-element vectors get
545                    // unboxed to scalars (e.g. `c("foo")` → `"foo"`) and serde
546                    // rejects them when deserializing `Vec<T>` fields.
547                    let r_list = json_to_r_preserve_arrays(val, true);
548                    let r_value = format!("{type_name}$from_json(jsonlite::toJSON({r_list}, auto_unbox = TRUE))");
549                    return Some(format!("{arg_name} = {r_value}"));
550                }
551                let r_value = json_to_r(val, true);
552                return Some(format!("{arg_name} = {r_value}"));
553            }
554            // `json_object` arrays are passed to extendr functions whose Rust
555            // signature is `items: String` (JSON-serialized batch items). The
556            // wrapper has no R-list → JSON conversion, so we must serialize the
557            // fixture value to a literal JSON string at test-emit time.
558            //
559            // Exception: when `element_type = "String"` the Rust signature is
560            // `Vec<String>` (e.g. `embed_texts(texts: Vec<String>, ...)`), which
561            // extendr binds as a native R character vector. Passing a JSON
562            // literal there would land as a single-element character vector
563            // containing the literal bytes `["a","b"]`, which is not what the
564            // caller intended. Emit a plain `c("a","b")` literal instead.
565            if arg.arg_type == "json_object" && val.is_array() {
566                if arg.element_type.as_deref() == Some("String") {
567                    // `c()` is `NULL` in R, which extendr rejects with
568                    // `Expected Strings got Null` when the Rust signature is
569                    // `Vec<String>`. Emit a typed empty char vector for the
570                    // empty-input case so the binding sees `character(0)`.
571                    let r_value = if val.as_array().is_some_and(|arr| arr.is_empty()) {
572                        "character(0)".to_string()
573                    } else {
574                        json_to_r(val, false)
575                    };
576                    return Some(format!("{arg_name} = {r_value}"));
577                }
578                let json_literal = serde_json::to_string(val).unwrap_or_else(|_| "[]".to_string());
579                let escaped = escape_r(&json_literal);
580                return Some(format!("{arg_name} = \"{escaped}\""));
581            }
582            // `bytes` arg type: convert string fixture values into runtime
583            // `readBin(...)` calls so the wrapper receives raw bytes instead
584            // of an R character vector. This mirrors the Python emit_bytes_arg
585            // helper and is what the extendr binding for Vec<u8> expects.
586            if arg.arg_type == "bytes" {
587                if let Some(raw) = val.as_str() {
588                    let r_value = render_bytes_value(raw);
589                    return Some(format!("{arg_name} = {r_value}"));
590                }
591            }
592            // `file_path` arg type: fixtures encode relative paths that resolve
593            // against the repo's `test_documents/` directory. Using a runtime
594            // helper that anchors paths to that directory avoids fragility from
595            // testthat resetting the working directory between files.
596            if arg.arg_type == "file_path" {
597                if let Some(raw) = val.as_str() {
598                    if !raw.starts_with('/') && !raw.is_empty() {
599                        let escaped = escape_r(raw);
600                        return Some(format!("{arg_name} = .resolve_fixture(\"{escaped}\")"));
601                    }
602                }
603            }
604            Some(format!("{arg_name} = {}", json_to_r(val, true)))
605        })
606        .collect();
607
608    parts.join(", ")
609}
610
611/// Render a `bytes` fixture value as the R expression that produces a raw
612/// vector at test time. Mirrors python's `emit_bytes_arg` classifier so we can
613/// support both file-path style fixtures (`"pdf/fake_memo.pdf"`) and inline
614/// text payloads (`"<html>..."`). The resulting expression is dropped directly
615/// into the call site, e.g. `content = readBin(.resolve_fixture("pdf/fake_memo.pdf"), ...)`.
616fn render_bytes_value(raw: &str) -> String {
617    if raw.starts_with('<') || raw.starts_with('{') || raw.starts_with('[') || raw.contains(' ') {
618        // Inline text payload — encode to raw via charToRaw.
619        let escaped = escape_r(raw);
620        return format!("charToRaw(\"{escaped}\")");
621    }
622    let first = raw.chars().next().unwrap_or('\0');
623    if first.is_ascii_alphanumeric() || first == '_' {
624        if let Some(slash) = raw.find('/') {
625            if slash > 0 {
626                let after = &raw[slash + 1..];
627                if after.contains('.') && !after.is_empty() {
628                    let escaped = escape_r(raw);
629                    return format!(
630                        "readBin(.resolve_fixture(\"{escaped}\"), what = \"raw\", n = file.info(.resolve_fixture(\"{escaped}\"))$size)"
631                    );
632                }
633            }
634        }
635    }
636    // Default to inline text encoding — matches Python's InlineText branch.
637    let escaped = escape_r(raw);
638    format!("charToRaw(\"{escaped}\")")
639}
640
641/// Map the extractor argument name onto its R `*Config$default()` constructor.
642/// Falls back to `list()` for unknown names — the extendr binding will error
643/// with a clear message, which is preferable to silently passing a wrong type.
644///
645/// When `options_type` is provided (via a per-call language override pinning
646/// the typed config, e.g. `EmbeddingConfig` for `embed_texts`), it takes
647/// precedence over the arg-name heuristic so the extendr binding receives the
648/// correct ExternalPtr type.
649fn r_default_for_config_arg(arg_name: &str, options_type: Option<&str>) -> String {
650    if let Some(type_name) = options_type {
651        return format!("{type_name}$default()");
652    }
653    match arg_name {
654        "config" => "ExtractionConfig$default()".to_string(),
655        "options" => "NULL".to_string(),
656        "html_output" => "HtmlOutputConfig$default()".to_string(),
657        "chunking" => "ChunkingConfig$default()".to_string(),
658        "ocr" => "OcrConfig$default()".to_string(),
659        "image" | "images" => "ImageExtractionConfig$default()".to_string(),
660        "language_detection" => "LanguageDetectionConfig$default()".to_string(),
661        _ => "list()".to_string(),
662    }
663}
664
665fn render_assertion(
666    out: &mut String,
667    assertion: &Assertion,
668    result_var: &str,
669    field_resolver: &FieldResolver,
670    result_is_simple: bool,
671    result_is_bytes: bool,
672    _e2e_config: &E2eConfig,
673) {
674    // Handle synthetic / derived fields before the is_valid_for_result check
675    // so they are never treated as struct attribute accesses on the result.
676    if let Some(f) = &assertion.field {
677        match f.as_str() {
678            "chunks_have_content" => {
679                let pred = format!("all(sapply({result_var}$chunks %||% list(), function(c) nchar(c$content) > 0))");
680                match assertion.assertion_type.as_str() {
681                    "is_true" => {
682                        let _ = writeln!(out, "  expect_true({pred})");
683                    }
684                    "is_false" => {
685                        let _ = writeln!(out, "  expect_false({pred})");
686                    }
687                    _ => {
688                        let _ = writeln!(out, "  # skipped: unsupported assertion type on synthetic field '{f}'");
689                    }
690                }
691                return;
692            }
693            "chunks_have_embeddings" => {
694                let pred = format!(
695                    "all(sapply({result_var}$chunks %||% list(), function(c) !is.null(c$embedding) && length(c$embedding) > 0))"
696                );
697                match assertion.assertion_type.as_str() {
698                    "is_true" => {
699                        let _ = writeln!(out, "  expect_true({pred})");
700                    }
701                    "is_false" => {
702                        let _ = writeln!(out, "  expect_false({pred})");
703                    }
704                    _ => {
705                        let _ = writeln!(out, "  # skipped: unsupported assertion type on synthetic field '{f}'");
706                    }
707                }
708                return;
709            }
710            "chunks_have_heading_context" => {
711                // prepend_heading_context adds heading text to chunk content, so verify chunks
712                // exist and every chunk has non-empty content.
713                let pred_true = format!(
714                    "!is.null({result_var}$chunks) && length({result_var}$chunks) > 0 && all(sapply({result_var}$chunks, function(c) nchar(c$content) > 0))"
715                );
716                let pred_false = format!("is.null({result_var}$chunks) || length({result_var}$chunks) == 0");
717                match assertion.assertion_type.as_str() {
718                    "is_true" => {
719                        let _ = writeln!(out, "  expect_true({pred_true})");
720                    }
721                    "is_false" => {
722                        let _ = writeln!(out, "  expect_true({pred_false})");
723                    }
724                    _ => {
725                        let _ = writeln!(out, "  # skipped: unsupported assertion type on synthetic field '{f}'");
726                    }
727                }
728                return;
729            }
730            "first_chunk_starts_with_heading" => {
731                // First chunk's content should start with a markdown heading marker (`#`)
732                // when prepend_heading_context is enabled.
733                let pred_true = format!(
734                    "!is.null({result_var}$chunks) && length({result_var}$chunks) > 0 && startsWith(trimws({result_var}$chunks[[1]]$content), \"#\")"
735                );
736                let pred_false = format!(
737                    "is.null({result_var}$chunks) || length({result_var}$chunks) == 0 || !startsWith(trimws({result_var}$chunks[[1]]$content), \"#\")"
738                );
739                match assertion.assertion_type.as_str() {
740                    "is_true" => {
741                        let _ = writeln!(out, "  expect_true({pred_true})");
742                    }
743                    "is_false" => {
744                        let _ = writeln!(out, "  expect_true({pred_false})");
745                    }
746                    _ => {
747                        let _ = writeln!(out, "  # skipped: unsupported assertion type on synthetic field '{f}'");
748                    }
749                }
750                return;
751            }
752            // ---- EmbedResponse virtual fields ----
753            // The extendr binding cannot return `Vec<Vec<f32>>` directly (extendr's
754            // Robj conversion has no impl for nested numeric vectors), so the
755            // wrapper serializes the result to a JSON string at the FFI boundary.
756            // Parse it on demand here so length/index assertions operate on the
757            // matrix structure rather than on the single string scalar.
758            "embeddings" => {
759                let parsed = format!(
760                    "(if (is.character({result_var}) && length({result_var}) == 1) jsonlite::fromJSON({result_var}, simplifyVector = FALSE) else {result_var})"
761                );
762                match assertion.assertion_type.as_str() {
763                    "count_equals" => {
764                        if let Some(val) = &assertion.value {
765                            let r_val = json_to_r(val, false);
766                            let _ = writeln!(out, "  expect_equal(length({parsed}), {r_val})");
767                        }
768                    }
769                    "count_min" => {
770                        if let Some(val) = &assertion.value {
771                            let r_val = json_to_r(val, false);
772                            let _ = writeln!(out, "  expect_gte(length({parsed}), {r_val})");
773                        }
774                    }
775                    "not_empty" => {
776                        let _ = writeln!(out, "  expect_gt(length({parsed}), 0)");
777                    }
778                    "is_empty" => {
779                        let _ = writeln!(out, "  expect_equal(length({parsed}), 0)");
780                    }
781                    _ => {
782                        let _ = writeln!(
783                            out,
784                            "  # skipped: unsupported assertion type on synthetic field 'embeddings'"
785                        );
786                    }
787                }
788                return;
789            }
790            "embedding_dimensions" => {
791                let expr = format!("(if (length({result_var}) == 0) 0L else length({result_var}[[1]]))");
792                match assertion.assertion_type.as_str() {
793                    "equals" => {
794                        if let Some(val) = &assertion.value {
795                            let r_val = json_to_r(val, false);
796                            let _ = writeln!(out, "  expect_equal({expr}, {r_val})");
797                        }
798                    }
799                    "greater_than" => {
800                        if let Some(val) = &assertion.value {
801                            let r_val = json_to_r(val, false);
802                            let _ = writeln!(out, "  expect_gt({expr}, {r_val})");
803                        }
804                    }
805                    _ => {
806                        let _ = writeln!(
807                            out,
808                            "  # skipped: unsupported assertion type on synthetic field 'embedding_dimensions'"
809                        );
810                    }
811                }
812                return;
813            }
814            "embeddings_valid" | "embeddings_finite" | "embeddings_non_zero" | "embeddings_normalized" => {
815                let pred = match f.as_str() {
816                    "embeddings_valid" => {
817                        format!("all(sapply({result_var}, function(e) length(e) > 0))")
818                    }
819                    "embeddings_finite" => {
820                        format!("all(sapply({result_var}, function(e) all(is.finite(e))))")
821                    }
822                    "embeddings_non_zero" => {
823                        format!("all(sapply({result_var}, function(e) any(e != 0.0)))")
824                    }
825                    "embeddings_normalized" => {
826                        format!("all(sapply({result_var}, function(e) abs(sum(e * e) - 1.0) < 1e-3))")
827                    }
828                    _ => unreachable!(),
829                };
830                match assertion.assertion_type.as_str() {
831                    "is_true" => {
832                        let _ = writeln!(out, "  expect_true({pred})");
833                    }
834                    "is_false" => {
835                        let _ = writeln!(out, "  expect_false({pred})");
836                    }
837                    _ => {
838                        let _ = writeln!(out, "  # skipped: unsupported assertion type on synthetic field '{f}'");
839                    }
840                }
841                return;
842            }
843            // ---- keywords / keywords_count ----
844            // R ExtractionResult does not expose extracted_keywords; skip.
845            "keywords" | "keywords_count" => {
846                let _ = writeln!(out, "  # skipped: field '{f}' not available on R ExtractionResult");
847                return;
848            }
849            _ => {}
850        }
851    }
852
853    // Skip assertions on fields that don't exist on the result type.
854    if let Some(f) = &assertion.field {
855        if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
856            let _ = writeln!(out, "  # skipped: field '{f}' not available on result type");
857            return;
858        }
859    }
860
861    // When result_is_simple, skip assertions that reference non-content fields
862    // (e.g., metadata, document, structure) since the binding returns a plain value.
863    if result_is_simple {
864        if let Some(f) = &assertion.field {
865            let f_lower = f.to_lowercase();
866            if !f.is_empty()
867                && f_lower != "content"
868                && (f_lower.starts_with("metadata")
869                    || f_lower.starts_with("document")
870                    || f_lower.starts_with("structure"))
871            {
872                let _ = writeln!(
873                    out,
874                    "  # skipped: result_is_simple for field '{f}' not available on result type"
875                );
876                return;
877            }
878        }
879    }
880
881    let field_expr = if result_is_simple {
882        result_var.to_string()
883    } else {
884        match &assertion.field {
885            Some(f) if !f.is_empty() => field_resolver.accessor(f, "r", result_var),
886            _ => result_var.to_string(),
887        }
888    };
889
890    // FormatMetadata is serialized as an internally-tagged enum, so terminal
891    // accesses on `metadata.format` land on a list shaped like
892    // `{image: {format: "PNG", ...}, excel: NULL, ...}` under
893    // `simplifyVector = FALSE`. Wrap the accessor with `.alef_format_value`
894    // (from setup-fixtures.R) so the assertion sees the inner format string.
895    let field_expr = match &assertion.field {
896        Some(f) if f == "metadata.format" => format!(".alef_format_value({field_expr})"),
897        _ => field_expr,
898    };
899
900    match assertion.assertion_type.as_str() {
901        "equals" => {
902            if let Some(expected) = &assertion.value {
903                let r_val = json_to_r(expected, false);
904                let _ = writeln!(out, "  expect_equal(trimws({field_expr}), {r_val})");
905            }
906        }
907        "contains" => {
908            if let Some(expected) = &assertion.value {
909                let r_val = json_to_r(expected, false);
910                let _ = writeln!(out, "  expect_true(grepl({r_val}, {field_expr}, fixed = TRUE))");
911            }
912        }
913        "contains_all" => {
914            if let Some(values) = &assertion.values {
915                for val in values {
916                    let r_val = json_to_r(val, false);
917                    let _ = writeln!(out, "  expect_true(any(grepl({r_val}, {field_expr}, fixed = TRUE)))");
918                }
919            }
920        }
921        "not_contains" => {
922            if let Some(expected) = &assertion.value {
923                let r_val = json_to_r(expected, false);
924                let _ = writeln!(out, "  expect_false(grepl({r_val}, {field_expr}, fixed = TRUE))");
925            }
926        }
927        "not_empty" => {
928            // Multi-element character vectors (e.g. `list_embedding_presets`)
929            // would otherwise evaluate `nchar(x) > 0` element-wise and fail
930            // `expect_true`'s scalar-logical contract. Reduce with `any()` so
931            // the predicate stays a single TRUE/FALSE regardless of length,
932            // and treat zero-length vectors as empty.
933            let _ = writeln!(
934                out,
935                "  expect_true(if (is.character({field_expr})) length({field_expr}) > 0 && any(nchar({field_expr}) > 0) else length({field_expr}) > 0)"
936            );
937        }
938        "is_empty" => {
939            // Rust `Option<String>::None` surfaces as `NA_character_` through
940            // extendr, and `Vec<...>` empties as a zero-length vector. Treat
941            // NULL, NA, "", and zero-length collections as "empty" so the same
942            // assertion works for scalar Option returns (`get_embedding_preset`)
943            // and collection returns alike.
944            let _ = writeln!(
945                out,
946                "  expect_true(is.null({field_expr}) || length({field_expr}) == 0 || (length({field_expr}) == 1 && (is.na({field_expr}) || identical({field_expr}, \"\"))))"
947            );
948        }
949        "contains_any" => {
950            if let Some(values) = &assertion.values {
951                let items: Vec<String> = values.iter().map(|v| json_to_r(v, false)).collect();
952                let vec_str = items.join(", ");
953                let _ = writeln!(
954                    out,
955                    "  expect_true(any(sapply(c({vec_str}), function(v) grepl(v, {field_expr}, fixed = TRUE))))"
956                );
957            }
958        }
959        "greater_than" => {
960            if let Some(val) = &assertion.value {
961                let r_val = json_to_r(val, false);
962                let _ = writeln!(out, "  expect_true({field_expr} > {r_val})");
963            }
964        }
965        "less_than" => {
966            if let Some(val) = &assertion.value {
967                let r_val = json_to_r(val, false);
968                let _ = writeln!(out, "  expect_true({field_expr} < {r_val})");
969            }
970        }
971        "greater_than_or_equal" => {
972            if let Some(val) = &assertion.value {
973                let r_val = json_to_r(val, false);
974                let _ = writeln!(out, "  expect_true({field_expr} >= {r_val})");
975            }
976        }
977        "less_than_or_equal" => {
978            if let Some(val) = &assertion.value {
979                let r_val = json_to_r(val, false);
980                let _ = writeln!(out, "  expect_true({field_expr} <= {r_val})");
981            }
982        }
983        "starts_with" => {
984            if let Some(expected) = &assertion.value {
985                let r_val = json_to_r(expected, false);
986                let _ = writeln!(out, "  expect_true(startsWith({field_expr}, {r_val}))");
987            }
988        }
989        "ends_with" => {
990            if let Some(expected) = &assertion.value {
991                let r_val = json_to_r(expected, false);
992                let _ = writeln!(out, "  expect_true(endsWith({field_expr}, {r_val}))");
993            }
994        }
995        "min_length" => {
996            if let Some(val) = &assertion.value {
997                if let Some(n) = val.as_u64() {
998                    // Raw byte returns (`result_is_bytes`) come back as an R
999                    // raw vector; `nchar()` element-wises and breaks the
1000                    // expect_true scalar contract. Use `length()` to compare
1001                    // the byte count instead.
1002                    let size_fn = if result_is_bytes { "length" } else { "nchar" };
1003                    let _ = writeln!(out, "  expect_true({size_fn}({field_expr}) >= {n})");
1004                }
1005            }
1006        }
1007        "max_length" => {
1008            if let Some(val) = &assertion.value {
1009                if let Some(n) = val.as_u64() {
1010                    let size_fn = if result_is_bytes { "length" } else { "nchar" };
1011                    let _ = writeln!(out, "  expect_true({size_fn}({field_expr}) <= {n})");
1012                }
1013            }
1014        }
1015        "count_min" => {
1016            if let Some(val) = &assertion.value {
1017                if let Some(n) = val.as_u64() {
1018                    let _ = writeln!(out, "  expect_true(length({field_expr}) >= {n})");
1019                }
1020            }
1021        }
1022        "count_equals" => {
1023            if let Some(val) = &assertion.value {
1024                if let Some(n) = val.as_u64() {
1025                    let _ = writeln!(out, "  expect_equal(length({field_expr}), {n})");
1026                }
1027            }
1028        }
1029        "is_true" => {
1030            let _ = writeln!(out, "  expect_true({field_expr})");
1031        }
1032        "is_false" => {
1033            let _ = writeln!(out, "  expect_false({field_expr})");
1034        }
1035        "method_result" => {
1036            if let Some(method_name) = &assertion.method {
1037                let call_expr = build_r_method_call(result_var, method_name, assertion.args.as_ref());
1038                let check = assertion.check.as_deref().unwrap_or("is_true");
1039                match check {
1040                    "equals" => {
1041                        if let Some(val) = &assertion.value {
1042                            if val.is_boolean() {
1043                                if val.as_bool() == Some(true) {
1044                                    let _ = writeln!(out, "  expect_true({call_expr})");
1045                                } else {
1046                                    let _ = writeln!(out, "  expect_false({call_expr})");
1047                                }
1048                            } else {
1049                                let r_val = json_to_r(val, false);
1050                                let _ = writeln!(out, "  expect_equal({call_expr}, {r_val})");
1051                            }
1052                        }
1053                    }
1054                    "is_true" => {
1055                        let _ = writeln!(out, "  expect_true({call_expr})");
1056                    }
1057                    "is_false" => {
1058                        let _ = writeln!(out, "  expect_false({call_expr})");
1059                    }
1060                    "greater_than_or_equal" => {
1061                        if let Some(val) = &assertion.value {
1062                            let r_val = json_to_r(val, false);
1063                            let _ = writeln!(out, "  expect_true({call_expr} >= {r_val})");
1064                        }
1065                    }
1066                    "count_min" => {
1067                        if let Some(val) = &assertion.value {
1068                            let n = val.as_u64().unwrap_or(0);
1069                            let _ = writeln!(out, "  expect_true(length({call_expr}) >= {n})");
1070                        }
1071                    }
1072                    "is_error" => {
1073                        let _ = writeln!(out, "  expect_error({call_expr})");
1074                    }
1075                    "contains" => {
1076                        if let Some(val) = &assertion.value {
1077                            let r_val = json_to_r(val, false);
1078                            let _ = writeln!(out, "  expect_true(grepl({r_val}, {call_expr}, fixed = TRUE))");
1079                        }
1080                    }
1081                    other_check => {
1082                        panic!("R e2e generator: unsupported method_result check type: {other_check}");
1083                    }
1084                }
1085            } else {
1086                panic!("R e2e generator: method_result assertion missing 'method' field");
1087            }
1088        }
1089        "matches_regex" => {
1090            if let Some(expected) = &assertion.value {
1091                let r_val = json_to_r(expected, false);
1092                let _ = writeln!(out, "  expect_true(grepl({r_val}, {field_expr}))");
1093            }
1094        }
1095        "not_error" => {
1096            // The call itself stops the test on error; emit an explicit
1097            // `expect_true(TRUE)` so testthat doesn't report the test as
1098            // empty when this is the only assertion.
1099            let _ = writeln!(out, "  expect_true(TRUE)");
1100        }
1101        "error" => {
1102            // Handled at the test level.
1103        }
1104        other => {
1105            panic!("R e2e generator: unsupported assertion type: {other}");
1106        }
1107    }
1108}
1109
1110/// Convert a `serde_json::Value` to an R literal string.
1111///
1112/// # Arguments
1113///
1114/// * `value` - The JSON value to convert
1115///
1116/// Convert a PascalCase string to snake_case.
1117/// e.g. "DoubleEqual" → "double_equal", "Backticks" → "backticks"
1118fn pascal_to_snake_case(s: &str) -> String {
1119    let mut result = String::with_capacity(s.len() + 4);
1120    for (i, ch) in s.chars().enumerate() {
1121        if ch.is_uppercase() && i > 0 {
1122            result.push('_');
1123        }
1124        for lc in ch.to_lowercase() {
1125            result.push(lc);
1126        }
1127    }
1128    result
1129}
1130
1131/// Convert a JSON value to an R expression suitable for embedding inside a
1132/// `list(...)` that will be passed to `jsonlite::toJSON(..., auto_unbox = TRUE)`.
1133///
1134/// Differs from [`json_to_r`] in that any array-valued field is wrapped with
1135/// `I(...)` (jsonlite's `AsIs` marker) so it remains a JSON array after the
1136/// `auto_unbox` transform. Empty arrays become `I(list())` (→ `[]`) and
1137/// non-empty arrays become `I(c(...))` (→ `[..]`). Without this wrapping,
1138/// `Vec<String>` fields like `exclude_selectors` get unboxed to scalars and
1139/// serde deserialization on the Rust side fails with
1140/// `invalid type: string "foo", expected a sequence`.
1141fn json_to_r_preserve_arrays(value: &serde_json::Value, lowercase_enum_values: bool) -> String {
1142    match value {
1143        serde_json::Value::Array(arr) => {
1144            if arr.is_empty() {
1145                "I(list())".to_string()
1146            } else {
1147                let items: Vec<String> = arr.iter().map(|v| json_to_r(v, lowercase_enum_values)).collect();
1148                format!("I(c({}))", items.join(", "))
1149            }
1150        }
1151        serde_json::Value::Object(map) => {
1152            let entries: Vec<String> = map
1153                .iter()
1154                .map(|(k, v)| {
1155                    format!(
1156                        "\"{}\" = {}",
1157                        escape_r(k),
1158                        json_to_r_preserve_arrays(v, lowercase_enum_values)
1159                    )
1160                })
1161                .collect();
1162            format!("list({})", entries.join(", "))
1163        }
1164        _ => json_to_r(value, lowercase_enum_values),
1165    }
1166}
1167
1168/// * `lowercase_enum_values` - If true, convert PascalCase strings to snake_case (for enum values).
1169///   If false, preserve original case (for assertion expected values).
1170fn json_to_r(value: &serde_json::Value, lowercase_enum_values: bool) -> String {
1171    match value {
1172        serde_json::Value::String(s) => {
1173            // Convert PascalCase enum values to snake_case only if requested.
1174            // e.g. "Backticks" → "backticks", "DoubleEqual" → "double_equal"
1175            let normalized = if lowercase_enum_values && s.chars().next().is_some_and(|c| c.is_uppercase()) {
1176                pascal_to_snake_case(s)
1177            } else {
1178                s.clone()
1179            };
1180            format!("\"{}\"", escape_r(&normalized))
1181        }
1182        serde_json::Value::Bool(true) => "TRUE".to_string(),
1183        serde_json::Value::Bool(false) => "FALSE".to_string(),
1184        serde_json::Value::Number(n) => n.to_string(),
1185        serde_json::Value::Null => "NULL".to_string(),
1186        serde_json::Value::Array(arr) => {
1187            let items: Vec<String> = arr.iter().map(|v| json_to_r(v, lowercase_enum_values)).collect();
1188            format!("c({})", items.join(", "))
1189        }
1190        serde_json::Value::Object(map) => {
1191            let entries: Vec<String> = map
1192                .iter()
1193                .map(|(k, v)| format!("\"{}\" = {}", escape_r(k), json_to_r(v, lowercase_enum_values)))
1194                .collect();
1195            format!("list({})", entries.join(", "))
1196        }
1197    }
1198}
1199
1200/// Build an R visitor list and add setup line.
1201fn build_r_visitor(setup_lines: &mut Vec<String>, visitor_spec: &crate::fixture::VisitorSpec) {
1202    use std::fmt::Write as FmtWrite;
1203    // Collect each callback as a separate string, then join with ",\n" to avoid
1204    // trailing commas — R's list() does not accept a trailing comma.
1205    let methods: Vec<String> = visitor_spec
1206        .callbacks
1207        .iter()
1208        .map(|(method_name, action)| {
1209            let mut buf = String::new();
1210            emit_r_visitor_method(&mut buf, method_name, action);
1211            // strip the trailing ",\n" added by emit_r_visitor_method
1212            buf.trim_end_matches(['\n', ',']).to_string()
1213        })
1214        .collect();
1215    let mut visitor_obj = String::new();
1216    let _ = writeln!(visitor_obj, "list(");
1217    let _ = write!(visitor_obj, "{}", methods.join(",\n"));
1218    let _ = writeln!(visitor_obj);
1219    let _ = writeln!(visitor_obj, "  )");
1220
1221    setup_lines.push(format!("visitor <- {visitor_obj}"));
1222}
1223
1224/// Build an R call expression for a `method_result` assertion.
1225/// Maps method names to the appropriate R function or method calls.
1226fn build_r_method_call(result_var: &str, method_name: &str, args: Option<&serde_json::Value>) -> String {
1227    match method_name {
1228        "root_child_count" => format!("{result_var}$root_child_count()"),
1229        "root_node_type" => format!("{result_var}$root_node_type()"),
1230        "named_children_count" => format!("{result_var}$named_children_count()"),
1231        "has_error_nodes" => format!("tree_has_error_nodes({result_var})"),
1232        "error_count" | "tree_error_count" => format!("tree_error_count({result_var})"),
1233        "tree_to_sexp" => format!("tree_to_sexp({result_var})"),
1234        "contains_node_type" => {
1235            let node_type = args
1236                .and_then(|a| a.get("node_type"))
1237                .and_then(|v| v.as_str())
1238                .unwrap_or("");
1239            format!("tree_contains_node_type({result_var}, \"{node_type}\")")
1240        }
1241        "find_nodes_by_type" => {
1242            let node_type = args
1243                .and_then(|a| a.get("node_type"))
1244                .and_then(|v| v.as_str())
1245                .unwrap_or("");
1246            format!("find_nodes_by_type({result_var}, \"{node_type}\")")
1247        }
1248        "run_query" => {
1249            let query_source = args
1250                .and_then(|a| a.get("query_source"))
1251                .and_then(|v| v.as_str())
1252                .unwrap_or("");
1253            let language = args
1254                .and_then(|a| a.get("language"))
1255                .and_then(|v| v.as_str())
1256                .unwrap_or("");
1257            format!("run_query({result_var}, \"{language}\", \"{query_source}\", source)")
1258        }
1259        _ => {
1260            if let Some(args_val) = args {
1261                let arg_str = args_val
1262                    .as_object()
1263                    .map(|obj| {
1264                        obj.iter()
1265                            .map(|(k, v)| {
1266                                let r_val = json_to_r(v, false);
1267                                format!("{k} = {r_val}")
1268                            })
1269                            .collect::<Vec<_>>()
1270                            .join(", ")
1271                    })
1272                    .unwrap_or_default();
1273                format!("{result_var}${method_name}({arg_str})")
1274            } else {
1275                format!("{result_var}${method_name}()")
1276            }
1277        }
1278    }
1279}
1280
1281/// Emit an R visitor method for a callback action.
1282fn emit_r_visitor_method(out: &mut String, method_name: &str, action: &CallbackAction) {
1283    use std::fmt::Write as FmtWrite;
1284
1285    // R uses visit_ prefix (matches binding signature)
1286    let params = match method_name {
1287        "visit_link" => "ctx, href, text, title",
1288        "visit_image" => "ctx, src, alt, title",
1289        "visit_heading" => "ctx, level, text, id",
1290        "visit_code_block" => "ctx, lang, code",
1291        "visit_code_inline"
1292        | "visit_strong"
1293        | "visit_emphasis"
1294        | "visit_strikethrough"
1295        | "visit_underline"
1296        | "visit_subscript"
1297        | "visit_superscript"
1298        | "visit_mark"
1299        | "visit_button"
1300        | "visit_summary"
1301        | "visit_figcaption"
1302        | "visit_definition_term"
1303        | "visit_definition_description" => "ctx, text",
1304        "visit_text" => "ctx, text",
1305        "visit_list_item" => "ctx, ordered, marker, text",
1306        "visit_blockquote" => "ctx, content, depth",
1307        "visit_table_row" => "ctx, cells, is_header",
1308        "visit_custom_element" => "ctx, tag_name, html",
1309        "visit_form" => "ctx, action_url, method",
1310        "visit_input" => "ctx, input_type, name, value",
1311        "visit_audio" | "visit_video" | "visit_iframe" => "ctx, src",
1312        "visit_details" => "ctx, open",
1313        "visit_element_end" | "visit_table_end" | "visit_definition_list_end" | "visit_figure_end" => "ctx, output",
1314        "visit_list_start" => "ctx, ordered",
1315        "visit_list_end" => "ctx, ordered, output",
1316        _ => "ctx",
1317    };
1318
1319    let _ = writeln!(out, "    {method_name} = function({params}) {{");
1320    match action {
1321        CallbackAction::Skip => {
1322            let _ = writeln!(out, "      \"skip\"");
1323        }
1324        CallbackAction::Continue => {
1325            let _ = writeln!(out, "      \"continue\"");
1326        }
1327        CallbackAction::PreserveHtml => {
1328            let _ = writeln!(out, "      \"preserve_html\"");
1329        }
1330        CallbackAction::Custom { output } => {
1331            let escaped = escape_r(output);
1332            let _ = writeln!(out, "      list(custom = \"{escaped}\")");
1333        }
1334        CallbackAction::CustomTemplate { template, return_form } => {
1335            let r_expr = r_template_to_paste0(template);
1336            match return_form {
1337                TemplateReturnForm::BareString => {
1338                    let _ = writeln!(out, "      {r_expr}");
1339                }
1340                TemplateReturnForm::Dict => {
1341                    let _ = writeln!(out, "      list(custom = {r_expr})");
1342                }
1343            }
1344        }
1345    }
1346    let _ = writeln!(out, "    }},");
1347}