Skip to main content

alef_e2e/codegen/
swift.rs

1//! Swift e2e test generator using XCTest.
2//!
3//! Generates a standalone Swift package at `e2e/swift_e2e/` that depends on the
4//! binding at `packages/swift/` via `.package(path:)`.
5//!
6//! IMPORTANT: SwiftPM 6.0 derives the identity of path-based dependencies from
7//! the path's *basename* and ignores any explicit `name:` override. If the
8//! consumer (`e2e/swift/`) and the dep (`packages/swift/`) share the same path
9//! basename `swift`, SwiftPM treats them as the same package and fails
10//! resolution with: `product '<X>' required by package 'swift' target '...' not
11//! found in package 'swift'`. The e2e package is therefore emitted under
12//! `swift_e2e/` to guarantee a distinct identity from any sibling
13//! `packages/swift/` dep.
14
15use crate::config::E2eConfig;
16use crate::escape::{escape_java as escape_swift_str, expand_fixture_templates, sanitize_filename, sanitize_ident};
17use crate::field_access::{FieldResolver, SwiftFirstClassMap};
18use crate::fixture::{Assertion, Fixture, FixtureGroup, ValidationErrorExpectation};
19use alef_codegen::keywords::swift_ident;
20use alef_core::backend::GeneratedFile;
21use alef_core::config::ResolvedCrateConfig;
22use alef_core::hash::{self, CommentStyle};
23use alef_core::template_versions::toolchain;
24use anyhow::Result;
25use heck::{ToLowerCamelCase, ToSnakeCase, ToUpperCamelCase};
26use std::collections::HashMap;
27use std::collections::HashSet;
28use std::fmt::Write as FmtWrite;
29use std::path::PathBuf;
30
31use super::E2eCodegen;
32
33// Empty `result_field_accessor` map shared across calls that don't configure
34// one. Using a `OnceLock` lets `render_test_method` hand out a stable
35// reference without rebuilding the empty `HashMap` for every fixture.
36static EMPTY_FIELD_ACCESSOR_MAP: std::sync::OnceLock<HashMap<String, String>> = std::sync::OnceLock::new();
37
38fn empty_field_accessor_map() -> &'static HashMap<String, String> {
39    EMPTY_FIELD_ACCESSOR_MAP.get_or_init(HashMap::new)
40}
41use super::client;
42
43/// Swift e2e code generator.
44pub struct SwiftE2eCodegen;
45
46impl E2eCodegen for SwiftE2eCodegen {
47    fn generate(
48        &self,
49        groups: &[FixtureGroup],
50        e2e_config: &E2eConfig,
51        config: &ResolvedCrateConfig,
52        type_defs: &[alef_core::ir::TypeDef],
53        enums: &[alef_core::ir::EnumDef],
54    ) -> Result<Vec<GeneratedFile>> {
55        let lang = self.language_name();
56        // Emit under `<output>/swift_e2e/` so the consumer's SwiftPM identity
57        // (derived from path basename) does not collide with the dep at
58        // `packages/swift/` (also basename `swift`). SwiftPM 6.0 deprecated the
59        // `name:` parameter on `.package(path:)` and uses the path basename as
60        // the package's identity unconditionally, so disambiguation must happen
61        // at the filesystem level. Consumers of the alef-emitted e2e must
62        // `cd e2e/swift_e2e/` to run `swift test`.
63        let output_base = PathBuf::from(e2e_config.effective_output()).join("swift_e2e");
64
65        let mut files = Vec::new();
66
67        // Resolve call config with overrides.
68        let call = &e2e_config.call;
69        let overrides = call.overrides.get(lang);
70        let function_name = overrides
71            .and_then(|o| o.function.as_ref())
72            .cloned()
73            .unwrap_or_else(|| call.function.clone());
74        let result_var = &call.result_var;
75        let result_is_simple = overrides.is_some_and(|o| o.result_is_simple);
76
77        // Resolve package config.
78        let swift_pkg = e2e_config.resolve_package("swift");
79        let pkg_name = swift_pkg
80            .as_ref()
81            .and_then(|p| p.name.as_ref())
82            .cloned()
83            .unwrap_or_else(|| config.name.to_upper_camel_case());
84        let pkg_path = swift_pkg
85            .as_ref()
86            .and_then(|p| p.path.as_ref())
87            .cloned()
88            .unwrap_or_else(|| "../../packages/swift".to_string());
89        let pkg_version = swift_pkg
90            .as_ref()
91            .and_then(|p| p.version.as_ref())
92            .cloned()
93            .or_else(|| config.resolved_version())
94            .unwrap_or_else(|| "0.1.0".to_string());
95
96        // The Swift module name: UpperCamelCase of the package name.
97        let module_name = pkg_name.as_str();
98
99        // Resolve the registry URL: derive from the configured repository when
100        // available (with a `.git` suffix per SwiftPM convention). Falls back
101        // to a vendor-neutral placeholder when no repo is configured.
102        let registry_url = config
103            .try_github_repo()
104            .map(|repo| {
105                let base = repo.trim_end_matches('/').trim_end_matches(".git");
106                format!("{base}.git")
107            })
108            .unwrap_or_else(|_| format!("https://example.invalid/{module_name}.git"));
109
110        // Generate Package.swift for the standalone e2e consumer at
111        // `<output>/swift_e2e/`. `swift test` is run from that directory.
112        files.push(GeneratedFile {
113            path: output_base.join("Package.swift"),
114            content: render_package_swift(module_name, &registry_url, &pkg_path, &pkg_version, e2e_config.dep_mode),
115            generated_header: false,
116        });
117
118        // Tests are placed alongside Package.swift under `<output>/swift_e2e/Tests/...`.
119        let tests_base = output_base.clone();
120
121        // Build the Swift first-class/opaque classification map for per-segment
122        // dispatch in `render_swift_with_first_class_map`. A TypeDef is treated
123        // as first-class (Codable struct → property access) when it's not opaque,
124        // has serde derives, and every binding field is primitive/optional. This
125        // mirrors `can_emit_first_class_struct` in alef-backend-swift.
126        let swift_first_class_map = build_swift_first_class_map(type_defs, enums, e2e_config);
127
128        let swift_first_class_map_ref = swift_first_class_map;
129
130        // Resolve client_factory override for swift (enables client-instance dispatch).
131        let client_factory: Option<&str> = overrides.and_then(|o| o.client_factory.as_deref());
132
133        // Emit a shared TestHelpers.swift that gives `RustString` a
134        // `CustomStringConvertible` conformance. swift-bridge generates the
135        // `RustString` opaque class but does NOT make it print readably — so
136        // any error thrown from a bridge function (the `throw RustString(...)`
137        // branches) surfaces in XCTest's failure output as the bare type name
138        // `"RustBridge.RustString"`, with the actual Rust error message
139        // hidden inside the unprinted instance. The retroactive extension
140        // here pulls `.toString()` into `.description` so failures print
141        // something diagnostic. Single file per test target; idempotent
142        // across regens.
143        files.push(GeneratedFile {
144            path: tests_base
145                .join("Tests")
146                .join(format!("{module_name}E2ETests"))
147                .join("TestHelpers.swift"),
148            content: render_test_helpers_swift(),
149            generated_header: true,
150        });
151
152        // One test file per fixture group.
153        for group in groups {
154            let active: Vec<&Fixture> = group
155                .fixtures
156                .iter()
157                .filter(|f| super::should_include_fixture(f, lang, e2e_config))
158                .collect();
159
160            if active.is_empty() {
161                continue;
162            }
163
164            let class_name = format!("{}Tests", sanitize_filename(&group.category).to_upper_camel_case());
165            let filename = format!("{class_name}.swift");
166            let content = render_test_file(
167                &group.category,
168                &active,
169                e2e_config,
170                module_name,
171                &class_name,
172                &function_name,
173                result_var,
174                &e2e_config.call.args,
175                result_is_simple,
176                client_factory,
177                &swift_first_class_map_ref,
178            );
179            files.push(GeneratedFile {
180                path: tests_base
181                    .join("Tests")
182                    .join(format!("{module_name}E2ETests"))
183                    .join(filename),
184                content,
185                generated_header: true,
186            });
187        }
188
189        Ok(files)
190    }
191
192    fn language_name(&self) -> &'static str {
193        "swift"
194    }
195}
196
197// ---------------------------------------------------------------------------
198// Rendering
199// ---------------------------------------------------------------------------
200
201/// Directive telling Apple's `swift-format` to skip the file entirely.
202///
203/// The e2e generator emits Swift source with 4-space indentation, fixed import
204/// order (`XCTest, Foundation, <Module>`) and unwrapped long lines
205/// — all of which violate `swift-format`'s defaults (2-space indent, sorted
206/// imports, 100-char line width). Reformatting after every regen would force
207/// every consumer repo to either bake `swift-format` into their pre-commit set
208/// or eat noisy diffs. Marking the files as ignored is the same workaround the
209/// Swift binding backend uses for `HtmlToMarkdown.swift` (see
210/// `alef-backend-swift/src/gen_bindings.rs`) and keeps the file
211/// byte-identical between `alef generate` runs and `swift-format` hooks.
212const SWIFT_FORMAT_IGNORE_DIRECTIVE: &str = "// swift-format-ignore-file\n\n";
213
214/// Render the shared `TestHelpers.swift` file emitted into each Swift e2e
215/// test target. Adds a `CustomStringConvertible` conformance to swift-bridge's
216/// `RustString` so error messages from bridge throws print their actual Rust
217/// content instead of the bare class name.
218fn render_test_helpers_swift() -> String {
219    let header = hash::header(CommentStyle::DoubleSlash);
220    let ignore = SWIFT_FORMAT_IGNORE_DIRECTIVE;
221    format!(
222        r#"{header}{ignore}import Foundation
223import RustBridge
224
225// Make `RustString` print its content in XCTest failure output. Without this,
226// every error thrown from the swift-bridge layer surfaces as
227// `caught error: "RustBridge.RustString"` with the actual message hidden
228// inside the opaque class instance. The `@retroactive` keyword acknowledges
229// that the conformed-to protocol (`CustomStringConvertible`) and the
230// conforming type (`RustString`) both live outside this module — required by
231// Swift 6 to silence the retroactive-conformance warning. swift-bridge does
232// not give `RustString` a `description` of its own, so there is no conflict.
233extension RustString: @retroactive CustomStringConvertible {{
234    public var description: String {{ self.toString() }}
235}}
236"#
237    )
238}
239
240fn render_package_swift(
241    module_name: &str,
242    registry_url: &str,
243    pkg_path: &str,
244    pkg_version: &str,
245    dep_mode: crate::config::DependencyMode,
246) -> String {
247    let min_macos = toolchain::SWIFT_MIN_MACOS;
248
249    // For local deps SwiftPM identity = last path component (e.g. "../../packages/swift" → "swift").
250    // For registry deps identity is inferred from the URL.
251    // Use explicit .product(name:package:) to avoid ambiguity under tools-version 6.0.
252    let (dep_block, product_dep) = match dep_mode {
253        crate::config::DependencyMode::Registry => {
254            let dep = format!(r#"        .package(url: "{registry_url}", from: "{pkg_version}")"#);
255            let pkg_id = registry_url
256                .trim_end_matches('/')
257                .trim_end_matches(".git")
258                .split('/')
259                .next_back()
260                .unwrap_or(module_name);
261            let prod = format!(r#".product(name: "{module_name}", package: "{pkg_id}")"#);
262            (dep, prod)
263        }
264        crate::config::DependencyMode::Local => {
265            // SwiftPM 6.0 deprecated the `name:` parameter on `.package(path:)`:
266            // package identity is derived from the path's last component, ignoring
267            // any explicit `name:`. The `.product(package:)` reference must therefore
268            // match that identity (the path basename), not the dep's declared
269            // `Package(name:)`. The product `name:` still matches the library
270            // declared in the dep's manifest (e.g. `.library(name: "Kreuzberg")`).
271            let pkg_id = pkg_path.trim_end_matches('/').rsplit('/').next().unwrap_or(module_name);
272            let dep = format!(r#"        .package(path: "{pkg_path}")"#);
273            let prod = format!(r#".product(name: "{module_name}", package: "{pkg_id}")"#);
274            (dep, prod)
275        }
276    };
277    // SwiftPM platform enums use the major version only (.v13, .v14, ...);
278    // strip patch components to match the scaffold's `Package.swift`.
279    let min_macos_major = min_macos.split('.').next().unwrap_or(min_macos);
280    let min_ios = toolchain::SWIFT_MIN_IOS;
281    let min_ios_major = min_ios.split('.').next().unwrap_or(min_ios);
282    // The consumer's minimum iOS must be >= the dep's minimum iOS or SwiftPM hides
283    // the product as platform-incompatible. Use the same constant the swift backend
284    // emits into the dep's Package.swift.
285    format!(
286        r#"// swift-tools-version: 6.0
287import PackageDescription
288
289let package = Package(
290    name: "E2eSwift",
291    platforms: [
292        .macOS(.v{min_macos_major}),
293        .iOS(.v{min_ios_major}),
294    ],
295    dependencies: [
296{dep_block},
297    ],
298    targets: [
299        .testTarget(
300            name: "{module_name}E2ETests",
301            dependencies: [{product_dep}]
302        ),
303    ]
304)
305"#
306    )
307}
308
309#[allow(clippy::too_many_arguments)]
310fn render_test_file(
311    category: &str,
312    fixtures: &[&Fixture],
313    e2e_config: &E2eConfig,
314    module_name: &str,
315    class_name: &str,
316    function_name: &str,
317    result_var: &str,
318    args: &[crate::config::ArgMapping],
319    result_is_simple: bool,
320    client_factory: Option<&str>,
321    swift_first_class_map: &SwiftFirstClassMap,
322) -> String {
323    // Detect whether any fixture in this group uses a file_path or bytes arg — if so
324    // the test class chdir's to <repo>/test_documents at setUp time so the
325    // fixture-relative paths in test bodies (e.g. "docx/fake.docx") resolve correctly.
326    // The Swift binding's `extractBytes`/`extractFile` e2e wrappers consult
327    // `FIXTURES_DIR` first, otherwise resolve against the current directory.
328    // Mirrors the Ruby/Python conftest pattern that chdirs to test_documents.
329    let needs_chdir = fixtures.iter().any(|f| {
330        let call_config =
331            e2e_config.resolve_call_for_fixture(f.call.as_deref(), &f.id, &f.resolved_category(), &f.tags, &f.input);
332        call_config
333            .args
334            .iter()
335            .any(|a| a.arg_type == "file_path" || a.arg_type == "bytes")
336    });
337
338    let mut out = String::new();
339    out.push_str(&hash::header(CommentStyle::DoubleSlash));
340    out.push_str(SWIFT_FORMAT_IGNORE_DIRECTIVE);
341    let _ = writeln!(out, "import XCTest");
342    let _ = writeln!(out, "import Foundation");
343    let _ = writeln!(out, "import {module_name}");
344    // Intentionally omit `import RustBridge`: every name a per-category test
345    // file references is part of the public `{module_name}` surface (first-class
346    // Swift enums, structs, and the trait-bridge `*FromJsonWith{Field}`
347    // forwarder emitted by the swift backend). Importing `RustBridge` here
348    // collides with first-class Swift types whose Rust counterparts are also
349    // declared as opaque `extern \"Rust\" { type X; }` shims in the bridge —
350    // most notably `VisitResult` (Codable enum in `{module_name}` vs opaque
351    // `public class VisitResult` in `RustBridge`), producing
352    // `'VisitResult' is ambiguous for type lookup` at every callback site.
353    let _ = writeln!(out);
354    let _ = writeln!(out, "/// E2e tests for category: {category}.");
355    let _ = writeln!(out, "final class {class_name}: XCTestCase {{");
356
357    if needs_chdir {
358        // Chdir once at class setUp so all fixture file_path arguments resolve relative
359        // to the repository's test_documents directory.
360        //
361        // #filePath = <repo>/e2e/swift_e2e/Tests/<Module>E2ETests/<Class>.swift
362        // 5 deletingLastPathComponent() calls climb to the repo root before appending
363        // "test_documents". Mirrors the Ruby/Python conftest pattern that chdirs to
364        // test_documents.
365        let _ = writeln!(out, "    override class func setUp() {{");
366        let _ = writeln!(out, "        super.setUp()");
367        let _ = writeln!(out, "        let _testDocs = URL(fileURLWithPath: #filePath)");
368        let _ = writeln!(out, "            .deletingLastPathComponent() // <Module>Tests/");
369        let _ = writeln!(out, "            .deletingLastPathComponent() // Tests/");
370        let _ = writeln!(out, "            .deletingLastPathComponent() // swift/");
371        let _ = writeln!(out, "            .deletingLastPathComponent() // packages/");
372        let _ = writeln!(out, "            .deletingLastPathComponent() // <repo root>");
373        let _ = writeln!(
374            out,
375            "            .appendingPathComponent(\"{}\")",
376            e2e_config.test_documents_dir
377        );
378        let _ = writeln!(
379            out,
380            "        if FileManager.default.fileExists(atPath: _testDocs.path) {{"
381        );
382        let _ = writeln!(
383            out,
384            "            FileManager.default.changeCurrentDirectoryPath(_testDocs.path)"
385        );
386        let _ = writeln!(out, "        }}");
387        let _ = writeln!(out, "    }}");
388        let _ = writeln!(out);
389    }
390
391    for fixture in fixtures {
392        if fixture.is_http_test() {
393            render_http_test_method(&mut out, fixture);
394        } else {
395            render_test_method(
396                &mut out,
397                fixture,
398                e2e_config,
399                function_name,
400                result_var,
401                args,
402                result_is_simple,
403                client_factory,
404                swift_first_class_map,
405                module_name,
406            );
407        }
408        let _ = writeln!(out);
409    }
410
411    let _ = writeln!(out, "}}");
412    out
413}
414
415// ---------------------------------------------------------------------------
416// HTTP test rendering — TestClientRenderer impl + thin driver wrapper
417// ---------------------------------------------------------------------------
418
419/// Renderer that emits XCTest `func test...() throws` methods using `URLSession`
420/// against the mock server (`ProcessInfo.processInfo.environment["MOCK_SERVER_URL"]`).
421struct SwiftTestClientRenderer;
422
423impl client::TestClientRenderer for SwiftTestClientRenderer {
424    fn language_name(&self) -> &'static str {
425        "swift"
426    }
427
428    fn sanitize_test_name(&self, id: &str) -> String {
429        // Swift test methods are `func testFoo()` — upper-camel-case after "test".
430        sanitize_ident(id).to_upper_camel_case()
431    }
432
433    /// Emit `func test{FnName}() throws {` (or a skip stub when the fixture is skipped).
434    ///
435    /// XCTest has no first-class skip annotation prior to Swift Testing (`@Test`).
436    /// For skipped fixtures we emit `try XCTSkipIf(true, reason)` inside the
437    /// function body so XCTest records them as skipped rather than omitting them.
438    fn render_test_open(&self, out: &mut String, fn_name: &str, description: &str, skip_reason: Option<&str>) {
439        let _ = writeln!(out, "    /// {description}");
440        let _ = writeln!(out, "    func test{fn_name}() throws {{");
441        if let Some(reason) = skip_reason {
442            let escaped = escape_swift(reason);
443            let _ = writeln!(out, "        try XCTSkipIf(true, \"{escaped}\")");
444        }
445    }
446
447    fn render_test_close(&self, out: &mut String) {
448        let _ = writeln!(out, "    }}");
449    }
450
451    /// Emit a synchronous `URLSession` round-trip to the mock server.
452    ///
453    /// `ProcessInfo.processInfo.environment["MOCK_SERVER_URL"]!` provides the base
454    /// URL; the fixture path is appended directly.  The call uses a semaphore so the
455    /// generated test body stays synchronous (compatible with `throws` functions —
456    /// no `async` XCTest support needed).
457    fn render_call(&self, out: &mut String, ctx: &client::CallCtx<'_>) {
458        let method = ctx.method.to_uppercase();
459        let fixture_path = escape_swift(ctx.path);
460
461        let _ = writeln!(
462            out,
463            "        let _baseURL = ProcessInfo.processInfo.environment[\"MOCK_SERVER_URL\"]!"
464        );
465        let _ = writeln!(
466            out,
467            "        var _req = URLRequest(url: URL(string: _baseURL + \"{fixture_path}\")!)"
468        );
469        let _ = writeln!(out, "        _req.httpMethod = \"{method}\"");
470
471        // Headers
472        let mut header_pairs: Vec<(&String, &String)> = ctx.headers.iter().collect();
473        header_pairs.sort_by_key(|(k, _)| k.as_str());
474        for (k, v) in &header_pairs {
475            let expanded_v = expand_fixture_templates(v);
476            let ek = escape_swift(k);
477            let ev = escape_swift(&expanded_v);
478            let _ = writeln!(out, "        _req.setValue(\"{ev}\", forHTTPHeaderField: \"{ek}\")");
479        }
480
481        // Body
482        if let Some(body) = ctx.body {
483            let json_str = serde_json::to_string(body).unwrap_or_default();
484            let escaped_body = escape_swift(&json_str);
485            let _ = writeln!(out, "        _req.httpBody = \"{escaped_body}\".data(using: .utf8)");
486            let _ = writeln!(
487                out,
488                "        _req.setValue(\"application/json\", forHTTPHeaderField: \"Content-Type\")"
489            );
490        }
491
492        let _ = writeln!(out, "        var {}: HTTPURLResponse?", ctx.response_var);
493        let _ = writeln!(out, "        var _responseData: Data?");
494        let _ = writeln!(out, "        let _sema = DispatchSemaphore(value: 0)");
495        let _ = writeln!(
496            out,
497            "        URLSession.shared.dataTask(with: _req) {{ data, resp, _ in"
498        );
499        let _ = writeln!(out, "            {} = resp as? HTTPURLResponse", ctx.response_var);
500        let _ = writeln!(out, "            _responseData = data");
501        let _ = writeln!(out, "            _sema.signal()");
502        let _ = writeln!(out, "        }}.resume()");
503        let _ = writeln!(out, "        _sema.wait()");
504        let _ = writeln!(out, "        let _resp = try XCTUnwrap({})", ctx.response_var);
505    }
506
507    fn render_assert_status(&self, out: &mut String, _response_var: &str, status: u16) {
508        let _ = writeln!(out, "        XCTAssertEqual(_resp.statusCode, {status})");
509    }
510
511    fn render_assert_header(&self, out: &mut String, _response_var: &str, name: &str, expected: &str) {
512        let lower_name = name.to_lowercase();
513        let header_expr = format!("_resp.value(forHTTPHeaderField: \"{}\")", escape_swift(&lower_name));
514        match expected {
515            "<<present>>" => {
516                let _ = writeln!(out, "        XCTAssertNotNil({header_expr})");
517            }
518            "<<absent>>" => {
519                let _ = writeln!(out, "        XCTAssertNil({header_expr})");
520            }
521            "<<uuid>>" => {
522                let _ = writeln!(out, "        let _hdrVal_{lower_name} = try XCTUnwrap({header_expr})");
523                let _ = writeln!(
524                    out,
525                    "        XCTAssertNotNil(_hdrVal_{lower_name}.range(of: #\"^[0-9a-f]{{8}}-[0-9a-f]{{4}}-[0-9a-f]{{4}}-[0-9a-f]{{4}}-[0-9a-f]{{12}}$\"#, options: .regularExpression))"
526                );
527            }
528            exact => {
529                let escaped = escape_swift(exact);
530                let _ = writeln!(out, "        XCTAssertEqual({header_expr}, \"{escaped}\")");
531            }
532        }
533    }
534
535    fn render_assert_json_body(&self, out: &mut String, _response_var: &str, expected: &serde_json::Value) {
536        if let serde_json::Value::String(s) = expected {
537            let escaped = escape_swift(s);
538            let _ = writeln!(
539                out,
540                "        let _bodyStr = String(data: try XCTUnwrap(_responseData), encoding: .utf8) ?? \"\""
541            );
542            let _ = writeln!(
543                out,
544                "        XCTAssertEqual(_bodyStr.trimmingCharacters(in: .whitespacesAndNewlines), \"{escaped}\")"
545            );
546        } else {
547            let json_str = serde_json::to_string(expected).unwrap_or_default();
548            let escaped = escape_swift(&json_str);
549            let _ = writeln!(out, "        let _bodyData = try XCTUnwrap(_responseData)");
550            let _ = writeln!(
551                out,
552                "        let _expected = try JSONSerialization.jsonObject(with: \"{escaped}\".data(using: .utf8)!)"
553            );
554            let _ = writeln!(
555                out,
556                "        let _actual = try JSONSerialization.jsonObject(with: _bodyData)"
557            );
558            let _ = writeln!(
559                out,
560                "        XCTAssertEqual(NSDictionary(dictionary: _expected as? [String: AnyHashable] ?? [:]), NSDictionary(dictionary: _actual as? [String: AnyHashable] ?? [:]))"
561            );
562        }
563    }
564
565    fn render_assert_partial_body(&self, out: &mut String, _response_var: &str, expected: &serde_json::Value) {
566        if let Some(obj) = expected.as_object() {
567            let _ = writeln!(out, "        let _bodyData = try XCTUnwrap(_responseData)");
568            let _ = writeln!(
569                out,
570                "        let _bodyObj = try XCTUnwrap(try JSONSerialization.jsonObject(with: _bodyData) as? [String: Any])"
571            );
572            for (key, val) in obj {
573                let escaped_key = escape_swift(key);
574                let swift_val = json_to_swift(val);
575                let _ = writeln!(
576                    out,
577                    "        XCTAssertEqual(_bodyObj[\"{escaped_key}\"] as? AnyHashable, ({swift_val}) as AnyHashable)"
578                );
579            }
580        }
581    }
582
583    fn render_assert_validation_errors(
584        &self,
585        out: &mut String,
586        _response_var: &str,
587        errors: &[ValidationErrorExpectation],
588    ) {
589        let _ = writeln!(out, "        let _bodyData = try XCTUnwrap(_responseData)");
590        let _ = writeln!(
591            out,
592            "        let _bodyObj = try XCTUnwrap(try JSONSerialization.jsonObject(with: _bodyData) as? [String: Any])"
593        );
594        let _ = writeln!(
595            out,
596            "        let _errors = _bodyObj[\"errors\"] as? [[String: Any]] ?? []"
597        );
598        for ve in errors {
599            let escaped_msg = escape_swift(&ve.msg);
600            let _ = writeln!(
601                out,
602                "        XCTAssertTrue(_errors.contains(where: {{ ($0[\"msg\"] as? String)?.contains(\"{escaped_msg}\") == true }}), \"expected validation error: {escaped_msg}\")"
603            );
604        }
605    }
606}
607
608/// Render an XCTest method for an HTTP server fixture via the shared driver.
609///
610/// HTTP 101 (WebSocket upgrade) is emitted as a skip stub because `URLSession`
611/// cannot handle Upgrade responses.
612fn render_http_test_method(out: &mut String, fixture: &Fixture) {
613    let Some(http) = &fixture.http else {
614        return;
615    };
616
617    // HTTP 101 (WebSocket upgrade) — URLSession cannot handle upgrade responses.
618    if http.expected_response.status_code == 101 {
619        let method_name = sanitize_ident(&fixture.id).to_upper_camel_case();
620        let description = fixture.description.replace('"', "\\\"");
621        let _ = writeln!(out, "    /// {description}");
622        let _ = writeln!(out, "    func test{method_name}() throws {{");
623        let _ = writeln!(
624            out,
625            "        try XCTSkipIf(true, \"HTTP 101 WebSocket upgrade cannot be tested via URLSession\")"
626        );
627        let _ = writeln!(out, "    }}");
628        return;
629    }
630
631    client::http_call::render_http_test(out, &SwiftTestClientRenderer, fixture);
632}
633
634// ---------------------------------------------------------------------------
635// Function-call test rendering
636// ---------------------------------------------------------------------------
637
638#[allow(clippy::too_many_arguments)]
639fn render_test_method(
640    out: &mut String,
641    fixture: &Fixture,
642    e2e_config: &E2eConfig,
643    _function_name: &str,
644    _result_var: &str,
645    _args: &[crate::config::ArgMapping],
646    result_is_simple: bool,
647    global_client_factory: Option<&str>,
648    swift_first_class_map: &SwiftFirstClassMap,
649    module_name: &str,
650) {
651    // Resolve per-fixture call config.
652    let call_config = e2e_config.resolve_call_for_fixture(
653        fixture.call.as_deref(),
654        &fixture.id,
655        &fixture.resolved_category(),
656        &fixture.tags,
657        &fixture.input,
658    );
659    // Build per-call field resolver using the effective field sets for this call.
660    let call_field_resolver = FieldResolver::new_with_swift_first_class(
661        e2e_config.effective_fields(call_config),
662        e2e_config.effective_fields_optional(call_config),
663        e2e_config.effective_result_fields(call_config),
664        e2e_config.effective_fields_array(call_config),
665        e2e_config.effective_fields_method_calls(call_config),
666        &HashMap::new(),
667        swift_first_class_map.clone(),
668    );
669    let field_resolver = &call_field_resolver;
670    let enum_fields = e2e_config.effective_fields_enum(call_config);
671    let lang = "swift";
672    let call_overrides = call_config.overrides.get(lang);
673    let function_name = call_overrides
674        .and_then(|o| o.function.as_ref())
675        .cloned()
676        .unwrap_or_else(|| swift_ident(&call_config.function.to_lower_camel_case()));
677    // Per-call client_factory takes precedence over the global one.
678    let client_factory: Option<&str> = call_overrides
679        .and_then(|o| o.client_factory.as_deref())
680        .or(global_client_factory);
681    let result_var = &call_config.result_var;
682    let args = &call_config.args;
683    // Per-call flags: base call flag OR per-language override OR global flag.
684    // Also treat the call as simple when *any* language override marks it as bytes.
685    // Calls like `speech()` have `result_is_bytes = true` on C/C#/Java overrides but
686    // no explicit `result_is_simple` on the Swift override — yet the Swift binding
687    // returns `Data` directly (not a struct), so assertions must use `result.isEmpty`
688    // rather than `result.audio().toString().isEmpty`.
689    let result_is_bytes_any_lang =
690        call_config.result_is_bytes || call_config.overrides.values().any(|o| o.result_is_bytes);
691    let result_is_simple = call_config.result_is_simple
692        || call_overrides.is_some_and(|o| o.result_is_simple)
693        || result_is_simple
694        || result_is_bytes_any_lang;
695    let result_is_array = call_config.result_is_array;
696    // When the call returns `Option<T>` the Swift binding exposes the result as
697    // `Optional<…>` (e.g. `getEmbeddingPreset(...) -> EmbeddingPreset?`). Bare-result
698    // `is_empty`/`not_empty` assertions must use `XCTAssertNil` / `XCTAssertNotNil`
699    // rather than `.toString().isEmpty`, which is undefined on opaque optionals.
700    let result_is_option = call_config.result_is_option || call_overrides.is_some_and(|o| o.result_is_option);
701    let result_element_is_string =
702        call_config.result_element_is_string || call_overrides.is_some_and(|o| o.result_element_is_string);
703    // Per-language map of array-result-field → element accessor method (e.g.
704    // `structure → kind`). Empty map when no override is configured.
705    let result_field_accessor: &HashMap<String, String> = call_overrides
706        .map(|o| &o.result_field_accessor)
707        .unwrap_or_else(|| empty_field_accessor_map());
708
709    let method_name = fixture.id.to_upper_camel_case();
710    let description = &fixture.description;
711    let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
712    let is_async = call_config.r#async;
713
714    // Streaming detection (call-level `streaming` opt-out is honored).
715    let is_streaming = crate::codegen::streaming_assertions::resolve_is_streaming(fixture, call_config.streaming);
716    let collect_snippet_opt = if is_streaming && !expects_error {
717        crate::codegen::streaming_assertions::StreamingFieldResolver::collect_snippet(lang, result_var, "chunks")
718    } else {
719        None
720    };
721    // When swift has streaming-virtual-field assertions but no collect snippet
722    // is available (the swift-bridge surface does not yet expose a typed
723    // `chatStream` async sequence we can drain into a typed
724    // `[ChatCompletionChunk]`), emit a skip stub rather than reference an
725    // undefined `chunks` local in the assertion expressions. This keeps the
726    // swift test target compiling while the binding catches up.
727    if is_streaming && !expects_error && collect_snippet_opt.is_none() {
728        if is_async {
729            let _ = writeln!(out, "    func test{method_name}() async throws {{");
730        } else {
731            let _ = writeln!(out, "    func test{method_name}() throws {{");
732        }
733        let _ = writeln!(out, "        // {description}");
734        let _ = writeln!(
735            out,
736            "        try XCTSkipIf(true, \"swift: streaming chunk collection is not yet supported via the swift-bridge surface (fixture: {})\")",
737            fixture.id
738        );
739        let _ = writeln!(out, "    }}");
740        return;
741    }
742    let collect_snippet = collect_snippet_opt.unwrap_or_default();
743    // The shared streaming snippet references the unqualified `ChatCompletionChunk`
744    // type, but Swift consumers import both `<Module>` (the alef-emitted first-class
745    // `public struct ChatCompletionChunk`) AND `RustBridge` (the swift-bridge
746    // generated `public class ChatCompletionChunk`). Without module qualification
747    // Swift fails the test target with "'ChatCompletionChunk' is ambiguous for
748    // type lookup". Qualify to the first-class type so `chunks` is `[<Module>.ChatCompletionChunk]`.
749    let collect_snippet = if collect_snippet.is_empty() {
750        collect_snippet
751    } else {
752        collect_snippet.replace("[ChatCompletionChunk]", &format!("[{module_name}.ChatCompletionChunk]"))
753    };
754
755    // Detect whether this call has any json_object args that cannot be constructed
756    // in Swift — swift-bridge opaque types do not provide a fromJson initialiser.
757    // When such args exist and no `options_via` is configured for swift, emit a
758    // skip stub so the test compiles but is recorded as skipped rather than
759    // generating invalid code that passes `nil` or a string literal where a
760    // strongly-typed request object is required.
761    //
762    // Args with a scalar `element_type` (e.g. `"String"`, `"i32"`, `"f64"`,
763    // `"bool"`) describe a `Vec<T>` parameter on the Rust side, which the Swift
764    // binding exposes as a native `[T]` array. These map cleanly onto Swift
765    // array literals and do not require options_via configuration.
766    let has_unresolvable_json_object_arg = {
767        let options_via = call_overrides.and_then(|o| o.options_via.as_deref());
768        options_via.is_none()
769            && args.iter().any(|a| {
770                a.arg_type == "json_object" && a.name != "config" && !is_scalar_element_type(a.element_type.as_deref())
771            })
772    };
773
774    if has_unresolvable_json_object_arg {
775        if is_async {
776            let _ = writeln!(out, "    func test{method_name}() async throws {{");
777        } else {
778            let _ = writeln!(out, "    func test{method_name}() throws {{");
779        }
780        let _ = writeln!(out, "        // {description}");
781        let _ = writeln!(
782            out,
783            "        try XCTSkipIf(true, \"swift: json_object request construction requires options_via configuration (fixture: {})\");",
784            fixture.id
785        );
786        let _ = writeln!(out, "    }}");
787        return;
788    }
789
790    // Visitor-driven fixtures: emit a class that conforms to `HtmlVisitorProtocol`
791    // and wrap it via `makeHtmlVisitorHandle(...)`. The handle is then threaded
792    // into the options via `conversionOptionsFromJsonWithVisitor(json, handle)`.
793    let mut visitor_setup_lines: Vec<String> = Vec::new();
794    let visitor_handle_expr: Option<String> = fixture
795        .visitor
796        .as_ref()
797        .map(|spec| super::swift_visitors::build_swift_visitor(&mut visitor_setup_lines, spec, &fixture.id));
798
799    // Resolve extra_args from per-call swift overrides (e.g. `nil` for optional
800    // query-param arguments on list_files/list_batches that have no fixture-level
801    // input field).
802    let extra_args: Vec<String> = call_overrides.map(|o| o.extra_args.clone()).unwrap_or_default();
803
804    // Merge per-call enum_fields keys into the effective enum set so that
805    // fields like "status" (BatchStatus, BatchObject) are treated as enum-typed
806    // even when they are not globally listed in fields_enum (they are context-
807    // dependent — BatchStatus on BatchObject but plain String on ResponseObject).
808    let effective_enum_fields: std::borrow::Cow<HashSet<String>> = {
809        let per_call = call_overrides.map(|o| &o.enum_fields);
810        if let Some(pc) = per_call {
811            if !pc.is_empty() {
812                let mut merged = enum_fields.clone();
813                merged.extend(pc.keys().cloned());
814                std::borrow::Cow::Owned(merged)
815            } else {
816                std::borrow::Cow::Borrowed(enum_fields)
817            }
818        } else {
819            std::borrow::Cow::Borrowed(enum_fields)
820        }
821    };
822
823    let options_via_str: Option<&str> = call_overrides.and_then(|o| o.options_via.as_deref());
824    let options_type_str: Option<&str> = call_overrides.and_then(|o| o.options_type.as_deref());
825    // Derive the Swift handle-config parsing function from the C override's
826    // `c_engine_factory` field. E.g. `"CrawlConfig"` → snake → `"crawl_config_from_json"`
827    // → camelCase → `"crawlConfigFromJson"`.
828    let handle_config_fn_owned: Option<String> = call_config
829        .overrides
830        .get("c")
831        .and_then(|c| c.c_engine_factory.as_deref())
832        .map(|ty| format!("{}_from_json", ty.to_snake_case()).to_lower_camel_case());
833    let (mut setup_lines, args_str) = build_args_and_setup(
834        &fixture.input,
835        args,
836        &fixture.id,
837        fixture.has_host_root_route(),
838        &function_name,
839        options_via_str,
840        options_type_str,
841        handle_config_fn_owned.as_deref(),
842        visitor_handle_expr.as_deref(),
843        client_factory.is_some(),
844        module_name,
845    );
846    // Prepend visitor class declarations (before any setup lines that reference the handle).
847    if !visitor_setup_lines.is_empty() {
848        visitor_setup_lines.extend(setup_lines);
849        setup_lines = visitor_setup_lines;
850    }
851
852    // Append extra_args to the argument list.
853    let args_str = if extra_args.is_empty() {
854        args_str
855    } else if args_str.is_empty() {
856        extra_args.join(", ")
857    } else {
858        format!("{args_str}, {}", extra_args.join(", "))
859    };
860
861    // When a client_factory is set, dispatch via a client instance:
862    //   let client = try <FactoryType>(apiKey: "test-key", baseUrl: <mock_url>)
863    //   try await client.<method>(args)
864    // Otherwise fall back to free-function call (Kreuzberg / non-client-factory libraries).
865    let has_mock = fixture.mock_response.is_some();
866    let (call_setup, call_expr) = if let Some(_factory) = client_factory {
867        let env_key = format!("MOCK_SERVER_{}", fixture.id.to_ascii_uppercase().replace('-', "_"));
868        let mock_url = if fixture.has_host_root_route() {
869            format!(
870                "ProcessInfo.processInfo.environment[\"{env_key}\"] ?? (ProcessInfo.processInfo.environment[\"MOCK_SERVER_URL\"]! + \"/fixtures/{}\")",
871                fixture.id
872            )
873        } else {
874            format!(
875                "ProcessInfo.processInfo.environment[\"MOCK_SERVER_URL\"]! + \"/fixtures/{}\"",
876                fixture.id
877            )
878        };
879        let client_constructor = if has_mock {
880            format!("let _client = try DefaultClient(apiKey: \"test-key\", baseUrl: {mock_url})")
881        } else {
882            // Live API: check for api_key_var; if not present use mock URL anyway.
883            if let Some(env_var) = fixture.env.as_ref().and_then(|e| e.api_key_var.as_deref()) {
884                format!(
885                    "let _apiKey = ProcessInfo.processInfo.environment[\"{env_var}\"]\n        \
886                     let _baseUrl: String? = _apiKey != nil ? nil : {mock_url}\n        \
887                     let _client = try DefaultClient(apiKey: _apiKey ?? \"test-key\", baseUrl: _baseUrl)"
888                )
889            } else {
890                format!("let _client = try DefaultClient(apiKey: \"test-key\", baseUrl: {mock_url})")
891            }
892        };
893        let expr = if is_async {
894            format!("try await _client.{function_name}({args_str})")
895        } else {
896            format!("try _client.{function_name}({args_str})")
897        };
898        (Some(client_constructor), expr)
899    } else {
900        // Free-function call (no client_factory).
901        // Qualify with module name to disambiguate between high-level and swift-bridge symbols.
902        let expr = if is_async {
903            format!("try await {module_name}.{function_name}({args_str})")
904        } else {
905            format!("try {module_name}.{function_name}({args_str})")
906        };
907        (None, expr)
908    };
909    // For backwards compatibility: qualified_function_name unused when client_factory is set.
910    let _ = function_name;
911
912    if is_async {
913        let _ = writeln!(out, "    func test{method_name}() async throws {{");
914    } else {
915        let _ = writeln!(out, "    func test{method_name}() throws {{");
916    }
917    let _ = writeln!(out, "        // {description}");
918
919    if expects_error {
920        // For error fixtures, setup may itself throw (e.g. config validation
921        // happens at engine construction). Wrap the whole pipeline — setup
922        // and the call — in a single do/catch so any throw counts as success.
923        if is_async {
924            // XCTAssertThrowsError is a synchronous macro; for async-throwing
925            // functions use a do/catch with explicit XCTFail to enforce that
926            // the throw actually happens. `await XCTAssertThrowsError(...)` is
927            // not valid Swift — it evaluates `await` against a non-async expr.
928            let _ = writeln!(out, "        do {{");
929            for line in &setup_lines {
930                let _ = writeln!(out, "            {line}");
931            }
932            if let Some(setup) = &call_setup {
933                let _ = writeln!(out, "            {setup}");
934            }
935            let _ = writeln!(out, "            _ = {call_expr}");
936            let _ = writeln!(out, "            XCTFail(\"expected to throw\")");
937            let _ = writeln!(out, "        }} catch {{");
938            let _ = writeln!(out, "            // success");
939            let _ = writeln!(out, "        }}");
940        } else {
941            // Synchronous: emit setup outside (it's expected to succeed) and
942            // wrap only the throwing call in XCTAssertThrowsError. If setup
943            // itself throws, that propagates as the test's own failure — but
944            // sync tests use `throws` so the test method itself rethrows,
945            // which XCTest still records as caught. Keep this simple: use a
946            // do/catch so setup-time throws also count as expected failures.
947            let _ = writeln!(out, "        do {{");
948            for line in &setup_lines {
949                let _ = writeln!(out, "            {line}");
950            }
951            if let Some(setup) = &call_setup {
952                let _ = writeln!(out, "            {setup}");
953            }
954            let _ = writeln!(out, "            _ = {call_expr}");
955            let _ = writeln!(out, "            XCTFail(\"expected to throw\")");
956            let _ = writeln!(out, "        }} catch {{");
957            let _ = writeln!(out, "            // success");
958            let _ = writeln!(out, "        }}");
959        }
960        let _ = writeln!(out, "    }}");
961        return;
962    }
963
964    for line in &setup_lines {
965        let _ = writeln!(out, "        {line}");
966    }
967
968    // Emit client construction if a client_factory is configured.
969    if let Some(setup) = &call_setup {
970        let _ = writeln!(out, "        {setup}");
971    }
972
973    let _ = writeln!(out, "        let {result_var} = {call_expr}");
974
975    // Emit the collect snippet for streaming fixtures (drains the async sequence into
976    // a local `chunks: [ChatCompletionChunk]` array used by streaming-virtual assertions).
977    if !collect_snippet.is_empty() {
978        for line in collect_snippet.lines() {
979            let _ = writeln!(out, "        {line}");
980        }
981    }
982
983    // Each fixture's call returns a different IR type. Override the resolver's
984    // Swift first-class-map `root_type` with the call's `result_type` (looked up
985    // across c/csharp/java/kotlin/go/php overrides — these are language-agnostic
986    // IR type names that any backend can use to anchor field-access dispatch).
987    let fixture_root_type: Option<String> = swift_call_result_type(call_config);
988    let fixture_resolver = field_resolver.with_swift_root_type(fixture_root_type);
989
990    for assertion in &fixture.assertions {
991        let mut assertion_out = String::new();
992        render_assertion(
993            &mut assertion_out,
994            assertion,
995            result_var,
996            &fixture_resolver,
997            result_is_simple,
998            result_is_array,
999            result_is_option,
1000            result_element_is_string,
1001            result_field_accessor,
1002            &effective_enum_fields,
1003            is_streaming,
1004        );
1005        // Module-qualify swift-bridge-ambiguous DTO type names that appear in
1006        // streaming-virtual assertion expressions (e.g. `[StreamToolCall]`,
1007        // `[ToolCall]`). Both `<Module>` (first-class Codable struct) and
1008        // `RustBridge` (swift-bridge opaque class) export the same identifier,
1009        // so unqualified usage fails Swift compilation with "X is ambiguous for
1010        // type lookup". Mirrors the `[ChatCompletionChunk]` replacement in
1011        // `render_test_method`.
1012        for unqualified in ["StreamToolCall", "ToolCall"] {
1013            assertion_out =
1014                assertion_out.replace(&format!("[{unqualified}]"), &format!("[{module_name}.{unqualified}]"));
1015        }
1016        out.push_str(&assertion_out);
1017    }
1018
1019    let _ = writeln!(out, "    }}");
1020}
1021
1022#[allow(clippy::too_many_arguments)]
1023/// Build setup lines and the argument list for the function call.
1024///
1025/// Swift-bridge wrappers require strongly-typed values that don't have implicit
1026/// Swift literal conversions:
1027///
1028/// - `bytes` args become `RustVec<UInt8>` — fixture supplies a relative file path
1029///   string which is read at test time and pushed into a `RustVec<UInt8>` setup
1030///   variable. A literal byte array is base64-decoded or UTF-8 encoded inline.
1031/// - `json_object` args become opaque `ExtractionConfig` (or sibling) instances —
1032///   a JSON string is decoded via `extractionConfigFromJson(...)` in a setup line.
1033/// - Optional args missing from the fixture must still appear at the call site
1034///   as `nil` whenever a later positional arg is present, otherwise Swift slots
1035///   subsequent values into the wrong parameter.
1036fn build_args_and_setup(
1037    input: &serde_json::Value,
1038    args: &[crate::config::ArgMapping],
1039    fixture_id: &str,
1040    has_host_root_route: bool,
1041    function_name: &str,
1042    options_via: Option<&str>,
1043    options_type: Option<&str>,
1044    handle_config_fn: Option<&str>,
1045    visitor_handle_expr: Option<&str>,
1046    is_method_call: bool,
1047    module_name: &str,
1048) -> (Vec<String>, String) {
1049    if args.is_empty() {
1050        return (Vec::new(), String::new());
1051    }
1052
1053    let mut setup_lines: Vec<String> = Vec::new();
1054    let mut parts: Vec<(usize, String)> = Vec::new();
1055
1056    // Pre-compute, for each arg index, whether any later arg has a fixture-provided
1057    // value (or is required and will emit a default). When an optional arg is empty
1058    // but a later arg WILL emit, we must keep the slot with `nil` so positional
1059    // alignment is preserved.
1060    let later_emits: Vec<bool> = (0..args.len())
1061        .map(|i| {
1062            args.iter().skip(i + 1).any(|a| {
1063                let f = a.field.strip_prefix("input.").unwrap_or(&a.field);
1064                let v = input.get(f);
1065                let has_value = matches!(v, Some(x) if !x.is_null());
1066                has_value || !a.optional || (a.arg_type == "json_object" && a.name == "config")
1067            })
1068        })
1069        .collect();
1070
1071    for (idx, arg) in args.iter().enumerate() {
1072        if arg.arg_type == "mock_url" {
1073            let env_key = format!("MOCK_SERVER_{}", fixture_id.to_ascii_uppercase().replace('-', "_"));
1074            let url_expr = if has_host_root_route {
1075                format!(
1076                    "ProcessInfo.processInfo.environment[\"{env_key}\"] ?? (ProcessInfo.processInfo.environment[\"MOCK_SERVER_URL\"]! + \"/fixtures/{fixture_id}\")"
1077                )
1078            } else {
1079                format!("ProcessInfo.processInfo.environment[\"MOCK_SERVER_URL\"]! + \"/fixtures/{fixture_id}\"")
1080            };
1081            setup_lines.push(format!("let {} = {url_expr}", arg.name));
1082            parts.push((idx, arg.name.clone()));
1083            continue;
1084        }
1085
1086        if arg.arg_type == "handle" {
1087            let var_name = format!("{}Obj", arg.name.to_lower_camel_case());
1088            let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1089            let config_val = input.get(field);
1090            let has_config = config_val
1091                .is_some_and(|v| !(v.is_null() || v.is_object() && v.as_object().is_some_and(|o| o.is_empty())));
1092            if has_config {
1093                if let Some(from_json_fn) = handle_config_fn {
1094                    let json_str = serde_json::to_string(config_val.unwrap()).unwrap_or_default();
1095                    let escaped = escape_swift_str(&json_str);
1096                    let config_var = format!("{}Config", arg.name.to_lower_camel_case());
1097                    setup_lines.push(format!("let {config_var} = try {from_json_fn}(\"{escaped}\")"));
1098                    setup_lines.push(format!("let {var_name} = try createEngine({config_var})"));
1099                } else {
1100                    setup_lines.push(format!("let {var_name} = try createEngine(nil)"));
1101                }
1102            } else {
1103                setup_lines.push(format!("let {var_name} = try createEngine(nil)"));
1104            }
1105            parts.push((idx, var_name));
1106            continue;
1107        }
1108
1109        // bytes args: fixture stores a fixture-relative path string. Generate
1110        // setup that reads it into a Data and pushes each byte into a
1111        // RustVec<UInt8>. Literal byte arrays inline the bytes; missing values
1112        // produce an empty vec (or `nil` when optional).
1113        if arg.arg_type == "bytes" {
1114            let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1115            let val = input.get(field);
1116            match val {
1117                None | Some(serde_json::Value::Null) if arg.optional => {
1118                    if later_emits[idx] {
1119                        parts.push((idx, "nil".to_string()));
1120                    }
1121                }
1122                None | Some(serde_json::Value::Null) => {
1123                    let var_name = format!("{}Vec", arg.name.to_lower_camel_case());
1124                    setup_lines.push(format!("let {var_name} = RustVec<UInt8>()"));
1125                    parts.push((idx, var_name));
1126                }
1127                Some(serde_json::Value::String(s)) => {
1128                    let escaped = escape_swift(s);
1129                    let var_name = format!("{}Vec", arg.name.to_lower_camel_case());
1130                    let data_var = format!("{}Data", arg.name.to_lower_camel_case());
1131                    setup_lines.push(format!(
1132                        "let {data_var} = try Data(contentsOf: URL(fileURLWithPath: \"{escaped}\"))"
1133                    ));
1134                    setup_lines.push(format!("let {var_name} = RustVec<UInt8>()"));
1135                    setup_lines.push(format!("for _byte in {data_var} {{ {var_name}.push(value: _byte) }}"));
1136                    parts.push((idx, var_name));
1137                }
1138                Some(serde_json::Value::Array(arr)) => {
1139                    let var_name = format!("{}Vec", arg.name.to_lower_camel_case());
1140                    setup_lines.push(format!("let {var_name} = RustVec<UInt8>()"));
1141                    for v in arr {
1142                        if let Some(n) = v.as_u64() {
1143                            setup_lines.push(format!("{var_name}.push(value: UInt8({n}))"));
1144                        }
1145                    }
1146                    parts.push((idx, var_name));
1147                }
1148                Some(other) => {
1149                    // Fallback: encode the JSON serialisation as UTF-8 bytes.
1150                    let json_str = serde_json::to_string(other).unwrap_or_default();
1151                    let escaped = escape_swift(&json_str);
1152                    let var_name = format!("{}Vec", arg.name.to_lower_camel_case());
1153                    setup_lines.push(format!("let {var_name} = RustVec<UInt8>()"));
1154                    setup_lines.push(format!(
1155                        "for _byte in Array(\"{escaped}\".utf8) {{ {var_name}.push(value: _byte) }}"
1156                    ));
1157                    parts.push((idx, var_name));
1158                }
1159            }
1160            continue;
1161        }
1162
1163        // json_object "config" args: the swift-bridge wrapper requires an opaque
1164        // config instance (e.g., `ExtractionConfig`, `ProcessConfig`), not a JSON string.
1165        // Derive the from-json helper name from options_type if available, else default
1166        // to kreuzberg's `extractionConfigFromJson` for backward compatibility.
1167        // Batch functions (batchExtract*) hardcode config internally — skip it.
1168        let is_config_arg = arg.name == "config" && arg.arg_type == "json_object";
1169        let is_batch_fn = function_name.starts_with("batch") || function_name.starts_with("Batch");
1170        if is_config_arg && !is_batch_fn {
1171            let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1172            let val = input.get(field);
1173            let json_str = match val {
1174                None | Some(serde_json::Value::Null) => "{}".to_string(),
1175                Some(v) => serde_json::to_string(v).unwrap_or_else(|_| "{}".to_string()),
1176            };
1177            let escaped = escape_swift(&json_str);
1178            let var_name = format!("{}Obj", arg.name.to_lower_camel_case());
1179            // Derive the from-json helper name from options_type, or default to extractionConfigFromJson
1180            let from_json_fn = if let Some(type_name) = options_type {
1181                format!("{}FromJson", type_name.to_lower_camel_case())
1182            } else {
1183                "extractionConfigFromJson".to_string()
1184            };
1185            setup_lines.push(format!("let {var_name} = try {from_json_fn}(\"{escaped}\")"));
1186            parts.push((idx, var_name));
1187            continue;
1188        }
1189
1190        // json_object non-config args with options_via = "from_json":
1191        // Use the generated `{typeCamelCase}FromJson(_:)` helper so the fixture JSON is
1192        // deserialised into the opaque swift-bridge type rather than passed as a raw string.
1193        // When arg.field == "input", the entire fixture input IS the request object.
1194        // When a visitor handle is present, use `{typeCamelCase}FromJsonWithVisitor(json, handle)`
1195        // instead to attach the visitor to the options in one step.
1196        if arg.arg_type == "json_object" && options_via == Some("from_json") {
1197            if let Some(type_name) = options_type {
1198                let resolved_val = super::resolve_field(input, &arg.field);
1199                let json_str = match resolved_val {
1200                    serde_json::Value::Null => "{}".to_string(),
1201                    v => serde_json::to_string(v).unwrap_or_else(|_| "{}".to_string()),
1202                };
1203                let escaped = escape_swift(&json_str);
1204                let var_name = format!("_{}", arg.name.to_lower_camel_case());
1205                if let Some(handle_expr) = visitor_handle_expr {
1206                    // Use the visitor-aware helper: `{typeCamelCase}FromJsonWithVisitor(json, handle)`.
1207                    // The handle expression builds a VisitorHandle from the local class instance.
1208                    // The function name mirrors emit_options_field_options_helper: camelCase of
1209                    // `{options_snake}_from_json_with_visitor`.
1210                    let with_visitor_fn = format!("{}FromJsonWithVisitor", type_name.to_lower_camel_case());
1211                    let handle_var = format!("_visitorHandle_{}", var_name.trim_start_matches('_'));
1212                    setup_lines.push(format!("let {handle_var} = {handle_expr}"));
1213                    setup_lines.push(format!(
1214                        "let {var_name} = try {module_name}.{with_visitor_fn}(\"{escaped}\", {handle_var})"
1215                    ));
1216                } else {
1217                    let from_json_fn = format!("{}FromJson", type_name.to_lower_camel_case());
1218                    setup_lines.push(format!(
1219                        "let {var_name} = try {module_name}.{from_json_fn}(\"{escaped}\")"
1220                    ));
1221                }
1222                parts.push((idx, var_name));
1223                continue;
1224            }
1225        }
1226
1227        let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1228        let val = input.get(field);
1229        match val {
1230            None | Some(serde_json::Value::Null) if arg.optional => {
1231                // Optional arg with no fixture value: keep the slot with `nil`
1232                // when a later arg will emit, so positional alignment matches
1233                // the swift-bridge wrapper signature.
1234                if later_emits[idx] {
1235                    parts.push((idx, "nil".to_string()));
1236                }
1237            }
1238            None | Some(serde_json::Value::Null) => {
1239                let default_val = match arg.arg_type.as_str() {
1240                    "string" => "\"\"".to_string(),
1241                    "int" | "integer" => "0".to_string(),
1242                    "float" | "number" => "0.0".to_string(),
1243                    "bool" | "boolean" => "false".to_string(),
1244                    _ => "nil".to_string(),
1245                };
1246                parts.push((idx, default_val));
1247            }
1248            Some(v) => {
1249                parts.push((idx, json_to_swift(v)));
1250            }
1251        }
1252    }
1253
1254    // Method calls on the DefaultClient handle (e.g. `_client.chat(req)`) use
1255    // anonymous Swift argument labels (`func chat(_ req:)`), so omit `name:` prefixes.
1256    // Free-function calls (e.g. `process(source:, config:)`) keep labelled args.
1257    let args_str = parts
1258        .into_iter()
1259        .map(|(idx, val)| {
1260            if is_method_call {
1261                val
1262            } else {
1263                format!("{}: {}", args[idx].name, val)
1264            }
1265        })
1266        .collect::<Vec<_>>()
1267        .join(", ");
1268    (setup_lines, args_str)
1269}
1270
1271#[allow(clippy::too_many_arguments)]
1272fn render_assertion(
1273    out: &mut String,
1274    assertion: &Assertion,
1275    result_var: &str,
1276    field_resolver: &FieldResolver,
1277    result_is_simple: bool,
1278    result_is_array: bool,
1279    result_is_option: bool,
1280    result_element_is_string: bool,
1281    result_field_accessor: &HashMap<String, String>,
1282    enum_fields: &HashSet<String>,
1283    is_streaming: bool,
1284) {
1285    // When the bare result is `Optional<T>` (no field path) the opaque class
1286    // exposed by swift-bridge has no `.toString()` method, so the usual
1287    // `.toString().isEmpty` pattern produces compile errors. Detect the
1288    // "bare result" case and prefer `XCTAssertNil` / `XCTAssertNotNil`.
1289    let bare_result_is_option = result_is_option && assertion.field.as_deref().filter(|f| !f.is_empty()).is_none();
1290    // Streaming virtual fields resolve against the `chunks` collected-array variable.
1291    // Intercept before is_valid_for_result so they are never skipped.
1292    // Also intercept `usage.*` deep-paths in streaming tests: `AsyncThrowingStream` does
1293    // not have a `usage()` method, so we must route them through the chunks accessor.
1294    if let Some(f) = &assertion.field {
1295        let is_streaming_usage_path =
1296            is_streaming && (f == "usage" || (f.starts_with("usage.") || f.starts_with("usage[")));
1297        // Only route through the streaming-virtual `chunks` accessor when this is
1298        // actually a streaming fixture. Non-streaming fixtures (e.g. `process()`
1299        // with `chunkMaxSize`) expose `chunks` as a real `ProcessResult` field, so
1300        // emit `result.chunks()` via the regular field-accessor path below.
1301        if is_streaming
1302            && !f.is_empty()
1303            && (crate::codegen::streaming_assertions::is_streaming_virtual_field(f) || is_streaming_usage_path)
1304        {
1305            if let Some(expr) =
1306                crate::codegen::streaming_assertions::StreamingFieldResolver::accessor(f, "swift", "chunks")
1307            {
1308                let line = match assertion.assertion_type.as_str() {
1309                    "count_min" => {
1310                        if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1311                            format!("        XCTAssertGreaterThanOrEqual(chunks.count, {n})\n")
1312                        } else {
1313                            String::new()
1314                        }
1315                    }
1316                    "count_equals" => {
1317                        if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1318                            format!("        XCTAssertEqual(chunks.count, {n})\n")
1319                        } else {
1320                            String::new()
1321                        }
1322                    }
1323                    "equals" => {
1324                        if let Some(serde_json::Value::String(s)) = &assertion.value {
1325                            let escaped = escape_swift(s);
1326                            format!("        XCTAssertEqual({expr}, \"{escaped}\")\n")
1327                        } else if let Some(b) = assertion.value.as_ref().and_then(|v| v.as_bool()) {
1328                            format!("        XCTAssertEqual({expr}, {b})\n")
1329                        } else {
1330                            String::new()
1331                        }
1332                    }
1333                    "not_empty" => {
1334                        format!("        XCTAssertFalse({expr}.isEmpty, \"expected non-empty\")\n")
1335                    }
1336                    "is_empty" => {
1337                        format!("        XCTAssertTrue({expr}.isEmpty, \"expected empty\")\n")
1338                    }
1339                    "is_true" => {
1340                        format!("        XCTAssertTrue({expr})\n")
1341                    }
1342                    "is_false" => {
1343                        format!("        XCTAssertFalse({expr})\n")
1344                    }
1345                    "greater_than" => {
1346                        if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1347                            format!("        XCTAssertGreaterThan(chunks.count, {n})\n")
1348                        } else {
1349                            String::new()
1350                        }
1351                    }
1352                    "contains" => {
1353                        if let Some(serde_json::Value::String(s)) = &assertion.value {
1354                            let escaped = escape_swift(s);
1355                            format!(
1356                                "        XCTAssertTrue({expr}.contains(\"{escaped}\"), \"expected to contain: {escaped}\")\n"
1357                            )
1358                        } else {
1359                            String::new()
1360                        }
1361                    }
1362                    _ => format!(
1363                        "        // streaming field '{f}': assertion type '{}' not rendered\n",
1364                        assertion.assertion_type
1365                    ),
1366                };
1367                if !line.is_empty() {
1368                    out.push_str(&line);
1369                }
1370            }
1371            return;
1372        }
1373    }
1374
1375    // Skip assertions on fields that don't exist on the result type.
1376    if let Some(f) = &assertion.field {
1377        if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
1378            let _ = writeln!(out, "        // skipped: field '{f}' not available on result type");
1379            return;
1380        }
1381    }
1382
1383    // Skip assertions that traverse a tagged-union variant boundary.
1384    // In Swift, FormatMetadata and similar enum-backed opaque types are exposed as
1385    // plain classes by swift-bridge — variant accessor methods (e.g., `.excel()`)
1386    // are not generated, so such assertions cannot be expressed.
1387    if let Some(f) = &assertion.field {
1388        if !f.is_empty() && field_resolver.tagged_union_split(f).is_some() {
1389            let _ = writeln!(
1390                out,
1391                "        // skipped: field '{f}' crosses a tagged-union variant boundary (not expressible in Swift)"
1392            );
1393            return;
1394        }
1395    }
1396
1397    // Determine if this field is an enum type.
1398    let field_is_enum = assertion
1399        .field
1400        .as_deref()
1401        .is_some_and(|f| enum_fields.contains(f) || enum_fields.contains(field_resolver.resolve(f)));
1402
1403    let field_is_optional = assertion.field.as_deref().is_some_and(|f| {
1404        !f.is_empty() && (field_resolver.is_optional(f) || field_resolver.is_optional(field_resolver.resolve(f)))
1405    });
1406    let field_is_array = assertion.field.as_deref().is_some_and(|f| {
1407        !f.is_empty()
1408            && (field_resolver.is_array(f)
1409                || field_resolver.is_array(field_resolver.resolve(f))
1410                || field_resolver.is_collection_root(f)
1411                || field_resolver.is_collection_root(field_resolver.resolve(f)))
1412    });
1413
1414    let field_expr_raw = if result_is_simple {
1415        result_var.to_string()
1416    } else {
1417        match &assertion.field {
1418            Some(f) if !f.is_empty() => field_resolver.accessor(f, "swift", result_var),
1419            _ => result_var.to_string(),
1420        }
1421    };
1422
1423    // swift-bridge `RustVec<T>` exposes its elements as `T.SelfRef`, which holds
1424    // a raw pointer into the parent Vec's storage. When the Vec is a temporary
1425    // (e.g. `result.json_ld()` called inline), Swift ARC may release it before
1426    // the ref is used, leaving the ref's pointer dangling. Materialise the
1427    // temporary into a local so it survives the full expression chain.
1428    //
1429    // The local name is suffixed with the assertion type plus a hash of the
1430    // assertion's discriminating fields so multiple assertions on the same
1431    // collection don't redeclare the same name.
1432    let local_suffix = {
1433        use std::hash::{Hash, Hasher};
1434        let mut hasher = std::collections::hash_map::DefaultHasher::new();
1435        assertion.field.hash(&mut hasher);
1436        assertion
1437            .value
1438            .as_ref()
1439            .map(|v| v.to_string())
1440            .unwrap_or_default()
1441            .hash(&mut hasher);
1442        format!(
1443            "{}_{:x}",
1444            assertion.assertion_type.replace(['-', '.'], "_"),
1445            hasher.finish() & 0xffff_ffff,
1446        )
1447    };
1448    let (vec_setup, field_expr, is_map_subscript) = materialise_vec_temporaries(&field_expr_raw, &local_suffix);
1449    // The `contains` / `not_contains` traversal branch builds its own
1450    // accessor from `field_resolver.accessor(array_part, ...)`, ignoring
1451    // `field_expr`. Emitting the vec_setup there would produce dead
1452    // `let _vec_… = …` lines, so skip it for those traversal cases.
1453    let field_uses_traversal = assertion.field.as_deref().is_some_and(|f| f.contains("[]."));
1454    let traversal_skips_field_expr = field_uses_traversal
1455        && matches!(
1456            assertion.assertion_type.as_str(),
1457            "contains" | "not_contains" | "not_empty" | "is_empty"
1458        );
1459    if !traversal_skips_field_expr {
1460        for line in &vec_setup {
1461            let _ = writeln!(out, "        {line}");
1462        }
1463    }
1464
1465    // In Swift, optional chaining with `?.` makes the result optional even if the
1466    // called method's return type isn't marked optional. For example:
1467    // `result.markdown()?.content()` returns `Optional<RustString>` because
1468    // `markdown()` is optional and the `?.` operator wraps the result.
1469    // Detect this by checking if the accessor contains `?.`.
1470    let accessor_is_optional = field_expr.contains("?.");
1471    // First-class Codable Swift struct property access leaves no trailing `()`
1472    // on the leaf segment — e.g. `result.text` (Swift `String`) vs
1473    // `result.text()` (RustBridge.RustString). When the leaf is property
1474    // access, we already have a Swift `String` (or `String?`) and must NOT
1475    // re-wrap with `.toString()`. Detect this by looking at the final segment
1476    // after the last `.` — property access ends in a bare identifier (no
1477    // trailing `()` or `()?`).
1478    let leaf_is_property_access = {
1479        let trimmed = field_expr.trim_end_matches('?');
1480        // Skip subscripts: `name?[0]` should still see `name` as the field.
1481        let last_segment = trimmed.rsplit_once('.').map(|(_, s)| s).unwrap_or(trimmed);
1482        let last_segment = last_segment.split('[').next().unwrap_or(last_segment);
1483        !last_segment.ends_with(')') && !last_segment.is_empty()
1484    };
1485
1486    // Bare-result Option<T> case: the call returns `Optional<String>` (or
1487    // similar) so the field_expr is `result` typed as `String?`. String
1488    // assertions like `XCTAssertEqual(result.trimmingCharacters(...), …)` will
1489    // not compile against an optional — coalesce to `""` so the macro sees a
1490    // concrete Swift `String`.
1491    let bare_result_is_simple_option =
1492        result_is_simple && result_is_option && assertion.field.as_deref().filter(|f| !f.is_empty()).is_none();
1493
1494    // For enum fields, need to handle the string representation differently in Swift.
1495    // Swift enums don't have `.rawValue` unless they're explicitly RawRepresentable.
1496    // Check if this is an enum type and handle accordingly.
1497    // For optional fields (Optional<RustString>), use optional chaining before toString().
1498    // For other fields: swift-bridge returns all Rust `String` fields as `RustString`.
1499    // We add .toString() here so string assertions (contains, hasPrefix, etc.) work.
1500    // Non-string opaque fields (DocumentStructure, etc.) should not appear in string
1501    // assertions — the fixture schema controls which assertions apply to which fields.
1502    let string_expr = if is_map_subscript {
1503        // The field_expr already evaluates to `String?` (from a JSON-decoded
1504        // `[String: String]` subscript). No `.toString()` chain needed —
1505        // coalesce the optional to "" and use the Swift String directly.
1506        format!("({field_expr} ?? \"\")")
1507    } else if leaf_is_property_access {
1508        // First-class Codable struct field access: leaf is already a Swift
1509        // `String` (or `String?`/enum type) — never a `RustString` requiring
1510        // `.toString()`. For optional leaves, coalesce to "" so XCTAssert
1511        // receives a non-optional Swift `String`.
1512        if field_is_enum && (field_is_optional || accessor_is_optional) {
1513            // Optional first-class Codable enum (e.g. `FinishReason?` where
1514            // `FinishReason: String, Codable`). `.rawValue` gives the serde
1515            // wire value (e.g. "tool_calls") so assertions match fixture JSON.
1516            format!("(({field_expr})?.rawValue ?? \"\")")
1517        } else if field_is_enum {
1518            format!("{field_expr}.rawValue")
1519        } else if field_is_optional || accessor_is_optional || bare_result_is_simple_option {
1520            format!("({field_expr} ?? \"\")")
1521        } else {
1522            field_expr.to_string()
1523        }
1524    } else if field_is_enum && (field_is_optional || accessor_is_optional) {
1525        // Enum-typed fields that are also optional (e.g. `finish_reason() -> Optional<RustString>`)
1526        // must use optional chaining: `?.toString() ?? ""` to unwrap before converting to Swift String.
1527        format!("({field_expr}?.toString() ?? \"\")")
1528    } else if field_is_enum {
1529        // Enum-typed fields are now bridged as `String` (RustString in Swift) rather than
1530        // as opaque enum handles. The getter on the Rust side calls `to_string()` internally
1531        // and returns a `String` across the FFI. In Swift this arrives as `RustString`, so
1532        // `.toString()` converts it to a Swift `String` — one call, not two.
1533        format!("{field_expr}.toString()")
1534    } else if field_is_optional {
1535        // Leaf field itself is Optional<RustString> — need ?.toString() to unwrap.
1536        format!("({field_expr}?.toString() ?? \"\")")
1537    } else if accessor_is_optional {
1538        // Ancestor optional chain propagates; leaf is non-optional RustString within chain.
1539        // Use .toString() directly — the whole expr is Optional<String> due to propagation.
1540        format!("({field_expr}.toString() ?? \"\")")
1541    } else {
1542        format!("{field_expr}.toString()")
1543    };
1544
1545    match assertion.assertion_type.as_str() {
1546        "equals" => {
1547            if let Some(expected) = &assertion.value {
1548                let swift_val = json_to_swift(expected);
1549                if expected.is_string() {
1550                    if field_is_enum {
1551                        // Enum fields: `to_string()` (snake_case) returns RustString;
1552                        // `.toString()` converts it to a Swift String.
1553                        // `string_expr` already incorporates this call chain.
1554                        let trim_expr =
1555                            format!("{string_expr}.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)");
1556                        let _ = writeln!(out, "        XCTAssertEqual({trim_expr}, {swift_val})");
1557                    } else {
1558                        // For optional strings (String?), use ?? to coalesce before trimming.
1559                        // `.toString()` converts RustString → Swift String before calling
1560                        // `.trimmingCharacters`, which requires a concrete String type.
1561                        // string_expr already incorporates field_is_optional via ?.toString() ?? "".
1562                        let trim_expr =
1563                            format!("{string_expr}.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)");
1564                        let _ = writeln!(out, "        XCTAssertEqual({trim_expr}, {swift_val})");
1565                    }
1566                } else {
1567                    // For numeric fields, cast the expected value to match the field's type (e.g., UInt).
1568                    let cast_swift_val = swift_numeric_literal_cast(&field_expr, &swift_val);
1569                    let _ = writeln!(out, "        XCTAssertEqual({field_expr}, {cast_swift_val})");
1570                }
1571            }
1572        }
1573        "contains" => {
1574            if let Some(expected) = &assertion.value {
1575                let swift_val = json_to_swift(expected);
1576                // When the root result IS the array (result_is_simple + result_is_array) and
1577                // there is no field path, check array membership via map+contains.
1578                let no_field = assertion.field.as_deref().is_none_or(|f| f.is_empty());
1579                if result_is_simple && result_is_array && no_field {
1580                    if result_element_is_string {
1581                        // The Swift binding exposes the result as a native
1582                        // `[String]` (e.g. `manifestLanguages() -> [String]`),
1583                        // not the opaque `RustVec<RustString>`. Iterating
1584                        // elements yields plain Swift `String`, which has no
1585                        // `asStr()` — emit a direct `.contains(...)` instead.
1586                        let _ = writeln!(
1587                            out,
1588                            "        XCTAssertTrue({result_var}.contains({swift_val}), \"expected to contain: \\({swift_val})\")"
1589                        );
1590                    } else {
1591                        // RustVec<RustString> iteration yields RustStringRef (no `toString()`);
1592                        // use `.asStr().toString()` to convert each element to a Swift String.
1593                        // swift-bridge renames `as_str` → `asStr` automatically.
1594                        let _ = writeln!(
1595                            out,
1596                            "        XCTAssertTrue({result_var}.map {{ $0.asStr().toString() }}.contains({swift_val}), \"expected to contain: \\({swift_val})\")"
1597                        );
1598                    }
1599                } else {
1600                    // []. traversal: field like "links[].url" → contains(where:) closure.
1601                    let traversal_handled = if let Some(f) = assertion.field.as_deref() {
1602                        if let Some(dot) = f.find("[].") {
1603                            let array_part = &f[..dot];
1604                            let elem_part = &f[dot + 3..];
1605                            let line = swift_traversal_contains_assert(
1606                                array_part,
1607                                elem_part,
1608                                f,
1609                                &swift_val,
1610                                result_var,
1611                                false,
1612                                &format!("expected to contain: \\({swift_val})"),
1613                                enum_fields,
1614                                field_resolver,
1615                            );
1616                            let _ = writeln!(out, "{line}");
1617                            true
1618                        } else {
1619                            false
1620                        }
1621                    } else {
1622                        false
1623                    };
1624                    if !traversal_handled {
1625                        // For array fields (RustVec<RustString>), check membership via map+contains.
1626                        let field_is_array = assertion
1627                            .field
1628                            .as_deref()
1629                            .is_some_and(|f| field_resolver.is_array(field_resolver.resolve(f)));
1630                        if field_is_array {
1631                            // First try the "stringy aggregator" path: when the array element
1632                            // is an opaque DTO with several text-bearing accessors (e.g.
1633                            // ImportInfo with source/items/alias, or StructureItem with
1634                            // kind/name/signature/...), emit a `contains(where: { ... })`
1635                            // closure that walks every accessor and does substring matching,
1636                            // mirroring python's `_alef_e2e_item_texts`. This avoids the
1637                            // brittle "primary accessor" guess (e.g. ImportInfo → source
1638                            // misses imports whose name lives in `items`).
1639                            let aggregator = swift_stringy_aggregator_contains_assert(
1640                                assertion.field.as_deref(),
1641                                result_var,
1642                                field_resolver,
1643                                &swift_val,
1644                            );
1645                            if let Some(line) = aggregator {
1646                                let _ = writeln!(out, "{line}");
1647                            } else {
1648                                let (contains_expr, is_optional) = swift_array_contains_expr(
1649                                    assertion.field.as_deref(),
1650                                    result_var,
1651                                    field_resolver,
1652                                    result_field_accessor,
1653                                );
1654                                let wrapped = if is_optional {
1655                                    format!("({contains_expr} ?? [])")
1656                                } else {
1657                                    contains_expr
1658                                };
1659                                let _ = writeln!(
1660                                    out,
1661                                    "        XCTAssertTrue({wrapped}.contains({swift_val}), \"expected to contain: \\({swift_val})\")"
1662                                );
1663                            }
1664                        } else if field_is_enum {
1665                            // Enum fields: use `toString().toString()` (via string_expr) to get the
1666                            // serde variant name as a Swift String, then check substring containment.
1667                            // Swift's `String.contains("")` returns false; guard with `.isEmpty` so
1668                            // fixtures that assert containment of an empty string still pass.
1669                            let _ = writeln!(
1670                                out,
1671                                "        XCTAssertTrue({swift_val}.isEmpty || {string_expr}.contains({swift_val}), \"expected to contain: \\({swift_val})\")"
1672                            );
1673                        } else {
1674                            // Same `isEmpty` guard as the enum branch — every string trivially
1675                            // "contains" the empty string, but Swift's `String.contains` does not.
1676                            let _ = writeln!(
1677                                out,
1678                                "        XCTAssertTrue({swift_val}.isEmpty || {string_expr}.contains({swift_val}), \"expected to contain: \\({swift_val})\")"
1679                            );
1680                        }
1681                    }
1682                }
1683            }
1684        }
1685        "contains_all" => {
1686            if let Some(values) = &assertion.values {
1687                // []. traversal: field like "links[].link_type" → contains(where:) per value.
1688                if let Some(f) = assertion.field.as_deref() {
1689                    if let Some(dot) = f.find("[].") {
1690                        let array_part = &f[..dot];
1691                        let elem_part = &f[dot + 3..];
1692                        for val in values {
1693                            let swift_val = json_to_swift(val);
1694                            let line = swift_traversal_contains_assert(
1695                                array_part,
1696                                elem_part,
1697                                f,
1698                                &swift_val,
1699                                result_var,
1700                                false,
1701                                &format!("expected to contain: \\({swift_val})"),
1702                                enum_fields,
1703                                field_resolver,
1704                            );
1705                            let _ = writeln!(out, "{line}");
1706                        }
1707                        // handled — skip remaining branches
1708                    } else {
1709                        // For array fields (RustVec<RustString>), check membership via map+contains.
1710                        let field_is_array = field_resolver.is_array(field_resolver.resolve(f));
1711                        if field_is_array {
1712                            let (contains_expr, is_optional) = swift_array_contains_expr(
1713                                assertion.field.as_deref(),
1714                                result_var,
1715                                field_resolver,
1716                                result_field_accessor,
1717                            );
1718                            let wrapped = if is_optional {
1719                                format!("({contains_expr} ?? [])")
1720                            } else {
1721                                contains_expr
1722                            };
1723                            for val in values {
1724                                let swift_val = json_to_swift(val);
1725                                let _ = writeln!(
1726                                    out,
1727                                    "        XCTAssertTrue({wrapped}.contains({swift_val}), \"expected to contain: \\({swift_val})\")"
1728                                );
1729                            }
1730                        } else if field_is_enum {
1731                            // Enum fields: use `toString().toString()` (via string_expr) to get the
1732                            // serde variant name as a Swift String, then check substring containment.
1733                            for val in values {
1734                                let swift_val = json_to_swift(val);
1735                                let _ = writeln!(
1736                                    out,
1737                                    "        XCTAssertTrue({string_expr}.contains({swift_val}), \"expected to contain: \\({swift_val})\")"
1738                                );
1739                            }
1740                        } else {
1741                            for val in values {
1742                                let swift_val = json_to_swift(val);
1743                                let _ = writeln!(
1744                                    out,
1745                                    "        XCTAssertTrue({string_expr}.contains({swift_val}), \"expected to contain: \\({swift_val})\")"
1746                                );
1747                            }
1748                        }
1749                    }
1750                } else {
1751                    // No field — fall back to existing string_expr path.
1752                    for val in values {
1753                        let swift_val = json_to_swift(val);
1754                        let _ = writeln!(
1755                            out,
1756                            "        XCTAssertTrue({string_expr}.contains({swift_val}), \"expected to contain: \\({swift_val})\")"
1757                        );
1758                    }
1759                }
1760            }
1761        }
1762        "not_contains" => {
1763            if let Some(expected) = &assertion.value {
1764                let swift_val = json_to_swift(expected);
1765                // []. traversal: "links[].url" → XCTAssertFalse(array.contains(where:))
1766                let traversal_handled = if let Some(f) = assertion.field.as_deref() {
1767                    if let Some(dot) = f.find("[].") {
1768                        let array_part = &f[..dot];
1769                        let elem_part = &f[dot + 3..];
1770                        let line = swift_traversal_contains_assert(
1771                            array_part,
1772                            elem_part,
1773                            f,
1774                            &swift_val,
1775                            result_var,
1776                            true,
1777                            &format!("expected NOT to contain: \\({swift_val})"),
1778                            enum_fields,
1779                            field_resolver,
1780                        );
1781                        let _ = writeln!(out, "{line}");
1782                        true
1783                    } else {
1784                        false
1785                    }
1786                } else {
1787                    false
1788                };
1789                if !traversal_handled {
1790                    let _ = writeln!(
1791                        out,
1792                        "        XCTAssertFalse({string_expr}.contains({swift_val}), \"expected NOT to contain: \\({swift_val})\")"
1793                    );
1794                }
1795            }
1796        }
1797        "not_empty" => {
1798            // For optional fields (Optional<T>), check that the value is non-nil.
1799            // For array fields (RustVec<T>), check .isEmpty on the vec directly.
1800            // For result_is_simple (e.g. Data, String), use .isEmpty directly on
1801            // the result — avoids calling .toString() on non-RustString types.
1802            // For string fields, convert to Swift String and check .isEmpty.
1803            // []. traversal: "links[].url" → contains(where: { !elem.isEmpty })
1804            let traversal_not_empty_handled = if let Some(f) = assertion.field.as_deref() {
1805                if let Some(dot) = f.find("[].") {
1806                    let array_part = &f[..dot];
1807                    let elem_part = &f[dot + 3..];
1808                    let array_accessor = field_resolver.accessor(array_part, "swift", result_var);
1809                    let resolved_full = field_resolver.resolve(f);
1810                    let resolved_elem_part = resolved_full
1811                        .find("[].")
1812                        .map(|d| &resolved_full[d + 3..])
1813                        .unwrap_or(elem_part);
1814                    let elem_accessor = field_resolver.accessor(resolved_elem_part, "swift", "$0");
1815                    let elem_is_enum = enum_fields.contains(f) || enum_fields.contains(resolved_full);
1816                    let elem_is_optional = field_resolver.is_optional(resolved_elem_part)
1817                        || field_resolver.is_optional(field_resolver.resolve(resolved_elem_part));
1818                    let elem_str = if elem_is_enum {
1819                        format!("{elem_accessor}.to_string().toString()")
1820                    } else if elem_is_optional {
1821                        format!("({elem_accessor}?.toString() ?? \"\")")
1822                    } else {
1823                        format!("{elem_accessor}.toString()")
1824                    };
1825                    let _ = writeln!(
1826                        out,
1827                        "        XCTAssertTrue({array_accessor}.contains(where: {{ !{elem_str}.isEmpty }}), \"expected non-empty value\")"
1828                    );
1829                    true
1830                } else {
1831                    false
1832                }
1833            } else {
1834                false
1835            };
1836            if !traversal_not_empty_handled {
1837                if bare_result_is_option {
1838                    let _ = writeln!(out, "        XCTAssertNotNil({result_var}, \"expected non-nil value\")");
1839                } else if field_is_optional {
1840                    let _ = writeln!(out, "        XCTAssertNotNil({field_expr}, \"expected non-nil value\")");
1841                } else if field_is_array {
1842                    let _ = writeln!(
1843                        out,
1844                        "        XCTAssertFalse({field_expr}.isEmpty, \"expected non-empty value\")"
1845                    );
1846                } else if result_is_simple {
1847                    // result_is_simple: result is a primitive (Data, String, etc.) — use .isEmpty directly.
1848                    let _ = writeln!(
1849                        out,
1850                        "        XCTAssertFalse({result_var}.isEmpty, \"expected non-empty value\")"
1851                    );
1852                } else {
1853                    // First-class Swift struct fields are properties typed as native Swift
1854                    // `String` / `[T]` / `Data` etc — all of which expose `.count` (and
1855                    // `String`/`Array` also expose `.isEmpty`). Use `.count > 0` so the same
1856                    // path works whether the field is a String or an Array.
1857                    //
1858                    // When the accessor contains a `?.` optional chain, `.count` returns an
1859                    // Optional which Swift cannot compare directly to `0`; coalesce via `?? 0`
1860                    // so the assertion typechecks.
1861                    //
1862                    // For opaque method-call accessors (`result.id()`), the returned type is
1863                    // `RustString`, which lacks `.count`. Convert to Swift `String` first via
1864                    // `.toString()`. Array fields short-circuit above via `field_is_array`, so
1865                    // method-call accessors landing here are guaranteed to be the scalar /
1866                    // string flavour; vec accessors return `RustVec` (whose `.count` is fine).
1867                    let count_target = swift_count_target(&field_expr, field_resolver, assertion.field.as_deref());
1868                    let len_expr = if accessor_is_optional {
1869                        format!("({count_target}.count ?? 0)")
1870                    } else {
1871                        format!("{count_target}.count")
1872                    };
1873                    let _ = writeln!(
1874                        out,
1875                        "        XCTAssertGreaterThan({len_expr}, 0, \"expected non-empty value\")"
1876                    );
1877                }
1878            }
1879        }
1880        "is_empty" => {
1881            if bare_result_is_option {
1882                let _ = writeln!(out, "        XCTAssertNil({result_var}, \"expected nil value\")");
1883            } else if field_is_optional {
1884                let _ = writeln!(out, "        XCTAssertNil({field_expr}, \"expected nil value\")");
1885            } else if field_is_array {
1886                let _ = writeln!(
1887                    out,
1888                    "        XCTAssertTrue({field_expr}.isEmpty, \"expected empty value\")"
1889                );
1890            } else {
1891                // Symmetric with not_empty: use .count == 0 on first-class Swift types.
1892                // Wrap opaque method-call accessors (`result.id()`) with `.toString()` so
1893                // `.count` lands on Swift `String`, not `RustString` (which lacks `.count`).
1894                let count_target = swift_count_target(&field_expr, field_resolver, assertion.field.as_deref());
1895                let len_expr = if accessor_is_optional {
1896                    format!("({count_target}.count ?? 0)")
1897                } else {
1898                    format!("{count_target}.count")
1899                };
1900                let _ = writeln!(out, "        XCTAssertEqual({len_expr}, 0, \"expected empty value\")");
1901            }
1902        }
1903        "contains_any" => {
1904            if let Some(values) = &assertion.values {
1905                let checks: Vec<String> = values
1906                    .iter()
1907                    .map(|v| {
1908                        let swift_val = json_to_swift(v);
1909                        format!("{string_expr}.contains({swift_val})")
1910                    })
1911                    .collect();
1912                let joined = checks.join(" || ");
1913                let _ = writeln!(
1914                    out,
1915                    "        XCTAssertTrue({joined}, \"expected to contain at least one of the specified values\")"
1916                );
1917            }
1918        }
1919        "greater_than" => {
1920            if let Some(val) = &assertion.value {
1921                let swift_val = json_to_swift(val);
1922                // For optional numeric fields (or when the accessor chain is optional),
1923                // coalesce to 0 before comparing so the expression is non-optional.
1924                let field_is_optional = accessor_is_optional
1925                    || assertion.field.as_deref().is_some_and(|f| {
1926                        field_resolver.is_optional(f) || field_resolver.is_optional(field_resolver.resolve(f))
1927                    });
1928                let compare_expr = if field_is_optional {
1929                    let cast_val = swift_numeric_literal_cast(&field_expr, "0");
1930                    format!("({field_expr} ?? {cast_val})")
1931                } else {
1932                    field_expr.clone()
1933                };
1934                let cast_swift_val = swift_numeric_literal_cast(&field_expr, &swift_val);
1935                let _ = writeln!(out, "        XCTAssertGreaterThan({compare_expr}, {cast_swift_val})");
1936            }
1937        }
1938        "less_than" => {
1939            if let Some(val) = &assertion.value {
1940                let swift_val = json_to_swift(val);
1941                let field_is_optional = accessor_is_optional
1942                    || assertion.field.as_deref().is_some_and(|f| {
1943                        field_resolver.is_optional(f) || field_resolver.is_optional(field_resolver.resolve(f))
1944                    });
1945                let compare_expr = if field_is_optional {
1946                    let cast_val = swift_numeric_literal_cast(&field_expr, "0");
1947                    format!("({field_expr} ?? {cast_val})")
1948                } else {
1949                    field_expr.clone()
1950                };
1951                let cast_swift_val = swift_numeric_literal_cast(&field_expr, &swift_val);
1952                let _ = writeln!(out, "        XCTAssertLessThan({compare_expr}, {cast_swift_val})");
1953            }
1954        }
1955        "greater_than_or_equal" => {
1956            if let Some(val) = &assertion.value {
1957                let swift_val = json_to_swift(val);
1958                // For optional numeric fields (or when the accessor chain is optional),
1959                // coalesce to 0 before comparing so the expression is non-optional.
1960                let field_is_optional = accessor_is_optional
1961                    || assertion.field.as_deref().is_some_and(|f| {
1962                        field_resolver.is_optional(f) || field_resolver.is_optional(field_resolver.resolve(f))
1963                    });
1964                let compare_expr = if field_is_optional {
1965                    let cast_val = swift_numeric_literal_cast(&field_expr, "0");
1966                    format!("({field_expr} ?? {cast_val})")
1967                } else {
1968                    field_expr.clone()
1969                };
1970                let cast_swift_val = swift_numeric_literal_cast(&field_expr, &swift_val);
1971                let _ = writeln!(
1972                    out,
1973                    "        XCTAssertGreaterThanOrEqual({compare_expr}, {cast_swift_val})"
1974                );
1975            }
1976        }
1977        "less_than_or_equal" => {
1978            if let Some(val) = &assertion.value {
1979                let swift_val = json_to_swift(val);
1980                let field_is_optional = accessor_is_optional
1981                    || assertion.field.as_deref().is_some_and(|f| {
1982                        field_resolver.is_optional(f) || field_resolver.is_optional(field_resolver.resolve(f))
1983                    });
1984                let compare_expr = if field_is_optional {
1985                    let cast_val = swift_numeric_literal_cast(&field_expr, "0");
1986                    format!("({field_expr} ?? {cast_val})")
1987                } else {
1988                    field_expr.clone()
1989                };
1990                let cast_swift_val = swift_numeric_literal_cast(&field_expr, &swift_val);
1991                let _ = writeln!(
1992                    out,
1993                    "        XCTAssertLessThanOrEqual({compare_expr}, {cast_swift_val})"
1994                );
1995            }
1996        }
1997        "starts_with" => {
1998            if let Some(expected) = &assertion.value {
1999                let swift_val = json_to_swift(expected);
2000                let _ = writeln!(
2001                    out,
2002                    "        XCTAssertTrue({string_expr}.hasPrefix({swift_val}), \"expected to start with: \\({swift_val})\")"
2003                );
2004            }
2005        }
2006        "ends_with" => {
2007            if let Some(expected) = &assertion.value {
2008                let swift_val = json_to_swift(expected);
2009                let _ = writeln!(
2010                    out,
2011                    "        XCTAssertTrue({string_expr}.hasSuffix({swift_val}), \"expected to end with: \\({swift_val})\")"
2012                );
2013            }
2014        }
2015        "min_length" => {
2016            if let Some(val) = &assertion.value {
2017                if let Some(n) = val.as_u64() {
2018                    // Use string_expr.count: for RustString fields string_expr already has
2019                    // .toString() appended, giving a Swift String whose .count is character count.
2020                    let _ = writeln!(out, "        XCTAssertGreaterThanOrEqual({string_expr}.count, {n})");
2021                }
2022            }
2023        }
2024        "max_length" => {
2025            if let Some(val) = &assertion.value {
2026                if let Some(n) = val.as_u64() {
2027                    let _ = writeln!(out, "        XCTAssertLessThanOrEqual({string_expr}.count, {n})");
2028                }
2029            }
2030        }
2031        "count_min" => {
2032            if let Some(val) = &assertion.value {
2033                if let Some(n) = val.as_u64() {
2034                    // For fields nested inside an optional parent (e.g. document.nodes where
2035                    // document is Optional), the accessor generates `result.document().nodes()`
2036                    // which doesn't compile in Swift without optional chaining.
2037                    let count_expr = swift_array_count_expr(assertion.field.as_deref(), result_var, field_resolver);
2038                    let _ = writeln!(out, "        XCTAssertGreaterThanOrEqual({count_expr}, {n})");
2039                }
2040            }
2041        }
2042        "count_equals" => {
2043            if let Some(val) = &assertion.value {
2044                if let Some(n) = val.as_u64() {
2045                    let count_expr = swift_array_count_expr(assertion.field.as_deref(), result_var, field_resolver);
2046                    let _ = writeln!(out, "        XCTAssertEqual({count_expr}, {n})");
2047                }
2048            }
2049        }
2050        "is_true" => {
2051            let _ = writeln!(out, "        XCTAssertTrue({field_expr})");
2052        }
2053        "is_false" => {
2054            let _ = writeln!(out, "        XCTAssertFalse({field_expr})");
2055        }
2056        "matches_regex" => {
2057            if let Some(expected) = &assertion.value {
2058                let swift_val = json_to_swift(expected);
2059                let _ = writeln!(
2060                    out,
2061                    "        XCTAssertNotNil({string_expr}.range(of: {swift_val}, options: .regularExpression), \"expected value to match regex: \\({swift_val})\")"
2062                );
2063            }
2064        }
2065        "not_error" => {
2066            // Already handled by the call succeeding without exception.
2067        }
2068        "error" => {
2069            // Handled at the test method level.
2070        }
2071        "method_result" => {
2072            let _ = writeln!(out, "        // method_result assertions not yet implemented for Swift");
2073        }
2074        other => {
2075            panic!("Swift e2e generator: unsupported assertion type: {other}");
2076        }
2077    }
2078}
2079
2080/// Build a Swift accessor path for the given fixture field, inserting `()` on
2081/// every segment and `?` after every optional non-leaf segment.
2082///
2083/// This is the core helper for count/contains helpers that need to reconstruct
2084/// the path with correct optional chaining from the raw fixture field name.
2085///
2086/// Rewrite a Swift accessor expression to capture any `RustVec` temporaries
2087/// in a local before subscripting them. Returns `(setup_lines, rewritten_expr)`.
2088///
2089/// swift-bridge's `Vec_<T>$get` returns a raw pointer into the Vec's storage
2090/// wrapped in a `T.SelfRef`. If the Vec was a temporary, ARC may release it
2091/// before the ref is dereferenced, leaving the pointer dangling and reads
2092/// returning empty/garbage. Hoisting the Vec into a `let` binding ties the
2093/// Vec's lifetime to the enclosing function scope, so the ref stays valid.
2094///
2095/// Only the first `()[...]` occurrence per expression is materialised — that
2096/// covers all current fixture access patterns (single-level subscripts on a
2097/// result field). Nested subscripts are rare and would need a more elaborate
2098/// pass; if they appear, this returns conservative output (just the first
2099/// hoist) which is still correct.
2100/// Returns `(setup_lines, rewritten_expr, is_map_subscript)`. `is_map_subscript` is
2101/// true when the subscript key was a string literal, indicating the parent
2102/// accessor returns a JSON-encoded Map (RustString) and the rewritten expression
2103/// already evaluates to `String?` so callers should NOT append `.toString()`.
2104fn materialise_vec_temporaries(expr: &str, name_suffix: &str) -> (Vec<String>, String, bool) {
2105    let Some(idx) = expr.find("()[") else {
2106        return (Vec::new(), expr.to_string(), false);
2107    };
2108    let after_open = idx + 3; // position after `()[`
2109    let Some(close_rel) = expr[after_open..].find(']') else {
2110        return (Vec::new(), expr.to_string(), false);
2111    };
2112    let subscript_end = after_open + close_rel; // index of `]`
2113    let prefix = &expr[..idx + 2]; // includes `()`
2114    let subscript = &expr[idx + 2..=subscript_end]; // `[N]`
2115    let tail = &expr[subscript_end + 1..]; // everything after `]`
2116    let method_dot = expr[..idx].rfind('.').unwrap_or(0);
2117    let method = &expr[method_dot + 1..idx];
2118    let local = format!("_vec_{}_{}", method, name_suffix);
2119
2120    // String-key subscript (e.g. `["title"]`) signals a Map-like access. swift-bridge
2121    // serialises non-leaf Maps (e.g. `HashMap<String, String>`) as JSON-encoded
2122    // RustString rather than exposing a Swift dictionary. Decode the RustString to
2123    // `[String: String]` before subscripting so `_vec_X["title"]` works.
2124    let inner = subscript.trim_start_matches('[').trim_end_matches(']');
2125    let is_string_key = inner.starts_with('"') && inner.ends_with('"');
2126    let setup = if is_string_key {
2127        format!(
2128            "let {local} = (try? JSONSerialization.jsonObject(with: ({prefix}.toString() ?? \"{{}}\").data(using: .utf8)!) as? [String: String]) ?? [:]"
2129        )
2130    } else {
2131        format!("let {local} = {prefix}")
2132    };
2133
2134    let rewritten = format!("{local}{subscript}{tail}");
2135    (vec![setup], rewritten, is_string_key)
2136}
2137
2138/// Returns `(accessor_expr, has_optional)` where `has_optional` is true when
2139/// at least one `?.` was inserted.
2140fn swift_build_accessor(field: &str, result_var: &str, field_resolver: &FieldResolver) -> (String, bool) {
2141    let resolved = field_resolver.resolve(field);
2142    let parts: Vec<&str> = resolved.split('.').collect();
2143
2144    // Track the current IR type as we walk segments so each segment can be
2145    // emitted with property syntax (first-class Codable struct) or method-call
2146    // syntax (typealias-to-`RustBridge.X`). Mirrors the per-segment dispatch in
2147    // `render_swift_with_first_class_map`.
2148    let mut current_type: Option<String> = field_resolver.swift_root_type().cloned();
2149    // Once a chain crosses a `[N]` subscript, we are operating on a RustVec
2150    // element, which is always the OPAQUE `RustBridge.T` (swift-bridge does not
2151    // convert RustVec elements into the first-class Codable struct). Pin
2152    // opaque method-call syntax after the first index step.
2153    let mut via_rust_vec = false;
2154    // Once a chain crosses an opaque (typealias-to-`RustBridge.X`) segment, every
2155    // subsequent accessor must also be opaque (method-call syntax). Calling a
2156    // method on `RustBridge.X` returns the OPAQUE wrapper of the next type, even
2157    // when that next type is independently eligible for first-class emission.
2158    // See `field_access::render_swift_with_first_class_map` for the matching
2159    // invariant. Without this, `metrics.total_lines` on an opaque parent emits
2160    // `.metrics().totalLines` instead of `.metrics().totalLines()`.
2161    let mut via_opaque = false;
2162
2163    let mut out = result_var.to_string();
2164    let mut has_optional = false;
2165    let mut path_so_far = String::new();
2166    let total = parts.len();
2167    for (i, part) in parts.iter().enumerate() {
2168        let is_leaf = i == total - 1;
2169        // Handle array index subscripts within a segment, e.g. `data[0]`.
2170        // `data[0]` must become `.data()[0]` (opaque) or `.data[0]` (first-class).
2171        // Split at the first `[` if present.
2172        let (field_name, subscript): (&str, Option<&str>) = if let Some(bracket_pos) = part.find('[') {
2173            (&part[..bracket_pos], Some(&part[bracket_pos..]))
2174        } else {
2175            (part, None)
2176        };
2177
2178        if !path_so_far.is_empty() {
2179            path_so_far.push('.');
2180        }
2181        // Build the base path (without subscript) for the optional check. When the
2182        // segment is e.g. `tool_calls[0]`, we want to check `is_optional` against
2183        // "choices[0].message.tool_calls" not "choices[0].message.tool_calls[0]".
2184        let base_path = {
2185            let mut p = path_so_far.clone();
2186            p.push_str(field_name);
2187            p
2188        };
2189        // Now push the full part (with subscript if any) so path_so_far is correct
2190        // for subsequent segment checks.
2191        path_so_far.push_str(part);
2192
2193        // First-class struct fields → property access (no `()`); typealias-to-
2194        // opaque fields → method-call access (`()`). Once we've indexed through
2195        // a RustVec, every subsequent segment is on an opaque element.
2196        // When current_type is None (opaque parent that doesn't appear in field_types),
2197        // treat it as opaque and use method-call syntax.
2198        let is_first_class = current_type
2199            .as_ref()
2200            .is_some_and(|t| field_resolver.swift_is_first_class(Some(t)));
2201        let property_syntax = !via_rust_vec && !via_opaque && is_first_class;
2202        if !property_syntax {
2203            via_opaque = true;
2204        }
2205        out.push('.');
2206        // Swift bindings (both first-class `public let` props and swift-bridge
2207        // method names) always use lowerCamelCase — never raw snake_case from IR.
2208        out.push_str(&field_name.to_lower_camel_case());
2209        if let Some(sub) = subscript {
2210            // When the getter for this subscripted field is itself optional
2211            // (e.g. tool_calls returns Optional<RustVec<T>>), insert `?` before
2212            // the subscript so Swift unwraps the Optional before indexing.
2213            let field_is_optional = field_resolver.is_optional(&base_path);
2214            let access = if property_syntax { "" } else { "()" };
2215            if field_is_optional {
2216                out.push_str(&format!("{access}?"));
2217                has_optional = true;
2218            } else {
2219                out.push_str(access);
2220            }
2221            out.push_str(sub);
2222            // Do NOT append a trailing `?` after the subscript index: in Swift,
2223            // `optionalVec?[N]` via `Collection.subscript` returns the element
2224            // type `T` directly. The parent `has_optional` flag is still set
2225            // when `field_is_optional` is true, which causes the enclosing
2226            // expression to be wrapped in `(... ?? fallback)` correctly.
2227            // Indexing into a Vec<Named> yields a Named element. Only pin opaque
2228            // syntax when the array itself was opaque (method-call); when the
2229            // owner is first-class, the array is a Swift `[T]` whose elements
2230            // are first-class T (property access).
2231            current_type = field_resolver.swift_advance(current_type.as_deref(), field_name);
2232            if !property_syntax {
2233                via_rust_vec = true;
2234            }
2235        } else {
2236            if !property_syntax {
2237                out.push_str("()");
2238            }
2239            // Insert `?` after the accessor for non-leaf optional fields so the
2240            // next member access becomes `?.`.
2241            if !is_leaf && field_resolver.is_optional(&base_path) {
2242                out.push('?');
2243                has_optional = true;
2244            }
2245            current_type = field_resolver.swift_advance(current_type.as_deref(), field_name);
2246        }
2247    }
2248    (out, has_optional)
2249}
2250
2251/// Generate a `[String]` (or `[String]?`) expression for a `RustVec<RustString>`
2252/// field so that `contains` membership checks work against plain Swift Strings.
2253///
2254/// We use `.map { $0.asStr().toString() }` because:
2255/// 1. Iterating a `RustVec<RustString>` yields `RustStringRef` (not `RustString`), which
2256///    only has `asStr()` but not `toString()` directly. swift-bridge auto-renames the
2257///    Rust `as_str` method to lowerCamelCase `asStr` on the Swift side.
2258/// 2. The accessor may end with an `Optional<RustVec<RustString>>` (e.g. `sheet_names()` is
2259///    `Option<Vec<String>>` in Rust, which becomes `Optional<RustVec<RustString>>` in Swift).
2260/// 3. Optional chaining from parent `?.` already produces `Optional<RustVec<T>>`.
2261///
2262/// The returned tuple's bool indicates whether the result is `Optional<[String]>`
2263/// (callers coalesce with `?? []`) or already a concrete `[String]`. Emitting
2264/// `?? []` against a non-optional value compiles with a Swift warning but is
2265/// surfaced as an error in strict CI configurations, so we only emit `?.map`
2266/// + `?? []` when the accessor is genuinely optional.
2267///
2268/// Generate a `XCTAssert{True|False}(array.contains(where: { elem_str.contains(val) }), msg)` line
2269/// for field paths that traverse a collection with `[].` notation (e.g. `links[].url`).
2270///
2271/// `array_part` — left side of `[].` (e.g. `"links"`)
2272/// `element_part` — right side (e.g. `"url"` or `"link_type"`)
2273/// `full_field` — original assertion.field (used for enum lookup against the full path)
2274#[allow(clippy::too_many_arguments)]
2275fn swift_traversal_contains_assert(
2276    array_part: &str,
2277    element_part: &str,
2278    full_field: &str,
2279    val_expr: &str,
2280    result_var: &str,
2281    negate: bool,
2282    msg: &str,
2283    enum_fields: &std::collections::HashSet<String>,
2284    field_resolver: &FieldResolver,
2285) -> String {
2286    let array_accessor = field_resolver.accessor(array_part, "swift", result_var);
2287    let resolved_full = field_resolver.resolve(full_field);
2288    let resolved_elem_part = resolved_full
2289        .find("[].")
2290        .map(|d| &resolved_full[d + 3..])
2291        .unwrap_or(element_part);
2292    let elem_accessor = field_resolver.accessor(resolved_elem_part, "swift", "$0");
2293    let elem_is_enum = enum_fields.contains(full_field) || enum_fields.contains(resolved_full);
2294    let elem_is_optional = field_resolver.is_optional(resolved_elem_part)
2295        || field_resolver.is_optional(field_resolver.resolve(resolved_elem_part));
2296    let elem_str = if elem_is_enum {
2297        // Enum-typed fields are bridged as `String` (RustString in Swift).
2298        // A single `.toString()` converts RustString → Swift String.
2299        format!("{elem_accessor}.toString()")
2300    } else if elem_is_optional {
2301        format!("({elem_accessor}?.toString() ?? \"\")")
2302    } else {
2303        format!("{elem_accessor}.toString()")
2304    };
2305    let assert_fn = if negate { "XCTAssertFalse" } else { "XCTAssertTrue" };
2306    format!("        {assert_fn}({array_accessor}.contains(where: {{ {elem_str}.contains({val_expr}) }}), \"{msg}\")")
2307}
2308
2309/// Returns `(map_expr, is_optional)` where `map_expr` is the `.map { … }` chain
2310/// that converts each element to a Swift `String`, and `is_optional` reports
2311/// whether the resulting expression is `Optional<[String]>` (callers should
2312/// coalesce with `?? []`) or already a concrete `[String]`.
2313fn swift_array_contains_expr(
2314    field: Option<&str>,
2315    result_var: &str,
2316    field_resolver: &FieldResolver,
2317    result_field_accessor: &HashMap<String, String>,
2318) -> (String, bool) {
2319    // swift-bridge auto-renames Rust snake_case methods to lowerCamelCase on the
2320    // Swift side. `RustStringRef::as_str()` is exposed as `asStr()` — emitting
2321    // `as_str()` produces "value of type 'XRef' has no member 'as_str'" at
2322    // compile time.
2323    let Some(f) = field else {
2324        return (format!("{result_var}.map {{ $0.asStr().toString() }}"), false);
2325    };
2326    // Allow per-call overrides to name a different element accessor — used when
2327    // the array element is an opaque struct whose "name string" accessor is
2328    // not `as_str` (e.g. `StructureItem` exposes `kind() -> String`). The map
2329    // is keyed on the fixture field name (and resolved alias as a fallback).
2330    let resolved_field = field_resolver.resolve(f);
2331    let elem_accessor_name = result_field_accessor
2332        .get(f)
2333        .or_else(|| result_field_accessor.get(resolved_field))
2334        .cloned()
2335        .unwrap_or_else(|| "as_str".to_string());
2336    let elem_call = swift_ident(&elem_accessor_name.to_lower_camel_case());
2337    let (accessor, has_optional) = swift_build_accessor(f, result_var, field_resolver);
2338    // Only chain `?.map` when the accessor is actually optional. The previous
2339    // unconditional `?.map` produced "cannot use optional chaining on
2340    // non-optional value of type 'RustVec<…>'" for plain `Vec<T>` fields.
2341    let field_is_optional =
2342        has_optional || field_resolver.is_optional(f) || field_resolver.is_optional(field_resolver.resolve(f));
2343    if field_is_optional {
2344        (format!("{accessor}?.map {{ $0.{elem_call}().toString() }}"), true)
2345    } else {
2346        (format!("{accessor}.map {{ $0.{elem_call}().toString() }}"), false)
2347    }
2348}
2349
2350/// Emit a `XCTAssertTrue(array.contains(where: { ... }), msg)` line that
2351/// aggregates every text-bearing accessor on the element type of a `Vec<T>`
2352/// field, mirroring python's `_alef_e2e_item_texts` helper.
2353///
2354/// Returns `None` when:
2355///   - `field` is missing
2356///   - The field's root or leaf type cannot be resolved
2357///   - The element type has fewer than 2 stringy fields (the existing
2358///     single-accessor path is good enough and emits simpler code)
2359///
2360/// When matched, emits a closure that gathers `source().toString()`,
2361/// `items().map { $0.asStr().toString() }`, `alias()?.toString()`, etc. into
2362/// a flat `[String]` and substring-matches the expected value against every
2363/// entry. The matcher is lenient so that fixtures asserting `"os"` against
2364/// the `imports` field — where `ImportInfo.source` may be the bare module
2365/// name (`"os"`), the entire import statement (`"import os"`), or the
2366/// imported items (`from os import path` → items=["path"]) — succeed
2367/// regardless of how the language extractor surfaces the value.
2368fn swift_stringy_aggregator_contains_assert(
2369    field: Option<&str>,
2370    result_var: &str,
2371    field_resolver: &FieldResolver,
2372    swift_val: &str,
2373) -> Option<String> {
2374    use crate::field_access::StringyFieldKind;
2375    let field = field?;
2376    let resolved = field_resolver.resolve(field);
2377    // Only handle simple top-level array fields (no nested chains) for now.
2378    // Field path containing `.` or `[` is left to the existing traversal/array
2379    // paths.
2380    if resolved.contains('.') || resolved.contains('[') {
2381        return None;
2382    }
2383    let root_type = field_resolver.swift_root_type()?.clone();
2384    let elem_type = field_resolver.swift_advance(Some(&root_type), resolved)?;
2385    let stringy = field_resolver.swift_stringy_fields(&elem_type)?;
2386    if stringy.len() < 2 {
2387        return None;
2388    }
2389    let array_accessor = field_resolver.accessor(field, "swift", result_var);
2390    let mut texts_lines: Vec<String> = Vec::new();
2391    for sf in stringy {
2392        let call = swift_ident(&sf.name.to_lower_camel_case());
2393        match sf.kind {
2394            StringyFieldKind::Plain => {
2395                texts_lines.push(format!("                texts.append(item.{call}().toString())"));
2396            }
2397            StringyFieldKind::Optional => {
2398                texts_lines.push(format!(
2399                    "                if let v = item.{call}() {{ texts.append(v.toString()) }}"
2400                ));
2401            }
2402            StringyFieldKind::Vec => {
2403                // `item.field()` returns `RustVec<RustString>`. Mapping its
2404                // elements yields `RustStringRef` — a swift-bridge wrapper
2405                // around the borrowed RustString — which has `as_str()`
2406                // (snake_case, defined in `SwiftBridgeCore.swift`), NOT
2407                // `toString()` (only `RustString` has the latter via the
2408                // extension that calls `self.as_str().toString()`).
2409                texts_lines.push(format!(
2410                    "                texts.append(contentsOf: item.{call}().map {{ $0.as_str().toString() }})"
2411                ));
2412            }
2413        }
2414    }
2415    let texts_block = texts_lines.join("\n");
2416    Some(format!(
2417        "        XCTAssertTrue({array_accessor}.contains(where: {{ item in\n            var texts = [String]()\n{texts_block}\n            return texts.contains(where: {{ $0.contains({swift_val}) }})\n        }}), \"expected to contain: \\({swift_val})\")"
2418    ))
2419}
2420
2421/// Generate a `.count` expression for an array field that may be nested inside optional parents.
2422///
2423/// Swift-bridge exposes all Rust fields as methods with `()`. When ancestor segments are
2424/// optional, we use `?.` chaining. The final count is coalesced with `?? 0` when there
2425/// are optional ancestors so the XCTAssert macro receives a non-optional `Int`.
2426///
2427/// Also check if the field itself (the leaf) is optional, which happens when the field
2428/// returns Optional<RustVec<T>> (e.g., `links()` may return Optional).
2429fn swift_array_count_expr(field: Option<&str>, result_var: &str, field_resolver: &FieldResolver) -> String {
2430    let Some(f) = field else {
2431        return format!("{result_var}.count");
2432    };
2433    let (accessor, mut has_optional) = swift_build_accessor(f, result_var, field_resolver);
2434    // Also check if the leaf field itself is optional.
2435    if field_resolver.is_optional(f) {
2436        has_optional = true;
2437    }
2438    if has_optional {
2439        // In Swift, accessing .count on an optional with ?. returns Optional<Int>,
2440        // so we coalesce with ?? 0 to get a concrete Int for XCTAssert.
2441        if accessor.contains("?.") {
2442            format!("{accessor}.count ?? 0")
2443        } else {
2444            // If no ?. but field is optional, the field_expr itself is Optional<RustVec<T>>
2445            // so we need ?. to call count.
2446            format!("({accessor}?.count ?? 0)")
2447        }
2448    } else {
2449        format!("{accessor}.count")
2450    }
2451}
2452
2453/// Convert a `serde_json::Value` to a Swift literal string.
2454/// Returns true when `element_type` names a scalar Rust/Swift element type.
2455///
2456/// Scalar element types describe `Vec<T>` Rust parameters that the swift-bridge
2457/// surface exposes as native Swift `[T]` arrays — these can be constructed from
2458/// a Swift array literal without any opaque-type intermediate. Object element
2459/// types (everything else) require an `options_via` configuration to construct.
2460fn is_scalar_element_type(element_type: Option<&str>) -> bool {
2461    matches!(
2462        element_type.map(str::trim),
2463        Some(
2464            "String"
2465                | "str"
2466                | "bool"
2467                | "i8"
2468                | "i16"
2469                | "i32"
2470                | "i64"
2471                | "isize"
2472                | "u8"
2473                | "u16"
2474                | "u32"
2475                | "u64"
2476                | "usize"
2477                | "f32"
2478                | "f64",
2479        )
2480    )
2481}
2482
2483fn json_to_swift(value: &serde_json::Value) -> String {
2484    match value {
2485        serde_json::Value::String(s) => format!("\"{}\"", escape_swift(s)),
2486        serde_json::Value::Bool(b) => b.to_string(),
2487        serde_json::Value::Number(n) => n.to_string(),
2488        serde_json::Value::Null => "nil".to_string(),
2489        serde_json::Value::Array(arr) => {
2490            let items: Vec<String> = arr.iter().map(json_to_swift).collect();
2491            format!("[{}]", items.join(", "))
2492        }
2493        serde_json::Value::Object(_) => {
2494            let json_str = serde_json::to_string(value).unwrap_or_default();
2495            format!("\"{}\"", escape_swift(&json_str))
2496        }
2497    }
2498}
2499
2500/// When comparing numeric values in Swift, if the field expression uses method-call
2501/// syntax (contains `()` indicating opaque swift-bridge types), we need to consider
2502/// the numeric literal type. Integer literals may need wrapping in `UInt(...)` to
2503/// match opaque methods that return UInt (like `metrics().totalLines()`). However,
2504/// floating-point literals should NOT be wrapped, as they may compare against fields
2505/// that return `Double` (like `relevanceScore()`). Type inference should handle the
2506/// field type correctly based on the comparison operator and literal value.
2507fn swift_numeric_literal_cast(field_expr: &str, numeric_literal: &str) -> String {
2508    // Only wrap integer literals in UInt(...) for method-call expressions.
2509    // Don't wrap floats, as the field type is unknown and may return Double.
2510    if field_expr.contains("()") && !numeric_literal.contains('.') {
2511        format!("UInt({})", numeric_literal)
2512    } else {
2513        numeric_literal.to_string()
2514    }
2515}
2516
2517/// Escape a string for embedding in a Swift double-quoted string literal.
2518fn escape_swift(s: &str) -> String {
2519    escape_swift_str(s)
2520}
2521
2522/// Return the count-able target expression for `field_expr`.
2523///
2524/// For opaque method-call accessors (ending in `()` or `()?`), the returned
2525/// value depends on the field's IR kind:
2526///
2527/// - `Vec<T>` ⇒ `RustVec<T>`, which exposes `.count` directly. No wrap.
2528/// - `String` ⇒ `RustString`, which does NOT expose `.count`. Wrap with
2529///   `.toString()` so `.count` lands on Swift `String`.
2530///
2531/// First-class property accessors (no trailing parens) return Swift values
2532/// that already support `.count` directly.
2533///
2534/// The discriminator is the field's resolved leaf type, looked up against the
2535/// `SwiftFirstClassMap`'s vec field set when available. If the field is
2536/// unknown (None), fall back to the conservative wrap — RustString is the
2537/// dominant scalar-leaf case for top-level assertions.
2538fn swift_count_target(field_expr: &str, field_resolver: &FieldResolver, field: Option<&str>) -> String {
2539    let is_method_call = field_expr.trim_end().ends_with(')');
2540    if !is_method_call {
2541        return field_expr.to_string();
2542    }
2543    if let Some(f) = field
2544        && field_resolver.leaf_is_vec_via_swift_map(field_resolver.resolve(f))
2545    {
2546        return field_expr.to_string();
2547    }
2548    format!("{field_expr}.toString()")
2549}
2550
2551/// Resolve the IR type name backing this call's result.
2552///
2553/// Lookup order mirrors PHP's `derive_root_type` for `[crates.e2e.calls.*]`
2554/// configs: any of `c, csharp, java, kotlin, go, php` overrides may carry a
2555/// `result_type = "ChatCompletionResponse"` field. The first non-empty value
2556/// wins. These overrides are language-agnostic IR type names — they were
2557/// originally added for the C/C# backends and other backends piggy-back on them
2558/// because the IR names are shared across every binding.
2559///
2560/// Returns `None` when no override sets `result_type`; the renderer then falls
2561/// back to the workspace-default heuristic in `SwiftFirstClassMap` (which
2562/// defaults to property access — the right call for first-class result types
2563/// like `FileObject` but wrong for opaque types like `ChatCompletionResponse`).
2564fn swift_call_result_type(call_config: &alef_core::config::e2e::CallConfig) -> Option<String> {
2565    const LOOKUP_LANGS: &[&str] = &["c", "csharp", "java", "kotlin", "go", "php"];
2566    for lang in LOOKUP_LANGS {
2567        if let Some(o) = call_config.overrides.get(*lang)
2568            && let Some(rt) = o.result_type.as_deref()
2569            && !rt.is_empty()
2570        {
2571            return Some(rt.to_string());
2572        }
2573    }
2574    None
2575}
2576
2577/// Returns true when the field type would be emitted as a Swift primitive value
2578/// or a known first-class Codable struct/unit-enum, so it can appear on a
2579/// first-class Codable Swift struct without forcing the host type into a
2580/// typealias. Mirrors `first_class_field_supported` in alef-backend-swift.
2581///
2582/// Accepts:
2583/// - `Primitive` and `String`
2584/// - `Named(S)` when `S` is in `known_dto_names` (seeded with unit-serde enums and
2585///   grown via fixed-point iteration over candidate struct DTOs)
2586/// - `Vec<T>` and `Optional<T>` recursively
2587///
2588/// Rejects `Map`, `Path`, `Bytes`, `Duration`, `Char`, `Json`, and unknown
2589/// `Named(_)` references (the backend treats those as typealias-to-opaque).
2590fn swift_first_class_field_supported(ty: &alef_core::ir::TypeRef, known_dto_names: &HashSet<String>) -> bool {
2591    use alef_core::ir::TypeRef;
2592    match ty {
2593        TypeRef::Primitive(_) | TypeRef::String => true,
2594        TypeRef::Named(name) => known_dto_names.contains(name),
2595        TypeRef::Vec(inner) | TypeRef::Optional(inner) => swift_first_class_field_supported(inner, known_dto_names),
2596        _ => false,
2597    }
2598}
2599
2600/// Build the per-type Swift first-class/opaque classification map used by
2601/// `render_swift_with_first_class_map`.
2602///
2603/// A TypeDef is treated as first-class (Codable Swift struct → property access)
2604/// when it is not opaque, has serde derives, has at least one field, and every
2605/// binding field is supported by `swift_first_class_field_supported` against the
2606/// current first-class set. All other public types end up as typealiases to
2607/// opaque `RustBridge.X` classes whose fields are swift-bridge methods
2608/// (`.id()`, `.status()`).
2609///
2610/// Mirrors the fixed-point iteration in `alef-backend-swift::gen_bindings.rs`
2611/// (lines 100-130). Without the fixed point, a type like `TranscriptionResponse`
2612/// that holds `Option<Vec<TranscriptionSegment>>` would be wrongly classified
2613/// opaque, causing the renderer to emit `.text()` against a first-class struct
2614/// whose `text` is a `public let` property.
2615///
2616/// `field_types` records the next-type that each Named field traverses into,
2617/// so the renderer can advance its current-type cursor through nested
2618/// `data[0].id` style paths.
2619fn build_swift_first_class_map(
2620    type_defs: &[alef_core::ir::TypeDef],
2621    enum_defs: &[alef_core::ir::EnumDef],
2622    e2e_config: &crate::config::E2eConfig,
2623) -> SwiftFirstClassMap {
2624    use alef_core::ir::TypeRef;
2625    let mut field_types: HashMap<String, HashMap<String, String>> = HashMap::new();
2626    let mut vec_field_names: HashSet<String> = HashSet::new();
2627    fn inner_named(ty: &TypeRef) -> Option<String> {
2628        match ty {
2629            TypeRef::Named(n) => Some(n.clone()),
2630            TypeRef::Optional(inner) | TypeRef::Vec(inner) => inner_named(inner),
2631            _ => None,
2632        }
2633    }
2634    fn is_vec_ty(ty: &TypeRef) -> bool {
2635        match ty {
2636            TypeRef::Vec(_) => true,
2637            TypeRef::Optional(inner) => is_vec_ty(inner),
2638            _ => false,
2639        }
2640    }
2641    // Seed with unit serde enum names — Codable on the Swift side and can appear
2642    // as leaf fields on struct DTOs (matches gen_bindings.rs unit_serde_enum_names).
2643    let mut known_dto_names: HashSet<String> = enum_defs
2644        .iter()
2645        .filter(|e| e.has_serde && e.variants.iter().all(|v| v.fields.is_empty()))
2646        .map(|e| e.name.clone())
2647        .collect();
2648
2649    // Candidate struct DTOs: non-opaque, has_serde, non-empty fields.
2650    // Trait types and binding-excluded types are skipped (matches backend semantics
2651    // — note backend further filters via `exclude_types`, which we don't have here,
2652    // but accepting a superset is safe: types not actually emitted simply never
2653    // appear in path-access chains).
2654    let candidates: Vec<&alef_core::ir::TypeDef> = type_defs
2655        .iter()
2656        .filter(|td| !td.is_trait && !td.is_opaque && td.has_serde && !td.fields.is_empty())
2657        .collect();
2658
2659    loop {
2660        let prev = known_dto_names.len();
2661        for td in &candidates {
2662            if known_dto_names.contains(&td.name) {
2663                continue;
2664            }
2665            let all_supported = td
2666                .fields
2667                .iter()
2668                .filter(|f| !f.binding_excluded)
2669                .all(|f| swift_first_class_field_supported(&f.ty, &known_dto_names));
2670            if all_supported {
2671                known_dto_names.insert(td.name.clone());
2672            }
2673        }
2674        if known_dto_names.len() == prev {
2675            break;
2676        }
2677    }
2678
2679    // The first-class set on SwiftFirstClassMap conceptually represents structs
2680    // accessed via property syntax. Unit enums never appear as the *owner* of a
2681    // chain segment (they are leaves), but including them is harmless since
2682    // `advance()` never returns them as a current_type for further traversal.
2683    let first_class_types: HashSet<String> = candidates
2684        .iter()
2685        .filter(|td| known_dto_names.contains(&td.name))
2686        .map(|td| td.name.clone())
2687        .collect();
2688
2689    use crate::field_access::{StringyField, StringyFieldKind};
2690    // Enums are bridged as `String` on the swift-bridge surface (the binding
2691    // emits `fn kind(&self) -> String` for `kind: SomeEnum`), so they must
2692    // also count as text-bearing accessors when aggregating contains-matchers.
2693    let enum_names: HashSet<&str> = enum_defs.iter().map(|e| e.name.as_str()).collect();
2694    let classify_stringy = |ty: &TypeRef, field_optional: bool| -> Option<StringyFieldKind> {
2695        match ty {
2696            TypeRef::String => Some(if field_optional {
2697                StringyFieldKind::Optional
2698            } else {
2699                StringyFieldKind::Plain
2700            }),
2701            TypeRef::Named(name) if enum_names.contains(name.as_str()) => Some(if field_optional {
2702                StringyFieldKind::Optional
2703            } else {
2704                StringyFieldKind::Plain
2705            }),
2706            TypeRef::Optional(inner) => match inner.as_ref() {
2707                TypeRef::String => Some(StringyFieldKind::Optional),
2708                TypeRef::Named(name) if enum_names.contains(name.as_str()) => Some(StringyFieldKind::Optional),
2709                _ => None,
2710            },
2711            TypeRef::Vec(inner) => match inner.as_ref() {
2712                TypeRef::String => Some(StringyFieldKind::Vec),
2713                TypeRef::Named(name) if enum_names.contains(name.as_str()) => Some(StringyFieldKind::Vec),
2714                _ => None,
2715            },
2716            _ => None,
2717        }
2718    };
2719    let mut stringy_fields_by_type: HashMap<String, Vec<StringyField>> = HashMap::new();
2720    for td in type_defs {
2721        let mut td_field_types: HashMap<String, String> = HashMap::new();
2722        let mut td_stringy: Vec<StringyField> = Vec::new();
2723        for f in &td.fields {
2724            if let Some(named) = inner_named(&f.ty) {
2725                td_field_types.insert(f.name.clone(), named);
2726            }
2727            if is_vec_ty(&f.ty) {
2728                vec_field_names.insert(f.name.clone());
2729            }
2730            if f.binding_excluded {
2731                continue;
2732            }
2733            if let Some(kind) = classify_stringy(&f.ty, f.optional) {
2734                td_stringy.push(StringyField {
2735                    name: f.name.clone(),
2736                    kind,
2737                });
2738            }
2739        }
2740        if !td_field_types.is_empty() {
2741            field_types.insert(td.name.clone(), td_field_types);
2742        }
2743        if !td_stringy.is_empty() {
2744            stringy_fields_by_type.insert(td.name.clone(), td_stringy);
2745        }
2746    }
2747    // Best-effort root-type detection: pick a unique TypeDef that contains all
2748    // `result_fields`. Falls back to `None` (renderer defaults to first-class
2749    // property syntax for unknown roots).
2750    let root_type = if e2e_config.result_fields.is_empty() {
2751        None
2752    } else {
2753        let matches: Vec<&alef_core::ir::TypeDef> = type_defs
2754            .iter()
2755            .filter(|td| {
2756                let names: HashSet<&str> = td.fields.iter().map(|f| f.name.as_str()).collect();
2757                e2e_config.result_fields.iter().all(|rf| names.contains(rf.as_str()))
2758            })
2759            .collect();
2760        if matches.len() == 1 {
2761            Some(matches[0].name.clone())
2762        } else {
2763            None
2764        }
2765    };
2766    SwiftFirstClassMap {
2767        first_class_types,
2768        field_types,
2769        vec_field_names,
2770        root_type,
2771        stringy_fields_by_type,
2772    }
2773}
2774
2775#[cfg(test)]
2776mod tests {
2777    use super::*;
2778    use crate::field_access::FieldResolver;
2779    use std::collections::{HashMap, HashSet};
2780
2781    fn make_resolver_tool_calls() -> FieldResolver {
2782        // Resolver for `choices[0].message.tool_calls[0].function.name`:
2783        //   - `choices` is a registered array field
2784        //   - `choices.message.tool_calls` is optional (Optional<RustVec<ToolCall>>)
2785        let mut optional = HashSet::new();
2786        optional.insert("choices.message.tool_calls".to_string());
2787        let mut arrays = HashSet::new();
2788        arrays.insert("choices".to_string());
2789        FieldResolver::new(&HashMap::new(), &optional, &HashSet::new(), &arrays, &HashSet::new())
2790    }
2791
2792    /// Regression: after the optional `[0]` subscript, the codegen must NOT
2793    /// append a trailing `?`. The Swift compiler sees `?[0]` as consuming the
2794    /// optional chain, yielding the non-optional element type, so a subsequent
2795    /// `?.member` would trigger "cannot use optional chaining on non-optional
2796    /// value".
2797    ///
2798    /// With no `SwiftFirstClassMap` configured (default in this test), every
2799    /// accessor is emitted as a swift-bridge method call — so accessors are
2800    /// `result.choices()[0].message().toolCalls()?[0].function().name()`.
2801    #[test]
2802    fn optional_vec_subscript_does_not_emit_trailing_question_mark_before_next_segment() {
2803        let resolver = make_resolver_tool_calls();
2804        let (accessor, has_optional) =
2805            swift_build_accessor("choices[0].message.tool_calls[0].function.name", "result", &resolver);
2806        // `?` before `[0]` is correct (tool_calls is optional). Method-call
2807        // syntax (with `()`) is the default when no SwiftFirstClassMap is
2808        // supplied.
2809        assert!(
2810            accessor.contains("toolCalls()?[0]"),
2811            "expected `toolCalls()?[0]` for optional tool_calls, got: {accessor}"
2812        );
2813        // There must NOT be `?[0]?` (trailing `?` after the index).
2814        assert!(
2815            !accessor.contains("?[0]?"),
2816            "must not emit trailing `?` after subscript index: {accessor}"
2817        );
2818        // The expression IS optional overall (tool_calls may be nil).
2819        assert!(has_optional, "expected has_optional=true for optional field chain");
2820        // Subsequent member access uses `.` (non-optional chain) not `?.`.
2821        assert!(
2822            accessor.contains("[0].function"),
2823            "expected `.function` (non-optional) after subscript: {accessor}"
2824        );
2825    }
2826
2827    /// `contains` against an array of opaque DTOs must aggregate every
2828    /// text-bearing accessor of the element type and substring-match the
2829    /// expected value, mirroring python's `_alef_e2e_item_texts`. This
2830    /// avoids the brittle "primary accessor" guess (e.g. ImportInfo →
2831    /// source) that misses values surfaced through sibling fields like
2832    /// `items` or `alias`.
2833    #[test]
2834    fn contains_against_vec_dto_aggregates_stringy_accessors() {
2835        use crate::field_access::{StringyField, StringyFieldKind, SwiftFirstClassMap};
2836        // Simulate the ImportInfo element type with its three text-bearing
2837        // accessors: source (plain), items (vec), alias (optional).
2838        let mut stringy_fields_by_type: HashMap<String, Vec<StringyField>> = HashMap::new();
2839        stringy_fields_by_type.insert(
2840            "ImportInfo".to_string(),
2841            vec![
2842                StringyField {
2843                    name: "source".to_string(),
2844                    kind: StringyFieldKind::Plain,
2845                },
2846                StringyField {
2847                    name: "items".to_string(),
2848                    kind: StringyFieldKind::Vec,
2849                },
2850                StringyField {
2851                    name: "alias".to_string(),
2852                    kind: StringyFieldKind::Optional,
2853                },
2854            ],
2855        );
2856        let mut field_types: HashMap<String, HashMap<String, String>> = HashMap::new();
2857        let mut process_fields = HashMap::new();
2858        process_fields.insert("imports".to_string(), "ImportInfo".to_string());
2859        field_types.insert("ProcessResult".to_string(), process_fields);
2860
2861        let mut arrays = HashSet::new();
2862        arrays.insert("imports".to_string());
2863
2864        let map = SwiftFirstClassMap {
2865            first_class_types: HashSet::new(),
2866            field_types,
2867            vec_field_names: HashSet::new(),
2868            root_type: None,
2869            stringy_fields_by_type,
2870        };
2871        let resolver = FieldResolver::new_with_swift_first_class(
2872            &HashMap::new(),
2873            &HashSet::new(),
2874            &HashSet::new(),
2875            &arrays,
2876            &HashSet::new(),
2877            &HashMap::new(),
2878            map,
2879        )
2880        .with_swift_root_type(Some("ProcessResult".to_string()));
2881
2882        let line = swift_stringy_aggregator_contains_assert(Some("imports"), "result", &resolver, "\"os\"")
2883            .expect("aggregator should fire for Vec<ImportInfo> contains");
2884        assert!(
2885            line.contains("result.imports().contains(where: { item in"),
2886            "expected contains(where:) over result.imports(): {line}"
2887        );
2888        assert!(
2889            line.contains("texts.append(item.source().toString())"),
2890            "expected plain source() accessor: {line}"
2891        );
2892        assert!(
2893            line.contains("texts.append(contentsOf: item.items().map { $0.as_str().toString() })"),
2894            "expected vec items() flattened via .map as_str(): {line}"
2895        );
2896        assert!(
2897            line.contains("if let v = item.alias()"),
2898            "expected optional alias() unwrap: {line}"
2899        );
2900        // Substring match — NOT exact equality.
2901        assert!(
2902            line.contains("$0.contains(\"os\")"),
2903            "expected substring contains over expected value: {line}"
2904        );
2905        assert!(!line.contains("$0 == \"os\""), "must not use exact equality: {line}");
2906    }
2907
2908    /// When the element type has fewer than 2 stringy accessors, the
2909    /// aggregator should bow out and let the simpler single-accessor path
2910    /// emit code — keeping diff churn minimal on fixtures that already pass.
2911    #[test]
2912    fn contains_aggregator_skips_when_only_one_stringy_field() {
2913        use crate::field_access::{StringyField, StringyFieldKind, SwiftFirstClassMap};
2914        let mut stringy_fields_by_type: HashMap<String, Vec<StringyField>> = HashMap::new();
2915        stringy_fields_by_type.insert(
2916            "TagInfo".to_string(),
2917            vec![StringyField {
2918                name: "name".to_string(),
2919                kind: StringyFieldKind::Plain,
2920            }],
2921        );
2922        let mut field_types: HashMap<String, HashMap<String, String>> = HashMap::new();
2923        let mut root_fields = HashMap::new();
2924        root_fields.insert("tags".to_string(), "TagInfo".to_string());
2925        field_types.insert("Root".to_string(), root_fields);
2926        let mut arrays = HashSet::new();
2927        arrays.insert("tags".to_string());
2928        let map = SwiftFirstClassMap {
2929            first_class_types: HashSet::new(),
2930            field_types,
2931            vec_field_names: HashSet::new(),
2932            root_type: None,
2933            stringy_fields_by_type,
2934        };
2935        let resolver = FieldResolver::new_with_swift_first_class(
2936            &HashMap::new(),
2937            &HashSet::new(),
2938            &HashSet::new(),
2939            &arrays,
2940            &HashSet::new(),
2941            &HashMap::new(),
2942            map,
2943        )
2944        .with_swift_root_type(Some("Root".to_string()));
2945        assert!(
2946            swift_stringy_aggregator_contains_assert(Some("tags"), "result", &resolver, "\"x\"").is_none(),
2947            "single-stringy-field types must not trigger the aggregator"
2948        );
2949    }
2950}