Skip to main content

alef_e2e/codegen/
swift.rs

1//! Swift e2e test generator using XCTest.
2//!
3//! Generates test files for the swift package in `packages/swift/Tests/<Module>Tests/`.
4//!
5//! IMPORTANT: Due to SwiftPM 6.0 limitations (forbids inter-package `.package(path:)`
6//! references within a monorepo), generated test files are placed directly inside
7//! the `packages/swift` package (not in a separate `e2e/swift` package). This allows
8//! tests to depend on the library target without an explicit package dependency.
9//!
10//! The generated `Package.swift` is placed in `e2e/swift/` for documentation and CI
11//! reference but is NOT used for running tests — tests are run from the
12//! `packages/swift/` directory using `swift test`.
13
14use crate::config::E2eConfig;
15use crate::escape::{escape_java as escape_swift_str, expand_fixture_templates, sanitize_filename, sanitize_ident};
16use crate::field_access::FieldResolver;
17use crate::fixture::{Assertion, Fixture, FixtureGroup, ValidationErrorExpectation};
18use alef_core::backend::GeneratedFile;
19use alef_core::config::ResolvedCrateConfig;
20use alef_core::hash::{self, CommentStyle};
21use alef_core::template_versions::toolchain;
22use anyhow::Result;
23use heck::{ToLowerCamelCase, ToSnakeCase, ToUpperCamelCase};
24use std::collections::HashSet;
25use std::fmt::Write as FmtWrite;
26use std::path::PathBuf;
27
28use super::E2eCodegen;
29use super::client;
30
31/// Swift e2e code generator.
32pub struct SwiftE2eCodegen;
33
34impl E2eCodegen for SwiftE2eCodegen {
35    fn generate(
36        &self,
37        groups: &[FixtureGroup],
38        e2e_config: &E2eConfig,
39        config: &ResolvedCrateConfig,
40        _type_defs: &[alef_core::ir::TypeDef],
41    ) -> Result<Vec<GeneratedFile>> {
42        let lang = self.language_name();
43        let output_base = PathBuf::from(e2e_config.effective_output()).join(lang);
44
45        let mut files = Vec::new();
46
47        // Resolve call config with overrides.
48        let call = &e2e_config.call;
49        let overrides = call.overrides.get(lang);
50        let function_name = overrides
51            .and_then(|o| o.function.as_ref())
52            .cloned()
53            .unwrap_or_else(|| call.function.clone());
54        let result_var = &call.result_var;
55        let result_is_simple = overrides.is_some_and(|o| o.result_is_simple);
56
57        // Resolve package config.
58        let swift_pkg = e2e_config.resolve_package("swift");
59        let pkg_name = swift_pkg
60            .as_ref()
61            .and_then(|p| p.name.as_ref())
62            .cloned()
63            .unwrap_or_else(|| config.name.to_upper_camel_case());
64        let pkg_path = swift_pkg
65            .as_ref()
66            .and_then(|p| p.path.as_ref())
67            .cloned()
68            .unwrap_or_else(|| "../../packages/swift".to_string());
69        let pkg_version = swift_pkg
70            .as_ref()
71            .and_then(|p| p.version.as_ref())
72            .cloned()
73            .or_else(|| config.resolved_version())
74            .unwrap_or_else(|| "0.1.0".to_string());
75
76        // The Swift module name: UpperCamelCase of the package name.
77        let module_name = pkg_name.as_str();
78
79        // Resolve the registry URL: derive from the configured repository when
80        // available (with a `.git` suffix per SwiftPM convention). Falls back
81        // to a vendor-neutral placeholder when no repo is configured.
82        let registry_url = config
83            .try_github_repo()
84            .map(|repo| {
85                let base = repo.trim_end_matches('/').trim_end_matches(".git");
86                format!("{base}.git")
87            })
88            .unwrap_or_else(|_| format!("https://example.invalid/{module_name}.git"));
89
90        // Generate Package.swift (kept for tooling/CI reference but not used
91        // for running tests — see note below).
92        files.push(GeneratedFile {
93            path: output_base.join("Package.swift"),
94            content: render_package_swift(module_name, &registry_url, &pkg_path, &pkg_version, e2e_config.dep_mode),
95            generated_header: false,
96        });
97
98        // Swift e2e tests are written into the *packages/swift* package rather
99        // than into the separate e2e/swift package.  SwiftPM 6.0 forbids local
100        // `.package(path:)` references between packages inside the same git
101        // repository, so a standalone e2e/swift package cannot depend on
102        // packages/swift.  Placing the test files directly inside
103        // packages/swift/Tests/<Module>Tests/ sidesteps the restriction: the
104        // tests are part of the same SwiftPM package that defines the library
105        // target, so no inter-package dependency is needed.
106        //
107        // `pkg_path` is expressed relative to the e2e/<lang> directory (e.g.
108        // "../../packages/swift").  Joining it onto `output_base` and
109        // normalising collapses the traversals to the actual project-root-
110        // relative path (e.g. "packages/swift").
111        let tests_base = normalize_path(&output_base.join(&pkg_path));
112
113        let field_resolver = FieldResolver::new(
114            &e2e_config.fields,
115            &e2e_config.fields_optional,
116            &e2e_config.result_fields,
117            &e2e_config.fields_array,
118            &e2e_config.fields_method_calls,
119        );
120
121        // Resolve client_factory override for swift (enables client-instance dispatch).
122        let client_factory: Option<&str> = overrides.and_then(|o| o.client_factory.as_deref());
123
124        // One test file per fixture group.
125        for group in groups {
126            let active: Vec<&Fixture> = group
127                .fixtures
128                .iter()
129                .filter(|f| super::should_include_fixture(f, lang, e2e_config))
130                .collect();
131
132            if active.is_empty() {
133                continue;
134            }
135
136            let class_name = format!("{}Tests", sanitize_filename(&group.category).to_upper_camel_case());
137            let filename = format!("{class_name}.swift");
138            let content = render_test_file(
139                &group.category,
140                &active,
141                e2e_config,
142                module_name,
143                &class_name,
144                &function_name,
145                result_var,
146                &e2e_config.call.args,
147                &field_resolver,
148                result_is_simple,
149                &e2e_config.fields_enum,
150                client_factory,
151            );
152            files.push(GeneratedFile {
153                path: tests_base
154                    .join("Tests")
155                    .join(format!("{module_name}Tests"))
156                    .join(filename),
157                content,
158                generated_header: true,
159            });
160        }
161
162        Ok(files)
163    }
164
165    fn language_name(&self) -> &'static str {
166        "swift"
167    }
168}
169
170// ---------------------------------------------------------------------------
171// Rendering
172// ---------------------------------------------------------------------------
173
174fn render_package_swift(
175    module_name: &str,
176    registry_url: &str,
177    pkg_path: &str,
178    pkg_version: &str,
179    dep_mode: crate::config::DependencyMode,
180) -> String {
181    let min_macos = toolchain::SWIFT_MIN_MACOS;
182
183    // For local deps SwiftPM identity = last path component (e.g. "../../packages/swift" → "swift").
184    // For registry deps identity is inferred from the URL.
185    // Use explicit .product(name:package:) to avoid ambiguity under tools-version 6.0.
186    let (dep_block, product_dep) = match dep_mode {
187        crate::config::DependencyMode::Registry => {
188            let dep = format!(r#"        .package(url: "{registry_url}", from: "{pkg_version}")"#);
189            let pkg_id = registry_url
190                .trim_end_matches('/')
191                .trim_end_matches(".git")
192                .split('/')
193                .next_back()
194                .unwrap_or(module_name);
195            let prod = format!(r#".product(name: "{module_name}", package: "{pkg_id}")"#);
196            (dep, prod)
197        }
198        crate::config::DependencyMode::Local => {
199            let dep = format!(r#"        .package(path: "{pkg_path}")"#);
200            let pkg_id = pkg_path
201                .trim_end_matches('/')
202                .split('/')
203                .next_back()
204                .unwrap_or(module_name);
205            let prod = format!(r#".product(name: "{module_name}", package: "{pkg_id}")"#);
206            (dep, prod)
207        }
208    };
209    // SwiftPM platform enums use the major version only (.v13, .v14, ...);
210    // strip patch components to match the scaffold's `Package.swift`.
211    let min_macos_major = min_macos.split('.').next().unwrap_or(min_macos);
212    // iOS (.v14) is always included — swift-bridge supports both macOS and iOS targets
213    // and the generated Package.swift is used as a CI reference for both platforms.
214    format!(
215        r#"// swift-tools-version: 6.0
216import PackageDescription
217
218let package = Package(
219    name: "E2eSwift",
220    platforms: [
221        .macOS(.v{min_macos_major}),
222        .iOS(.v14),
223    ],
224    dependencies: [
225{dep_block},
226    ],
227    targets: [
228        .testTarget(
229            name: "{module_name}Tests",
230            dependencies: [{product_dep}]
231        ),
232    ]
233)
234"#
235    )
236}
237
238#[allow(clippy::too_many_arguments)]
239fn render_test_file(
240    category: &str,
241    fixtures: &[&Fixture],
242    e2e_config: &E2eConfig,
243    module_name: &str,
244    class_name: &str,
245    function_name: &str,
246    result_var: &str,
247    args: &[crate::config::ArgMapping],
248    field_resolver: &FieldResolver,
249    result_is_simple: bool,
250    enum_fields: &HashSet<String>,
251    client_factory: Option<&str>,
252) -> String {
253    // Detect whether any fixture in this group uses a file_path or bytes arg — if so
254    // the test class chdir's to <repo>/test_documents at setUp time so the
255    // fixture-relative paths in test bodies (e.g. "docx/fake.docx") resolve correctly.
256    // The Swift binding's `extractBytes`/`extractFile` e2e wrappers consult
257    // `FIXTURES_DIR` first, otherwise resolve against the current directory.
258    // Mirrors the Ruby/Python conftest pattern that chdirs to test_documents.
259    let needs_chdir = fixtures.iter().any(|f| {
260        let call_config = e2e_config.resolve_call_for_fixture(f.call.as_deref(), &f.input);
261        call_config
262            .args
263            .iter()
264            .any(|a| a.arg_type == "file_path" || a.arg_type == "bytes")
265    });
266
267    let mut out = String::new();
268    out.push_str(&hash::header(CommentStyle::DoubleSlash));
269    let _ = writeln!(out, "import XCTest");
270    let _ = writeln!(out, "import Foundation");
271    let _ = writeln!(out, "import {module_name}");
272    let _ = writeln!(out, "import RustBridge");
273    let _ = writeln!(out);
274    let _ = writeln!(out, "/// E2e tests for category: {category}.");
275    let _ = writeln!(out, "final class {class_name}: XCTestCase {{");
276
277    if needs_chdir {
278        // Chdir once at class setUp so all fixture file_path arguments resolve relative
279        // to the repository's test_documents directory.
280        //
281        // #filePath = <repo>/packages/swift/Tests/<Module>Tests/<Class>.swift
282        // 5 deletingLastPathComponent() calls climb to the repo root before appending
283        // "test_documents". Mirrors the Ruby/Python conftest pattern that chdirs to
284        // test_documents.
285        let _ = writeln!(out, "    override class func setUp() {{");
286        let _ = writeln!(out, "        super.setUp()");
287        let _ = writeln!(out, "        let _testDocs = URL(fileURLWithPath: #filePath)");
288        let _ = writeln!(out, "            .deletingLastPathComponent() // <Module>Tests/");
289        let _ = writeln!(out, "            .deletingLastPathComponent() // Tests/");
290        let _ = writeln!(out, "            .deletingLastPathComponent() // swift/");
291        let _ = writeln!(out, "            .deletingLastPathComponent() // packages/");
292        let _ = writeln!(out, "            .deletingLastPathComponent() // <repo root>");
293        let _ = writeln!(
294            out,
295            "            .appendingPathComponent(\"{}\")",
296            e2e_config.test_documents_dir
297        );
298        let _ = writeln!(
299            out,
300            "        if FileManager.default.fileExists(atPath: _testDocs.path) {{"
301        );
302        let _ = writeln!(
303            out,
304            "            FileManager.default.changeCurrentDirectoryPath(_testDocs.path)"
305        );
306        let _ = writeln!(out, "        }}");
307        let _ = writeln!(out, "    }}");
308        let _ = writeln!(out);
309    }
310
311    for fixture in fixtures {
312        if fixture.is_http_test() {
313            render_http_test_method(&mut out, fixture);
314        } else {
315            render_test_method(
316                &mut out,
317                fixture,
318                e2e_config,
319                function_name,
320                result_var,
321                args,
322                field_resolver,
323                result_is_simple,
324                enum_fields,
325                client_factory,
326            );
327        }
328        let _ = writeln!(out);
329    }
330
331    let _ = writeln!(out, "}}");
332    out
333}
334
335// ---------------------------------------------------------------------------
336// HTTP test rendering — TestClientRenderer impl + thin driver wrapper
337// ---------------------------------------------------------------------------
338
339/// Renderer that emits XCTest `func test...() throws` methods using `URLSession`
340/// against the mock server (`ProcessInfo.processInfo.environment["MOCK_SERVER_URL"]`).
341struct SwiftTestClientRenderer;
342
343impl client::TestClientRenderer for SwiftTestClientRenderer {
344    fn language_name(&self) -> &'static str {
345        "swift"
346    }
347
348    fn sanitize_test_name(&self, id: &str) -> String {
349        // Swift test methods are `func testFoo()` — upper-camel-case after "test".
350        sanitize_ident(id).to_upper_camel_case()
351    }
352
353    /// Emit `func test{FnName}() throws {` (or a skip stub when the fixture is skipped).
354    ///
355    /// XCTest has no first-class skip annotation prior to Swift Testing (`@Test`).
356    /// For skipped fixtures we emit `try XCTSkipIf(true, reason)` inside the
357    /// function body so XCTest records them as skipped rather than omitting them.
358    fn render_test_open(&self, out: &mut String, fn_name: &str, description: &str, skip_reason: Option<&str>) {
359        let _ = writeln!(out, "    /// {description}");
360        let _ = writeln!(out, "    func test{fn_name}() throws {{");
361        if let Some(reason) = skip_reason {
362            let escaped = escape_swift(reason);
363            let _ = writeln!(out, "        try XCTSkipIf(true, \"{escaped}\")");
364        }
365    }
366
367    fn render_test_close(&self, out: &mut String) {
368        let _ = writeln!(out, "    }}");
369    }
370
371    /// Emit a synchronous `URLSession` round-trip to the mock server.
372    ///
373    /// `ProcessInfo.processInfo.environment["MOCK_SERVER_URL"]!` provides the base
374    /// URL; the fixture path is appended directly.  The call uses a semaphore so the
375    /// generated test body stays synchronous (compatible with `throws` functions —
376    /// no `async` XCTest support needed).
377    fn render_call(&self, out: &mut String, ctx: &client::CallCtx<'_>) {
378        let method = ctx.method.to_uppercase();
379        let fixture_path = escape_swift(ctx.path);
380
381        let _ = writeln!(
382            out,
383            "        let _baseURL = ProcessInfo.processInfo.environment[\"MOCK_SERVER_URL\"]!"
384        );
385        let _ = writeln!(
386            out,
387            "        var _req = URLRequest(url: URL(string: _baseURL + \"{fixture_path}\")!)"
388        );
389        let _ = writeln!(out, "        _req.httpMethod = \"{method}\"");
390
391        // Headers
392        let mut header_pairs: Vec<(&String, &String)> = ctx.headers.iter().collect();
393        header_pairs.sort_by_key(|(k, _)| k.as_str());
394        for (k, v) in &header_pairs {
395            let expanded_v = expand_fixture_templates(v);
396            let ek = escape_swift(k);
397            let ev = escape_swift(&expanded_v);
398            let _ = writeln!(out, "        _req.setValue(\"{ev}\", forHTTPHeaderField: \"{ek}\")");
399        }
400
401        // Body
402        if let Some(body) = ctx.body {
403            let json_str = serde_json::to_string(body).unwrap_or_default();
404            let escaped_body = escape_swift(&json_str);
405            let _ = writeln!(out, "        _req.httpBody = \"{escaped_body}\".data(using: .utf8)");
406            let _ = writeln!(
407                out,
408                "        _req.setValue(\"application/json\", forHTTPHeaderField: \"Content-Type\")"
409            );
410        }
411
412        let _ = writeln!(out, "        var {}: HTTPURLResponse?", ctx.response_var);
413        let _ = writeln!(out, "        var _responseData: Data?");
414        let _ = writeln!(out, "        let _sema = DispatchSemaphore(value: 0)");
415        let _ = writeln!(
416            out,
417            "        URLSession.shared.dataTask(with: _req) {{ data, resp, _ in"
418        );
419        let _ = writeln!(out, "            {} = resp as? HTTPURLResponse", ctx.response_var);
420        let _ = writeln!(out, "            _responseData = data");
421        let _ = writeln!(out, "            _sema.signal()");
422        let _ = writeln!(out, "        }}.resume()");
423        let _ = writeln!(out, "        _sema.wait()");
424        let _ = writeln!(out, "        let _resp = try XCTUnwrap({})", ctx.response_var);
425    }
426
427    fn render_assert_status(&self, out: &mut String, _response_var: &str, status: u16) {
428        let _ = writeln!(out, "        XCTAssertEqual(_resp.statusCode, {status})");
429    }
430
431    fn render_assert_header(&self, out: &mut String, _response_var: &str, name: &str, expected: &str) {
432        let lower_name = name.to_lowercase();
433        let header_expr = format!("_resp.value(forHTTPHeaderField: \"{}\")", escape_swift(&lower_name));
434        match expected {
435            "<<present>>" => {
436                let _ = writeln!(out, "        XCTAssertNotNil({header_expr})");
437            }
438            "<<absent>>" => {
439                let _ = writeln!(out, "        XCTAssertNil({header_expr})");
440            }
441            "<<uuid>>" => {
442                let _ = writeln!(out, "        let _hdrVal_{lower_name} = try XCTUnwrap({header_expr})");
443                let _ = writeln!(
444                    out,
445                    "        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))"
446                );
447            }
448            exact => {
449                let escaped = escape_swift(exact);
450                let _ = writeln!(out, "        XCTAssertEqual({header_expr}, \"{escaped}\")");
451            }
452        }
453    }
454
455    fn render_assert_json_body(&self, out: &mut String, _response_var: &str, expected: &serde_json::Value) {
456        if let serde_json::Value::String(s) = expected {
457            let escaped = escape_swift(s);
458            let _ = writeln!(
459                out,
460                "        let _bodyStr = String(data: try XCTUnwrap(_responseData), encoding: .utf8) ?? \"\""
461            );
462            let _ = writeln!(
463                out,
464                "        XCTAssertEqual(_bodyStr.trimmingCharacters(in: .whitespacesAndNewlines), \"{escaped}\")"
465            );
466        } else {
467            let json_str = serde_json::to_string(expected).unwrap_or_default();
468            let escaped = escape_swift(&json_str);
469            let _ = writeln!(out, "        let _bodyData = try XCTUnwrap(_responseData)");
470            let _ = writeln!(
471                out,
472                "        let _expected = try JSONSerialization.jsonObject(with: \"{escaped}\".data(using: .utf8)!)"
473            );
474            let _ = writeln!(
475                out,
476                "        let _actual = try JSONSerialization.jsonObject(with: _bodyData)"
477            );
478            let _ = writeln!(
479                out,
480                "        XCTAssertEqual(NSDictionary(dictionary: _expected as? [String: AnyHashable] ?? [:]), NSDictionary(dictionary: _actual as? [String: AnyHashable] ?? [:]))"
481            );
482        }
483    }
484
485    fn render_assert_partial_body(&self, out: &mut String, _response_var: &str, expected: &serde_json::Value) {
486        if let Some(obj) = expected.as_object() {
487            let _ = writeln!(out, "        let _bodyData = try XCTUnwrap(_responseData)");
488            let _ = writeln!(
489                out,
490                "        let _bodyObj = try XCTUnwrap(try JSONSerialization.jsonObject(with: _bodyData) as? [String: Any])"
491            );
492            for (key, val) in obj {
493                let escaped_key = escape_swift(key);
494                let swift_val = json_to_swift(val);
495                let _ = writeln!(
496                    out,
497                    "        XCTAssertEqual(_bodyObj[\"{escaped_key}\"] as? AnyHashable, ({swift_val}) as AnyHashable)"
498                );
499            }
500        }
501    }
502
503    fn render_assert_validation_errors(
504        &self,
505        out: &mut String,
506        _response_var: &str,
507        errors: &[ValidationErrorExpectation],
508    ) {
509        let _ = writeln!(out, "        let _bodyData = try XCTUnwrap(_responseData)");
510        let _ = writeln!(
511            out,
512            "        let _bodyObj = try XCTUnwrap(try JSONSerialization.jsonObject(with: _bodyData) as? [String: Any])"
513        );
514        let _ = writeln!(
515            out,
516            "        let _errors = _bodyObj[\"errors\"] as? [[String: Any]] ?? []"
517        );
518        for ve in errors {
519            let escaped_msg = escape_swift(&ve.msg);
520            let _ = writeln!(
521                out,
522                "        XCTAssertTrue(_errors.contains(where: {{ ($0[\"msg\"] as? String)?.contains(\"{escaped_msg}\") == true }}), \"expected validation error: {escaped_msg}\")"
523            );
524        }
525    }
526}
527
528/// Render an XCTest method for an HTTP server fixture via the shared driver.
529///
530/// HTTP 101 (WebSocket upgrade) is emitted as a skip stub because `URLSession`
531/// cannot handle Upgrade responses.
532fn render_http_test_method(out: &mut String, fixture: &Fixture) {
533    let Some(http) = &fixture.http else {
534        return;
535    };
536
537    // HTTP 101 (WebSocket upgrade) — URLSession cannot handle upgrade responses.
538    if http.expected_response.status_code == 101 {
539        let method_name = sanitize_ident(&fixture.id).to_upper_camel_case();
540        let description = fixture.description.replace('"', "\\\"");
541        let _ = writeln!(out, "    /// {description}");
542        let _ = writeln!(out, "    func test{method_name}() throws {{");
543        let _ = writeln!(
544            out,
545            "        try XCTSkipIf(true, \"HTTP 101 WebSocket upgrade cannot be tested via URLSession\")"
546        );
547        let _ = writeln!(out, "    }}");
548        return;
549    }
550
551    client::http_call::render_http_test(out, &SwiftTestClientRenderer, fixture);
552}
553
554// ---------------------------------------------------------------------------
555// Function-call test rendering
556// ---------------------------------------------------------------------------
557
558#[allow(clippy::too_many_arguments)]
559fn render_test_method(
560    out: &mut String,
561    fixture: &Fixture,
562    e2e_config: &E2eConfig,
563    _function_name: &str,
564    _result_var: &str,
565    _args: &[crate::config::ArgMapping],
566    field_resolver: &FieldResolver,
567    result_is_simple: bool,
568    enum_fields: &HashSet<String>,
569    global_client_factory: Option<&str>,
570) {
571    // Resolve per-fixture call config.
572    let call_config = e2e_config.resolve_call_for_fixture(fixture.call.as_deref(), &fixture.input);
573    let lang = "swift";
574    let call_overrides = call_config.overrides.get(lang);
575    let function_name = call_overrides
576        .and_then(|o| o.function.as_ref())
577        .cloned()
578        .unwrap_or_else(|| call_config.function.to_lower_camel_case());
579    // Per-call client_factory takes precedence over the global one.
580    let client_factory: Option<&str> = call_overrides
581        .and_then(|o| o.client_factory.as_deref())
582        .or(global_client_factory);
583    let result_var = &call_config.result_var;
584    let args = &call_config.args;
585    // Per-call flags: base call flag OR per-language override OR global flag.
586    // Also treat the call as simple when *any* language override marks it as bytes.
587    // Calls like `speech()` have `result_is_bytes = true` on C/C#/Java overrides but
588    // no explicit `result_is_simple` on the Swift override — yet the Swift binding
589    // returns `Data` directly (not a struct), so assertions must use `result.isEmpty`
590    // rather than `result.audio().toString().isEmpty`.
591    let result_is_bytes_any_lang =
592        call_config.result_is_bytes || call_config.overrides.values().any(|o| o.result_is_bytes);
593    eprintln!(
594        "[swift debug] fixture={} call={:?} result_is_bytes={} any_override_bytes={} overrides={}",
595        fixture.id,
596        fixture.call,
597        call_config.result_is_bytes,
598        call_config.overrides.values().any(|o| o.result_is_bytes),
599        call_config.overrides.len()
600    );
601    let result_is_simple = call_config.result_is_simple
602        || call_overrides.is_some_and(|o| o.result_is_simple)
603        || result_is_simple
604        || result_is_bytes_any_lang;
605    let result_is_array = call_config.result_is_array;
606    // When the call returns `Option<T>` the Swift binding exposes the result as
607    // `Optional<…>` (e.g. `getEmbeddingPreset(...) -> EmbeddingPreset?`). Bare-result
608    // `is_empty`/`not_empty` assertions must use `XCTAssertNil` / `XCTAssertNotNil`
609    // rather than `.toString().isEmpty`, which is undefined on opaque optionals.
610    let result_is_option = call_config.result_is_option || call_overrides.is_some_and(|o| o.result_is_option);
611
612    let method_name = fixture.id.to_upper_camel_case();
613    let description = &fixture.description;
614    let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
615    let is_async = call_config.r#async;
616
617    // Streaming detection (call-level `streaming` opt-out is honored).
618    let is_streaming = crate::codegen::streaming_assertions::resolve_is_streaming(fixture, call_config.streaming);
619    let collect_snippet_opt = if is_streaming && !expects_error {
620        crate::codegen::streaming_assertions::StreamingFieldResolver::collect_snippet(lang, result_var, "chunks")
621    } else {
622        None
623    };
624    // When swift has streaming-virtual-field assertions but no collect snippet
625    // is available (the swift-bridge surface does not yet expose a typed
626    // `chatStream` async sequence we can drain into a typed
627    // `[ChatCompletionChunk]`), emit a skip stub rather than reference an
628    // undefined `chunks` local in the assertion expressions. This keeps the
629    // swift test target compiling while the binding catches up.
630    if is_streaming && !expects_error && collect_snippet_opt.is_none() {
631        if is_async {
632            let _ = writeln!(out, "    func test{method_name}() async throws {{");
633        } else {
634            let _ = writeln!(out, "    func test{method_name}() throws {{");
635        }
636        let _ = writeln!(out, "        // {description}");
637        let _ = writeln!(
638            out,
639            "        try XCTSkipIf(true, \"swift: streaming chunk collection is not yet supported via the swift-bridge surface (fixture: {})\")",
640            fixture.id
641        );
642        let _ = writeln!(out, "    }}");
643        return;
644    }
645    let collect_snippet = collect_snippet_opt.unwrap_or_default();
646
647    // Detect whether this call has any json_object args that cannot be constructed
648    // in Swift — swift-bridge opaque types do not provide a fromJson initialiser.
649    // When such args exist and no `options_via` is configured for swift, emit a
650    // skip stub so the test compiles but is recorded as skipped rather than
651    // generating invalid code that passes `nil` or a string literal where a
652    // strongly-typed request object is required.
653    let has_unresolvable_json_object_arg = {
654        let options_via = call_overrides.and_then(|o| o.options_via.as_deref());
655        options_via.is_none() && args.iter().any(|a| a.arg_type == "json_object" && a.name != "config")
656    };
657
658    if has_unresolvable_json_object_arg {
659        if is_async {
660            let _ = writeln!(out, "    func test{method_name}() async throws {{");
661        } else {
662            let _ = writeln!(out, "    func test{method_name}() throws {{");
663        }
664        let _ = writeln!(out, "        // {description}");
665        let _ = writeln!(
666            out,
667            "        try XCTSkipIf(true, \"swift: json_object request construction requires options_via configuration (fixture: {})\");",
668            fixture.id
669        );
670        let _ = writeln!(out, "    }}");
671        return;
672    }
673
674    // Resolve extra_args from per-call swift overrides (e.g. `nil` for optional
675    // query-param arguments on list_files/list_batches that have no fixture-level
676    // input field).
677    let extra_args: Vec<String> = call_overrides.map(|o| o.extra_args.clone()).unwrap_or_default();
678
679    // Merge per-call enum_fields keys into the effective enum set so that
680    // fields like "status" (BatchStatus, BatchObject) are treated as enum-typed
681    // even when they are not globally listed in fields_enum (they are context-
682    // dependent — BatchStatus on BatchObject but plain String on ResponseObject).
683    let effective_enum_fields: std::borrow::Cow<HashSet<String>> = {
684        let per_call = call_overrides.map(|o| &o.enum_fields);
685        if let Some(pc) = per_call {
686            if !pc.is_empty() {
687                let mut merged = enum_fields.clone();
688                merged.extend(pc.keys().cloned());
689                std::borrow::Cow::Owned(merged)
690            } else {
691                std::borrow::Cow::Borrowed(enum_fields)
692            }
693        } else {
694            std::borrow::Cow::Borrowed(enum_fields)
695        }
696    };
697
698    let options_via_str: Option<&str> = call_overrides.and_then(|o| o.options_via.as_deref());
699    let options_type_str: Option<&str> = call_overrides.and_then(|o| o.options_type.as_deref());
700    // Derive the Swift handle-config parsing function from the C override's
701    // `c_engine_factory` field. E.g. `"CrawlConfig"` → snake → `"crawl_config_from_json"`
702    // → camelCase → `"crawlConfigFromJson"`.
703    let handle_config_fn_owned: Option<String> = call_config
704        .overrides
705        .get("c")
706        .and_then(|c| c.c_engine_factory.as_deref())
707        .map(|ty| format!("{}_from_json", ty.to_snake_case()).to_lower_camel_case());
708    let (setup_lines, args_str) = build_args_and_setup(
709        &fixture.input,
710        args,
711        &fixture.id,
712        fixture.has_host_root_route(),
713        &function_name,
714        options_via_str,
715        options_type_str,
716        handle_config_fn_owned.as_deref(),
717    );
718
719    // Append extra_args to the argument list.
720    let args_str = if extra_args.is_empty() {
721        args_str
722    } else if args_str.is_empty() {
723        extra_args.join(", ")
724    } else {
725        format!("{args_str}, {}", extra_args.join(", "))
726    };
727
728    // When a client_factory is set, dispatch via a client instance:
729    //   let client = try <FactoryType>(apiKey: "test-key", baseUrl: <mock_url>)
730    //   try await client.<method>(args)
731    // Otherwise fall back to free-function call (Kreuzberg / non-client-factory libraries).
732    let has_mock = fixture.mock_response.is_some();
733    let (call_setup, call_expr) = if let Some(_factory) = client_factory {
734        let env_key = format!("MOCK_SERVER_{}", fixture.id.to_ascii_uppercase().replace('-', "_"));
735        let mock_url = if fixture.has_host_root_route() {
736            format!(
737                "ProcessInfo.processInfo.environment[\"{env_key}\"] ?? (ProcessInfo.processInfo.environment[\"MOCK_SERVER_URL\"]! + \"/fixtures/{}\")",
738                fixture.id
739            )
740        } else {
741            format!(
742                "ProcessInfo.processInfo.environment[\"MOCK_SERVER_URL\"]! + \"/fixtures/{}\"",
743                fixture.id
744            )
745        };
746        let client_constructor = if has_mock {
747            format!("let _client = try DefaultClient(apiKey: \"test-key\", baseUrl: {mock_url})")
748        } else {
749            // Live API: check for api_key_var; if not present use mock URL anyway.
750            if let Some(env_var) = fixture.env.as_ref().and_then(|e| e.api_key_var.as_deref()) {
751                format!(
752                    "let _apiKey = ProcessInfo.processInfo.environment[\"{env_var}\"]\n        \
753                     let _baseUrl: String? = _apiKey != nil ? nil : {mock_url}\n        \
754                     let _client = try DefaultClient(apiKey: _apiKey ?? \"test-key\", baseUrl: _baseUrl)"
755                )
756            } else {
757                format!("let _client = try DefaultClient(apiKey: \"test-key\", baseUrl: {mock_url})")
758            }
759        };
760        let expr = if is_async {
761            format!("try await _client.{function_name}({args_str})")
762        } else {
763            format!("try _client.{function_name}({args_str})")
764        };
765        (Some(client_constructor), expr)
766    } else {
767        // Free-function call (no client_factory).
768        let expr = if is_async {
769            format!("try await {function_name}({args_str})")
770        } else {
771            format!("try {function_name}({args_str})")
772        };
773        (None, expr)
774    };
775    // For backwards compatibility: qualified_function_name unused when client_factory is set.
776    let _ = function_name;
777
778    if is_async {
779        let _ = writeln!(out, "    func test{method_name}() async throws {{");
780    } else {
781        let _ = writeln!(out, "    func test{method_name}() throws {{");
782    }
783    let _ = writeln!(out, "        // {description}");
784
785    if expects_error {
786        // For error fixtures, setup may itself throw (e.g. config validation
787        // happens at engine construction). Wrap the whole pipeline — setup
788        // and the call — in a single do/catch so any throw counts as success.
789        if is_async {
790            // XCTAssertThrowsError is a synchronous macro; for async-throwing
791            // functions use a do/catch with explicit XCTFail to enforce that
792            // the throw actually happens. `await XCTAssertThrowsError(...)` is
793            // not valid Swift — it evaluates `await` against a non-async expr.
794            let _ = writeln!(out, "        do {{");
795            for line in &setup_lines {
796                let _ = writeln!(out, "            {line}");
797            }
798            if let Some(setup) = &call_setup {
799                let _ = writeln!(out, "            {setup}");
800            }
801            let _ = writeln!(out, "            _ = {call_expr}");
802            let _ = writeln!(out, "            XCTFail(\"expected to throw\")");
803            let _ = writeln!(out, "        }} catch {{");
804            let _ = writeln!(out, "            // success");
805            let _ = writeln!(out, "        }}");
806        } else {
807            // Synchronous: emit setup outside (it's expected to succeed) and
808            // wrap only the throwing call in XCTAssertThrowsError. If setup
809            // itself throws, that propagates as the test's own failure — but
810            // sync tests use `throws` so the test method itself rethrows,
811            // which XCTest still records as caught. Keep this simple: use a
812            // do/catch so setup-time throws also count as expected failures.
813            let _ = writeln!(out, "        do {{");
814            for line in &setup_lines {
815                let _ = writeln!(out, "            {line}");
816            }
817            if let Some(setup) = &call_setup {
818                let _ = writeln!(out, "            {setup}");
819            }
820            let _ = writeln!(out, "            _ = {call_expr}");
821            let _ = writeln!(out, "            XCTFail(\"expected to throw\")");
822            let _ = writeln!(out, "        }} catch {{");
823            let _ = writeln!(out, "            // success");
824            let _ = writeln!(out, "        }}");
825        }
826        let _ = writeln!(out, "    }}");
827        return;
828    }
829
830    for line in &setup_lines {
831        let _ = writeln!(out, "        {line}");
832    }
833
834    // Emit client construction if a client_factory is configured.
835    if let Some(setup) = &call_setup {
836        let _ = writeln!(out, "        {setup}");
837    }
838
839    let _ = writeln!(out, "        let {result_var} = {call_expr}");
840
841    // Emit the collect snippet for streaming fixtures (drains the async sequence into
842    // a local `chunks: [ChatCompletionChunk]` array used by streaming-virtual assertions).
843    if !collect_snippet.is_empty() {
844        for line in collect_snippet.lines() {
845            let _ = writeln!(out, "        {line}");
846        }
847    }
848
849    for assertion in &fixture.assertions {
850        render_assertion(
851            out,
852            assertion,
853            result_var,
854            field_resolver,
855            result_is_simple,
856            result_is_array,
857            result_is_option,
858            &effective_enum_fields,
859        );
860    }
861
862    let _ = writeln!(out, "    }}");
863}
864
865#[allow(clippy::too_many_arguments)]
866/// Build setup lines and the argument list for the function call.
867///
868/// Swift-bridge wrappers require strongly-typed values that don't have implicit
869/// Swift literal conversions:
870///
871/// - `bytes` args become `RustVec<UInt8>` — fixture supplies a relative file path
872///   string which is read at test time and pushed into a `RustVec<UInt8>` setup
873///   variable. A literal byte array is base64-decoded or UTF-8 encoded inline.
874/// - `json_object` args become opaque `ExtractionConfig` (or sibling) instances —
875///   a JSON string is decoded via `extractionConfigFromJson(...)` in a setup line.
876/// - Optional args missing from the fixture must still appear at the call site
877///   as `nil` whenever a later positional arg is present, otherwise Swift slots
878///   subsequent values into the wrong parameter.
879fn build_args_and_setup(
880    input: &serde_json::Value,
881    args: &[crate::config::ArgMapping],
882    fixture_id: &str,
883    has_host_root_route: bool,
884    function_name: &str,
885    options_via: Option<&str>,
886    options_type: Option<&str>,
887    handle_config_fn: Option<&str>,
888) -> (Vec<String>, String) {
889    if args.is_empty() {
890        return (Vec::new(), String::new());
891    }
892
893    let mut setup_lines: Vec<String> = Vec::new();
894    let mut parts: Vec<String> = Vec::new();
895
896    // Pre-compute, for each arg index, whether any later arg has a fixture-provided
897    // value (or is required and will emit a default). When an optional arg is empty
898    // but a later arg WILL emit, we must keep the slot with `nil` so positional
899    // alignment is preserved.
900    let later_emits: Vec<bool> = (0..args.len())
901        .map(|i| {
902            args.iter().skip(i + 1).any(|a| {
903                let f = a.field.strip_prefix("input.").unwrap_or(&a.field);
904                let v = input.get(f);
905                let has_value = matches!(v, Some(x) if !x.is_null());
906                has_value || !a.optional || (a.arg_type == "json_object" && a.name == "config")
907            })
908        })
909        .collect();
910
911    for (idx, arg) in args.iter().enumerate() {
912        if arg.arg_type == "mock_url" {
913            let env_key = format!("MOCK_SERVER_{}", fixture_id.to_ascii_uppercase().replace('-', "_"));
914            let url_expr = if has_host_root_route {
915                format!(
916                    "ProcessInfo.processInfo.environment[\"{env_key}\"] ?? (ProcessInfo.processInfo.environment[\"MOCK_SERVER_URL\"]! + \"/fixtures/{fixture_id}\")"
917                )
918            } else {
919                format!("ProcessInfo.processInfo.environment[\"MOCK_SERVER_URL\"]! + \"/fixtures/{fixture_id}\"")
920            };
921            setup_lines.push(format!("let {} = {url_expr}", arg.name));
922            parts.push(arg.name.clone());
923            continue;
924        }
925
926        if arg.arg_type == "handle" {
927            let var_name = format!("{}Obj", arg.name.to_lower_camel_case());
928            let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
929            let config_val = input.get(field);
930            let has_config = config_val
931                .is_some_and(|v| !(v.is_null() || v.is_object() && v.as_object().is_some_and(|o| o.is_empty())));
932            if has_config {
933                if let Some(from_json_fn) = handle_config_fn {
934                    let json_str = serde_json::to_string(config_val.unwrap()).unwrap_or_default();
935                    let escaped = escape_swift_str(&json_str);
936                    let config_var = format!("{}Config", arg.name.to_lower_camel_case());
937                    setup_lines.push(format!("let {config_var} = try {from_json_fn}(\"{escaped}\")"));
938                    setup_lines.push(format!("let {var_name} = try createEngine({config_var})"));
939                } else {
940                    setup_lines.push(format!("let {var_name} = try createEngine(nil)"));
941                }
942            } else {
943                setup_lines.push(format!("let {var_name} = try createEngine(nil)"));
944            }
945            parts.push(var_name);
946            continue;
947        }
948
949        // bytes args: fixture stores a fixture-relative path string. Generate
950        // setup that reads it into a Data and pushes each byte into a
951        // RustVec<UInt8>. Literal byte arrays inline the bytes; missing values
952        // produce an empty vec (or `nil` when optional).
953        if arg.arg_type == "bytes" {
954            let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
955            let val = input.get(field);
956            match val {
957                None | Some(serde_json::Value::Null) if arg.optional => {
958                    if later_emits[idx] {
959                        parts.push("nil".to_string());
960                    }
961                }
962                None | Some(serde_json::Value::Null) => {
963                    let var_name = format!("{}Vec", arg.name.to_lower_camel_case());
964                    setup_lines.push(format!("let {var_name} = RustVec<UInt8>()"));
965                    parts.push(var_name);
966                }
967                Some(serde_json::Value::String(s)) => {
968                    let escaped = escape_swift(s);
969                    let var_name = format!("{}Vec", arg.name.to_lower_camel_case());
970                    let data_var = format!("{}Data", arg.name.to_lower_camel_case());
971                    setup_lines.push(format!(
972                        "let {data_var} = try Data(contentsOf: URL(fileURLWithPath: \"{escaped}\"))"
973                    ));
974                    setup_lines.push(format!("let {var_name} = RustVec<UInt8>()"));
975                    setup_lines.push(format!("for _byte in {data_var} {{ {var_name}.push(value: _byte) }}"));
976                    parts.push(var_name);
977                }
978                Some(serde_json::Value::Array(arr)) => {
979                    let var_name = format!("{}Vec", arg.name.to_lower_camel_case());
980                    setup_lines.push(format!("let {var_name} = RustVec<UInt8>()"));
981                    for v in arr {
982                        if let Some(n) = v.as_u64() {
983                            setup_lines.push(format!("{var_name}.push(value: UInt8({n}))"));
984                        }
985                    }
986                    parts.push(var_name);
987                }
988                Some(other) => {
989                    // Fallback: encode the JSON serialisation as UTF-8 bytes.
990                    let json_str = serde_json::to_string(other).unwrap_or_default();
991                    let escaped = escape_swift(&json_str);
992                    let var_name = format!("{}Vec", arg.name.to_lower_camel_case());
993                    setup_lines.push(format!("let {var_name} = RustVec<UInt8>()"));
994                    setup_lines.push(format!(
995                        "for _byte in Array(\"{escaped}\".utf8) {{ {var_name}.push(value: _byte) }}"
996                    ));
997                    parts.push(var_name);
998                }
999            }
1000            continue;
1001        }
1002
1003        // json_object "config" args: the swift-bridge wrapper requires an opaque
1004        // `ExtractionConfig` (or sibling) instance, not a JSON string. Use the
1005        // generated `extractionConfigFromJson(_:)` helper from RustBridge.
1006        // Batch functions (batchExtract*) hardcode config internally — skip it.
1007        let is_config_arg = arg.name == "config" && arg.arg_type == "json_object";
1008        let is_batch_fn = function_name.starts_with("batch") || function_name.starts_with("Batch");
1009        if is_config_arg && !is_batch_fn {
1010            let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1011            let val = input.get(field);
1012            let json_str = match val {
1013                None | Some(serde_json::Value::Null) => "{}".to_string(),
1014                Some(v) => serde_json::to_string(v).unwrap_or_else(|_| "{}".to_string()),
1015            };
1016            let escaped = escape_swift(&json_str);
1017            let var_name = format!("{}Obj", arg.name.to_lower_camel_case());
1018            setup_lines.push(format!("let {var_name} = try extractionConfigFromJson(\"{escaped}\")"));
1019            parts.push(var_name);
1020            continue;
1021        }
1022
1023        // json_object non-config args with options_via = "from_json":
1024        // Use the generated `{typeCamelCase}FromJson(_:)` helper so the fixture JSON is
1025        // deserialised into the opaque swift-bridge type rather than passed as a raw string.
1026        // When arg.field == "input", the entire fixture input IS the request object.
1027        if arg.arg_type == "json_object" && options_via == Some("from_json") {
1028            if let Some(type_name) = options_type {
1029                let resolved_val = super::resolve_field(input, &arg.field);
1030                let json_str = match resolved_val {
1031                    serde_json::Value::Null => "{}".to_string(),
1032                    v => serde_json::to_string(v).unwrap_or_else(|_| "{}".to_string()),
1033                };
1034                let escaped = escape_swift(&json_str);
1035                let var_name = format!("_{}", arg.name.to_lower_camel_case());
1036                let from_json_fn = format!("{}FromJson", type_name.to_lower_camel_case());
1037                setup_lines.push(format!("let {var_name} = try {from_json_fn}(\"{escaped}\")"));
1038                parts.push(var_name);
1039                continue;
1040            }
1041        }
1042
1043        let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1044        let val = input.get(field);
1045        match val {
1046            None | Some(serde_json::Value::Null) if arg.optional => {
1047                // Optional arg with no fixture value: keep the slot with `nil`
1048                // when a later arg will emit, so positional alignment matches
1049                // the swift-bridge wrapper signature.
1050                if later_emits[idx] {
1051                    parts.push("nil".to_string());
1052                }
1053            }
1054            None | Some(serde_json::Value::Null) => {
1055                let default_val = match arg.arg_type.as_str() {
1056                    "string" => "\"\"".to_string(),
1057                    "int" | "integer" => "0".to_string(),
1058                    "float" | "number" => "0.0".to_string(),
1059                    "bool" | "boolean" => "false".to_string(),
1060                    _ => "nil".to_string(),
1061                };
1062                parts.push(default_val);
1063            }
1064            Some(v) => {
1065                parts.push(json_to_swift(v));
1066            }
1067        }
1068    }
1069
1070    (setup_lines, parts.join(", "))
1071}
1072
1073#[allow(clippy::too_many_arguments)]
1074fn render_assertion(
1075    out: &mut String,
1076    assertion: &Assertion,
1077    result_var: &str,
1078    field_resolver: &FieldResolver,
1079    result_is_simple: bool,
1080    result_is_array: bool,
1081    result_is_option: bool,
1082    enum_fields: &HashSet<String>,
1083) {
1084    // When the bare result is `Optional<T>` (no field path) the opaque class
1085    // exposed by swift-bridge has no `.toString()` method, so the usual
1086    // `.toString().isEmpty` pattern produces compile errors. Detect the
1087    // "bare result" case and prefer `XCTAssertNil` / `XCTAssertNotNil`.
1088    let bare_result_is_option = result_is_option && assertion.field.as_deref().filter(|f| !f.is_empty()).is_none();
1089    // Streaming virtual fields resolve against the `chunks` collected-array variable.
1090    // Intercept before is_valid_for_result so they are never skipped.
1091    if let Some(f) = &assertion.field {
1092        if !f.is_empty() && crate::codegen::streaming_assertions::is_streaming_virtual_field(f) {
1093            if let Some(expr) =
1094                crate::codegen::streaming_assertions::StreamingFieldResolver::accessor(f, "swift", "chunks")
1095            {
1096                let line = match assertion.assertion_type.as_str() {
1097                    "count_min" => {
1098                        if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1099                            format!("        XCTAssertGreaterThanOrEqual(chunks.count, {n})\n")
1100                        } else {
1101                            String::new()
1102                        }
1103                    }
1104                    "count_equals" => {
1105                        if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1106                            format!("        XCTAssertEqual(chunks.count, {n})\n")
1107                        } else {
1108                            String::new()
1109                        }
1110                    }
1111                    "equals" => {
1112                        if let Some(serde_json::Value::String(s)) = &assertion.value {
1113                            let escaped = escape_swift(s);
1114                            format!("        XCTAssertEqual({expr}, \"{escaped}\")\n")
1115                        } else if let Some(b) = assertion.value.as_ref().and_then(|v| v.as_bool()) {
1116                            format!("        XCTAssertEqual({expr}, {b})\n")
1117                        } else {
1118                            String::new()
1119                        }
1120                    }
1121                    "not_empty" => {
1122                        format!("        XCTAssertFalse({expr}.isEmpty, \"expected non-empty\")\n")
1123                    }
1124                    "is_empty" => {
1125                        format!("        XCTAssertTrue({expr}.isEmpty, \"expected empty\")\n")
1126                    }
1127                    "is_true" => {
1128                        format!("        XCTAssertTrue({expr})\n")
1129                    }
1130                    "is_false" => {
1131                        format!("        XCTAssertFalse({expr})\n")
1132                    }
1133                    "greater_than" => {
1134                        if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1135                            format!("        XCTAssertGreaterThan(chunks.count, {n})\n")
1136                        } else {
1137                            String::new()
1138                        }
1139                    }
1140                    "contains" => {
1141                        if let Some(serde_json::Value::String(s)) = &assertion.value {
1142                            let escaped = escape_swift(s);
1143                            format!(
1144                                "        XCTAssertTrue({expr}.contains(\"{escaped}\"), \"expected to contain: {escaped}\")\n"
1145                            )
1146                        } else {
1147                            String::new()
1148                        }
1149                    }
1150                    _ => format!(
1151                        "        // streaming field '{f}': assertion type '{}' not rendered\n",
1152                        assertion.assertion_type
1153                    ),
1154                };
1155                if !line.is_empty() {
1156                    out.push_str(&line);
1157                }
1158            }
1159            return;
1160        }
1161    }
1162
1163    // Skip assertions on fields that don't exist on the result type.
1164    if let Some(f) = &assertion.field {
1165        if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
1166            let _ = writeln!(out, "        // skipped: field '{f}' not available on result type");
1167            return;
1168        }
1169    }
1170
1171    // Skip assertions that traverse a tagged-union variant boundary.
1172    // In Swift, FormatMetadata and similar enum-backed opaque types are exposed as
1173    // plain classes by swift-bridge — variant accessor methods (e.g., `.excel()`)
1174    // are not generated, so such assertions cannot be expressed.
1175    if let Some(f) = &assertion.field {
1176        if !f.is_empty() && field_resolver.tagged_union_split(f).is_some() {
1177            let _ = writeln!(
1178                out,
1179                "        // skipped: field '{f}' crosses a tagged-union variant boundary (not expressible in Swift)"
1180            );
1181            return;
1182        }
1183    }
1184
1185    // Determine if this field is an enum type.
1186    let field_is_enum = assertion
1187        .field
1188        .as_deref()
1189        .is_some_and(|f| enum_fields.contains(f) || enum_fields.contains(field_resolver.resolve(f)));
1190
1191    let field_is_optional = assertion.field.as_deref().is_some_and(|f| {
1192        !f.is_empty() && (field_resolver.is_optional(f) || field_resolver.is_optional(field_resolver.resolve(f)))
1193    });
1194    let field_is_array = assertion.field.as_deref().is_some_and(|f| {
1195        !f.is_empty() && (field_resolver.is_array(f) || field_resolver.is_array(field_resolver.resolve(f)))
1196    });
1197
1198    let field_expr_raw = if result_is_simple {
1199        result_var.to_string()
1200    } else {
1201        match &assertion.field {
1202            Some(f) if !f.is_empty() => field_resolver.accessor(f, "swift", result_var),
1203            _ => result_var.to_string(),
1204        }
1205    };
1206
1207    // swift-bridge `RustVec<T>` exposes its elements as `T.SelfRef`, which holds
1208    // a raw pointer into the parent Vec's storage. When the Vec is a temporary
1209    // (e.g. `result.json_ld()` called inline), Swift ARC may release it before
1210    // the ref is used, leaving the ref's pointer dangling. Materialise the
1211    // temporary into a local so it survives the full expression chain.
1212    //
1213    // The local name is suffixed with the assertion type plus a hash of the
1214    // assertion's discriminating fields so multiple assertions on the same
1215    // collection don't redeclare the same name.
1216    let local_suffix = {
1217        use std::hash::{Hash, Hasher};
1218        let mut hasher = std::collections::hash_map::DefaultHasher::new();
1219        assertion.field.hash(&mut hasher);
1220        assertion
1221            .value
1222            .as_ref()
1223            .map(|v| v.to_string())
1224            .unwrap_or_default()
1225            .hash(&mut hasher);
1226        format!(
1227            "{}_{:x}",
1228            assertion.assertion_type.replace(['-', '.'], "_"),
1229            hasher.finish() & 0xffff_ffff,
1230        )
1231    };
1232    let (vec_setup, field_expr) = materialise_vec_temporaries(&field_expr_raw, &local_suffix);
1233    // The `contains` / `not_contains` traversal branch builds its own
1234    // accessor from `field_resolver.accessor(array_part, ...)`, ignoring
1235    // `field_expr`. Emitting the vec_setup there would produce dead
1236    // `let _vec_… = …` lines, so skip it for those traversal cases.
1237    let field_uses_traversal = assertion.field.as_deref().is_some_and(|f| f.contains("[]."));
1238    let traversal_skips_field_expr = field_uses_traversal
1239        && matches!(
1240            assertion.assertion_type.as_str(),
1241            "contains" | "not_contains" | "not_empty" | "is_empty"
1242        );
1243    if !traversal_skips_field_expr {
1244        for line in &vec_setup {
1245            let _ = writeln!(out, "        {line}");
1246        }
1247    }
1248
1249    // In Swift, optional chaining with `?.` makes the result optional even if the
1250    // called method's return type isn't marked optional. For example:
1251    // `result.markdown()?.content()` returns `Optional<RustString>` because
1252    // `markdown()` is optional and the `?.` operator wraps the result.
1253    // Detect this by checking if the accessor contains `?.`.
1254    let accessor_is_optional = field_expr.contains("?.");
1255
1256    // For enum fields, need to handle the string representation differently in Swift.
1257    // Swift enums don't have `.rawValue` unless they're explicitly RawRepresentable.
1258    // Check if this is an enum type and handle accordingly.
1259    // For optional fields (Optional<RustString>), use optional chaining before toString().
1260    // For other fields: swift-bridge returns all Rust `String` fields as `RustString`.
1261    // We add .toString() here so string assertions (contains, hasPrefix, etc.) work.
1262    // Non-string opaque fields (DocumentStructure, etc.) should not appear in string
1263    // assertions — the fixture schema controls which assertions apply to which fields.
1264    let string_expr = if field_is_enum && (field_is_optional || accessor_is_optional) {
1265        // Enum-typed fields that are also optional (e.g. `finish_reason() -> Optional<RustString>`)
1266        // must use optional chaining: `?.toString() ?? ""` to unwrap before converting to Swift String.
1267        format!("({field_expr}?.toString() ?? \"\")")
1268    } else if field_is_enum {
1269        // Enum-typed fields are now bridged as `String` (RustString in Swift) rather than
1270        // as opaque enum handles. The getter on the Rust side calls `to_string()` internally
1271        // and returns a `String` across the FFI. In Swift this arrives as `RustString`, so
1272        // `.toString()` converts it to a Swift `String` — one call, not two.
1273        format!("{field_expr}.toString()")
1274    } else if field_is_optional {
1275        // Leaf field itself is Optional<RustString> — need ?.toString() to unwrap.
1276        format!("({field_expr}?.toString() ?? \"\")")
1277    } else if accessor_is_optional {
1278        // Ancestor optional chain propagates; leaf is non-optional RustString within chain.
1279        // Use .toString() directly — the whole expr is Optional<String> due to propagation.
1280        format!("({field_expr}.toString() ?? \"\")")
1281    } else {
1282        format!("{field_expr}.toString()")
1283    };
1284
1285    match assertion.assertion_type.as_str() {
1286        "equals" => {
1287            if let Some(expected) = &assertion.value {
1288                let swift_val = json_to_swift(expected);
1289                if expected.is_string() {
1290                    if field_is_enum {
1291                        // Enum fields: `to_string()` (snake_case) returns RustString;
1292                        // `.toString()` converts it to a Swift String.
1293                        // `string_expr` already incorporates this call chain.
1294                        let trim_expr = format!("{string_expr}.trimmingCharacters(in: CharacterSet.whitespaces)");
1295                        let _ = writeln!(out, "        XCTAssertEqual({trim_expr}, {swift_val})");
1296                    } else {
1297                        // For optional strings (String?), use ?? to coalesce before trimming.
1298                        // `.toString()` converts RustString → Swift String before calling
1299                        // `.trimmingCharacters`, which requires a concrete String type.
1300                        // string_expr already incorporates field_is_optional via ?.toString() ?? "".
1301                        let trim_expr = format!("{string_expr}.trimmingCharacters(in: CharacterSet.whitespaces)");
1302                        let _ = writeln!(out, "        XCTAssertEqual({trim_expr}, {swift_val})");
1303                    }
1304                } else {
1305                    let _ = writeln!(out, "        XCTAssertEqual({field_expr}, {swift_val})");
1306                }
1307            }
1308        }
1309        "contains" => {
1310            if let Some(expected) = &assertion.value {
1311                let swift_val = json_to_swift(expected);
1312                // When the root result IS the array (result_is_simple + result_is_array) and
1313                // there is no field path, check array membership via map+contains.
1314                let no_field = assertion.field.as_deref().is_none_or(|f| f.is_empty());
1315                if result_is_simple && result_is_array && no_field {
1316                    // RustVec<RustString> iteration yields RustStringRef (no `toString()`);
1317                    // use `.as_str().toString()` to convert each element to a Swift String.
1318                    let _ = writeln!(
1319                        out,
1320                        "        XCTAssertTrue({result_var}.map {{ $0.as_str().toString() }}.contains({swift_val}), \"expected to contain: \\({swift_val})\")"
1321                    );
1322                } else {
1323                    // []. traversal: field like "links[].url" → contains(where:) closure.
1324                    let traversal_handled = if let Some(f) = assertion.field.as_deref() {
1325                        if let Some(dot) = f.find("[].") {
1326                            let array_part = &f[..dot];
1327                            let elem_part = &f[dot + 3..];
1328                            let line = swift_traversal_contains_assert(
1329                                array_part,
1330                                elem_part,
1331                                f,
1332                                &swift_val,
1333                                result_var,
1334                                false,
1335                                &format!("expected to contain: \\({swift_val})"),
1336                                enum_fields,
1337                                field_resolver,
1338                            );
1339                            let _ = writeln!(out, "{line}");
1340                            true
1341                        } else {
1342                            false
1343                        }
1344                    } else {
1345                        false
1346                    };
1347                    if !traversal_handled {
1348                        // For array fields (RustVec<RustString>), check membership via map+contains.
1349                        let field_is_array = assertion
1350                            .field
1351                            .as_deref()
1352                            .is_some_and(|f| field_resolver.is_array(field_resolver.resolve(f)));
1353                        if field_is_array {
1354                            let contains_expr =
1355                                swift_array_contains_expr(assertion.field.as_deref(), result_var, field_resolver);
1356                            let _ = writeln!(
1357                                out,
1358                                "        XCTAssertTrue(({contains_expr} ?? []).contains({swift_val}), \"expected to contain: \\({swift_val})\")"
1359                            );
1360                        } else if field_is_enum {
1361                            // Enum fields: use `toString().toString()` (via string_expr) to get the
1362                            // serde variant name as a Swift String, then check substring containment.
1363                            let _ = writeln!(
1364                                out,
1365                                "        XCTAssertTrue({string_expr}.contains({swift_val}), \"expected to contain: \\({swift_val})\")"
1366                            );
1367                        } else {
1368                            let _ = writeln!(
1369                                out,
1370                                "        XCTAssertTrue({string_expr}.contains({swift_val}), \"expected to contain: \\({swift_val})\")"
1371                            );
1372                        }
1373                    }
1374                }
1375            }
1376        }
1377        "contains_all" => {
1378            if let Some(values) = &assertion.values {
1379                // []. traversal: field like "links[].link_type" → contains(where:) per value.
1380                if let Some(f) = assertion.field.as_deref() {
1381                    if let Some(dot) = f.find("[].") {
1382                        let array_part = &f[..dot];
1383                        let elem_part = &f[dot + 3..];
1384                        for val in values {
1385                            let swift_val = json_to_swift(val);
1386                            let line = swift_traversal_contains_assert(
1387                                array_part,
1388                                elem_part,
1389                                f,
1390                                &swift_val,
1391                                result_var,
1392                                false,
1393                                &format!("expected to contain: \\({swift_val})"),
1394                                enum_fields,
1395                                field_resolver,
1396                            );
1397                            let _ = writeln!(out, "{line}");
1398                        }
1399                        // handled — skip remaining branches
1400                    } else {
1401                        // For array fields (RustVec<RustString>), check membership via map+contains.
1402                        let field_is_array = field_resolver.is_array(field_resolver.resolve(f));
1403                        if field_is_array {
1404                            let contains_expr =
1405                                swift_array_contains_expr(assertion.field.as_deref(), result_var, field_resolver);
1406                            for val in values {
1407                                let swift_val = json_to_swift(val);
1408                                let _ = writeln!(
1409                                    out,
1410                                    "        XCTAssertTrue(({contains_expr} ?? []).contains({swift_val}), \"expected to contain: \\({swift_val})\")"
1411                                );
1412                            }
1413                        } else if field_is_enum {
1414                            // Enum fields: use `toString().toString()` (via string_expr) to get the
1415                            // serde variant name as a Swift String, then check substring containment.
1416                            for val in values {
1417                                let swift_val = json_to_swift(val);
1418                                let _ = writeln!(
1419                                    out,
1420                                    "        XCTAssertTrue({string_expr}.contains({swift_val}), \"expected to contain: \\({swift_val})\")"
1421                                );
1422                            }
1423                        } else {
1424                            for val in values {
1425                                let swift_val = json_to_swift(val);
1426                                let _ = writeln!(
1427                                    out,
1428                                    "        XCTAssertTrue({string_expr}.contains({swift_val}), \"expected to contain: \\({swift_val})\")"
1429                                );
1430                            }
1431                        }
1432                    }
1433                } else {
1434                    // No field — fall back to existing string_expr path.
1435                    for val in values {
1436                        let swift_val = json_to_swift(val);
1437                        let _ = writeln!(
1438                            out,
1439                            "        XCTAssertTrue({string_expr}.contains({swift_val}), \"expected to contain: \\({swift_val})\")"
1440                        );
1441                    }
1442                }
1443            }
1444        }
1445        "not_contains" => {
1446            if let Some(expected) = &assertion.value {
1447                let swift_val = json_to_swift(expected);
1448                // []. traversal: "links[].url" → XCTAssertFalse(array.contains(where:))
1449                let traversal_handled = if let Some(f) = assertion.field.as_deref() {
1450                    if let Some(dot) = f.find("[].") {
1451                        let array_part = &f[..dot];
1452                        let elem_part = &f[dot + 3..];
1453                        let line = swift_traversal_contains_assert(
1454                            array_part,
1455                            elem_part,
1456                            f,
1457                            &swift_val,
1458                            result_var,
1459                            true,
1460                            &format!("expected NOT to contain: \\({swift_val})"),
1461                            enum_fields,
1462                            field_resolver,
1463                        );
1464                        let _ = writeln!(out, "{line}");
1465                        true
1466                    } else {
1467                        false
1468                    }
1469                } else {
1470                    false
1471                };
1472                if !traversal_handled {
1473                    let _ = writeln!(
1474                        out,
1475                        "        XCTAssertFalse({string_expr}.contains({swift_val}), \"expected NOT to contain: \\({swift_val})\")"
1476                    );
1477                }
1478            }
1479        }
1480        "not_empty" => {
1481            // For optional fields (Optional<T>), check that the value is non-nil.
1482            // For array fields (RustVec<T>), check .isEmpty on the vec directly.
1483            // For result_is_simple (e.g. Data, String), use .isEmpty directly on
1484            // the result — avoids calling .toString() on non-RustString types.
1485            // For string fields, convert to Swift String and check .isEmpty.
1486            // []. traversal: "links[].url" → contains(where: { !elem.isEmpty })
1487            let traversal_not_empty_handled = if let Some(f) = assertion.field.as_deref() {
1488                if let Some(dot) = f.find("[].") {
1489                    let array_part = &f[..dot];
1490                    let elem_part = &f[dot + 3..];
1491                    let array_accessor = field_resolver.accessor(array_part, "swift", result_var);
1492                    let resolved_full = field_resolver.resolve(f);
1493                    let resolved_elem_part = resolved_full
1494                        .find("[].")
1495                        .map(|d| &resolved_full[d + 3..])
1496                        .unwrap_or(elem_part);
1497                    let elem_accessor = field_resolver.accessor(resolved_elem_part, "swift", "$0");
1498                    let elem_is_enum = enum_fields.contains(f) || enum_fields.contains(resolved_full);
1499                    let elem_is_optional = field_resolver.is_optional(resolved_elem_part)
1500                        || field_resolver.is_optional(field_resolver.resolve(resolved_elem_part));
1501                    let elem_str = if elem_is_enum {
1502                        format!("{elem_accessor}.to_string().toString()")
1503                    } else if elem_is_optional {
1504                        format!("({elem_accessor}?.toString() ?? \"\")")
1505                    } else {
1506                        format!("{elem_accessor}.toString()")
1507                    };
1508                    let _ = writeln!(
1509                        out,
1510                        "        XCTAssertTrue({array_accessor}.contains(where: {{ !{elem_str}.isEmpty }}), \"expected non-empty value\")"
1511                    );
1512                    true
1513                } else {
1514                    false
1515                }
1516            } else {
1517                false
1518            };
1519            if !traversal_not_empty_handled {
1520                if bare_result_is_option {
1521                    let _ = writeln!(out, "        XCTAssertNotNil({result_var}, \"expected non-nil value\")");
1522                } else if field_is_optional {
1523                    let _ = writeln!(out, "        XCTAssertNotNil({field_expr}, \"expected non-nil value\")");
1524                } else if field_is_array {
1525                    let _ = writeln!(
1526                        out,
1527                        "        XCTAssertFalse({field_expr}.isEmpty, \"expected non-empty value\")"
1528                    );
1529                } else if result_is_simple {
1530                    // result_is_simple: result is a primitive (Data, String, etc.) — use .isEmpty directly.
1531                    let _ = writeln!(
1532                        out,
1533                        "        XCTAssertFalse({result_var}.isEmpty, \"expected non-empty value\")"
1534                    );
1535                } else {
1536                    // string_expr has .toString() appended; .isEmpty works on Swift String.
1537                    let _ = writeln!(
1538                        out,
1539                        "        XCTAssertFalse({string_expr}.isEmpty, \"expected non-empty value\")"
1540                    );
1541                }
1542            }
1543        }
1544        "is_empty" => {
1545            if bare_result_is_option {
1546                let _ = writeln!(out, "        XCTAssertNil({result_var}, \"expected nil value\")");
1547            } else if field_is_optional {
1548                let _ = writeln!(out, "        XCTAssertNil({field_expr}, \"expected nil value\")");
1549            } else if field_is_array {
1550                let _ = writeln!(
1551                    out,
1552                    "        XCTAssertTrue({field_expr}.isEmpty, \"expected empty value\")"
1553                );
1554            } else {
1555                let _ = writeln!(
1556                    out,
1557                    "        XCTAssertTrue({string_expr}.isEmpty, \"expected empty value\")"
1558                );
1559            }
1560        }
1561        "contains_any" => {
1562            if let Some(values) = &assertion.values {
1563                let checks: Vec<String> = values
1564                    .iter()
1565                    .map(|v| {
1566                        let swift_val = json_to_swift(v);
1567                        format!("{string_expr}.contains({swift_val})")
1568                    })
1569                    .collect();
1570                let joined = checks.join(" || ");
1571                let _ = writeln!(
1572                    out,
1573                    "        XCTAssertTrue({joined}, \"expected to contain at least one of the specified values\")"
1574                );
1575            }
1576        }
1577        "greater_than" => {
1578            if let Some(val) = &assertion.value {
1579                let swift_val = json_to_swift(val);
1580                // For optional numeric fields (or when the accessor chain is optional),
1581                // coalesce to 0 before comparing so the expression is non-optional.
1582                let field_is_optional = accessor_is_optional
1583                    || assertion.field.as_deref().is_some_and(|f| {
1584                        field_resolver.is_optional(f) || field_resolver.is_optional(field_resolver.resolve(f))
1585                    });
1586                let compare_expr = if field_is_optional {
1587                    format!("({field_expr} ?? 0)")
1588                } else {
1589                    field_expr.clone()
1590                };
1591                let _ = writeln!(out, "        XCTAssertGreaterThan({compare_expr}, {swift_val})");
1592            }
1593        }
1594        "less_than" => {
1595            if let Some(val) = &assertion.value {
1596                let swift_val = json_to_swift(val);
1597                let field_is_optional = accessor_is_optional
1598                    || assertion.field.as_deref().is_some_and(|f| {
1599                        field_resolver.is_optional(f) || field_resolver.is_optional(field_resolver.resolve(f))
1600                    });
1601                let compare_expr = if field_is_optional {
1602                    format!("({field_expr} ?? 0)")
1603                } else {
1604                    field_expr.clone()
1605                };
1606                let _ = writeln!(out, "        XCTAssertLessThan({compare_expr}, {swift_val})");
1607            }
1608        }
1609        "greater_than_or_equal" => {
1610            if let Some(val) = &assertion.value {
1611                let swift_val = json_to_swift(val);
1612                // For optional numeric fields (or when the accessor chain is optional),
1613                // coalesce to 0 before comparing so the expression is non-optional.
1614                let field_is_optional = accessor_is_optional
1615                    || assertion.field.as_deref().is_some_and(|f| {
1616                        field_resolver.is_optional(f) || field_resolver.is_optional(field_resolver.resolve(f))
1617                    });
1618                let compare_expr = if field_is_optional {
1619                    format!("({field_expr} ?? 0)")
1620                } else {
1621                    field_expr.clone()
1622                };
1623                let _ = writeln!(out, "        XCTAssertGreaterThanOrEqual({compare_expr}, {swift_val})");
1624            }
1625        }
1626        "less_than_or_equal" => {
1627            if let Some(val) = &assertion.value {
1628                let swift_val = json_to_swift(val);
1629                let field_is_optional = accessor_is_optional
1630                    || assertion.field.as_deref().is_some_and(|f| {
1631                        field_resolver.is_optional(f) || field_resolver.is_optional(field_resolver.resolve(f))
1632                    });
1633                let compare_expr = if field_is_optional {
1634                    format!("({field_expr} ?? 0)")
1635                } else {
1636                    field_expr.clone()
1637                };
1638                let _ = writeln!(out, "        XCTAssertLessThanOrEqual({compare_expr}, {swift_val})");
1639            }
1640        }
1641        "starts_with" => {
1642            if let Some(expected) = &assertion.value {
1643                let swift_val = json_to_swift(expected);
1644                let _ = writeln!(
1645                    out,
1646                    "        XCTAssertTrue({string_expr}.hasPrefix({swift_val}), \"expected to start with: \\({swift_val})\")"
1647                );
1648            }
1649        }
1650        "ends_with" => {
1651            if let Some(expected) = &assertion.value {
1652                let swift_val = json_to_swift(expected);
1653                let _ = writeln!(
1654                    out,
1655                    "        XCTAssertTrue({string_expr}.hasSuffix({swift_val}), \"expected to end with: \\({swift_val})\")"
1656                );
1657            }
1658        }
1659        "min_length" => {
1660            if let Some(val) = &assertion.value {
1661                if let Some(n) = val.as_u64() {
1662                    // Use string_expr.count: for RustString fields string_expr already has
1663                    // .toString() appended, giving a Swift String whose .count is character count.
1664                    let _ = writeln!(out, "        XCTAssertGreaterThanOrEqual({string_expr}.count, {n})");
1665                }
1666            }
1667        }
1668        "max_length" => {
1669            if let Some(val) = &assertion.value {
1670                if let Some(n) = val.as_u64() {
1671                    let _ = writeln!(out, "        XCTAssertLessThanOrEqual({string_expr}.count, {n})");
1672                }
1673            }
1674        }
1675        "count_min" => {
1676            if let Some(val) = &assertion.value {
1677                if let Some(n) = val.as_u64() {
1678                    // For fields nested inside an optional parent (e.g. document.nodes where
1679                    // document is Optional), the accessor generates `result.document().nodes()`
1680                    // which doesn't compile in Swift without optional chaining.
1681                    let count_expr = swift_array_count_expr(assertion.field.as_deref(), result_var, field_resolver);
1682                    let _ = writeln!(out, "        XCTAssertGreaterThanOrEqual({count_expr}, {n})");
1683                }
1684            }
1685        }
1686        "count_equals" => {
1687            if let Some(val) = &assertion.value {
1688                if let Some(n) = val.as_u64() {
1689                    let count_expr = swift_array_count_expr(assertion.field.as_deref(), result_var, field_resolver);
1690                    let _ = writeln!(out, "        XCTAssertEqual({count_expr}, {n})");
1691                }
1692            }
1693        }
1694        "is_true" => {
1695            let _ = writeln!(out, "        XCTAssertTrue({field_expr})");
1696        }
1697        "is_false" => {
1698            let _ = writeln!(out, "        XCTAssertFalse({field_expr})");
1699        }
1700        "matches_regex" => {
1701            if let Some(expected) = &assertion.value {
1702                let swift_val = json_to_swift(expected);
1703                let _ = writeln!(
1704                    out,
1705                    "        XCTAssertNotNil({string_expr}.range(of: {swift_val}, options: .regularExpression), \"expected value to match regex: \\({swift_val})\")"
1706                );
1707            }
1708        }
1709        "not_error" => {
1710            // Already handled by the call succeeding without exception.
1711        }
1712        "error" => {
1713            // Handled at the test method level.
1714        }
1715        "method_result" => {
1716            let _ = writeln!(out, "        // method_result assertions not yet implemented for Swift");
1717        }
1718        other => {
1719            panic!("Swift e2e generator: unsupported assertion type: {other}");
1720        }
1721    }
1722}
1723
1724/// Build a Swift accessor path for the given fixture field, inserting `()` on
1725/// every segment and `?` after every optional non-leaf segment.
1726///
1727/// This is the core helper for count/contains helpers that need to reconstruct
1728/// the path with correct optional chaining from the raw fixture field name.
1729///
1730/// Rewrite a Swift accessor expression to capture any `RustVec` temporaries
1731/// in a local before subscripting them. Returns `(setup_lines, rewritten_expr)`.
1732///
1733/// swift-bridge's `Vec_<T>$get` returns a raw pointer into the Vec's storage
1734/// wrapped in a `T.SelfRef`. If the Vec was a temporary, ARC may release it
1735/// before the ref is dereferenced, leaving the pointer dangling and reads
1736/// returning empty/garbage. Hoisting the Vec into a `let` binding ties the
1737/// Vec's lifetime to the enclosing function scope, so the ref stays valid.
1738///
1739/// Only the first `()[...]` occurrence per expression is materialised — that
1740/// covers all current fixture access patterns (single-level subscripts on a
1741/// result field). Nested subscripts are rare and would need a more elaborate
1742/// pass; if they appear, this returns conservative output (just the first
1743/// hoist) which is still correct.
1744fn materialise_vec_temporaries(expr: &str, name_suffix: &str) -> (Vec<String>, String) {
1745    let Some(idx) = expr.find("()[") else {
1746        return (Vec::new(), expr.to_string());
1747    };
1748    let after_open = idx + 3; // position after `()[`
1749    let Some(close_rel) = expr[after_open..].find(']') else {
1750        return (Vec::new(), expr.to_string());
1751    };
1752    let subscript_end = after_open + close_rel; // index of `]`
1753    let prefix = &expr[..idx + 2]; // includes `()`
1754    let subscript = &expr[idx + 2..=subscript_end]; // `[N]`
1755    let tail = &expr[subscript_end + 1..]; // everything after `]`
1756    let method_dot = expr[..idx].rfind('.').unwrap_or(0);
1757    let method = &expr[method_dot + 1..idx];
1758    let local = format!("_vec_{}_{}", method, name_suffix);
1759    let setup = format!("let {local} = {prefix}");
1760    let rewritten = format!("{local}{subscript}{tail}");
1761    (vec![setup], rewritten)
1762}
1763
1764/// Returns `(accessor_expr, has_optional)` where `has_optional` is true when
1765/// at least one `?.` was inserted.
1766fn swift_build_accessor(field: &str, result_var: &str, field_resolver: &FieldResolver) -> (String, bool) {
1767    let resolved = field_resolver.resolve(field);
1768    let parts: Vec<&str> = resolved.split('.').collect();
1769
1770    // Build a set of optional prefix paths for O(1) lookup during the walk.
1771    // We track path_so_far incrementally.
1772    let mut out = result_var.to_string();
1773    let mut has_optional = false;
1774    let mut path_so_far = String::new();
1775    let total = parts.len();
1776    for (i, part) in parts.iter().enumerate() {
1777        let is_leaf = i == total - 1;
1778        // Handle array index subscripts within a segment, e.g. `data[0]`.
1779        // `data[0]` must become `.data()[0]` not `.data[0]()`.
1780        // Split at the first `[` if present.
1781        let (field_name, subscript): (&str, Option<&str>) = if let Some(bracket_pos) = part.find('[') {
1782            (&part[..bracket_pos], Some(&part[bracket_pos..]))
1783        } else {
1784            (part, None)
1785        };
1786
1787        if !path_so_far.is_empty() {
1788            path_so_far.push('.');
1789        }
1790        // Build the base path (without subscript) for the optional check. When the
1791        // segment is e.g. `tool_calls[0]`, we want to check `is_optional` against
1792        // "choices[0].message.tool_calls" not "choices[0].message.tool_calls[0]".
1793        let base_path = {
1794            let mut p = path_so_far.clone();
1795            p.push_str(field_name);
1796            p
1797        };
1798        // Now push the full part (with subscript if any) so path_so_far is correct
1799        // for subsequent segment checks.
1800        path_so_far.push_str(part);
1801
1802        out.push('.');
1803        out.push_str(field_name);
1804        if let Some(sub) = subscript {
1805            // When the getter for this subscripted field is itself optional
1806            // (e.g. tool_calls returns Optional<RustVec<T>>), insert `?` before
1807            // the subscript so Swift unwraps the Optional before indexing.
1808            let field_is_optional = field_resolver.is_optional(&base_path);
1809            if field_is_optional {
1810                out.push_str("()?");
1811                has_optional = true;
1812            } else {
1813                out.push_str("()");
1814            }
1815            out.push_str(sub);
1816            // Do NOT append a trailing `?` after the subscript index: in Swift,
1817            // `optionalVec?[N]` via `Collection.subscript` returns the element
1818            // type `T` directly (the subscript is non-optional and the force-unwrap
1819            // inside RustVec's subscript is unconditional).  Optional chaining
1820            // already consumed the `?` in `?[N]`, so the result is `T` (non-optional
1821            // in the compiler's view), and a subsequent `?.member()` would be flagged
1822            // as "optional chaining on non-optional value".  The parent `has_optional`
1823            // flag is still set when `field_is_optional` is true, which causes the
1824            // enclosing expression to be wrapped in `(... ?? fallback)` correctly.
1825        } else {
1826            out.push_str("()");
1827            // Insert `?` after `()` for non-leaf optional fields so the next
1828            // member access becomes `?.`.
1829            if !is_leaf && field_resolver.is_optional(&base_path) {
1830                out.push('?');
1831                has_optional = true;
1832            }
1833        }
1834    }
1835    (out, has_optional)
1836}
1837
1838/// Generate a `[String]?` expression for a `RustVec<RustString>` (or optional variant) field
1839/// so that `contains` membership checks work against plain Swift Strings.
1840///
1841/// The result is `Optional<[String]>` — callers should coalesce with `?? []`.
1842///
1843/// We use `?.map { $0.as_str().toString() }` because:
1844/// 1. Iterating a `RustVec<RustString>` yields `RustStringRef` (not `RustString`), which
1845///    only has `as_str()` but not `toString()` directly.
1846/// 2. The accessor may end with an `Optional<RustVec<RustString>>` (e.g. `sheet_names()` is
1847///    `Option<Vec<String>>` in Rust, which becomes `Optional<RustVec<RustString>>` in Swift).
1848/// 3. Optional chaining from parent `?.` already produces `Optional<RustVec<T>>`.
1849///
1850/// `?.map { $0.as_str().toString() }` converts each `RustStringRef` to a Swift `String`,
1851/// giving `[String]` wrapped in `Optional`. The `?? []` in callers coalesces nil to an empty
1852/// array.
1853/// Generate a `XCTAssert{True|False}(array.contains(where: { elem_str.contains(val) }), msg)` line
1854/// for field paths that traverse a collection with `[].` notation (e.g. `links[].url`).
1855///
1856/// `array_part` — left side of `[].` (e.g. `"links"`)
1857/// `element_part` — right side (e.g. `"url"` or `"link_type"`)
1858/// `full_field` — original assertion.field (used for enum lookup against the full path)
1859#[allow(clippy::too_many_arguments)]
1860fn swift_traversal_contains_assert(
1861    array_part: &str,
1862    element_part: &str,
1863    full_field: &str,
1864    val_expr: &str,
1865    result_var: &str,
1866    negate: bool,
1867    msg: &str,
1868    enum_fields: &std::collections::HashSet<String>,
1869    field_resolver: &FieldResolver,
1870) -> String {
1871    let array_accessor = field_resolver.accessor(array_part, "swift", result_var);
1872    let resolved_full = field_resolver.resolve(full_field);
1873    let resolved_elem_part = resolved_full
1874        .find("[].")
1875        .map(|d| &resolved_full[d + 3..])
1876        .unwrap_or(element_part);
1877    let elem_accessor = field_resolver.accessor(resolved_elem_part, "swift", "$0");
1878    let elem_is_enum = enum_fields.contains(full_field) || enum_fields.contains(resolved_full);
1879    let elem_is_optional = field_resolver.is_optional(resolved_elem_part)
1880        || field_resolver.is_optional(field_resolver.resolve(resolved_elem_part));
1881    let elem_str = if elem_is_enum {
1882        // Enum-typed fields are bridged as `String` (RustString in Swift).
1883        // A single `.toString()` converts RustString → Swift String.
1884        format!("{elem_accessor}.toString()")
1885    } else if elem_is_optional {
1886        format!("({elem_accessor}?.toString() ?? \"\")")
1887    } else {
1888        format!("{elem_accessor}.toString()")
1889    };
1890    let assert_fn = if negate { "XCTAssertFalse" } else { "XCTAssertTrue" };
1891    format!("        {assert_fn}({array_accessor}.contains(where: {{ {elem_str}.contains({val_expr}) }}), \"{msg}\")")
1892}
1893
1894fn swift_array_contains_expr(field: Option<&str>, result_var: &str, field_resolver: &FieldResolver) -> String {
1895    let Some(f) = field else {
1896        return format!("{result_var}.map {{ $0.as_str().toString() }}");
1897    };
1898    let (accessor, _has_optional) = swift_build_accessor(f, result_var, field_resolver);
1899    // Always use `?.map` — the array field (sheet_names, etc.) may itself return
1900    // Optional<RustVec<T>> even if not listed in fields_optional.
1901    format!("{accessor}?.map {{ $0.as_str().toString() }}")
1902}
1903
1904/// Generate a `.count` expression for an array field that may be nested inside optional parents.
1905///
1906/// Swift-bridge exposes all Rust fields as methods with `()`. When ancestor segments are
1907/// optional, we use `?.` chaining. The final count is coalesced with `?? 0` when there
1908/// are optional ancestors so the XCTAssert macro receives a non-optional `Int`.
1909///
1910/// Also check if the field itself (the leaf) is optional, which happens when the field
1911/// returns Optional<RustVec<T>> (e.g., `links()` may return Optional).
1912fn swift_array_count_expr(field: Option<&str>, result_var: &str, field_resolver: &FieldResolver) -> String {
1913    let Some(f) = field else {
1914        return format!("{result_var}.count");
1915    };
1916    let (accessor, mut has_optional) = swift_build_accessor(f, result_var, field_resolver);
1917    // Also check if the leaf field itself is optional.
1918    if field_resolver.is_optional(f) {
1919        has_optional = true;
1920    }
1921    if has_optional {
1922        // In Swift, accessing .count on an optional with ?. returns Optional<Int>,
1923        // so we coalesce with ?? 0 to get a concrete Int for XCTAssert.
1924        if accessor.contains("?.") {
1925            format!("{accessor}.count ?? 0")
1926        } else {
1927            // If no ?. but field is optional, the field_expr itself is Optional<RustVec<T>>
1928            // so we need ?. to call count.
1929            format!("({accessor}?.count ?? 0)")
1930        }
1931    } else {
1932        format!("{accessor}.count")
1933    }
1934}
1935
1936/// Normalise a path by resolving `..` components without hitting the filesystem.
1937///
1938/// This mirrors what `std::fs::canonicalize` does but works on paths that do
1939/// not yet exist on disk (generated-file paths).  Only `..` traversals are
1940/// collapsed; `.` components are dropped; nothing else is changed.
1941fn normalize_path(path: &std::path::Path) -> std::path::PathBuf {
1942    let mut components = std::path::PathBuf::new();
1943    for component in path.components() {
1944        match component {
1945            std::path::Component::ParentDir => {
1946                // Pop the last pushed component if there is one that isn't
1947                // already a `..` (avoids over-collapsing `../../foo`).
1948                if !components.as_os_str().is_empty() {
1949                    components.pop();
1950                } else {
1951                    components.push(component);
1952                }
1953            }
1954            std::path::Component::CurDir => {}
1955            other => components.push(other),
1956        }
1957    }
1958    components
1959}
1960
1961/// Convert a `serde_json::Value` to a Swift literal string.
1962fn json_to_swift(value: &serde_json::Value) -> String {
1963    match value {
1964        serde_json::Value::String(s) => format!("\"{}\"", escape_swift(s)),
1965        serde_json::Value::Bool(b) => b.to_string(),
1966        serde_json::Value::Number(n) => n.to_string(),
1967        serde_json::Value::Null => "nil".to_string(),
1968        serde_json::Value::Array(arr) => {
1969            let items: Vec<String> = arr.iter().map(json_to_swift).collect();
1970            format!("[{}]", items.join(", "))
1971        }
1972        serde_json::Value::Object(_) => {
1973            let json_str = serde_json::to_string(value).unwrap_or_default();
1974            format!("\"{}\"", escape_swift(&json_str))
1975        }
1976    }
1977}
1978
1979/// Escape a string for embedding in a Swift double-quoted string literal.
1980fn escape_swift(s: &str) -> String {
1981    escape_swift_str(s)
1982}
1983
1984#[cfg(test)]
1985mod tests {
1986    use super::*;
1987    use crate::field_access::FieldResolver;
1988    use std::collections::{HashMap, HashSet};
1989
1990    fn make_resolver_tool_calls() -> FieldResolver {
1991        // Resolver for `choices[0].message.tool_calls[0].function.name`:
1992        //   - `choices` is a registered array field
1993        //   - `choices.message.tool_calls` is optional (Optional<RustVec<ToolCall>>)
1994        let mut optional = HashSet::new();
1995        optional.insert("choices.message.tool_calls".to_string());
1996        let mut arrays = HashSet::new();
1997        arrays.insert("choices".to_string());
1998        FieldResolver::new(&HashMap::new(), &optional, &HashSet::new(), &arrays, &HashSet::new())
1999    }
2000
2001    /// Regression: after `tool_calls()?[0]` the codegen must NOT append a trailing `?`
2002    /// before the next segment.  The Swift compiler sees `?[0]` as consuming the optional
2003    /// chain, yielding `ToolCallRef` (non-optional from the subscript's perspective), so
2004    /// `?.function()` triggers "cannot use optional chaining on non-optional value".
2005    ///
2006    /// The fix: do not emit `?` after the subscript index for non-leaf segments.
2007    #[test]
2008    fn optional_vec_subscript_does_not_emit_trailing_question_mark_before_next_segment() {
2009        let resolver = make_resolver_tool_calls();
2010        // Access `choices[0].message.tool_calls[0].function.name`:
2011        //   `tool_calls` is optional, `function` and `name` are non-optional.
2012        let (accessor, has_optional) =
2013            swift_build_accessor("choices[0].message.tool_calls[0].function.name", "result", &resolver);
2014        // `?` before `[0]` is correct (tool_calls is optional).
2015        // swift_build_accessor uses the raw field name without camelCase conversion.
2016        assert!(
2017            accessor.contains("tool_calls()?[0]"),
2018            "expected `tool_calls()?[0]` for optional tool_calls, got: {accessor}"
2019        );
2020        // There must NOT be `?[0]?` (trailing `?` after the index).
2021        assert!(
2022            !accessor.contains("?[0]?"),
2023            "must not emit trailing `?` after subscript index: {accessor}"
2024        );
2025        // The expression IS optional overall (tool_calls may be nil).
2026        assert!(has_optional, "expected has_optional=true for optional field chain");
2027        // Subsequent member access uses `.` (non-optional chain) not `?.`.
2028        assert!(
2029            accessor.contains("[0].function()"),
2030            "expected `.function()` (non-optional) after subscript: {accessor}"
2031        );
2032    }
2033}