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, 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    let result_is_simple =
587        call_config.result_is_simple || call_overrides.is_some_and(|o| o.result_is_simple) || result_is_simple;
588    let result_is_array = call_config.result_is_array;
589
590    let method_name = fixture.id.to_upper_camel_case();
591    let description = &fixture.description;
592    let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
593    let is_async = call_config.r#async;
594
595    // Detect whether this call has any json_object args that cannot be constructed
596    // in Swift — swift-bridge opaque types do not provide a fromJson initialiser.
597    // When such args exist and no `options_via` is configured for swift, emit a
598    // skip stub so the test compiles but is recorded as skipped rather than
599    // generating invalid code that passes `nil` or a string literal where a
600    // strongly-typed request object is required.
601    let has_unresolvable_json_object_arg = {
602        let options_via = call_overrides.and_then(|o| o.options_via.as_deref());
603        options_via.is_none() && args.iter().any(|a| a.arg_type == "json_object" && a.name != "config")
604    };
605
606    if has_unresolvable_json_object_arg {
607        if is_async {
608            let _ = writeln!(out, "    func test{method_name}() async throws {{");
609        } else {
610            let _ = writeln!(out, "    func test{method_name}() throws {{");
611        }
612        let _ = writeln!(out, "        // {description}");
613        let _ = writeln!(
614            out,
615            "        try XCTSkipIf(true, \"swift: json_object request construction requires options_via configuration (fixture: {})\");",
616            fixture.id
617        );
618        let _ = writeln!(out, "    }}");
619        return;
620    }
621
622    // Resolve extra_args from per-call swift overrides (e.g. `nil` for optional
623    // query-param arguments on list_files/list_batches that have no fixture-level
624    // input field).
625    let extra_args: Vec<String> = call_overrides.map(|o| o.extra_args.clone()).unwrap_or_default();
626
627    // Merge per-call enum_fields keys into the effective enum set so that
628    // fields like "status" (BatchStatus, BatchObject) are treated as enum-typed
629    // even when they are not globally listed in fields_enum (they are context-
630    // dependent — BatchStatus on BatchObject but plain String on ResponseObject).
631    let effective_enum_fields: std::borrow::Cow<HashSet<String>> = {
632        let per_call = call_overrides.map(|o| &o.enum_fields);
633        if let Some(pc) = per_call {
634            if !pc.is_empty() {
635                let mut merged = enum_fields.clone();
636                merged.extend(pc.keys().cloned());
637                std::borrow::Cow::Owned(merged)
638            } else {
639                std::borrow::Cow::Borrowed(enum_fields)
640            }
641        } else {
642            std::borrow::Cow::Borrowed(enum_fields)
643        }
644    };
645
646    let options_via_str: Option<&str> = call_overrides.and_then(|o| o.options_via.as_deref());
647    let options_type_str: Option<&str> = call_overrides.and_then(|o| o.options_type.as_deref());
648    let (setup_lines, args_str) =
649        build_args_and_setup(&fixture.input, args, &fixture.id, &function_name, options_via_str, options_type_str);
650
651    // Append extra_args to the argument list.
652    let args_str = if extra_args.is_empty() {
653        args_str
654    } else if args_str.is_empty() {
655        extra_args.join(", ")
656    } else {
657        format!("{args_str}, {}", extra_args.join(", "))
658    };
659
660    // When a client_factory is set, dispatch via a client instance:
661    //   let client = try <FactoryType>(apiKey: "test-key", baseUrl: <mock_url>)
662    //   try await client.<method>(args)
663    // Otherwise fall back to free-function call (Kreuzberg / non-client-factory libraries).
664    let has_mock = fixture.mock_response.is_some();
665    let (call_setup, call_expr) = if let Some(_factory) = client_factory {
666        let mock_url = format!(
667            "ProcessInfo.processInfo.environment[\"MOCK_SERVER_URL\"]! + \"/fixtures/{}\"",
668            fixture.id
669        );
670        let client_constructor = if has_mock {
671            format!("let _client = try DefaultClient(apiKey: \"test-key\", baseUrl: {mock_url})")
672        } else {
673            // Live API: check for api_key_var; if not present use mock URL anyway.
674            if let Some(env_var) = fixture.env.as_ref().and_then(|e| e.api_key_var.as_deref()) {
675                format!(
676                    "let _apiKey = ProcessInfo.processInfo.environment[\"{env_var}\"]\n        \
677                     let _baseUrl: String? = _apiKey != nil ? nil : {mock_url}\n        \
678                     let _client = try DefaultClient(apiKey: _apiKey ?? \"test-key\", baseUrl: _baseUrl)"
679                )
680            } else {
681                format!("let _client = try DefaultClient(apiKey: \"test-key\", baseUrl: {mock_url})")
682            }
683        };
684        let expr = if is_async {
685            format!("try await _client.{function_name}({args_str})")
686        } else {
687            format!("try _client.{function_name}({args_str})")
688        };
689        (Some(client_constructor), expr)
690    } else {
691        // Free-function call (no client_factory).
692        let expr = if is_async {
693            format!("try await {function_name}({args_str})")
694        } else {
695            format!("try {function_name}({args_str})")
696        };
697        (None, expr)
698    };
699    // For backwards compatibility: qualified_function_name unused when client_factory is set.
700    let _ = function_name;
701
702    if is_async {
703        let _ = writeln!(out, "    func test{method_name}() async throws {{");
704    } else {
705        let _ = writeln!(out, "    func test{method_name}() throws {{");
706    }
707    let _ = writeln!(out, "        // {description}");
708
709    for line in &setup_lines {
710        let _ = writeln!(out, "        {line}");
711    }
712
713    // Emit client construction if a client_factory is configured.
714    if let Some(setup) = &call_setup {
715        let _ = writeln!(out, "        {setup}");
716    }
717
718    if expects_error {
719        if is_async {
720            // XCTAssertThrowsError is a synchronous macro; for async-throwing
721            // functions use a do/catch with explicit XCTFail to enforce that
722            // the throw actually happens. `await XCTAssertThrowsError(...)` is
723            // not valid Swift — it evaluates `await` against a non-async expr.
724            let _ = writeln!(out, "        do {{");
725            let _ = writeln!(out, "            _ = {call_expr}");
726            let _ = writeln!(out, "            XCTFail(\"expected to throw\")");
727            let _ = writeln!(out, "        }} catch {{");
728            let _ = writeln!(out, "            // success");
729            let _ = writeln!(out, "        }}");
730        } else {
731            let _ = writeln!(out, "        XCTAssertThrowsError({call_expr})");
732        }
733        let _ = writeln!(out, "    }}");
734        return;
735    }
736
737    let _ = writeln!(out, "        let {result_var} = {call_expr}");
738
739    for assertion in &fixture.assertions {
740        render_assertion(
741            out,
742            assertion,
743            result_var,
744            field_resolver,
745            result_is_simple,
746            result_is_array,
747            &effective_enum_fields,
748        );
749    }
750
751    let _ = writeln!(out, "    }}");
752}
753
754/// Build setup lines and the argument list for the function call.
755///
756/// Swift-bridge wrappers require strongly-typed values that don't have implicit
757/// Swift literal conversions:
758///
759/// - `bytes` args become `RustVec<UInt8>` — fixture supplies a relative file path
760///   string which is read at test time and pushed into a `RustVec<UInt8>` setup
761///   variable. A literal byte array is base64-decoded or UTF-8 encoded inline.
762/// - `json_object` args become opaque `ExtractionConfig` (or sibling) instances —
763///   a JSON string is decoded via `extractionConfigFromJson(...)` in a setup line.
764/// - Optional args missing from the fixture must still appear at the call site
765///   as `nil` whenever a later positional arg is present, otherwise Swift slots
766///   subsequent values into the wrong parameter.
767fn build_args_and_setup(
768    input: &serde_json::Value,
769    args: &[crate::config::ArgMapping],
770    fixture_id: &str,
771    function_name: &str,
772    options_via: Option<&str>,
773    options_type: Option<&str>,
774) -> (Vec<String>, String) {
775    if args.is_empty() {
776        return (Vec::new(), String::new());
777    }
778
779    let mut setup_lines: Vec<String> = Vec::new();
780    let mut parts: Vec<String> = Vec::new();
781
782    // Pre-compute, for each arg index, whether any later arg has a fixture-provided
783    // value (or is required and will emit a default). When an optional arg is empty
784    // but a later arg WILL emit, we must keep the slot with `nil` so positional
785    // alignment is preserved.
786    let later_emits: Vec<bool> = (0..args.len())
787        .map(|i| {
788            args.iter().skip(i + 1).any(|a| {
789                let f = a.field.strip_prefix("input.").unwrap_or(&a.field);
790                let v = input.get(f);
791                let has_value = matches!(v, Some(x) if !x.is_null());
792                has_value || !a.optional || (a.arg_type == "json_object" && a.name == "config")
793            })
794        })
795        .collect();
796
797    for (idx, arg) in args.iter().enumerate() {
798        if arg.arg_type == "mock_url" {
799            setup_lines.push(format!(
800                "let {} = ProcessInfo.processInfo.environment[\"MOCK_SERVER_URL\"]! + \"/fixtures/{fixture_id}\"",
801                arg.name,
802            ));
803            parts.push(arg.name.clone());
804            continue;
805        }
806
807        if arg.arg_type == "handle" {
808            let var_name = format!("{}Obj", arg.name.to_lower_camel_case());
809            setup_lines.push(format!("let {var_name} = try createEngine(nil)"));
810            parts.push(var_name);
811            continue;
812        }
813
814        // bytes args: fixture stores a fixture-relative path string. Generate
815        // setup that reads it into a Data and pushes each byte into a
816        // RustVec<UInt8>. Literal byte arrays inline the bytes; missing values
817        // produce an empty vec (or `nil` when optional).
818        if arg.arg_type == "bytes" {
819            let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
820            let val = input.get(field);
821            match val {
822                None | Some(serde_json::Value::Null) if arg.optional => {
823                    if later_emits[idx] {
824                        parts.push("nil".to_string());
825                    }
826                }
827                None | Some(serde_json::Value::Null) => {
828                    let var_name = format!("{}Vec", arg.name.to_lower_camel_case());
829                    setup_lines.push(format!("let {var_name} = RustVec<UInt8>()"));
830                    parts.push(var_name);
831                }
832                Some(serde_json::Value::String(s)) => {
833                    let escaped = escape_swift(s);
834                    let var_name = format!("{}Vec", arg.name.to_lower_camel_case());
835                    let data_var = format!("{}Data", arg.name.to_lower_camel_case());
836                    setup_lines.push(format!(
837                        "let {data_var} = try Data(contentsOf: URL(fileURLWithPath: \"{escaped}\"))"
838                    ));
839                    setup_lines.push(format!("let {var_name} = RustVec<UInt8>()"));
840                    setup_lines.push(format!("for _byte in {data_var} {{ {var_name}.push(value: _byte) }}"));
841                    parts.push(var_name);
842                }
843                Some(serde_json::Value::Array(arr)) => {
844                    let var_name = format!("{}Vec", arg.name.to_lower_camel_case());
845                    setup_lines.push(format!("let {var_name} = RustVec<UInt8>()"));
846                    for v in arr {
847                        if let Some(n) = v.as_u64() {
848                            setup_lines.push(format!("{var_name}.push(value: UInt8({n}))"));
849                        }
850                    }
851                    parts.push(var_name);
852                }
853                Some(other) => {
854                    // Fallback: encode the JSON serialisation as UTF-8 bytes.
855                    let json_str = serde_json::to_string(other).unwrap_or_default();
856                    let escaped = escape_swift(&json_str);
857                    let var_name = format!("{}Vec", arg.name.to_lower_camel_case());
858                    setup_lines.push(format!("let {var_name} = RustVec<UInt8>()"));
859                    setup_lines.push(format!(
860                        "for _byte in Array(\"{escaped}\".utf8) {{ {var_name}.push(value: _byte) }}"
861                    ));
862                    parts.push(var_name);
863                }
864            }
865            continue;
866        }
867
868        // json_object "config" args: the swift-bridge wrapper requires an opaque
869        // `ExtractionConfig` (or sibling) instance, not a JSON string. Use the
870        // generated `extractionConfigFromJson(_:)` helper from RustBridge.
871        // Batch functions (batchExtract*) hardcode config internally — skip it.
872        let is_config_arg = arg.name == "config" && arg.arg_type == "json_object";
873        let is_batch_fn = function_name.starts_with("batch") || function_name.starts_with("Batch");
874        if is_config_arg && !is_batch_fn {
875            let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
876            let val = input.get(field);
877            let json_str = match val {
878                None | Some(serde_json::Value::Null) => "{}".to_string(),
879                Some(v) => serde_json::to_string(v).unwrap_or_else(|_| "{}".to_string()),
880            };
881            let escaped = escape_swift(&json_str);
882            let var_name = format!("{}Obj", arg.name.to_lower_camel_case());
883            setup_lines.push(format!("let {var_name} = try extractionConfigFromJson(\"{escaped}\")"));
884            parts.push(var_name);
885            continue;
886        }
887
888        // json_object non-config args with options_via = "from_json":
889        // Use the generated `{typeCamelCase}FromJson(_:)` helper so the fixture JSON is
890        // deserialised into the opaque swift-bridge type rather than passed as a raw string.
891        // When arg.field == "input", the entire fixture input IS the request object.
892        if arg.arg_type == "json_object" && options_via == Some("from_json") {
893            if let Some(type_name) = options_type {
894                let resolved_val = super::resolve_field(input, &arg.field);
895                let json_str = match resolved_val {
896                    serde_json::Value::Null => "{}".to_string(),
897                    v => serde_json::to_string(v).unwrap_or_else(|_| "{}".to_string()),
898                };
899                let escaped = escape_swift(&json_str);
900                let var_name = format!("_{}", arg.name.to_lower_camel_case());
901                let from_json_fn = format!("{}FromJson", type_name.to_lower_camel_case());
902                setup_lines.push(format!("let {var_name} = try {from_json_fn}(\"{escaped}\")"));
903                parts.push(var_name);
904                continue;
905            }
906        }
907
908        let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
909        let val = input.get(field);
910        match val {
911            None | Some(serde_json::Value::Null) if arg.optional => {
912                // Optional arg with no fixture value: keep the slot with `nil`
913                // when a later arg will emit, so positional alignment matches
914                // the swift-bridge wrapper signature.
915                if later_emits[idx] {
916                    parts.push("nil".to_string());
917                }
918            }
919            None | Some(serde_json::Value::Null) => {
920                let default_val = match arg.arg_type.as_str() {
921                    "string" => "\"\"".to_string(),
922                    "int" | "integer" => "0".to_string(),
923                    "float" | "number" => "0.0".to_string(),
924                    "bool" | "boolean" => "false".to_string(),
925                    _ => "nil".to_string(),
926                };
927                parts.push(default_val);
928            }
929            Some(v) => {
930                parts.push(json_to_swift(v));
931            }
932        }
933    }
934
935    (setup_lines, parts.join(", "))
936}
937
938fn render_assertion(
939    out: &mut String,
940    assertion: &Assertion,
941    result_var: &str,
942    field_resolver: &FieldResolver,
943    result_is_simple: bool,
944    result_is_array: bool,
945    enum_fields: &HashSet<String>,
946) {
947    // Skip assertions on fields that don't exist on the result type.
948    if let Some(f) = &assertion.field {
949        if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
950            let _ = writeln!(out, "        // skipped: field '{{f}}' not available on result type");
951            return;
952        }
953    }
954
955    // Skip assertions that traverse a tagged-union variant boundary.
956    // In Swift, FormatMetadata and similar enum-backed opaque types are exposed as
957    // plain classes by swift-bridge — variant accessor methods (e.g., `.excel()`)
958    // are not generated, so such assertions cannot be expressed.
959    if let Some(f) = &assertion.field {
960        if !f.is_empty() && field_resolver.tagged_union_split(f).is_some() {
961            let _ = writeln!(
962                out,
963                "        // skipped: field '{f}' crosses a tagged-union variant boundary (not expressible in Swift)"
964            );
965            return;
966        }
967    }
968
969    // Determine if this field is an enum type.
970    let field_is_enum = assertion
971        .field
972        .as_deref()
973        .is_some_and(|f| enum_fields.contains(f) || enum_fields.contains(field_resolver.resolve(f)));
974
975    let field_is_optional = assertion.field.as_deref().is_some_and(|f| {
976        !f.is_empty() && (field_resolver.is_optional(f) || field_resolver.is_optional(field_resolver.resolve(f)))
977    });
978    let field_is_array = assertion.field.as_deref().is_some_and(|f| {
979        !f.is_empty() && (field_resolver.is_array(f) || field_resolver.is_array(field_resolver.resolve(f)))
980    });
981
982    let field_expr = if result_is_simple {
983        result_var.to_string()
984    } else {
985        match &assertion.field {
986            Some(f) if !f.is_empty() => field_resolver.accessor(f, "swift", result_var),
987            _ => result_var.to_string(),
988        }
989    };
990
991    // In Swift, optional chaining with `?.` makes the result optional even if the
992    // called method's return type isn't marked optional. For example:
993    // `result.markdown()?.content()` returns `Optional<RustString>` because
994    // `markdown()` is optional and the `?.` operator wraps the result.
995    // Detect this by checking if the accessor contains `?.`.
996    let accessor_is_optional = field_expr.contains("?.");
997
998    // For enum fields, need to handle the string representation differently in Swift.
999    // Swift enums don't have `.rawValue` unless they're explicitly RawRepresentable.
1000    // Check if this is an enum type and handle accordingly.
1001    // For optional fields (Optional<RustString>), use optional chaining before toString().
1002    // For other fields: swift-bridge returns all Rust `String` fields as `RustString`.
1003    // We add .toString() here so string assertions (contains, hasPrefix, etc.) work.
1004    // Non-string opaque fields (DocumentStructure, etc.) should not appear in string
1005    // assertions — the fixture schema controls which assertions apply to which fields.
1006    let string_expr = if field_is_enum {
1007        // swift-bridge exposes enum types as opaque classes. The generated Rust wrapper
1008        // implements `fn to_string(&self) -> String` (swift-bridge keeps Rust name as
1009        // `.to_string()` returning `RustString`). `.toString()` converts RustString to Swift String.
1010        format!("{field_expr}.to_string().toString()")
1011    } else if field_is_optional {
1012        // Leaf field itself is Optional<RustString> — need ?.toString() to unwrap.
1013        format!("({field_expr}?.toString() ?? \"\")")
1014    } else if accessor_is_optional {
1015        // Ancestor optional chain propagates; leaf is non-optional RustString within chain.
1016        // Use .toString() directly — the whole expr is Optional<String> due to propagation.
1017        format!("({field_expr}.toString() ?? \"\")")
1018    } else {
1019        format!("{field_expr}.toString()")
1020    };
1021
1022    match assertion.assertion_type.as_str() {
1023        "equals" => {
1024            if let Some(expected) = &assertion.value {
1025                let swift_val = json_to_swift(expected);
1026                if expected.is_string() {
1027                    if field_is_enum {
1028                        // Enum fields: `toString()` on the opaque swift-bridge class returns a
1029                        // `RustString`; the second `.toString()` converts it to a Swift String.
1030                        // `string_expr` already incorporates this double call.
1031                        let trim_expr = format!("{string_expr}.trimmingCharacters(in: CharacterSet.whitespaces)");
1032                        let _ = writeln!(out, "        XCTAssertEqual({trim_expr}, {swift_val})");
1033                    } else {
1034                        // For optional strings (String?), use ?? to coalesce before trimming.
1035                        // `.toString()` converts RustString → Swift String before calling
1036                        // `.trimmingCharacters`, which requires a concrete String type.
1037                        // string_expr already incorporates field_is_optional via ?.toString() ?? "".
1038                        let trim_expr = format!("{string_expr}.trimmingCharacters(in: CharacterSet.whitespaces)");
1039                        let _ = writeln!(out, "        XCTAssertEqual({trim_expr}, {swift_val})");
1040                    }
1041                } else {
1042                    let _ = writeln!(out, "        XCTAssertEqual({field_expr}, {swift_val})");
1043                }
1044            }
1045        }
1046        "contains" => {
1047            if let Some(expected) = &assertion.value {
1048                let swift_val = json_to_swift(expected);
1049                // When the root result IS the array (result_is_simple + result_is_array) and
1050                // there is no field path, check array membership via map+contains.
1051                let no_field = assertion.field.as_deref().is_none_or(|f| f.is_empty());
1052                if result_is_simple && result_is_array && no_field {
1053                    // RustVec<RustString> iteration yields RustStringRef (no `toString()`);
1054                    // use `.as_str().toString()` to convert each element to a Swift String.
1055                    let _ = writeln!(
1056                        out,
1057                        "        XCTAssertTrue({result_var}.map {{ $0.as_str().toString() }}.contains({swift_val}), \"expected to contain: \\({swift_val})\")"
1058                    );
1059                } else {
1060                    // For array fields (RustVec<RustString>), check membership via map+contains.
1061                    let field_is_array = assertion
1062                        .field
1063                        .as_deref()
1064                        .is_some_and(|f| field_resolver.is_array(field_resolver.resolve(f)));
1065                    if field_is_array {
1066                        let contains_expr =
1067                            swift_array_contains_expr(assertion.field.as_deref(), result_var, field_resolver);
1068                        let _ = writeln!(
1069                            out,
1070                            "        XCTAssertTrue(({contains_expr} ?? []).contains({swift_val}), \"expected to contain: \\({swift_val})\")"
1071                        );
1072                    } else if field_is_enum {
1073                        // Enum fields: use `toString().toString()` (via string_expr) to get the
1074                        // serde variant name as a Swift String, then check substring containment.
1075                        let _ = writeln!(
1076                            out,
1077                            "        XCTAssertTrue({string_expr}.contains({swift_val}), \"expected to contain: \\({swift_val})\")"
1078                        );
1079                    } else {
1080                        let _ = writeln!(
1081                            out,
1082                            "        XCTAssertTrue({string_expr}.contains({swift_val}), \"expected to contain: \\({swift_val})\")"
1083                        );
1084                    }
1085                }
1086            }
1087        }
1088        "contains_all" => {
1089            if let Some(values) = &assertion.values {
1090                // For array fields (RustVec<RustString>), check membership via map+contains.
1091                let field_is_array = assertion
1092                    .field
1093                    .as_deref()
1094                    .is_some_and(|f| field_resolver.is_array(field_resolver.resolve(f)));
1095                if field_is_array {
1096                    let contains_expr =
1097                        swift_array_contains_expr(assertion.field.as_deref(), result_var, field_resolver);
1098                    for val in values {
1099                        let swift_val = json_to_swift(val);
1100                        let _ = writeln!(
1101                            out,
1102                            "        XCTAssertTrue(({contains_expr} ?? []).contains({swift_val}), \"expected to contain: \\({swift_val})\")"
1103                        );
1104                    }
1105                } else if field_is_enum {
1106                    // Enum fields: use `toString().toString()` (via string_expr) to get the
1107                    // serde variant name as a Swift String, then check substring containment.
1108                    for val in values {
1109                        let swift_val = json_to_swift(val);
1110                        let _ = writeln!(
1111                            out,
1112                            "        XCTAssertTrue({string_expr}.contains({swift_val}), \"expected to contain: \\({swift_val})\")"
1113                        );
1114                    }
1115                } else {
1116                    for val in values {
1117                        let swift_val = json_to_swift(val);
1118                        let _ = writeln!(
1119                            out,
1120                            "        XCTAssertTrue({string_expr}.contains({swift_val}), \"expected to contain: \\({swift_val})\")"
1121                        );
1122                    }
1123                }
1124            }
1125        }
1126        "not_contains" => {
1127            if let Some(expected) = &assertion.value {
1128                let swift_val = json_to_swift(expected);
1129                let _ = writeln!(
1130                    out,
1131                    "        XCTAssertFalse({string_expr}.contains({swift_val}), \"expected NOT to contain: \\({swift_val})\")"
1132                );
1133            }
1134        }
1135        "not_empty" => {
1136            // For optional fields (Optional<T>), check that the value is non-nil.
1137            // For array fields (RustVec<T>), check .isEmpty on the vec directly.
1138            // For result_is_simple (e.g. Data, String), use .isEmpty directly on
1139            // the result — avoids calling .toString() on non-RustString types.
1140            // For string fields, convert to Swift String and check .isEmpty.
1141            if field_is_optional {
1142                let _ = writeln!(out, "        XCTAssertNotNil({field_expr}, \"expected non-nil value\")");
1143            } else if field_is_array {
1144                let _ = writeln!(
1145                    out,
1146                    "        XCTAssertFalse({field_expr}.isEmpty, \"expected non-empty value\")"
1147                );
1148            } else if result_is_simple {
1149                // result_is_simple: result is a primitive (Data, String, etc.) — use .isEmpty directly.
1150                let _ = writeln!(
1151                    out,
1152                    "        XCTAssertFalse({result_var}.isEmpty, \"expected non-empty value\")"
1153                );
1154            } else {
1155                // string_expr has .toString() appended; .isEmpty works on Swift String.
1156                let _ = writeln!(
1157                    out,
1158                    "        XCTAssertFalse({string_expr}.isEmpty, \"expected non-empty value\")"
1159                );
1160            }
1161        }
1162        "is_empty" => {
1163            if field_is_optional {
1164                let _ = writeln!(out, "        XCTAssertNil({field_expr}, \"expected nil value\")");
1165            } else if field_is_array {
1166                let _ = writeln!(
1167                    out,
1168                    "        XCTAssertTrue({field_expr}.isEmpty, \"expected empty value\")"
1169                );
1170            } else {
1171                let _ = writeln!(
1172                    out,
1173                    "        XCTAssertTrue({string_expr}.isEmpty, \"expected empty value\")"
1174                );
1175            }
1176        }
1177        "contains_any" => {
1178            if let Some(values) = &assertion.values {
1179                let checks: Vec<String> = values
1180                    .iter()
1181                    .map(|v| {
1182                        let swift_val = json_to_swift(v);
1183                        format!("{string_expr}.contains({swift_val})")
1184                    })
1185                    .collect();
1186                let joined = checks.join(" || ");
1187                let _ = writeln!(
1188                    out,
1189                    "        XCTAssertTrue({joined}, \"expected to contain at least one of the specified values\")"
1190                );
1191            }
1192        }
1193        "greater_than" => {
1194            if let Some(val) = &assertion.value {
1195                let swift_val = json_to_swift(val);
1196                // For optional numeric fields (or when the accessor chain is optional),
1197                // coalesce to 0 before comparing so the expression is non-optional.
1198                let field_is_optional = accessor_is_optional
1199                    || assertion.field.as_deref().is_some_and(|f| {
1200                        field_resolver.is_optional(f) || field_resolver.is_optional(field_resolver.resolve(f))
1201                    });
1202                let compare_expr = if field_is_optional {
1203                    format!("({field_expr} ?? 0)")
1204                } else {
1205                    field_expr.clone()
1206                };
1207                let _ = writeln!(out, "        XCTAssertGreaterThan({compare_expr}, {swift_val})");
1208            }
1209        }
1210        "less_than" => {
1211            if let Some(val) = &assertion.value {
1212                let swift_val = json_to_swift(val);
1213                let field_is_optional = accessor_is_optional
1214                    || assertion.field.as_deref().is_some_and(|f| {
1215                        field_resolver.is_optional(f) || field_resolver.is_optional(field_resolver.resolve(f))
1216                    });
1217                let compare_expr = if field_is_optional {
1218                    format!("({field_expr} ?? 0)")
1219                } else {
1220                    field_expr.clone()
1221                };
1222                let _ = writeln!(out, "        XCTAssertLessThan({compare_expr}, {swift_val})");
1223            }
1224        }
1225        "greater_than_or_equal" => {
1226            if let Some(val) = &assertion.value {
1227                let swift_val = json_to_swift(val);
1228                // For optional numeric fields (or when the accessor chain is optional),
1229                // coalesce to 0 before comparing so the expression is non-optional.
1230                let field_is_optional = accessor_is_optional
1231                    || assertion.field.as_deref().is_some_and(|f| {
1232                        field_resolver.is_optional(f) || field_resolver.is_optional(field_resolver.resolve(f))
1233                    });
1234                let compare_expr = if field_is_optional {
1235                    format!("({field_expr} ?? 0)")
1236                } else {
1237                    field_expr.clone()
1238                };
1239                let _ = writeln!(out, "        XCTAssertGreaterThanOrEqual({compare_expr}, {swift_val})");
1240            }
1241        }
1242        "less_than_or_equal" => {
1243            if let Some(val) = &assertion.value {
1244                let swift_val = json_to_swift(val);
1245                let field_is_optional = accessor_is_optional
1246                    || assertion.field.as_deref().is_some_and(|f| {
1247                        field_resolver.is_optional(f) || field_resolver.is_optional(field_resolver.resolve(f))
1248                    });
1249                let compare_expr = if field_is_optional {
1250                    format!("({field_expr} ?? 0)")
1251                } else {
1252                    field_expr.clone()
1253                };
1254                let _ = writeln!(out, "        XCTAssertLessThanOrEqual({compare_expr}, {swift_val})");
1255            }
1256        }
1257        "starts_with" => {
1258            if let Some(expected) = &assertion.value {
1259                let swift_val = json_to_swift(expected);
1260                let _ = writeln!(
1261                    out,
1262                    "        XCTAssertTrue({string_expr}.hasPrefix({swift_val}), \"expected to start with: \\({swift_val})\")"
1263                );
1264            }
1265        }
1266        "ends_with" => {
1267            if let Some(expected) = &assertion.value {
1268                let swift_val = json_to_swift(expected);
1269                let _ = writeln!(
1270                    out,
1271                    "        XCTAssertTrue({string_expr}.hasSuffix({swift_val}), \"expected to end with: \\({swift_val})\")"
1272                );
1273            }
1274        }
1275        "min_length" => {
1276            if let Some(val) = &assertion.value {
1277                if let Some(n) = val.as_u64() {
1278                    // Use string_expr.count: for RustString fields string_expr already has
1279                    // .toString() appended, giving a Swift String whose .count is character count.
1280                    let _ = writeln!(out, "        XCTAssertGreaterThanOrEqual({string_expr}.count, {n})");
1281                }
1282            }
1283        }
1284        "max_length" => {
1285            if let Some(val) = &assertion.value {
1286                if let Some(n) = val.as_u64() {
1287                    let _ = writeln!(out, "        XCTAssertLessThanOrEqual({string_expr}.count, {n})");
1288                }
1289            }
1290        }
1291        "count_min" => {
1292            if let Some(val) = &assertion.value {
1293                if let Some(n) = val.as_u64() {
1294                    // For fields nested inside an optional parent (e.g. document.nodes where
1295                    // document is Optional), the accessor generates `result.document().nodes()`
1296                    // which doesn't compile in Swift without optional chaining.
1297                    let count_expr = swift_array_count_expr(assertion.field.as_deref(), result_var, field_resolver);
1298                    let _ = writeln!(out, "        XCTAssertGreaterThanOrEqual({count_expr}, {n})");
1299                }
1300            }
1301        }
1302        "count_equals" => {
1303            if let Some(val) = &assertion.value {
1304                if let Some(n) = val.as_u64() {
1305                    let count_expr = swift_array_count_expr(assertion.field.as_deref(), result_var, field_resolver);
1306                    let _ = writeln!(out, "        XCTAssertEqual({count_expr}, {n})");
1307                }
1308            }
1309        }
1310        "is_true" => {
1311            let _ = writeln!(out, "        XCTAssertTrue({field_expr})");
1312        }
1313        "is_false" => {
1314            let _ = writeln!(out, "        XCTAssertFalse({field_expr})");
1315        }
1316        "matches_regex" => {
1317            if let Some(expected) = &assertion.value {
1318                let swift_val = json_to_swift(expected);
1319                let _ = writeln!(
1320                    out,
1321                    "        XCTAssertNotNil({string_expr}.range(of: {swift_val}, options: .regularExpression), \"expected value to match regex: \\({swift_val})\")"
1322                );
1323            }
1324        }
1325        "not_error" => {
1326            // Already handled by the call succeeding without exception.
1327        }
1328        "error" => {
1329            // Handled at the test method level.
1330        }
1331        "method_result" => {
1332            let _ = writeln!(out, "        // method_result assertions not yet implemented for Swift");
1333        }
1334        other => {
1335            panic!("Swift e2e generator: unsupported assertion type: {other}");
1336        }
1337    }
1338}
1339
1340/// Build a Swift accessor path for the given fixture field, inserting `()` on
1341/// every segment and `?` after every optional non-leaf segment.
1342///
1343/// This is the core helper for count/contains helpers that need to reconstruct
1344/// the path with correct optional chaining from the raw fixture field name.
1345///
1346/// Returns `(accessor_expr, has_optional)` where `has_optional` is true when
1347/// at least one `?.` was inserted.
1348fn swift_build_accessor(field: &str, result_var: &str, field_resolver: &FieldResolver) -> (String, bool) {
1349    let resolved = field_resolver.resolve(field);
1350    let parts: Vec<&str> = resolved.split('.').collect();
1351
1352    // Build a set of optional prefix paths for O(1) lookup during the walk.
1353    // We track path_so_far incrementally.
1354    let mut out = result_var.to_string();
1355    let mut has_optional = false;
1356    let mut path_so_far = String::new();
1357    let total = parts.len();
1358    for (i, part) in parts.iter().enumerate() {
1359        let is_leaf = i == total - 1;
1360        // Handle array index subscripts within a segment, e.g. `data[0]`.
1361        // `data[0]` must become `.data()[0]` not `.data[0]()`.
1362        // Split at the first `[` if present.
1363        let (field_name, subscript): (&str, Option<&str>) = if let Some(bracket_pos) = part.find('[') {
1364            (&part[..bracket_pos], Some(&part[bracket_pos..]))
1365        } else {
1366            (part, None)
1367        };
1368
1369        if !path_so_far.is_empty() {
1370            path_so_far.push('.');
1371        }
1372        path_so_far.push_str(part);
1373        out.push('.');
1374        out.push_str(field_name);
1375        out.push_str("()");
1376        if let Some(sub) = subscript {
1377            out.push_str(sub);
1378        }
1379        // Insert `?` after the last `()` (or subscript) for any non-leaf optional field
1380        // so the next member access becomes `?.`.
1381        if !is_leaf && field_resolver.is_optional(&path_so_far) {
1382            out.push('?');
1383            has_optional = true;
1384        }
1385    }
1386    (out, has_optional)
1387}
1388
1389/// Generate a `[String]?` expression for a `RustVec<RustString>` (or optional variant) field
1390/// so that `contains` membership checks work against plain Swift Strings.
1391///
1392/// The result is `Optional<[String]>` — callers should coalesce with `?? []`.
1393///
1394/// We use `?.map { $0.as_str().toString() }` because:
1395/// 1. Iterating a `RustVec<RustString>` yields `RustStringRef` (not `RustString`), which
1396///    only has `as_str()` but not `toString()` directly.
1397/// 2. The accessor may end with an `Optional<RustVec<RustString>>` (e.g. `sheet_names()` is
1398///    `Option<Vec<String>>` in Rust, which becomes `Optional<RustVec<RustString>>` in Swift).
1399/// 3. Optional chaining from parent `?.` already produces `Optional<RustVec<T>>`.
1400///
1401/// `?.map { $0.as_str().toString() }` converts each `RustStringRef` to a Swift `String`,
1402/// giving `[String]` wrapped in `Optional`. The `?? []` in callers coalesces nil to an empty
1403/// array.
1404fn swift_array_contains_expr(field: Option<&str>, result_var: &str, field_resolver: &FieldResolver) -> String {
1405    let Some(f) = field else {
1406        return format!("{result_var}.map {{ $0.as_str().toString() }}");
1407    };
1408    let (accessor, _has_optional) = swift_build_accessor(f, result_var, field_resolver);
1409    // Always use `?.map` — the array field (sheet_names, etc.) may itself return
1410    // Optional<RustVec<T>> even if not listed in fields_optional.
1411    format!("{accessor}?.map {{ $0.as_str().toString() }}")
1412}
1413
1414/// Generate a `.count` expression for an array field that may be nested inside optional parents.
1415///
1416/// Swift-bridge exposes all Rust fields as methods with `()`. When ancestor segments are
1417/// optional, we use `?.` chaining. The final count is coalesced with `?? 0` when there
1418/// are optional ancestors so the XCTAssert macro receives a non-optional `Int`.
1419///
1420/// Also check if the field itself (the leaf) is optional, which happens when the field
1421/// returns Optional<RustVec<T>> (e.g., `links()` may return Optional).
1422fn swift_array_count_expr(field: Option<&str>, result_var: &str, field_resolver: &FieldResolver) -> String {
1423    let Some(f) = field else {
1424        return format!("{result_var}.count");
1425    };
1426    let (accessor, mut has_optional) = swift_build_accessor(f, result_var, field_resolver);
1427    // Also check if the leaf field itself is optional.
1428    if field_resolver.is_optional(f) {
1429        has_optional = true;
1430    }
1431    if has_optional {
1432        // In Swift, accessing .count on an optional with ?. returns Optional<Int>,
1433        // so we coalesce with ?? 0 to get a concrete Int for XCTAssert.
1434        if accessor.contains("?.") {
1435            format!("{accessor}.count ?? 0")
1436        } else {
1437            // If no ?. but field is optional, the field_expr itself is Optional<RustVec<T>>
1438            // so we need ?. to call count.
1439            format!("({accessor}?.count ?? 0)")
1440        }
1441    } else {
1442        format!("{accessor}.count")
1443    }
1444}
1445
1446/// Normalise a path by resolving `..` components without hitting the filesystem.
1447///
1448/// This mirrors what `std::fs::canonicalize` does but works on paths that do
1449/// not yet exist on disk (generated-file paths).  Only `..` traversals are
1450/// collapsed; `.` components are dropped; nothing else is changed.
1451fn normalize_path(path: &std::path::Path) -> std::path::PathBuf {
1452    let mut components = std::path::PathBuf::new();
1453    for component in path.components() {
1454        match component {
1455            std::path::Component::ParentDir => {
1456                // Pop the last pushed component if there is one that isn't
1457                // already a `..` (avoids over-collapsing `../../foo`).
1458                if !components.as_os_str().is_empty() {
1459                    components.pop();
1460                } else {
1461                    components.push(component);
1462                }
1463            }
1464            std::path::Component::CurDir => {}
1465            other => components.push(other),
1466        }
1467    }
1468    components
1469}
1470
1471/// Convert a `serde_json::Value` to a Swift literal string.
1472fn json_to_swift(value: &serde_json::Value) -> String {
1473    match value {
1474        serde_json::Value::String(s) => format!("\"{}\"", escape_swift(s)),
1475        serde_json::Value::Bool(b) => b.to_string(),
1476        serde_json::Value::Number(n) => n.to_string(),
1477        serde_json::Value::Null => "nil".to_string(),
1478        serde_json::Value::Array(arr) => {
1479            let items: Vec<String> = arr.iter().map(json_to_swift).collect();
1480            format!("[{}]", items.join(", "))
1481        }
1482        serde_json::Value::Object(_) => {
1483            let json_str = serde_json::to_string(value).unwrap_or_default();
1484            format!("\"{}\"", escape_swift(&json_str))
1485        }
1486    }
1487}
1488
1489/// Escape a string for embedding in a Swift double-quoted string literal.
1490fn escape_swift(s: &str) -> String {
1491    escape_swift_str(s)
1492}