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        // Qualify with module name to disambiguate between high-level and swift-bridge symbols.
867        let expr = if is_async {
868            format!("try await {module_name}.{function_name}({args_str})")
869        } else {
870            format!("try {module_name}.{function_name}({args_str})")
871        };
872        (None, expr)
873    };
874    // For backwards compatibility: qualified_function_name unused when client_factory is set.
875    let _ = function_name;
876
877    if is_async {
878        let _ = writeln!(out, "    func test{method_name}() async throws {{");
879    } else {
880        let _ = writeln!(out, "    func test{method_name}() throws {{");
881    }
882    let _ = writeln!(out, "        // {description}");
883
884    if expects_error {
885        // For error fixtures, setup may itself throw (e.g. config validation
886        // happens at engine construction). Wrap the whole pipeline — setup
887        // and the call — in a single do/catch so any throw counts as success.
888        if is_async {
889            // XCTAssertThrowsError is a synchronous macro; for async-throwing
890            // functions use a do/catch with explicit XCTFail to enforce that
891            // the throw actually happens. `await XCTAssertThrowsError(...)` is
892            // not valid Swift — it evaluates `await` against a non-async expr.
893            let _ = writeln!(out, "        do {{");
894            for line in &setup_lines {
895                let _ = writeln!(out, "            {line}");
896            }
897            if let Some(setup) = &call_setup {
898                let _ = writeln!(out, "            {setup}");
899            }
900            let _ = writeln!(out, "            _ = {call_expr}");
901            let _ = writeln!(out, "            XCTFail(\"expected to throw\")");
902            let _ = writeln!(out, "        }} catch {{");
903            let _ = writeln!(out, "            // success");
904            let _ = writeln!(out, "        }}");
905        } else {
906            // Synchronous: emit setup outside (it's expected to succeed) and
907            // wrap only the throwing call in XCTAssertThrowsError. If setup
908            // itself throws, that propagates as the test's own failure — but
909            // sync tests use `throws` so the test method itself rethrows,
910            // which XCTest still records as caught. Keep this simple: use a
911            // do/catch so setup-time throws also count as expected failures.
912            let _ = writeln!(out, "        do {{");
913            for line in &setup_lines {
914                let _ = writeln!(out, "            {line}");
915            }
916            if let Some(setup) = &call_setup {
917                let _ = writeln!(out, "            {setup}");
918            }
919            let _ = writeln!(out, "            _ = {call_expr}");
920            let _ = writeln!(out, "            XCTFail(\"expected to throw\")");
921            let _ = writeln!(out, "        }} catch {{");
922            let _ = writeln!(out, "            // success");
923            let _ = writeln!(out, "        }}");
924        }
925        let _ = writeln!(out, "    }}");
926        return;
927    }
928
929    for line in &setup_lines {
930        let _ = writeln!(out, "        {line}");
931    }
932
933    // Emit client construction if a client_factory is configured.
934    if let Some(setup) = &call_setup {
935        let _ = writeln!(out, "        {setup}");
936    }
937
938    let _ = writeln!(out, "        let {result_var} = {call_expr}");
939
940    // Emit the collect snippet for streaming fixtures (drains the async sequence into
941    // a local `chunks: [ChatCompletionChunk]` array used by streaming-virtual assertions).
942    if !collect_snippet.is_empty() {
943        for line in collect_snippet.lines() {
944            let _ = writeln!(out, "        {line}");
945        }
946    }
947
948    // Each fixture's call returns a different IR type. Override the resolver's
949    // Swift first-class-map `root_type` with the call's `result_type` (looked up
950    // across c/csharp/java/kotlin/go/php overrides — these are language-agnostic
951    // IR type names that any backend can use to anchor field-access dispatch).
952    let fixture_root_type: Option<String> = swift_call_result_type(call_config);
953    let fixture_resolver = field_resolver.with_swift_root_type(fixture_root_type);
954
955    for assertion in &fixture.assertions {
956        let mut assertion_out = String::new();
957        render_assertion(
958            &mut assertion_out,
959            assertion,
960            result_var,
961            &fixture_resolver,
962            result_is_simple,
963            result_is_array,
964            result_is_option,
965            &effective_enum_fields,
966            is_streaming,
967        );
968        // Module-qualify swift-bridge-ambiguous DTO type names that appear in
969        // streaming-virtual assertion expressions (e.g. `[StreamToolCall]`,
970        // `[ToolCall]`). Both `<Module>` (first-class Codable struct) and
971        // `RustBridge` (swift-bridge opaque class) export the same identifier,
972        // so unqualified usage fails Swift compilation with "X is ambiguous for
973        // type lookup". Mirrors the `[ChatCompletionChunk]` replacement in
974        // `render_test_method`.
975        for unqualified in ["StreamToolCall", "ToolCall"] {
976            assertion_out =
977                assertion_out.replace(&format!("[{unqualified}]"), &format!("[{module_name}.{unqualified}]"));
978        }
979        out.push_str(&assertion_out);
980    }
981
982    let _ = writeln!(out, "    }}");
983}
984
985#[allow(clippy::too_many_arguments)]
986/// Build setup lines and the argument list for the function call.
987///
988/// Swift-bridge wrappers require strongly-typed values that don't have implicit
989/// Swift literal conversions:
990///
991/// - `bytes` args become `RustVec<UInt8>` — fixture supplies a relative file path
992///   string which is read at test time and pushed into a `RustVec<UInt8>` setup
993///   variable. A literal byte array is base64-decoded or UTF-8 encoded inline.
994/// - `json_object` args become opaque `ExtractionConfig` (or sibling) instances —
995///   a JSON string is decoded via `extractionConfigFromJson(...)` in a setup line.
996/// - Optional args missing from the fixture must still appear at the call site
997///   as `nil` whenever a later positional arg is present, otherwise Swift slots
998///   subsequent values into the wrong parameter.
999fn build_args_and_setup(
1000    input: &serde_json::Value,
1001    args: &[crate::config::ArgMapping],
1002    fixture_id: &str,
1003    has_host_root_route: bool,
1004    function_name: &str,
1005    options_via: Option<&str>,
1006    options_type: Option<&str>,
1007    handle_config_fn: Option<&str>,
1008    visitor_handle_expr: Option<&str>,
1009) -> (Vec<String>, String) {
1010    if args.is_empty() {
1011        return (Vec::new(), String::new());
1012    }
1013
1014    let mut setup_lines: Vec<String> = Vec::new();
1015    let mut parts: Vec<(usize, String)> = Vec::new();
1016
1017    // Pre-compute, for each arg index, whether any later arg has a fixture-provided
1018    // value (or is required and will emit a default). When an optional arg is empty
1019    // but a later arg WILL emit, we must keep the slot with `nil` so positional
1020    // alignment is preserved.
1021    let later_emits: Vec<bool> = (0..args.len())
1022        .map(|i| {
1023            args.iter().skip(i + 1).any(|a| {
1024                let f = a.field.strip_prefix("input.").unwrap_or(&a.field);
1025                let v = input.get(f);
1026                let has_value = matches!(v, Some(x) if !x.is_null());
1027                has_value || !a.optional || (a.arg_type == "json_object" && a.name == "config")
1028            })
1029        })
1030        .collect();
1031
1032    for (idx, arg) in args.iter().enumerate() {
1033        if arg.arg_type == "mock_url" {
1034            let env_key = format!("MOCK_SERVER_{}", fixture_id.to_ascii_uppercase().replace('-', "_"));
1035            let url_expr = if has_host_root_route {
1036                format!(
1037                    "ProcessInfo.processInfo.environment[\"{env_key}\"] ?? (ProcessInfo.processInfo.environment[\"MOCK_SERVER_URL\"]! + \"/fixtures/{fixture_id}\")"
1038                )
1039            } else {
1040                format!("ProcessInfo.processInfo.environment[\"MOCK_SERVER_URL\"]! + \"/fixtures/{fixture_id}\"")
1041            };
1042            setup_lines.push(format!("let {} = {url_expr}", arg.name));
1043            parts.push((idx, arg.name.clone()));
1044            continue;
1045        }
1046
1047        if arg.arg_type == "handle" {
1048            let var_name = format!("{}Obj", arg.name.to_lower_camel_case());
1049            let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1050            let config_val = input.get(field);
1051            let has_config = config_val
1052                .is_some_and(|v| !(v.is_null() || v.is_object() && v.as_object().is_some_and(|o| o.is_empty())));
1053            if has_config {
1054                if let Some(from_json_fn) = handle_config_fn {
1055                    let json_str = serde_json::to_string(config_val.unwrap()).unwrap_or_default();
1056                    let escaped = escape_swift_str(&json_str);
1057                    let config_var = format!("{}Config", arg.name.to_lower_camel_case());
1058                    setup_lines.push(format!("let {config_var} = try {from_json_fn}(\"{escaped}\")"));
1059                    setup_lines.push(format!("let {var_name} = try createEngine({config_var})"));
1060                } else {
1061                    setup_lines.push(format!("let {var_name} = try createEngine(nil)"));
1062                }
1063            } else {
1064                setup_lines.push(format!("let {var_name} = try createEngine(nil)"));
1065            }
1066            parts.push((idx, var_name));
1067            continue;
1068        }
1069
1070        // bytes args: fixture stores a fixture-relative path string. Generate
1071        // setup that reads it into a Data and pushes each byte into a
1072        // RustVec<UInt8>. Literal byte arrays inline the bytes; missing values
1073        // produce an empty vec (or `nil` when optional).
1074        if arg.arg_type == "bytes" {
1075            let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1076            let val = input.get(field);
1077            match val {
1078                None | Some(serde_json::Value::Null) if arg.optional => {
1079                    if later_emits[idx] {
1080                        parts.push((idx, "nil".to_string()));
1081                    }
1082                }
1083                None | Some(serde_json::Value::Null) => {
1084                    let var_name = format!("{}Vec", arg.name.to_lower_camel_case());
1085                    setup_lines.push(format!("let {var_name} = RustVec<UInt8>()"));
1086                    parts.push((idx, var_name));
1087                }
1088                Some(serde_json::Value::String(s)) => {
1089                    let escaped = escape_swift(s);
1090                    let var_name = format!("{}Vec", arg.name.to_lower_camel_case());
1091                    let data_var = format!("{}Data", arg.name.to_lower_camel_case());
1092                    setup_lines.push(format!(
1093                        "let {data_var} = try Data(contentsOf: URL(fileURLWithPath: \"{escaped}\"))"
1094                    ));
1095                    setup_lines.push(format!("let {var_name} = RustVec<UInt8>()"));
1096                    setup_lines.push(format!("for _byte in {data_var} {{ {var_name}.push(value: _byte) }}"));
1097                    parts.push((idx, var_name));
1098                }
1099                Some(serde_json::Value::Array(arr)) => {
1100                    let var_name = format!("{}Vec", arg.name.to_lower_camel_case());
1101                    setup_lines.push(format!("let {var_name} = RustVec<UInt8>()"));
1102                    for v in arr {
1103                        if let Some(n) = v.as_u64() {
1104                            setup_lines.push(format!("{var_name}.push(value: UInt8({n}))"));
1105                        }
1106                    }
1107                    parts.push((idx, var_name));
1108                }
1109                Some(other) => {
1110                    // Fallback: encode the JSON serialisation as UTF-8 bytes.
1111                    let json_str = serde_json::to_string(other).unwrap_or_default();
1112                    let escaped = escape_swift(&json_str);
1113                    let var_name = format!("{}Vec", arg.name.to_lower_camel_case());
1114                    setup_lines.push(format!("let {var_name} = RustVec<UInt8>()"));
1115                    setup_lines.push(format!(
1116                        "for _byte in Array(\"{escaped}\".utf8) {{ {var_name}.push(value: _byte) }}"
1117                    ));
1118                    parts.push((idx, var_name));
1119                }
1120            }
1121            continue;
1122        }
1123
1124        // json_object "config" args: the swift-bridge wrapper requires an opaque
1125        // config instance (e.g., `ExtractionConfig`, `ProcessConfig`), not a JSON string.
1126        // Derive the from-json helper name from options_type if available, else default
1127        // to kreuzberg's `extractionConfigFromJson` for backward compatibility.
1128        // Batch functions (batchExtract*) hardcode config internally — skip it.
1129        let is_config_arg = arg.name == "config" && arg.arg_type == "json_object";
1130        let is_batch_fn = function_name.starts_with("batch") || function_name.starts_with("Batch");
1131        if is_config_arg && !is_batch_fn {
1132            let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1133            let val = input.get(field);
1134            let json_str = match val {
1135                None | Some(serde_json::Value::Null) => "{}".to_string(),
1136                Some(v) => serde_json::to_string(v).unwrap_or_else(|_| "{}".to_string()),
1137            };
1138            let escaped = escape_swift(&json_str);
1139            let var_name = format!("{}Obj", arg.name.to_lower_camel_case());
1140            // Derive the from-json helper name from options_type, or default to extractionConfigFromJson
1141            let from_json_fn = if let Some(type_name) = options_type {
1142                format!("{}FromJson", type_name.to_lower_camel_case())
1143            } else {
1144                "extractionConfigFromJson".to_string()
1145            };
1146            setup_lines.push(format!("let {var_name} = try {from_json_fn}(\"{escaped}\")"));
1147            parts.push((idx, var_name));
1148            continue;
1149        }
1150
1151        // json_object non-config args with options_via = "from_json":
1152        // Use the generated `{typeCamelCase}FromJson(_:)` helper so the fixture JSON is
1153        // deserialised into the opaque swift-bridge type rather than passed as a raw string.
1154        // When arg.field == "input", the entire fixture input IS the request object.
1155        // When a visitor handle is present, use `{typeCamelCase}FromJsonWithVisitor(json, handle)`
1156        // instead to attach the visitor to the options in one step.
1157        if arg.arg_type == "json_object" && options_via == Some("from_json") {
1158            if let Some(type_name) = options_type {
1159                let resolved_val = super::resolve_field(input, &arg.field);
1160                let json_str = match resolved_val {
1161                    serde_json::Value::Null => "{}".to_string(),
1162                    v => serde_json::to_string(v).unwrap_or_else(|_| "{}".to_string()),
1163                };
1164                let escaped = escape_swift(&json_str);
1165                let var_name = format!("_{}", arg.name.to_lower_camel_case());
1166                if let Some(handle_expr) = visitor_handle_expr {
1167                    // Use the visitor-aware helper: `{typeCamelCase}FromJsonWithVisitor(json, handle)`.
1168                    // The handle expression builds a VisitorHandle from the local class instance.
1169                    // The function name mirrors emit_options_field_options_helper: camelCase of
1170                    // `{options_snake}_from_json_with_visitor`.
1171                    let with_visitor_fn = format!("{}FromJsonWithVisitor", type_name.to_lower_camel_case());
1172                    let handle_var = format!("_visitorHandle_{}", var_name.trim_start_matches('_'));
1173                    setup_lines.push(format!("let {handle_var} = {handle_expr}"));
1174                    setup_lines.push(format!(
1175                        "let {var_name} = try {with_visitor_fn}(\"{escaped}\", {handle_var})"
1176                    ));
1177                } else {
1178                    let from_json_fn = format!("{}FromJson", type_name.to_lower_camel_case());
1179                    setup_lines.push(format!("let {var_name} = try {from_json_fn}(\"{escaped}\")"));
1180                }
1181                parts.push((idx, var_name));
1182                continue;
1183            }
1184        }
1185
1186        let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1187        let val = input.get(field);
1188        match val {
1189            None | Some(serde_json::Value::Null) if arg.optional => {
1190                // Optional arg with no fixture value: keep the slot with `nil`
1191                // when a later arg will emit, so positional alignment matches
1192                // the swift-bridge wrapper signature.
1193                if later_emits[idx] {
1194                    parts.push((idx, "nil".to_string()));
1195                }
1196            }
1197            None | Some(serde_json::Value::Null) => {
1198                let default_val = match arg.arg_type.as_str() {
1199                    "string" => "\"\"".to_string(),
1200                    "int" | "integer" => "0".to_string(),
1201                    "float" | "number" => "0.0".to_string(),
1202                    "bool" | "boolean" => "false".to_string(),
1203                    _ => "nil".to_string(),
1204                };
1205                parts.push((idx, default_val));
1206            }
1207            Some(v) => {
1208                parts.push((idx, json_to_swift(v)));
1209            }
1210        }
1211    }
1212
1213    let args_str = parts
1214        .into_iter()
1215        .map(|(idx, val)| format!("{}: {}", args[idx].name, val))
1216        .collect::<Vec<_>>()
1217        .join(", ");
1218    (setup_lines, args_str)
1219}
1220
1221#[allow(clippy::too_many_arguments)]
1222fn render_assertion(
1223    out: &mut String,
1224    assertion: &Assertion,
1225    result_var: &str,
1226    field_resolver: &FieldResolver,
1227    result_is_simple: bool,
1228    result_is_array: bool,
1229    result_is_option: bool,
1230    enum_fields: &HashSet<String>,
1231    is_streaming: bool,
1232) {
1233    // When the bare result is `Optional<T>` (no field path) the opaque class
1234    // exposed by swift-bridge has no `.toString()` method, so the usual
1235    // `.toString().isEmpty` pattern produces compile errors. Detect the
1236    // "bare result" case and prefer `XCTAssertNil` / `XCTAssertNotNil`.
1237    let bare_result_is_option = result_is_option && assertion.field.as_deref().filter(|f| !f.is_empty()).is_none();
1238    // Streaming virtual fields resolve against the `chunks` collected-array variable.
1239    // Intercept before is_valid_for_result so they are never skipped.
1240    // Also intercept `usage.*` deep-paths in streaming tests: `AsyncThrowingStream` does
1241    // not have a `usage()` method, so we must route them through the chunks accessor.
1242    if let Some(f) = &assertion.field {
1243        let is_streaming_usage_path =
1244            is_streaming && (f == "usage" || (f.starts_with("usage.") || f.starts_with("usage[")));
1245        if !f.is_empty()
1246            && (crate::codegen::streaming_assertions::is_streaming_virtual_field(f) || is_streaming_usage_path)
1247        {
1248            if let Some(expr) =
1249                crate::codegen::streaming_assertions::StreamingFieldResolver::accessor(f, "swift", "chunks")
1250            {
1251                let line = match assertion.assertion_type.as_str() {
1252                    "count_min" => {
1253                        if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1254                            format!("        XCTAssertGreaterThanOrEqual(chunks.count, {n})\n")
1255                        } else {
1256                            String::new()
1257                        }
1258                    }
1259                    "count_equals" => {
1260                        if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1261                            format!("        XCTAssertEqual(chunks.count, {n})\n")
1262                        } else {
1263                            String::new()
1264                        }
1265                    }
1266                    "equals" => {
1267                        if let Some(serde_json::Value::String(s)) = &assertion.value {
1268                            let escaped = escape_swift(s);
1269                            format!("        XCTAssertEqual({expr}, \"{escaped}\")\n")
1270                        } else if let Some(b) = assertion.value.as_ref().and_then(|v| v.as_bool()) {
1271                            format!("        XCTAssertEqual({expr}, {b})\n")
1272                        } else {
1273                            String::new()
1274                        }
1275                    }
1276                    "not_empty" => {
1277                        format!("        XCTAssertFalse({expr}.isEmpty, \"expected non-empty\")\n")
1278                    }
1279                    "is_empty" => {
1280                        format!("        XCTAssertTrue({expr}.isEmpty, \"expected empty\")\n")
1281                    }
1282                    "is_true" => {
1283                        format!("        XCTAssertTrue({expr})\n")
1284                    }
1285                    "is_false" => {
1286                        format!("        XCTAssertFalse({expr})\n")
1287                    }
1288                    "greater_than" => {
1289                        if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1290                            format!("        XCTAssertGreaterThan(chunks.count, {n})\n")
1291                        } else {
1292                            String::new()
1293                        }
1294                    }
1295                    "contains" => {
1296                        if let Some(serde_json::Value::String(s)) = &assertion.value {
1297                            let escaped = escape_swift(s);
1298                            format!(
1299                                "        XCTAssertTrue({expr}.contains(\"{escaped}\"), \"expected to contain: {escaped}\")\n"
1300                            )
1301                        } else {
1302                            String::new()
1303                        }
1304                    }
1305                    _ => format!(
1306                        "        // streaming field '{f}': assertion type '{}' not rendered\n",
1307                        assertion.assertion_type
1308                    ),
1309                };
1310                if !line.is_empty() {
1311                    out.push_str(&line);
1312                }
1313            }
1314            return;
1315        }
1316    }
1317
1318    // Skip assertions on fields that don't exist on the result type.
1319    if let Some(f) = &assertion.field {
1320        if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
1321            let _ = writeln!(out, "        // skipped: field '{f}' not available on result type");
1322            return;
1323        }
1324    }
1325
1326    // Skip assertions that traverse a tagged-union variant boundary.
1327    // In Swift, FormatMetadata and similar enum-backed opaque types are exposed as
1328    // plain classes by swift-bridge — variant accessor methods (e.g., `.excel()`)
1329    // are not generated, so such assertions cannot be expressed.
1330    if let Some(f) = &assertion.field {
1331        if !f.is_empty() && field_resolver.tagged_union_split(f).is_some() {
1332            let _ = writeln!(
1333                out,
1334                "        // skipped: field '{f}' crosses a tagged-union variant boundary (not expressible in Swift)"
1335            );
1336            return;
1337        }
1338    }
1339
1340    // Determine if this field is an enum type.
1341    let field_is_enum = assertion
1342        .field
1343        .as_deref()
1344        .is_some_and(|f| enum_fields.contains(f) || enum_fields.contains(field_resolver.resolve(f)));
1345
1346    let field_is_optional = assertion.field.as_deref().is_some_and(|f| {
1347        !f.is_empty() && (field_resolver.is_optional(f) || field_resolver.is_optional(field_resolver.resolve(f)))
1348    });
1349    let field_is_array = assertion.field.as_deref().is_some_and(|f| {
1350        !f.is_empty()
1351            && (field_resolver.is_array(f)
1352                || field_resolver.is_array(field_resolver.resolve(f))
1353                || field_resolver.is_collection_root(f)
1354                || field_resolver.is_collection_root(field_resolver.resolve(f)))
1355    });
1356
1357    let field_expr_raw = if result_is_simple {
1358        result_var.to_string()
1359    } else {
1360        match &assertion.field {
1361            Some(f) if !f.is_empty() => field_resolver.accessor(f, "swift", result_var),
1362            _ => result_var.to_string(),
1363        }
1364    };
1365
1366    // swift-bridge `RustVec<T>` exposes its elements as `T.SelfRef`, which holds
1367    // a raw pointer into the parent Vec's storage. When the Vec is a temporary
1368    // (e.g. `result.json_ld()` called inline), Swift ARC may release it before
1369    // the ref is used, leaving the ref's pointer dangling. Materialise the
1370    // temporary into a local so it survives the full expression chain.
1371    //
1372    // The local name is suffixed with the assertion type plus a hash of the
1373    // assertion's discriminating fields so multiple assertions on the same
1374    // collection don't redeclare the same name.
1375    let local_suffix = {
1376        use std::hash::{Hash, Hasher};
1377        let mut hasher = std::collections::hash_map::DefaultHasher::new();
1378        assertion.field.hash(&mut hasher);
1379        assertion
1380            .value
1381            .as_ref()
1382            .map(|v| v.to_string())
1383            .unwrap_or_default()
1384            .hash(&mut hasher);
1385        format!(
1386            "{}_{:x}",
1387            assertion.assertion_type.replace(['-', '.'], "_"),
1388            hasher.finish() & 0xffff_ffff,
1389        )
1390    };
1391    let (vec_setup, field_expr, is_map_subscript) = materialise_vec_temporaries(&field_expr_raw, &local_suffix);
1392    // The `contains` / `not_contains` traversal branch builds its own
1393    // accessor from `field_resolver.accessor(array_part, ...)`, ignoring
1394    // `field_expr`. Emitting the vec_setup there would produce dead
1395    // `let _vec_… = …` lines, so skip it for those traversal cases.
1396    let field_uses_traversal = assertion.field.as_deref().is_some_and(|f| f.contains("[]."));
1397    let traversal_skips_field_expr = field_uses_traversal
1398        && matches!(
1399            assertion.assertion_type.as_str(),
1400            "contains" | "not_contains" | "not_empty" | "is_empty"
1401        );
1402    if !traversal_skips_field_expr {
1403        for line in &vec_setup {
1404            let _ = writeln!(out, "        {line}");
1405        }
1406    }
1407
1408    // In Swift, optional chaining with `?.` makes the result optional even if the
1409    // called method's return type isn't marked optional. For example:
1410    // `result.markdown()?.content()` returns `Optional<RustString>` because
1411    // `markdown()` is optional and the `?.` operator wraps the result.
1412    // Detect this by checking if the accessor contains `?.`.
1413    let accessor_is_optional = field_expr.contains("?.");
1414    // First-class Codable Swift struct property access leaves no trailing `()`
1415    // on the leaf segment — e.g. `result.text` (Swift `String`) vs
1416    // `result.text()` (RustBridge.RustString). When the leaf is property
1417    // access, we already have a Swift `String` (or `String?`) and must NOT
1418    // re-wrap with `.toString()`. Detect this by looking at the final segment
1419    // after the last `.` — property access ends in a bare identifier (no
1420    // trailing `()` or `()?`).
1421    let leaf_is_property_access = {
1422        let trimmed = field_expr.trim_end_matches('?');
1423        // Skip subscripts: `name?[0]` should still see `name` as the field.
1424        let last_segment = trimmed.rsplit_once('.').map(|(_, s)| s).unwrap_or(trimmed);
1425        let last_segment = last_segment.split('[').next().unwrap_or(last_segment);
1426        !last_segment.ends_with(')') && !last_segment.is_empty()
1427    };
1428
1429    // For enum fields, need to handle the string representation differently in Swift.
1430    // Swift enums don't have `.rawValue` unless they're explicitly RawRepresentable.
1431    // Check if this is an enum type and handle accordingly.
1432    // For optional fields (Optional<RustString>), use optional chaining before toString().
1433    // For other fields: swift-bridge returns all Rust `String` fields as `RustString`.
1434    // We add .toString() here so string assertions (contains, hasPrefix, etc.) work.
1435    // Non-string opaque fields (DocumentStructure, etc.) should not appear in string
1436    // assertions — the fixture schema controls which assertions apply to which fields.
1437    let string_expr = if is_map_subscript {
1438        // The field_expr already evaluates to `String?` (from a JSON-decoded
1439        // `[String: String]` subscript). No `.toString()` chain needed —
1440        // coalesce the optional to "" and use the Swift String directly.
1441        format!("({field_expr} ?? \"\")")
1442    } else if leaf_is_property_access {
1443        // First-class Codable struct field access: leaf is already a Swift
1444        // `String` (or `String?`/enum type) — never a `RustString` requiring
1445        // `.toString()`. For optional leaves, coalesce to "" so XCTAssert
1446        // receives a non-optional Swift `String`.
1447        if field_is_enum && (field_is_optional || accessor_is_optional) {
1448            // Optional first-class Codable enum (e.g. `FinishReason?` where
1449            // `FinishReason: String, Codable`). `.rawValue` gives the serde
1450            // wire value (e.g. "tool_calls") so assertions match fixture JSON.
1451            format!("(({field_expr})?.rawValue ?? \"\")")
1452        } else if field_is_enum {
1453            format!("{field_expr}.rawValue")
1454        } else if field_is_optional || accessor_is_optional {
1455            format!("({field_expr} ?? \"\")")
1456        } else {
1457            field_expr.to_string()
1458        }
1459    } else if field_is_enum && (field_is_optional || accessor_is_optional) {
1460        // Enum-typed fields that are also optional (e.g. `finish_reason() -> Optional<RustString>`)
1461        // must use optional chaining: `?.toString() ?? ""` to unwrap before converting to Swift String.
1462        format!("({field_expr}?.toString() ?? \"\")")
1463    } else if field_is_enum {
1464        // Enum-typed fields are now bridged as `String` (RustString in Swift) rather than
1465        // as opaque enum handles. The getter on the Rust side calls `to_string()` internally
1466        // and returns a `String` across the FFI. In Swift this arrives as `RustString`, so
1467        // `.toString()` converts it to a Swift `String` — one call, not two.
1468        format!("{field_expr}.toString()")
1469    } else if field_is_optional {
1470        // Leaf field itself is Optional<RustString> — need ?.toString() to unwrap.
1471        format!("({field_expr}?.toString() ?? \"\")")
1472    } else if accessor_is_optional {
1473        // Ancestor optional chain propagates; leaf is non-optional RustString within chain.
1474        // Use .toString() directly — the whole expr is Optional<String> due to propagation.
1475        format!("({field_expr}.toString() ?? \"\")")
1476    } else {
1477        format!("{field_expr}.toString()")
1478    };
1479
1480    match assertion.assertion_type.as_str() {
1481        "equals" => {
1482            if let Some(expected) = &assertion.value {
1483                let swift_val = json_to_swift(expected);
1484                if expected.is_string() {
1485                    if field_is_enum {
1486                        // Enum fields: `to_string()` (snake_case) returns RustString;
1487                        // `.toString()` converts it to a Swift String.
1488                        // `string_expr` already incorporates this call chain.
1489                        let trim_expr =
1490                            format!("{string_expr}.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)");
1491                        let _ = writeln!(out, "        XCTAssertEqual({trim_expr}, {swift_val})");
1492                    } else {
1493                        // For optional strings (String?), use ?? to coalesce before trimming.
1494                        // `.toString()` converts RustString → Swift String before calling
1495                        // `.trimmingCharacters`, which requires a concrete String type.
1496                        // string_expr already incorporates field_is_optional via ?.toString() ?? "".
1497                        let trim_expr =
1498                            format!("{string_expr}.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)");
1499                        let _ = writeln!(out, "        XCTAssertEqual({trim_expr}, {swift_val})");
1500                    }
1501                } else {
1502                    let _ = writeln!(out, "        XCTAssertEqual({field_expr}, {swift_val})");
1503                }
1504            }
1505        }
1506        "contains" => {
1507            if let Some(expected) = &assertion.value {
1508                let swift_val = json_to_swift(expected);
1509                // When the root result IS the array (result_is_simple + result_is_array) and
1510                // there is no field path, check array membership via map+contains.
1511                let no_field = assertion.field.as_deref().is_none_or(|f| f.is_empty());
1512                if result_is_simple && result_is_array && no_field {
1513                    // RustVec<RustString> iteration yields RustStringRef (no `toString()`);
1514                    // use `.as_str().toString()` to convert each element to a Swift String.
1515                    let _ = writeln!(
1516                        out,
1517                        "        XCTAssertTrue({result_var}.map {{ $0.as_str().toString() }}.contains({swift_val}), \"expected to contain: \\({swift_val})\")"
1518                    );
1519                } else {
1520                    // []. traversal: field like "links[].url" → contains(where:) closure.
1521                    let traversal_handled = if let Some(f) = assertion.field.as_deref() {
1522                        if let Some(dot) = f.find("[].") {
1523                            let array_part = &f[..dot];
1524                            let elem_part = &f[dot + 3..];
1525                            let line = swift_traversal_contains_assert(
1526                                array_part,
1527                                elem_part,
1528                                f,
1529                                &swift_val,
1530                                result_var,
1531                                false,
1532                                &format!("expected to contain: \\({swift_val})"),
1533                                enum_fields,
1534                                field_resolver,
1535                            );
1536                            let _ = writeln!(out, "{line}");
1537                            true
1538                        } else {
1539                            false
1540                        }
1541                    } else {
1542                        false
1543                    };
1544                    if !traversal_handled {
1545                        // For array fields (RustVec<RustString>), check membership via map+contains.
1546                        let field_is_array = assertion
1547                            .field
1548                            .as_deref()
1549                            .is_some_and(|f| field_resolver.is_array(field_resolver.resolve(f)));
1550                        if field_is_array {
1551                            let contains_expr =
1552                                swift_array_contains_expr(assertion.field.as_deref(), result_var, field_resolver);
1553                            let _ = writeln!(
1554                                out,
1555                                "        XCTAssertTrue(({contains_expr} ?? []).contains({swift_val}), \"expected to contain: \\({swift_val})\")"
1556                            );
1557                        } else if field_is_enum {
1558                            // Enum fields: use `toString().toString()` (via string_expr) to get the
1559                            // serde variant name as a Swift String, then check substring containment.
1560                            let _ = writeln!(
1561                                out,
1562                                "        XCTAssertTrue({string_expr}.contains({swift_val}), \"expected to contain: \\({swift_val})\")"
1563                            );
1564                        } else {
1565                            let _ = writeln!(
1566                                out,
1567                                "        XCTAssertTrue({string_expr}.contains({swift_val}), \"expected to contain: \\({swift_val})\")"
1568                            );
1569                        }
1570                    }
1571                }
1572            }
1573        }
1574        "contains_all" => {
1575            if let Some(values) = &assertion.values {
1576                // []. traversal: field like "links[].link_type" → contains(where:) per value.
1577                if let Some(f) = assertion.field.as_deref() {
1578                    if let Some(dot) = f.find("[].") {
1579                        let array_part = &f[..dot];
1580                        let elem_part = &f[dot + 3..];
1581                        for val in values {
1582                            let swift_val = json_to_swift(val);
1583                            let line = swift_traversal_contains_assert(
1584                                array_part,
1585                                elem_part,
1586                                f,
1587                                &swift_val,
1588                                result_var,
1589                                false,
1590                                &format!("expected to contain: \\({swift_val})"),
1591                                enum_fields,
1592                                field_resolver,
1593                            );
1594                            let _ = writeln!(out, "{line}");
1595                        }
1596                        // handled — skip remaining branches
1597                    } else {
1598                        // For array fields (RustVec<RustString>), check membership via map+contains.
1599                        let field_is_array = field_resolver.is_array(field_resolver.resolve(f));
1600                        if field_is_array {
1601                            let contains_expr =
1602                                swift_array_contains_expr(assertion.field.as_deref(), result_var, field_resolver);
1603                            for val in values {
1604                                let swift_val = json_to_swift(val);
1605                                let _ = writeln!(
1606                                    out,
1607                                    "        XCTAssertTrue(({contains_expr} ?? []).contains({swift_val}), \"expected to contain: \\({swift_val})\")"
1608                                );
1609                            }
1610                        } else if field_is_enum {
1611                            // Enum fields: use `toString().toString()` (via string_expr) to get the
1612                            // serde variant name as a Swift String, then check substring containment.
1613                            for val in values {
1614                                let swift_val = json_to_swift(val);
1615                                let _ = writeln!(
1616                                    out,
1617                                    "        XCTAssertTrue({string_expr}.contains({swift_val}), \"expected to contain: \\({swift_val})\")"
1618                                );
1619                            }
1620                        } else {
1621                            for val in values {
1622                                let swift_val = json_to_swift(val);
1623                                let _ = writeln!(
1624                                    out,
1625                                    "        XCTAssertTrue({string_expr}.contains({swift_val}), \"expected to contain: \\({swift_val})\")"
1626                                );
1627                            }
1628                        }
1629                    }
1630                } else {
1631                    // No field — fall back to existing string_expr path.
1632                    for val in values {
1633                        let swift_val = json_to_swift(val);
1634                        let _ = writeln!(
1635                            out,
1636                            "        XCTAssertTrue({string_expr}.contains({swift_val}), \"expected to contain: \\({swift_val})\")"
1637                        );
1638                    }
1639                }
1640            }
1641        }
1642        "not_contains" => {
1643            if let Some(expected) = &assertion.value {
1644                let swift_val = json_to_swift(expected);
1645                // []. traversal: "links[].url" → XCTAssertFalse(array.contains(where:))
1646                let traversal_handled = if let Some(f) = assertion.field.as_deref() {
1647                    if let Some(dot) = f.find("[].") {
1648                        let array_part = &f[..dot];
1649                        let elem_part = &f[dot + 3..];
1650                        let line = swift_traversal_contains_assert(
1651                            array_part,
1652                            elem_part,
1653                            f,
1654                            &swift_val,
1655                            result_var,
1656                            true,
1657                            &format!("expected NOT to contain: \\({swift_val})"),
1658                            enum_fields,
1659                            field_resolver,
1660                        );
1661                        let _ = writeln!(out, "{line}");
1662                        true
1663                    } else {
1664                        false
1665                    }
1666                } else {
1667                    false
1668                };
1669                if !traversal_handled {
1670                    let _ = writeln!(
1671                        out,
1672                        "        XCTAssertFalse({string_expr}.contains({swift_val}), \"expected NOT to contain: \\({swift_val})\")"
1673                    );
1674                }
1675            }
1676        }
1677        "not_empty" => {
1678            // For optional fields (Optional<T>), check that the value is non-nil.
1679            // For array fields (RustVec<T>), check .isEmpty on the vec directly.
1680            // For result_is_simple (e.g. Data, String), use .isEmpty directly on
1681            // the result — avoids calling .toString() on non-RustString types.
1682            // For string fields, convert to Swift String and check .isEmpty.
1683            // []. traversal: "links[].url" → contains(where: { !elem.isEmpty })
1684            let traversal_not_empty_handled = if let Some(f) = assertion.field.as_deref() {
1685                if let Some(dot) = f.find("[].") {
1686                    let array_part = &f[..dot];
1687                    let elem_part = &f[dot + 3..];
1688                    let array_accessor = field_resolver.accessor(array_part, "swift", result_var);
1689                    let resolved_full = field_resolver.resolve(f);
1690                    let resolved_elem_part = resolved_full
1691                        .find("[].")
1692                        .map(|d| &resolved_full[d + 3..])
1693                        .unwrap_or(elem_part);
1694                    let elem_accessor = field_resolver.accessor(resolved_elem_part, "swift", "$0");
1695                    let elem_is_enum = enum_fields.contains(f) || enum_fields.contains(resolved_full);
1696                    let elem_is_optional = field_resolver.is_optional(resolved_elem_part)
1697                        || field_resolver.is_optional(field_resolver.resolve(resolved_elem_part));
1698                    let elem_str = if elem_is_enum {
1699                        format!("{elem_accessor}.to_string().toString()")
1700                    } else if elem_is_optional {
1701                        format!("({elem_accessor}?.toString() ?? \"\")")
1702                    } else {
1703                        format!("{elem_accessor}.toString()")
1704                    };
1705                    let _ = writeln!(
1706                        out,
1707                        "        XCTAssertTrue({array_accessor}.contains(where: {{ !{elem_str}.isEmpty }}), \"expected non-empty value\")"
1708                    );
1709                    true
1710                } else {
1711                    false
1712                }
1713            } else {
1714                false
1715            };
1716            if !traversal_not_empty_handled {
1717                if bare_result_is_option {
1718                    let _ = writeln!(out, "        XCTAssertNotNil({result_var}, \"expected non-nil value\")");
1719                } else if field_is_optional {
1720                    let _ = writeln!(out, "        XCTAssertNotNil({field_expr}, \"expected non-nil value\")");
1721                } else if field_is_array {
1722                    let _ = writeln!(
1723                        out,
1724                        "        XCTAssertFalse({field_expr}.isEmpty, \"expected non-empty value\")"
1725                    );
1726                } else if result_is_simple {
1727                    // result_is_simple: result is a primitive (Data, String, etc.) — use .isEmpty directly.
1728                    let _ = writeln!(
1729                        out,
1730                        "        XCTAssertFalse({result_var}.isEmpty, \"expected non-empty value\")"
1731                    );
1732                } else {
1733                    // First-class Swift struct fields are properties typed as native Swift
1734                    // `String` / `[T]` / `Data` etc — all of which expose `.count` (and
1735                    // `String`/`Array` also expose `.isEmpty`). Use `.count > 0` so the same
1736                    // path works whether the field is a String or an Array.
1737                    //
1738                    // When the accessor contains a `?.` optional chain, `.count` returns an
1739                    // Optional which Swift cannot compare directly to `0`; coalesce via `?? 0`
1740                    // so the assertion typechecks.
1741                    //
1742                    // For opaque method-call accessors (`result.id()`), the returned type is
1743                    // `RustString`, which lacks `.count`. Convert to Swift `String` first via
1744                    // `.toString()`. Array fields short-circuit above via `field_is_array`, so
1745                    // method-call accessors landing here are guaranteed to be the scalar /
1746                    // string flavour; vec accessors return `RustVec` (whose `.count` is fine).
1747                    let count_target = swift_count_target(&field_expr, field_resolver, assertion.field.as_deref());
1748                    let len_expr = if accessor_is_optional {
1749                        format!("({count_target}.count ?? 0)")
1750                    } else {
1751                        format!("{count_target}.count")
1752                    };
1753                    let _ = writeln!(
1754                        out,
1755                        "        XCTAssertGreaterThan({len_expr}, 0, \"expected non-empty value\")"
1756                    );
1757                }
1758            }
1759        }
1760        "is_empty" => {
1761            if bare_result_is_option {
1762                let _ = writeln!(out, "        XCTAssertNil({result_var}, \"expected nil value\")");
1763            } else if field_is_optional {
1764                let _ = writeln!(out, "        XCTAssertNil({field_expr}, \"expected nil value\")");
1765            } else if field_is_array {
1766                let _ = writeln!(
1767                    out,
1768                    "        XCTAssertTrue({field_expr}.isEmpty, \"expected empty value\")"
1769                );
1770            } else {
1771                // Symmetric with not_empty: use .count == 0 on first-class Swift types.
1772                // Wrap opaque method-call accessors (`result.id()`) with `.toString()` so
1773                // `.count` lands on Swift `String`, not `RustString` (which lacks `.count`).
1774                let count_target = swift_count_target(&field_expr, field_resolver, assertion.field.as_deref());
1775                let len_expr = if accessor_is_optional {
1776                    format!("({count_target}.count ?? 0)")
1777                } else {
1778                    format!("{count_target}.count")
1779                };
1780                let _ = writeln!(out, "        XCTAssertEqual({len_expr}, 0, \"expected empty value\")");
1781            }
1782        }
1783        "contains_any" => {
1784            if let Some(values) = &assertion.values {
1785                let checks: Vec<String> = values
1786                    .iter()
1787                    .map(|v| {
1788                        let swift_val = json_to_swift(v);
1789                        format!("{string_expr}.contains({swift_val})")
1790                    })
1791                    .collect();
1792                let joined = checks.join(" || ");
1793                let _ = writeln!(
1794                    out,
1795                    "        XCTAssertTrue({joined}, \"expected to contain at least one of the specified values\")"
1796                );
1797            }
1798        }
1799        "greater_than" => {
1800            if let Some(val) = &assertion.value {
1801                let swift_val = json_to_swift(val);
1802                // For optional numeric fields (or when the accessor chain is optional),
1803                // coalesce to 0 before comparing so the expression is non-optional.
1804                let field_is_optional = accessor_is_optional
1805                    || assertion.field.as_deref().is_some_and(|f| {
1806                        field_resolver.is_optional(f) || field_resolver.is_optional(field_resolver.resolve(f))
1807                    });
1808                let compare_expr = if field_is_optional {
1809                    format!("({field_expr} ?? 0)")
1810                } else {
1811                    field_expr.clone()
1812                };
1813                let _ = writeln!(out, "        XCTAssertGreaterThan({compare_expr}, {swift_val})");
1814            }
1815        }
1816        "less_than" => {
1817            if let Some(val) = &assertion.value {
1818                let swift_val = json_to_swift(val);
1819                let field_is_optional = accessor_is_optional
1820                    || assertion.field.as_deref().is_some_and(|f| {
1821                        field_resolver.is_optional(f) || field_resolver.is_optional(field_resolver.resolve(f))
1822                    });
1823                let compare_expr = if field_is_optional {
1824                    format!("({field_expr} ?? 0)")
1825                } else {
1826                    field_expr.clone()
1827                };
1828                let _ = writeln!(out, "        XCTAssertLessThan({compare_expr}, {swift_val})");
1829            }
1830        }
1831        "greater_than_or_equal" => {
1832            if let Some(val) = &assertion.value {
1833                let swift_val = json_to_swift(val);
1834                // For optional numeric fields (or when the accessor chain is optional),
1835                // coalesce to 0 before comparing so the expression is non-optional.
1836                let field_is_optional = accessor_is_optional
1837                    || assertion.field.as_deref().is_some_and(|f| {
1838                        field_resolver.is_optional(f) || field_resolver.is_optional(field_resolver.resolve(f))
1839                    });
1840                let compare_expr = if field_is_optional {
1841                    format!("({field_expr} ?? 0)")
1842                } else {
1843                    field_expr.clone()
1844                };
1845                let _ = writeln!(out, "        XCTAssertGreaterThanOrEqual({compare_expr}, {swift_val})");
1846            }
1847        }
1848        "less_than_or_equal" => {
1849            if let Some(val) = &assertion.value {
1850                let swift_val = json_to_swift(val);
1851                let field_is_optional = accessor_is_optional
1852                    || assertion.field.as_deref().is_some_and(|f| {
1853                        field_resolver.is_optional(f) || field_resolver.is_optional(field_resolver.resolve(f))
1854                    });
1855                let compare_expr = if field_is_optional {
1856                    format!("({field_expr} ?? 0)")
1857                } else {
1858                    field_expr.clone()
1859                };
1860                let _ = writeln!(out, "        XCTAssertLessThanOrEqual({compare_expr}, {swift_val})");
1861            }
1862        }
1863        "starts_with" => {
1864            if let Some(expected) = &assertion.value {
1865                let swift_val = json_to_swift(expected);
1866                let _ = writeln!(
1867                    out,
1868                    "        XCTAssertTrue({string_expr}.hasPrefix({swift_val}), \"expected to start with: \\({swift_val})\")"
1869                );
1870            }
1871        }
1872        "ends_with" => {
1873            if let Some(expected) = &assertion.value {
1874                let swift_val = json_to_swift(expected);
1875                let _ = writeln!(
1876                    out,
1877                    "        XCTAssertTrue({string_expr}.hasSuffix({swift_val}), \"expected to end with: \\({swift_val})\")"
1878                );
1879            }
1880        }
1881        "min_length" => {
1882            if let Some(val) = &assertion.value {
1883                if let Some(n) = val.as_u64() {
1884                    // Use string_expr.count: for RustString fields string_expr already has
1885                    // .toString() appended, giving a Swift String whose .count is character count.
1886                    let _ = writeln!(out, "        XCTAssertGreaterThanOrEqual({string_expr}.count, {n})");
1887                }
1888            }
1889        }
1890        "max_length" => {
1891            if let Some(val) = &assertion.value {
1892                if let Some(n) = val.as_u64() {
1893                    let _ = writeln!(out, "        XCTAssertLessThanOrEqual({string_expr}.count, {n})");
1894                }
1895            }
1896        }
1897        "count_min" => {
1898            if let Some(val) = &assertion.value {
1899                if let Some(n) = val.as_u64() {
1900                    // For fields nested inside an optional parent (e.g. document.nodes where
1901                    // document is Optional), the accessor generates `result.document().nodes()`
1902                    // which doesn't compile in Swift without optional chaining.
1903                    let count_expr = swift_array_count_expr(assertion.field.as_deref(), result_var, field_resolver);
1904                    let _ = writeln!(out, "        XCTAssertGreaterThanOrEqual({count_expr}, {n})");
1905                }
1906            }
1907        }
1908        "count_equals" => {
1909            if let Some(val) = &assertion.value {
1910                if let Some(n) = val.as_u64() {
1911                    let count_expr = swift_array_count_expr(assertion.field.as_deref(), result_var, field_resolver);
1912                    let _ = writeln!(out, "        XCTAssertEqual({count_expr}, {n})");
1913                }
1914            }
1915        }
1916        "is_true" => {
1917            let _ = writeln!(out, "        XCTAssertTrue({field_expr})");
1918        }
1919        "is_false" => {
1920            let _ = writeln!(out, "        XCTAssertFalse({field_expr})");
1921        }
1922        "matches_regex" => {
1923            if let Some(expected) = &assertion.value {
1924                let swift_val = json_to_swift(expected);
1925                let _ = writeln!(
1926                    out,
1927                    "        XCTAssertNotNil({string_expr}.range(of: {swift_val}, options: .regularExpression), \"expected value to match regex: \\({swift_val})\")"
1928                );
1929            }
1930        }
1931        "not_error" => {
1932            // Already handled by the call succeeding without exception.
1933        }
1934        "error" => {
1935            // Handled at the test method level.
1936        }
1937        "method_result" => {
1938            let _ = writeln!(out, "        // method_result assertions not yet implemented for Swift");
1939        }
1940        other => {
1941            panic!("Swift e2e generator: unsupported assertion type: {other}");
1942        }
1943    }
1944}
1945
1946/// Build a Swift accessor path for the given fixture field, inserting `()` on
1947/// every segment and `?` after every optional non-leaf segment.
1948///
1949/// This is the core helper for count/contains helpers that need to reconstruct
1950/// the path with correct optional chaining from the raw fixture field name.
1951///
1952/// Rewrite a Swift accessor expression to capture any `RustVec` temporaries
1953/// in a local before subscripting them. Returns `(setup_lines, rewritten_expr)`.
1954///
1955/// swift-bridge's `Vec_<T>$get` returns a raw pointer into the Vec's storage
1956/// wrapped in a `T.SelfRef`. If the Vec was a temporary, ARC may release it
1957/// before the ref is dereferenced, leaving the pointer dangling and reads
1958/// returning empty/garbage. Hoisting the Vec into a `let` binding ties the
1959/// Vec's lifetime to the enclosing function scope, so the ref stays valid.
1960///
1961/// Only the first `()[...]` occurrence per expression is materialised — that
1962/// covers all current fixture access patterns (single-level subscripts on a
1963/// result field). Nested subscripts are rare and would need a more elaborate
1964/// pass; if they appear, this returns conservative output (just the first
1965/// hoist) which is still correct.
1966/// Returns `(setup_lines, rewritten_expr, is_map_subscript)`. `is_map_subscript` is
1967/// true when the subscript key was a string literal, indicating the parent
1968/// accessor returns a JSON-encoded Map (RustString) and the rewritten expression
1969/// already evaluates to `String?` so callers should NOT append `.toString()`.
1970fn materialise_vec_temporaries(expr: &str, name_suffix: &str) -> (Vec<String>, String, bool) {
1971    let Some(idx) = expr.find("()[") else {
1972        return (Vec::new(), expr.to_string(), false);
1973    };
1974    let after_open = idx + 3; // position after `()[`
1975    let Some(close_rel) = expr[after_open..].find(']') else {
1976        return (Vec::new(), expr.to_string(), false);
1977    };
1978    let subscript_end = after_open + close_rel; // index of `]`
1979    let prefix = &expr[..idx + 2]; // includes `()`
1980    let subscript = &expr[idx + 2..=subscript_end]; // `[N]`
1981    let tail = &expr[subscript_end + 1..]; // everything after `]`
1982    let method_dot = expr[..idx].rfind('.').unwrap_or(0);
1983    let method = &expr[method_dot + 1..idx];
1984    let local = format!("_vec_{}_{}", method, name_suffix);
1985
1986    // String-key subscript (e.g. `["title"]`) signals a Map-like access. swift-bridge
1987    // serialises non-leaf Maps (e.g. `HashMap<String, String>`) as JSON-encoded
1988    // RustString rather than exposing a Swift dictionary. Decode the RustString to
1989    // `[String: String]` before subscripting so `_vec_X["title"]` works.
1990    let inner = subscript.trim_start_matches('[').trim_end_matches(']');
1991    let is_string_key = inner.starts_with('"') && inner.ends_with('"');
1992    let setup = if is_string_key {
1993        format!(
1994            "let {local} = (try? JSONSerialization.jsonObject(with: ({prefix}.toString() ?? \"{{}}\").data(using: .utf8)!) as? [String: String]) ?? [:]"
1995        )
1996    } else {
1997        format!("let {local} = {prefix}")
1998    };
1999
2000    let rewritten = format!("{local}{subscript}{tail}");
2001    (vec![setup], rewritten, is_string_key)
2002}
2003
2004/// Returns `(accessor_expr, has_optional)` where `has_optional` is true when
2005/// at least one `?.` was inserted.
2006fn swift_build_accessor(field: &str, result_var: &str, field_resolver: &FieldResolver) -> (String, bool) {
2007    let resolved = field_resolver.resolve(field);
2008    let parts: Vec<&str> = resolved.split('.').collect();
2009
2010    // Track the current IR type as we walk segments so each segment can be
2011    // emitted with property syntax (first-class Codable struct) or method-call
2012    // syntax (typealias-to-`RustBridge.X`). Mirrors the per-segment dispatch in
2013    // `render_swift_with_first_class_map`.
2014    let mut current_type: Option<String> = field_resolver.swift_root_type().cloned();
2015    // Once a chain crosses a `[N]` subscript, we are operating on a RustVec
2016    // element, which is always the OPAQUE `RustBridge.T` (swift-bridge does not
2017    // convert RustVec elements into the first-class Codable struct). Pin
2018    // opaque method-call syntax after the first index step.
2019    let mut via_rust_vec = false;
2020
2021    let mut out = result_var.to_string();
2022    let mut has_optional = false;
2023    let mut path_so_far = String::new();
2024    let total = parts.len();
2025    for (i, part) in parts.iter().enumerate() {
2026        let is_leaf = i == total - 1;
2027        // Handle array index subscripts within a segment, e.g. `data[0]`.
2028        // `data[0]` must become `.data()[0]` (opaque) or `.data[0]` (first-class).
2029        // Split at the first `[` if present.
2030        let (field_name, subscript): (&str, Option<&str>) = if let Some(bracket_pos) = part.find('[') {
2031            (&part[..bracket_pos], Some(&part[bracket_pos..]))
2032        } else {
2033            (part, None)
2034        };
2035
2036        if !path_so_far.is_empty() {
2037            path_so_far.push('.');
2038        }
2039        // Build the base path (without subscript) for the optional check. When the
2040        // segment is e.g. `tool_calls[0]`, we want to check `is_optional` against
2041        // "choices[0].message.tool_calls" not "choices[0].message.tool_calls[0]".
2042        let base_path = {
2043            let mut p = path_so_far.clone();
2044            p.push_str(field_name);
2045            p
2046        };
2047        // Now push the full part (with subscript if any) so path_so_far is correct
2048        // for subsequent segment checks.
2049        path_so_far.push_str(part);
2050
2051        // First-class struct fields → property access (no `()`); typealias-to-
2052        // opaque fields → method-call access (`()`). Once we've indexed through
2053        // a RustVec, every subsequent segment is on an opaque element.
2054        let property_syntax = !via_rust_vec && field_resolver.swift_is_first_class(current_type.as_deref());
2055        out.push('.');
2056        // Swift bindings (both first-class `public let` props and swift-bridge
2057        // method names) always use lowerCamelCase — never raw snake_case from IR.
2058        out.push_str(&field_name.to_lower_camel_case());
2059        if let Some(sub) = subscript {
2060            // When the getter for this subscripted field is itself optional
2061            // (e.g. tool_calls returns Optional<RustVec<T>>), insert `?` before
2062            // the subscript so Swift unwraps the Optional before indexing.
2063            let field_is_optional = field_resolver.is_optional(&base_path);
2064            let access = if property_syntax { "" } else { "()" };
2065            if field_is_optional {
2066                out.push_str(&format!("{access}?"));
2067                has_optional = true;
2068            } else {
2069                out.push_str(access);
2070            }
2071            out.push_str(sub);
2072            // Do NOT append a trailing `?` after the subscript index: in Swift,
2073            // `optionalVec?[N]` via `Collection.subscript` returns the element
2074            // type `T` directly. The parent `has_optional` flag is still set
2075            // when `field_is_optional` is true, which causes the enclosing
2076            // expression to be wrapped in `(... ?? fallback)` correctly.
2077            // Indexing into a Vec<Named> yields a Named element. Only pin opaque
2078            // syntax when the array itself was opaque (method-call); when the
2079            // owner is first-class, the array is a Swift `[T]` whose elements
2080            // are first-class T (property access).
2081            current_type = field_resolver.swift_advance(current_type.as_deref(), field_name);
2082            if !property_syntax {
2083                via_rust_vec = true;
2084            }
2085        } else {
2086            if !property_syntax {
2087                out.push_str("()");
2088            }
2089            // Insert `?` after the accessor for non-leaf optional fields so the
2090            // next member access becomes `?.`.
2091            if !is_leaf && field_resolver.is_optional(&base_path) {
2092                out.push('?');
2093                has_optional = true;
2094            }
2095            current_type = field_resolver.swift_advance(current_type.as_deref(), field_name);
2096        }
2097    }
2098    (out, has_optional)
2099}
2100
2101/// Generate a `[String]?` expression for a `RustVec<RustString>` (or optional variant) field
2102/// so that `contains` membership checks work against plain Swift Strings.
2103///
2104/// The result is `Optional<[String]>` — callers should coalesce with `?? []`.
2105///
2106/// We use `?.map { $0.as_str().toString() }` because:
2107/// 1. Iterating a `RustVec<RustString>` yields `RustStringRef` (not `RustString`), which
2108///    only has `as_str()` but not `toString()` directly.
2109/// 2. The accessor may end with an `Optional<RustVec<RustString>>` (e.g. `sheet_names()` is
2110///    `Option<Vec<String>>` in Rust, which becomes `Optional<RustVec<RustString>>` in Swift).
2111/// 3. Optional chaining from parent `?.` already produces `Optional<RustVec<T>>`.
2112///
2113/// `?.map { $0.as_str().toString() }` converts each `RustStringRef` to a Swift `String`,
2114/// giving `[String]` wrapped in `Optional`. The `?? []` in callers coalesces nil to an empty
2115/// array.
2116/// Generate a `XCTAssert{True|False}(array.contains(where: { elem_str.contains(val) }), msg)` line
2117/// for field paths that traverse a collection with `[].` notation (e.g. `links[].url`).
2118///
2119/// `array_part` — left side of `[].` (e.g. `"links"`)
2120/// `element_part` — right side (e.g. `"url"` or `"link_type"`)
2121/// `full_field` — original assertion.field (used for enum lookup against the full path)
2122#[allow(clippy::too_many_arguments)]
2123fn swift_traversal_contains_assert(
2124    array_part: &str,
2125    element_part: &str,
2126    full_field: &str,
2127    val_expr: &str,
2128    result_var: &str,
2129    negate: bool,
2130    msg: &str,
2131    enum_fields: &std::collections::HashSet<String>,
2132    field_resolver: &FieldResolver,
2133) -> String {
2134    let array_accessor = field_resolver.accessor(array_part, "swift", result_var);
2135    let resolved_full = field_resolver.resolve(full_field);
2136    let resolved_elem_part = resolved_full
2137        .find("[].")
2138        .map(|d| &resolved_full[d + 3..])
2139        .unwrap_or(element_part);
2140    let elem_accessor = field_resolver.accessor(resolved_elem_part, "swift", "$0");
2141    let elem_is_enum = enum_fields.contains(full_field) || enum_fields.contains(resolved_full);
2142    let elem_is_optional = field_resolver.is_optional(resolved_elem_part)
2143        || field_resolver.is_optional(field_resolver.resolve(resolved_elem_part));
2144    let elem_str = if elem_is_enum {
2145        // Enum-typed fields are bridged as `String` (RustString in Swift).
2146        // A single `.toString()` converts RustString → Swift String.
2147        format!("{elem_accessor}.toString()")
2148    } else if elem_is_optional {
2149        format!("({elem_accessor}?.toString() ?? \"\")")
2150    } else {
2151        format!("{elem_accessor}.toString()")
2152    };
2153    let assert_fn = if negate { "XCTAssertFalse" } else { "XCTAssertTrue" };
2154    format!("        {assert_fn}({array_accessor}.contains(where: {{ {elem_str}.contains({val_expr}) }}), \"{msg}\")")
2155}
2156
2157fn swift_array_contains_expr(field: Option<&str>, result_var: &str, field_resolver: &FieldResolver) -> String {
2158    let Some(f) = field else {
2159        return format!("{result_var}.map {{ $0.as_str().toString() }}");
2160    };
2161    let (accessor, _has_optional) = swift_build_accessor(f, result_var, field_resolver);
2162    // Always use `?.map` — the array field (sheet_names, etc.) may itself return
2163    // Optional<RustVec<T>> even if not listed in fields_optional.
2164    format!("{accessor}?.map {{ $0.as_str().toString() }}")
2165}
2166
2167/// Generate a `.count` expression for an array field that may be nested inside optional parents.
2168///
2169/// Swift-bridge exposes all Rust fields as methods with `()`. When ancestor segments are
2170/// optional, we use `?.` chaining. The final count is coalesced with `?? 0` when there
2171/// are optional ancestors so the XCTAssert macro receives a non-optional `Int`.
2172///
2173/// Also check if the field itself (the leaf) is optional, which happens when the field
2174/// returns Optional<RustVec<T>> (e.g., `links()` may return Optional).
2175fn swift_array_count_expr(field: Option<&str>, result_var: &str, field_resolver: &FieldResolver) -> String {
2176    let Some(f) = field else {
2177        return format!("{result_var}.count");
2178    };
2179    let (accessor, mut has_optional) = swift_build_accessor(f, result_var, field_resolver);
2180    // Also check if the leaf field itself is optional.
2181    if field_resolver.is_optional(f) {
2182        has_optional = true;
2183    }
2184    if has_optional {
2185        // In Swift, accessing .count on an optional with ?. returns Optional<Int>,
2186        // so we coalesce with ?? 0 to get a concrete Int for XCTAssert.
2187        if accessor.contains("?.") {
2188            format!("{accessor}.count ?? 0")
2189        } else {
2190            // If no ?. but field is optional, the field_expr itself is Optional<RustVec<T>>
2191            // so we need ?. to call count.
2192            format!("({accessor}?.count ?? 0)")
2193        }
2194    } else {
2195        format!("{accessor}.count")
2196    }
2197}
2198
2199/// Convert a `serde_json::Value` to a Swift literal string.
2200fn json_to_swift(value: &serde_json::Value) -> String {
2201    match value {
2202        serde_json::Value::String(s) => format!("\"{}\"", escape_swift(s)),
2203        serde_json::Value::Bool(b) => b.to_string(),
2204        serde_json::Value::Number(n) => n.to_string(),
2205        serde_json::Value::Null => "nil".to_string(),
2206        serde_json::Value::Array(arr) => {
2207            let items: Vec<String> = arr.iter().map(json_to_swift).collect();
2208            format!("[{}]", items.join(", "))
2209        }
2210        serde_json::Value::Object(_) => {
2211            let json_str = serde_json::to_string(value).unwrap_or_default();
2212            format!("\"{}\"", escape_swift(&json_str))
2213        }
2214    }
2215}
2216
2217/// Escape a string for embedding in a Swift double-quoted string literal.
2218fn escape_swift(s: &str) -> String {
2219    escape_swift_str(s)
2220}
2221
2222/// Return the count-able target expression for `field_expr`.
2223///
2224/// For opaque method-call accessors (ending in `()` or `()?`), the returned
2225/// value depends on the field's IR kind:
2226///
2227/// - `Vec<T>` ⇒ `RustVec<T>`, which exposes `.count` directly. No wrap.
2228/// - `String` ⇒ `RustString`, which does NOT expose `.count`. Wrap with
2229///   `.toString()` so `.count` lands on Swift `String`.
2230///
2231/// First-class property accessors (no trailing parens) return Swift values
2232/// that already support `.count` directly.
2233///
2234/// The discriminator is the field's resolved leaf type, looked up against the
2235/// `SwiftFirstClassMap`'s vec field set when available. If the field is
2236/// unknown (None), fall back to the conservative wrap — RustString is the
2237/// dominant scalar-leaf case for top-level assertions.
2238fn swift_count_target(field_expr: &str, field_resolver: &FieldResolver, field: Option<&str>) -> String {
2239    let is_method_call = field_expr.trim_end().ends_with(')');
2240    if !is_method_call {
2241        return field_expr.to_string();
2242    }
2243    if let Some(f) = field
2244        && field_resolver.leaf_is_vec_via_swift_map(field_resolver.resolve(f))
2245    {
2246        return field_expr.to_string();
2247    }
2248    format!("{field_expr}.toString()")
2249}
2250
2251/// Resolve the IR type name backing this call's result.
2252///
2253/// Lookup order mirrors PHP's `derive_root_type` for `[crates.e2e.calls.*]`
2254/// configs: any of `c, csharp, java, kotlin, go, php` overrides may carry a
2255/// `result_type = "ChatCompletionResponse"` field. The first non-empty value
2256/// wins. These overrides are language-agnostic IR type names — they were
2257/// originally added for the C/C# backends and other backends piggy-back on them
2258/// because the IR names are shared across every binding.
2259///
2260/// Returns `None` when no override sets `result_type`; the renderer then falls
2261/// back to the workspace-default heuristic in `SwiftFirstClassMap` (which
2262/// defaults to property access — the right call for first-class result types
2263/// like `FileObject` but wrong for opaque types like `ChatCompletionResponse`).
2264fn swift_call_result_type(call_config: &alef_core::config::e2e::CallConfig) -> Option<String> {
2265    const LOOKUP_LANGS: &[&str] = &["c", "csharp", "java", "kotlin", "go", "php"];
2266    for lang in LOOKUP_LANGS {
2267        if let Some(o) = call_config.overrides.get(*lang)
2268            && let Some(rt) = o.result_type.as_deref()
2269            && !rt.is_empty()
2270        {
2271            return Some(rt.to_string());
2272        }
2273    }
2274    None
2275}
2276
2277/// Returns true when the field type would be emitted as a Swift primitive value
2278/// or a known first-class Codable struct/unit-enum, so it can appear on a
2279/// first-class Codable Swift struct without forcing the host type into a
2280/// typealias. Mirrors `first_class_field_supported` in alef-backend-swift.
2281///
2282/// Accepts:
2283/// - `Primitive` and `String`
2284/// - `Named(S)` when `S` is in `known_dto_names` (seeded with unit-serde enums and
2285///   grown via fixed-point iteration over candidate struct DTOs)
2286/// - `Vec<T>` and `Optional<T>` recursively
2287///
2288/// Rejects `Map`, `Path`, `Bytes`, `Duration`, `Char`, `Json`, and unknown
2289/// `Named(_)` references (the backend treats those as typealias-to-opaque).
2290fn swift_first_class_field_supported(ty: &alef_core::ir::TypeRef, known_dto_names: &HashSet<String>) -> bool {
2291    use alef_core::ir::TypeRef;
2292    match ty {
2293        TypeRef::Primitive(_) | TypeRef::String => true,
2294        TypeRef::Named(name) => known_dto_names.contains(name),
2295        TypeRef::Vec(inner) | TypeRef::Optional(inner) => swift_first_class_field_supported(inner, known_dto_names),
2296        _ => false,
2297    }
2298}
2299
2300/// Build the per-type Swift first-class/opaque classification map used by
2301/// `render_swift_with_first_class_map`.
2302///
2303/// A TypeDef is treated as first-class (Codable Swift struct → property access)
2304/// when it is not opaque, has serde derives, has at least one field, and every
2305/// binding field is supported by `swift_first_class_field_supported` against the
2306/// current first-class set. All other public types end up as typealiases to
2307/// opaque `RustBridge.X` classes whose fields are swift-bridge methods
2308/// (`.id()`, `.status()`).
2309///
2310/// Mirrors the fixed-point iteration in `alef-backend-swift::gen_bindings.rs`
2311/// (lines 100-130). Without the fixed point, a type like `TranscriptionResponse`
2312/// that holds `Option<Vec<TranscriptionSegment>>` would be wrongly classified
2313/// opaque, causing the renderer to emit `.text()` against a first-class struct
2314/// whose `text` is a `public let` property.
2315///
2316/// `field_types` records the next-type that each Named field traverses into,
2317/// so the renderer can advance its current-type cursor through nested
2318/// `data[0].id` style paths.
2319fn build_swift_first_class_map(
2320    type_defs: &[alef_core::ir::TypeDef],
2321    enum_defs: &[alef_core::ir::EnumDef],
2322    e2e_config: &crate::config::E2eConfig,
2323) -> SwiftFirstClassMap {
2324    use alef_core::ir::TypeRef;
2325    let mut field_types: HashMap<String, HashMap<String, String>> = HashMap::new();
2326    let mut vec_field_names: HashSet<String> = HashSet::new();
2327    fn inner_named(ty: &TypeRef) -> Option<String> {
2328        match ty {
2329            TypeRef::Named(n) => Some(n.clone()),
2330            TypeRef::Optional(inner) | TypeRef::Vec(inner) => inner_named(inner),
2331            _ => None,
2332        }
2333    }
2334    fn is_vec_ty(ty: &TypeRef) -> bool {
2335        match ty {
2336            TypeRef::Vec(_) => true,
2337            TypeRef::Optional(inner) => is_vec_ty(inner),
2338            _ => false,
2339        }
2340    }
2341    // Seed with unit serde enum names — Codable on the Swift side and can appear
2342    // as leaf fields on struct DTOs (matches gen_bindings.rs unit_serde_enum_names).
2343    let mut known_dto_names: HashSet<String> = enum_defs
2344        .iter()
2345        .filter(|e| e.has_serde && e.variants.iter().all(|v| v.fields.is_empty()))
2346        .map(|e| e.name.clone())
2347        .collect();
2348
2349    // Candidate struct DTOs: non-opaque, has_serde, non-empty fields.
2350    // Trait types and binding-excluded types are skipped (matches backend semantics
2351    // — note backend further filters via `exclude_types`, which we don't have here,
2352    // but accepting a superset is safe: types not actually emitted simply never
2353    // appear in path-access chains).
2354    let candidates: Vec<&alef_core::ir::TypeDef> = type_defs
2355        .iter()
2356        .filter(|td| !td.is_trait && !td.is_opaque && td.has_serde && !td.fields.is_empty())
2357        .collect();
2358
2359    loop {
2360        let prev = known_dto_names.len();
2361        for td in &candidates {
2362            if known_dto_names.contains(&td.name) {
2363                continue;
2364            }
2365            let all_supported = td
2366                .fields
2367                .iter()
2368                .filter(|f| !f.binding_excluded)
2369                .all(|f| swift_first_class_field_supported(&f.ty, &known_dto_names));
2370            if all_supported {
2371                known_dto_names.insert(td.name.clone());
2372            }
2373        }
2374        if known_dto_names.len() == prev {
2375            break;
2376        }
2377    }
2378
2379    // The first-class set on SwiftFirstClassMap conceptually represents structs
2380    // accessed via property syntax. Unit enums never appear as the *owner* of a
2381    // chain segment (they are leaves), but including them is harmless since
2382    // `advance()` never returns them as a current_type for further traversal.
2383    let first_class_types: HashSet<String> = candidates
2384        .iter()
2385        .filter(|td| known_dto_names.contains(&td.name))
2386        .map(|td| td.name.clone())
2387        .collect();
2388
2389    for td in type_defs {
2390        let mut td_field_types: HashMap<String, String> = HashMap::new();
2391        for f in &td.fields {
2392            if let Some(named) = inner_named(&f.ty) {
2393                td_field_types.insert(f.name.clone(), named);
2394            }
2395            if is_vec_ty(&f.ty) {
2396                vec_field_names.insert(f.name.clone());
2397            }
2398        }
2399        if !td_field_types.is_empty() {
2400            field_types.insert(td.name.clone(), td_field_types);
2401        }
2402    }
2403    // Best-effort root-type detection: pick a unique TypeDef that contains all
2404    // `result_fields`. Falls back to `None` (renderer defaults to first-class
2405    // property syntax for unknown roots).
2406    let root_type = if e2e_config.result_fields.is_empty() {
2407        None
2408    } else {
2409        let matches: Vec<&alef_core::ir::TypeDef> = type_defs
2410            .iter()
2411            .filter(|td| {
2412                let names: HashSet<&str> = td.fields.iter().map(|f| f.name.as_str()).collect();
2413                e2e_config.result_fields.iter().all(|rf| names.contains(rf.as_str()))
2414            })
2415            .collect();
2416        if matches.len() == 1 {
2417            Some(matches[0].name.clone())
2418        } else {
2419            None
2420        }
2421    };
2422    SwiftFirstClassMap {
2423        first_class_types,
2424        field_types,
2425        vec_field_names,
2426        root_type,
2427    }
2428}
2429
2430#[cfg(test)]
2431mod tests {
2432    use super::*;
2433    use crate::field_access::FieldResolver;
2434    use std::collections::{HashMap, HashSet};
2435
2436    fn make_resolver_tool_calls() -> FieldResolver {
2437        // Resolver for `choices[0].message.tool_calls[0].function.name`:
2438        //   - `choices` is a registered array field
2439        //   - `choices.message.tool_calls` is optional (Optional<RustVec<ToolCall>>)
2440        let mut optional = HashSet::new();
2441        optional.insert("choices.message.tool_calls".to_string());
2442        let mut arrays = HashSet::new();
2443        arrays.insert("choices".to_string());
2444        FieldResolver::new(&HashMap::new(), &optional, &HashSet::new(), &arrays, &HashSet::new())
2445    }
2446
2447    /// Regression: after the optional `[0]` subscript, the codegen must NOT
2448    /// append a trailing `?`. The Swift compiler sees `?[0]` as consuming the
2449    /// optional chain, yielding the non-optional element type, so a subsequent
2450    /// `?.member` would trigger "cannot use optional chaining on non-optional
2451    /// value".
2452    ///
2453    /// With no `SwiftFirstClassMap` configured (default in this test), all
2454    /// types default to first-class property syntax — so accessors are
2455    /// `result.choices[0].message.toolCalls?[0].function.name` (no `()`).
2456    #[test]
2457    fn optional_vec_subscript_does_not_emit_trailing_question_mark_before_next_segment() {
2458        let resolver = make_resolver_tool_calls();
2459        let (accessor, has_optional) =
2460            swift_build_accessor("choices[0].message.tool_calls[0].function.name", "result", &resolver);
2461        // `?` before `[0]` is correct (tool_calls is optional). Property syntax
2462        // is the default when no SwiftFirstClassMap is supplied.
2463        assert!(
2464            accessor.contains("toolCalls?[0]"),
2465            "expected `toolCalls?[0]` for optional tool_calls, got: {accessor}"
2466        );
2467        // There must NOT be `?[0]?` (trailing `?` after the index).
2468        assert!(
2469            !accessor.contains("?[0]?"),
2470            "must not emit trailing `?` after subscript index: {accessor}"
2471        );
2472        // The expression IS optional overall (tool_calls may be nil).
2473        assert!(has_optional, "expected has_optional=true for optional field chain");
2474        // Subsequent member access uses `.` (non-optional chain) not `?.`.
2475        assert!(
2476            accessor.contains("[0].function"),
2477            "expected `.function` (non-optional) after subscript: {accessor}"
2478        );
2479    }
2480}