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