1use crate::config::E2eConfig;
16use crate::escape::{escape_java as escape_swift_str, expand_fixture_templates, sanitize_filename, sanitize_ident};
17use crate::field_access::{FieldResolver, SwiftFirstClassMap};
18use crate::fixture::{Assertion, Fixture, FixtureGroup, ValidationErrorExpectation};
19use alef_core::backend::GeneratedFile;
20use alef_core::config::ResolvedCrateConfig;
21use alef_core::hash::{self, CommentStyle};
22use alef_core::template_versions::toolchain;
23use anyhow::Result;
24use heck::{ToLowerCamelCase, ToSnakeCase, ToUpperCamelCase};
25use std::collections::HashMap;
26use std::collections::HashSet;
27use std::fmt::Write as FmtWrite;
28use std::path::PathBuf;
29
30use super::E2eCodegen;
31use super::client;
32
33pub struct SwiftE2eCodegen;
35
36impl E2eCodegen for SwiftE2eCodegen {
37 fn generate(
38 &self,
39 groups: &[FixtureGroup],
40 e2e_config: &E2eConfig,
41 config: &ResolvedCrateConfig,
42 type_defs: &[alef_core::ir::TypeDef],
43 enums: &[alef_core::ir::EnumDef],
44 ) -> Result<Vec<GeneratedFile>> {
45 let lang = self.language_name();
46 let output_base = PathBuf::from(e2e_config.effective_output()).join("swift_e2e");
54
55 let mut files = Vec::new();
56
57 let call = &e2e_config.call;
59 let overrides = call.overrides.get(lang);
60 let function_name = overrides
61 .and_then(|o| o.function.as_ref())
62 .cloned()
63 .unwrap_or_else(|| call.function.clone());
64 let result_var = &call.result_var;
65 let result_is_simple = overrides.is_some_and(|o| o.result_is_simple);
66
67 let swift_pkg = e2e_config.resolve_package("swift");
69 let pkg_name = swift_pkg
70 .as_ref()
71 .and_then(|p| p.name.as_ref())
72 .cloned()
73 .unwrap_or_else(|| config.name.to_upper_camel_case());
74 let pkg_path = swift_pkg
75 .as_ref()
76 .and_then(|p| p.path.as_ref())
77 .cloned()
78 .unwrap_or_else(|| "../../packages/swift".to_string());
79 let pkg_version = swift_pkg
80 .as_ref()
81 .and_then(|p| p.version.as_ref())
82 .cloned()
83 .or_else(|| config.resolved_version())
84 .unwrap_or_else(|| "0.1.0".to_string());
85
86 let module_name = pkg_name.as_str();
88
89 let registry_url = config
93 .try_github_repo()
94 .map(|repo| {
95 let base = repo.trim_end_matches('/').trim_end_matches(".git");
96 format!("{base}.git")
97 })
98 .unwrap_or_else(|_| format!("https://example.invalid/{module_name}.git"));
99
100 files.push(GeneratedFile {
103 path: output_base.join("Package.swift"),
104 content: render_package_swift(module_name, ®istry_url, &pkg_path, &pkg_version, e2e_config.dep_mode),
105 generated_header: false,
106 });
107
108 let tests_base = output_base.clone();
110
111 let swift_first_class_map = build_swift_first_class_map(type_defs, enums, e2e_config);
117
118 let swift_first_class_map_ref = swift_first_class_map;
119
120 let client_factory: Option<&str> = overrides.and_then(|o| o.client_factory.as_deref());
122
123 files.push(GeneratedFile {
134 path: tests_base
135 .join("Tests")
136 .join(format!("{module_name}E2ETests"))
137 .join("TestHelpers.swift"),
138 content: render_test_helpers_swift(),
139 generated_header: true,
140 });
141
142 for group in groups {
144 let active: Vec<&Fixture> = group
145 .fixtures
146 .iter()
147 .filter(|f| super::should_include_fixture(f, lang, e2e_config))
148 .collect();
149
150 if active.is_empty() {
151 continue;
152 }
153
154 let class_name = format!("{}Tests", sanitize_filename(&group.category).to_upper_camel_case());
155 let filename = format!("{class_name}.swift");
156 let content = render_test_file(
157 &group.category,
158 &active,
159 e2e_config,
160 module_name,
161 &class_name,
162 &function_name,
163 result_var,
164 &e2e_config.call.args,
165 result_is_simple,
166 client_factory,
167 &swift_first_class_map_ref,
168 );
169 files.push(GeneratedFile {
170 path: tests_base
171 .join("Tests")
172 .join(format!("{module_name}E2ETests"))
173 .join(filename),
174 content,
175 generated_header: true,
176 });
177 }
178
179 Ok(files)
180 }
181
182 fn language_name(&self) -> &'static str {
183 "swift"
184 }
185}
186
187const SWIFT_FORMAT_IGNORE_DIRECTIVE: &str = "// swift-format-ignore-file\n\n";
203
204fn render_test_helpers_swift() -> String {
209 let header = hash::header(CommentStyle::DoubleSlash);
210 let ignore = SWIFT_FORMAT_IGNORE_DIRECTIVE;
211 format!(
212 r#"{header}{ignore}import Foundation
213import RustBridge
214
215// Make `RustString` print its content in XCTest failure output. Without this,
216// every error thrown from the swift-bridge layer surfaces as
217// `caught error: "RustBridge.RustString"` with the actual message hidden
218// inside the opaque class instance. The `@retroactive` keyword acknowledges
219// that the conformed-to protocol (`CustomStringConvertible`) and the
220// conforming type (`RustString`) both live outside this module — required by
221// Swift 6 to silence the retroactive-conformance warning. swift-bridge does
222// not give `RustString` a `description` of its own, so there is no conflict.
223extension RustString: @retroactive CustomStringConvertible {{
224 public var description: String {{ self.toString() }}
225}}
226"#
227 )
228}
229
230fn render_package_swift(
231 module_name: &str,
232 registry_url: &str,
233 pkg_path: &str,
234 pkg_version: &str,
235 dep_mode: crate::config::DependencyMode,
236) -> String {
237 let min_macos = toolchain::SWIFT_MIN_MACOS;
238
239 let (dep_block, product_dep) = match dep_mode {
243 crate::config::DependencyMode::Registry => {
244 let dep = format!(r#" .package(url: "{registry_url}", from: "{pkg_version}")"#);
245 let pkg_id = registry_url
246 .trim_end_matches('/')
247 .trim_end_matches(".git")
248 .split('/')
249 .next_back()
250 .unwrap_or(module_name);
251 let prod = format!(r#".product(name: "{module_name}", package: "{pkg_id}")"#);
252 (dep, prod)
253 }
254 crate::config::DependencyMode::Local => {
255 let pkg_id = pkg_path.trim_end_matches('/').rsplit('/').next().unwrap_or(module_name);
262 let dep = format!(r#" .package(path: "{pkg_path}")"#);
263 let prod = format!(r#".product(name: "{module_name}", package: "{pkg_id}")"#);
264 (dep, prod)
265 }
266 };
267 let min_macos_major = min_macos.split('.').next().unwrap_or(min_macos);
270 let min_ios = toolchain::SWIFT_MIN_IOS;
271 let min_ios_major = min_ios.split('.').next().unwrap_or(min_ios);
272 format!(
276 r#"// swift-tools-version: 6.0
277import PackageDescription
278
279let package = Package(
280 name: "E2eSwift",
281 platforms: [
282 .macOS(.v{min_macos_major}),
283 .iOS(.v{min_ios_major}),
284 ],
285 dependencies: [
286{dep_block},
287 ],
288 targets: [
289 .testTarget(
290 name: "{module_name}E2ETests",
291 dependencies: [{product_dep}]
292 ),
293 ]
294)
295"#
296 )
297}
298
299#[allow(clippy::too_many_arguments)]
300fn render_test_file(
301 category: &str,
302 fixtures: &[&Fixture],
303 e2e_config: &E2eConfig,
304 module_name: &str,
305 class_name: &str,
306 function_name: &str,
307 result_var: &str,
308 args: &[crate::config::ArgMapping],
309 result_is_simple: bool,
310 client_factory: Option<&str>,
311 swift_first_class_map: &SwiftFirstClassMap,
312) -> String {
313 let needs_chdir = fixtures.iter().any(|f| {
320 let call_config =
321 e2e_config.resolve_call_for_fixture(f.call.as_deref(), &f.id, &f.resolved_category(), &f.tags, &f.input);
322 call_config
323 .args
324 .iter()
325 .any(|a| a.arg_type == "file_path" || a.arg_type == "bytes")
326 });
327
328 let mut out = String::new();
329 out.push_str(&hash::header(CommentStyle::DoubleSlash));
330 out.push_str(SWIFT_FORMAT_IGNORE_DIRECTIVE);
331 let _ = writeln!(out, "import XCTest");
332 let _ = writeln!(out, "import Foundation");
333 let _ = writeln!(out, "import {module_name}");
334 let _ = writeln!(out, "import RustBridge");
335 let _ = writeln!(out);
336 let _ = writeln!(out, "/// E2e tests for category: {category}.");
337 let _ = writeln!(out, "final class {class_name}: XCTestCase {{");
338
339 if needs_chdir {
340 let _ = writeln!(out, " override class func setUp() {{");
348 let _ = writeln!(out, " super.setUp()");
349 let _ = writeln!(out, " let _testDocs = URL(fileURLWithPath: #filePath)");
350 let _ = writeln!(out, " .deletingLastPathComponent() // <Module>Tests/");
351 let _ = writeln!(out, " .deletingLastPathComponent() // Tests/");
352 let _ = writeln!(out, " .deletingLastPathComponent() // swift/");
353 let _ = writeln!(out, " .deletingLastPathComponent() // packages/");
354 let _ = writeln!(out, " .deletingLastPathComponent() // <repo root>");
355 let _ = writeln!(
356 out,
357 " .appendingPathComponent(\"{}\")",
358 e2e_config.test_documents_dir
359 );
360 let _ = writeln!(
361 out,
362 " if FileManager.default.fileExists(atPath: _testDocs.path) {{"
363 );
364 let _ = writeln!(
365 out,
366 " FileManager.default.changeCurrentDirectoryPath(_testDocs.path)"
367 );
368 let _ = writeln!(out, " }}");
369 let _ = writeln!(out, " }}");
370 let _ = writeln!(out);
371 }
372
373 for fixture in fixtures {
374 if fixture.is_http_test() {
375 render_http_test_method(&mut out, fixture);
376 } else {
377 render_test_method(
378 &mut out,
379 fixture,
380 e2e_config,
381 function_name,
382 result_var,
383 args,
384 result_is_simple,
385 client_factory,
386 swift_first_class_map,
387 module_name,
388 );
389 }
390 let _ = writeln!(out);
391 }
392
393 let _ = writeln!(out, "}}");
394 out
395}
396
397struct SwiftTestClientRenderer;
404
405impl client::TestClientRenderer for SwiftTestClientRenderer {
406 fn language_name(&self) -> &'static str {
407 "swift"
408 }
409
410 fn sanitize_test_name(&self, id: &str) -> String {
411 sanitize_ident(id).to_upper_camel_case()
413 }
414
415 fn render_test_open(&self, out: &mut String, fn_name: &str, description: &str, skip_reason: Option<&str>) {
421 let _ = writeln!(out, " /// {description}");
422 let _ = writeln!(out, " func test{fn_name}() throws {{");
423 if let Some(reason) = skip_reason {
424 let escaped = escape_swift(reason);
425 let _ = writeln!(out, " try XCTSkipIf(true, \"{escaped}\")");
426 }
427 }
428
429 fn render_test_close(&self, out: &mut String) {
430 let _ = writeln!(out, " }}");
431 }
432
433 fn render_call(&self, out: &mut String, ctx: &client::CallCtx<'_>) {
440 let method = ctx.method.to_uppercase();
441 let fixture_path = escape_swift(ctx.path);
442
443 let _ = writeln!(
444 out,
445 " let _baseURL = ProcessInfo.processInfo.environment[\"MOCK_SERVER_URL\"]!"
446 );
447 let _ = writeln!(
448 out,
449 " var _req = URLRequest(url: URL(string: _baseURL + \"{fixture_path}\")!)"
450 );
451 let _ = writeln!(out, " _req.httpMethod = \"{method}\"");
452
453 let mut header_pairs: Vec<(&String, &String)> = ctx.headers.iter().collect();
455 header_pairs.sort_by_key(|(k, _)| k.as_str());
456 for (k, v) in &header_pairs {
457 let expanded_v = expand_fixture_templates(v);
458 let ek = escape_swift(k);
459 let ev = escape_swift(&expanded_v);
460 let _ = writeln!(out, " _req.setValue(\"{ev}\", forHTTPHeaderField: \"{ek}\")");
461 }
462
463 if let Some(body) = ctx.body {
465 let json_str = serde_json::to_string(body).unwrap_or_default();
466 let escaped_body = escape_swift(&json_str);
467 let _ = writeln!(out, " _req.httpBody = \"{escaped_body}\".data(using: .utf8)");
468 let _ = writeln!(
469 out,
470 " _req.setValue(\"application/json\", forHTTPHeaderField: \"Content-Type\")"
471 );
472 }
473
474 let _ = writeln!(out, " var {}: HTTPURLResponse?", ctx.response_var);
475 let _ = writeln!(out, " var _responseData: Data?");
476 let _ = writeln!(out, " let _sema = DispatchSemaphore(value: 0)");
477 let _ = writeln!(
478 out,
479 " URLSession.shared.dataTask(with: _req) {{ data, resp, _ in"
480 );
481 let _ = writeln!(out, " {} = resp as? HTTPURLResponse", ctx.response_var);
482 let _ = writeln!(out, " _responseData = data");
483 let _ = writeln!(out, " _sema.signal()");
484 let _ = writeln!(out, " }}.resume()");
485 let _ = writeln!(out, " _sema.wait()");
486 let _ = writeln!(out, " let _resp = try XCTUnwrap({})", ctx.response_var);
487 }
488
489 fn render_assert_status(&self, out: &mut String, _response_var: &str, status: u16) {
490 let _ = writeln!(out, " XCTAssertEqual(_resp.statusCode, {status})");
491 }
492
493 fn render_assert_header(&self, out: &mut String, _response_var: &str, name: &str, expected: &str) {
494 let lower_name = name.to_lowercase();
495 let header_expr = format!("_resp.value(forHTTPHeaderField: \"{}\")", escape_swift(&lower_name));
496 match expected {
497 "<<present>>" => {
498 let _ = writeln!(out, " XCTAssertNotNil({header_expr})");
499 }
500 "<<absent>>" => {
501 let _ = writeln!(out, " XCTAssertNil({header_expr})");
502 }
503 "<<uuid>>" => {
504 let _ = writeln!(out, " let _hdrVal_{lower_name} = try XCTUnwrap({header_expr})");
505 let _ = writeln!(
506 out,
507 " XCTAssertNotNil(_hdrVal_{lower_name}.range(of: #\"^[0-9a-f]{{8}}-[0-9a-f]{{4}}-[0-9a-f]{{4}}-[0-9a-f]{{4}}-[0-9a-f]{{12}}$\"#, options: .regularExpression))"
508 );
509 }
510 exact => {
511 let escaped = escape_swift(exact);
512 let _ = writeln!(out, " XCTAssertEqual({header_expr}, \"{escaped}\")");
513 }
514 }
515 }
516
517 fn render_assert_json_body(&self, out: &mut String, _response_var: &str, expected: &serde_json::Value) {
518 if let serde_json::Value::String(s) = expected {
519 let escaped = escape_swift(s);
520 let _ = writeln!(
521 out,
522 " let _bodyStr = String(data: try XCTUnwrap(_responseData), encoding: .utf8) ?? \"\""
523 );
524 let _ = writeln!(
525 out,
526 " XCTAssertEqual(_bodyStr.trimmingCharacters(in: .whitespacesAndNewlines), \"{escaped}\")"
527 );
528 } else {
529 let json_str = serde_json::to_string(expected).unwrap_or_default();
530 let escaped = escape_swift(&json_str);
531 let _ = writeln!(out, " let _bodyData = try XCTUnwrap(_responseData)");
532 let _ = writeln!(
533 out,
534 " let _expected = try JSONSerialization.jsonObject(with: \"{escaped}\".data(using: .utf8)!)"
535 );
536 let _ = writeln!(
537 out,
538 " let _actual = try JSONSerialization.jsonObject(with: _bodyData)"
539 );
540 let _ = writeln!(
541 out,
542 " XCTAssertEqual(NSDictionary(dictionary: _expected as? [String: AnyHashable] ?? [:]), NSDictionary(dictionary: _actual as? [String: AnyHashable] ?? [:]))"
543 );
544 }
545 }
546
547 fn render_assert_partial_body(&self, out: &mut String, _response_var: &str, expected: &serde_json::Value) {
548 if let Some(obj) = expected.as_object() {
549 let _ = writeln!(out, " let _bodyData = try XCTUnwrap(_responseData)");
550 let _ = writeln!(
551 out,
552 " let _bodyObj = try XCTUnwrap(try JSONSerialization.jsonObject(with: _bodyData) as? [String: Any])"
553 );
554 for (key, val) in obj {
555 let escaped_key = escape_swift(key);
556 let swift_val = json_to_swift(val);
557 let _ = writeln!(
558 out,
559 " XCTAssertEqual(_bodyObj[\"{escaped_key}\"] as? AnyHashable, ({swift_val}) as AnyHashable)"
560 );
561 }
562 }
563 }
564
565 fn render_assert_validation_errors(
566 &self,
567 out: &mut String,
568 _response_var: &str,
569 errors: &[ValidationErrorExpectation],
570 ) {
571 let _ = writeln!(out, " let _bodyData = try XCTUnwrap(_responseData)");
572 let _ = writeln!(
573 out,
574 " let _bodyObj = try XCTUnwrap(try JSONSerialization.jsonObject(with: _bodyData) as? [String: Any])"
575 );
576 let _ = writeln!(
577 out,
578 " let _errors = _bodyObj[\"errors\"] as? [[String: Any]] ?? []"
579 );
580 for ve in errors {
581 let escaped_msg = escape_swift(&ve.msg);
582 let _ = writeln!(
583 out,
584 " XCTAssertTrue(_errors.contains(where: {{ ($0[\"msg\"] as? String)?.contains(\"{escaped_msg}\") == true }}), \"expected validation error: {escaped_msg}\")"
585 );
586 }
587 }
588}
589
590fn render_http_test_method(out: &mut String, fixture: &Fixture) {
595 let Some(http) = &fixture.http else {
596 return;
597 };
598
599 if http.expected_response.status_code == 101 {
601 let method_name = sanitize_ident(&fixture.id).to_upper_camel_case();
602 let description = fixture.description.replace('"', "\\\"");
603 let _ = writeln!(out, " /// {description}");
604 let _ = writeln!(out, " func test{method_name}() throws {{");
605 let _ = writeln!(
606 out,
607 " try XCTSkipIf(true, \"HTTP 101 WebSocket upgrade cannot be tested via URLSession\")"
608 );
609 let _ = writeln!(out, " }}");
610 return;
611 }
612
613 client::http_call::render_http_test(out, &SwiftTestClientRenderer, fixture);
614}
615
616#[allow(clippy::too_many_arguments)]
621fn render_test_method(
622 out: &mut String,
623 fixture: &Fixture,
624 e2e_config: &E2eConfig,
625 _function_name: &str,
626 _result_var: &str,
627 _args: &[crate::config::ArgMapping],
628 result_is_simple: bool,
629 global_client_factory: Option<&str>,
630 swift_first_class_map: &SwiftFirstClassMap,
631 module_name: &str,
632) {
633 let call_config = e2e_config.resolve_call_for_fixture(
635 fixture.call.as_deref(),
636 &fixture.id,
637 &fixture.resolved_category(),
638 &fixture.tags,
639 &fixture.input,
640 );
641 let call_field_resolver = FieldResolver::new_with_swift_first_class(
643 e2e_config.effective_fields(call_config),
644 e2e_config.effective_fields_optional(call_config),
645 e2e_config.effective_result_fields(call_config),
646 e2e_config.effective_fields_array(call_config),
647 e2e_config.effective_fields_method_calls(call_config),
648 &HashMap::new(),
649 swift_first_class_map.clone(),
650 );
651 let field_resolver = &call_field_resolver;
652 let enum_fields = e2e_config.effective_fields_enum(call_config);
653 let lang = "swift";
654 let call_overrides = call_config.overrides.get(lang);
655 let function_name = call_overrides
656 .and_then(|o| o.function.as_ref())
657 .cloned()
658 .unwrap_or_else(|| call_config.function.to_lower_camel_case());
659 let client_factory: Option<&str> = call_overrides
661 .and_then(|o| o.client_factory.as_deref())
662 .or(global_client_factory);
663 let result_var = &call_config.result_var;
664 let args = &call_config.args;
665 let result_is_bytes_any_lang =
672 call_config.result_is_bytes || call_config.overrides.values().any(|o| o.result_is_bytes);
673 let result_is_simple = call_config.result_is_simple
674 || call_overrides.is_some_and(|o| o.result_is_simple)
675 || result_is_simple
676 || result_is_bytes_any_lang;
677 let result_is_array = call_config.result_is_array;
678 let result_is_option = call_config.result_is_option || call_overrides.is_some_and(|o| o.result_is_option);
683
684 let method_name = fixture.id.to_upper_camel_case();
685 let description = &fixture.description;
686 let expects_error = fixture.assertions.iter().any(|a| a.assertion_type == "error");
687 let is_async = call_config.r#async;
688
689 let is_streaming = crate::codegen::streaming_assertions::resolve_is_streaming(fixture, call_config.streaming);
691 let collect_snippet_opt = if is_streaming && !expects_error {
692 crate::codegen::streaming_assertions::StreamingFieldResolver::collect_snippet(lang, result_var, "chunks")
693 } else {
694 None
695 };
696 if is_streaming && !expects_error && collect_snippet_opt.is_none() {
703 if is_async {
704 let _ = writeln!(out, " func test{method_name}() async throws {{");
705 } else {
706 let _ = writeln!(out, " func test{method_name}() throws {{");
707 }
708 let _ = writeln!(out, " // {description}");
709 let _ = writeln!(
710 out,
711 " try XCTSkipIf(true, \"swift: streaming chunk collection is not yet supported via the swift-bridge surface (fixture: {})\")",
712 fixture.id
713 );
714 let _ = writeln!(out, " }}");
715 return;
716 }
717 let collect_snippet = collect_snippet_opt.unwrap_or_default();
718 let collect_snippet = if collect_snippet.is_empty() {
725 collect_snippet
726 } else {
727 collect_snippet.replace("[ChatCompletionChunk]", &format!("[{module_name}.ChatCompletionChunk]"))
728 };
729
730 let has_unresolvable_json_object_arg = {
737 let options_via = call_overrides.and_then(|o| o.options_via.as_deref());
738 options_via.is_none() && args.iter().any(|a| a.arg_type == "json_object" && a.name != "config")
739 };
740
741 if has_unresolvable_json_object_arg {
742 if is_async {
743 let _ = writeln!(out, " func test{method_name}() async throws {{");
744 } else {
745 let _ = writeln!(out, " func test{method_name}() throws {{");
746 }
747 let _ = writeln!(out, " // {description}");
748 let _ = writeln!(
749 out,
750 " try XCTSkipIf(true, \"swift: json_object request construction requires options_via configuration (fixture: {})\");",
751 fixture.id
752 );
753 let _ = writeln!(out, " }}");
754 return;
755 }
756
757 let mut visitor_setup_lines: Vec<String> = Vec::new();
761 let visitor_handle_expr: Option<String> = fixture
762 .visitor
763 .as_ref()
764 .map(|spec| super::swift_visitors::build_swift_visitor(&mut visitor_setup_lines, spec, &fixture.id));
765
766 let extra_args: Vec<String> = call_overrides.map(|o| o.extra_args.clone()).unwrap_or_default();
770
771 let effective_enum_fields: std::borrow::Cow<HashSet<String>> = {
776 let per_call = call_overrides.map(|o| &o.enum_fields);
777 if let Some(pc) = per_call {
778 if !pc.is_empty() {
779 let mut merged = enum_fields.clone();
780 merged.extend(pc.keys().cloned());
781 std::borrow::Cow::Owned(merged)
782 } else {
783 std::borrow::Cow::Borrowed(enum_fields)
784 }
785 } else {
786 std::borrow::Cow::Borrowed(enum_fields)
787 }
788 };
789
790 let options_via_str: Option<&str> = call_overrides.and_then(|o| o.options_via.as_deref());
791 let options_type_str: Option<&str> = call_overrides.and_then(|o| o.options_type.as_deref());
792 let handle_config_fn_owned: Option<String> = call_config
796 .overrides
797 .get("c")
798 .and_then(|c| c.c_engine_factory.as_deref())
799 .map(|ty| format!("{}_from_json", ty.to_snake_case()).to_lower_camel_case());
800 let (mut setup_lines, args_str) = build_args_and_setup(
801 &fixture.input,
802 args,
803 &fixture.id,
804 fixture.has_host_root_route(),
805 &function_name,
806 options_via_str,
807 options_type_str,
808 handle_config_fn_owned.as_deref(),
809 visitor_handle_expr.as_deref(),
810 );
811 if !visitor_setup_lines.is_empty() {
813 visitor_setup_lines.extend(setup_lines);
814 setup_lines = visitor_setup_lines;
815 }
816
817 let args_str = if extra_args.is_empty() {
819 args_str
820 } else if args_str.is_empty() {
821 extra_args.join(", ")
822 } else {
823 format!("{args_str}, {}", extra_args.join(", "))
824 };
825
826 let has_mock = fixture.mock_response.is_some();
831 let (call_setup, call_expr) = if let Some(_factory) = client_factory {
832 let env_key = format!("MOCK_SERVER_{}", fixture.id.to_ascii_uppercase().replace('-', "_"));
833 let mock_url = if fixture.has_host_root_route() {
834 format!(
835 "ProcessInfo.processInfo.environment[\"{env_key}\"] ?? (ProcessInfo.processInfo.environment[\"MOCK_SERVER_URL\"]! + \"/fixtures/{}\")",
836 fixture.id
837 )
838 } else {
839 format!(
840 "ProcessInfo.processInfo.environment[\"MOCK_SERVER_URL\"]! + \"/fixtures/{}\"",
841 fixture.id
842 )
843 };
844 let client_constructor = if has_mock {
845 format!("let _client = try DefaultClient(apiKey: \"test-key\", baseUrl: {mock_url})")
846 } else {
847 if let Some(env_var) = fixture.env.as_ref().and_then(|e| e.api_key_var.as_deref()) {
849 format!(
850 "let _apiKey = ProcessInfo.processInfo.environment[\"{env_var}\"]\n \
851 let _baseUrl: String? = _apiKey != nil ? nil : {mock_url}\n \
852 let _client = try DefaultClient(apiKey: _apiKey ?? \"test-key\", baseUrl: _baseUrl)"
853 )
854 } else {
855 format!("let _client = try DefaultClient(apiKey: \"test-key\", baseUrl: {mock_url})")
856 }
857 };
858 let expr = if is_async {
859 format!("try await _client.{function_name}({args_str})")
860 } else {
861 format!("try _client.{function_name}({args_str})")
862 };
863 (Some(client_constructor), expr)
864 } else {
865 let expr = if is_async {
868 format!("try await {module_name}.{function_name}({args_str})")
869 } else {
870 format!("try {module_name}.{function_name}({args_str})")
871 };
872 (None, expr)
873 };
874 let _ = function_name;
876
877 if is_async {
878 let _ = writeln!(out, " func test{method_name}() async throws {{");
879 } else {
880 let _ = writeln!(out, " func test{method_name}() throws {{");
881 }
882 let _ = writeln!(out, " // {description}");
883
884 if expects_error {
885 if is_async {
889 let _ = writeln!(out, " do {{");
894 for line in &setup_lines {
895 let _ = writeln!(out, " {line}");
896 }
897 if let Some(setup) = &call_setup {
898 let _ = writeln!(out, " {setup}");
899 }
900 let _ = writeln!(out, " _ = {call_expr}");
901 let _ = writeln!(out, " XCTFail(\"expected to throw\")");
902 let _ = writeln!(out, " }} catch {{");
903 let _ = writeln!(out, " // success");
904 let _ = writeln!(out, " }}");
905 } else {
906 let _ = writeln!(out, " do {{");
913 for line in &setup_lines {
914 let _ = writeln!(out, " {line}");
915 }
916 if let Some(setup) = &call_setup {
917 let _ = writeln!(out, " {setup}");
918 }
919 let _ = writeln!(out, " _ = {call_expr}");
920 let _ = writeln!(out, " XCTFail(\"expected to throw\")");
921 let _ = writeln!(out, " }} catch {{");
922 let _ = writeln!(out, " // success");
923 let _ = writeln!(out, " }}");
924 }
925 let _ = writeln!(out, " }}");
926 return;
927 }
928
929 for line in &setup_lines {
930 let _ = writeln!(out, " {line}");
931 }
932
933 if let Some(setup) = &call_setup {
935 let _ = writeln!(out, " {setup}");
936 }
937
938 let _ = writeln!(out, " let {result_var} = {call_expr}");
939
940 if !collect_snippet.is_empty() {
943 for line in collect_snippet.lines() {
944 let _ = writeln!(out, " {line}");
945 }
946 }
947
948 let fixture_root_type: Option<String> = swift_call_result_type(call_config);
953 let fixture_resolver = field_resolver.with_swift_root_type(fixture_root_type);
954
955 for assertion in &fixture.assertions {
956 let mut assertion_out = String::new();
957 render_assertion(
958 &mut assertion_out,
959 assertion,
960 result_var,
961 &fixture_resolver,
962 result_is_simple,
963 result_is_array,
964 result_is_option,
965 &effective_enum_fields,
966 is_streaming,
967 );
968 for unqualified in ["StreamToolCall", "ToolCall"] {
976 assertion_out =
977 assertion_out.replace(&format!("[{unqualified}]"), &format!("[{module_name}.{unqualified}]"));
978 }
979 out.push_str(&assertion_out);
980 }
981
982 let _ = writeln!(out, " }}");
983}
984
985#[allow(clippy::too_many_arguments)]
986fn build_args_and_setup(
1000 input: &serde_json::Value,
1001 args: &[crate::config::ArgMapping],
1002 fixture_id: &str,
1003 has_host_root_route: bool,
1004 function_name: &str,
1005 options_via: Option<&str>,
1006 options_type: Option<&str>,
1007 handle_config_fn: Option<&str>,
1008 visitor_handle_expr: Option<&str>,
1009) -> (Vec<String>, String) {
1010 if args.is_empty() {
1011 return (Vec::new(), String::new());
1012 }
1013
1014 let mut setup_lines: Vec<String> = Vec::new();
1015 let mut parts: Vec<(usize, String)> = Vec::new();
1016
1017 let later_emits: Vec<bool> = (0..args.len())
1022 .map(|i| {
1023 args.iter().skip(i + 1).any(|a| {
1024 let f = a.field.strip_prefix("input.").unwrap_or(&a.field);
1025 let v = input.get(f);
1026 let has_value = matches!(v, Some(x) if !x.is_null());
1027 has_value || !a.optional || (a.arg_type == "json_object" && a.name == "config")
1028 })
1029 })
1030 .collect();
1031
1032 for (idx, arg) in args.iter().enumerate() {
1033 if arg.arg_type == "mock_url" {
1034 let env_key = format!("MOCK_SERVER_{}", fixture_id.to_ascii_uppercase().replace('-', "_"));
1035 let url_expr = if has_host_root_route {
1036 format!(
1037 "ProcessInfo.processInfo.environment[\"{env_key}\"] ?? (ProcessInfo.processInfo.environment[\"MOCK_SERVER_URL\"]! + \"/fixtures/{fixture_id}\")"
1038 )
1039 } else {
1040 format!("ProcessInfo.processInfo.environment[\"MOCK_SERVER_URL\"]! + \"/fixtures/{fixture_id}\"")
1041 };
1042 setup_lines.push(format!("let {} = {url_expr}", arg.name));
1043 parts.push((idx, arg.name.clone()));
1044 continue;
1045 }
1046
1047 if arg.arg_type == "handle" {
1048 let var_name = format!("{}Obj", arg.name.to_lower_camel_case());
1049 let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1050 let config_val = input.get(field);
1051 let has_config = config_val
1052 .is_some_and(|v| !(v.is_null() || v.is_object() && v.as_object().is_some_and(|o| o.is_empty())));
1053 if has_config {
1054 if let Some(from_json_fn) = handle_config_fn {
1055 let json_str = serde_json::to_string(config_val.unwrap()).unwrap_or_default();
1056 let escaped = escape_swift_str(&json_str);
1057 let config_var = format!("{}Config", arg.name.to_lower_camel_case());
1058 setup_lines.push(format!("let {config_var} = try {from_json_fn}(\"{escaped}\")"));
1059 setup_lines.push(format!("let {var_name} = try createEngine({config_var})"));
1060 } else {
1061 setup_lines.push(format!("let {var_name} = try createEngine(nil)"));
1062 }
1063 } else {
1064 setup_lines.push(format!("let {var_name} = try createEngine(nil)"));
1065 }
1066 parts.push((idx, var_name));
1067 continue;
1068 }
1069
1070 if arg.arg_type == "bytes" {
1075 let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1076 let val = input.get(field);
1077 match val {
1078 None | Some(serde_json::Value::Null) if arg.optional => {
1079 if later_emits[idx] {
1080 parts.push((idx, "nil".to_string()));
1081 }
1082 }
1083 None | Some(serde_json::Value::Null) => {
1084 let var_name = format!("{}Vec", arg.name.to_lower_camel_case());
1085 setup_lines.push(format!("let {var_name} = RustVec<UInt8>()"));
1086 parts.push((idx, var_name));
1087 }
1088 Some(serde_json::Value::String(s)) => {
1089 let escaped = escape_swift(s);
1090 let var_name = format!("{}Vec", arg.name.to_lower_camel_case());
1091 let data_var = format!("{}Data", arg.name.to_lower_camel_case());
1092 setup_lines.push(format!(
1093 "let {data_var} = try Data(contentsOf: URL(fileURLWithPath: \"{escaped}\"))"
1094 ));
1095 setup_lines.push(format!("let {var_name} = RustVec<UInt8>()"));
1096 setup_lines.push(format!("for _byte in {data_var} {{ {var_name}.push(value: _byte) }}"));
1097 parts.push((idx, var_name));
1098 }
1099 Some(serde_json::Value::Array(arr)) => {
1100 let var_name = format!("{}Vec", arg.name.to_lower_camel_case());
1101 setup_lines.push(format!("let {var_name} = RustVec<UInt8>()"));
1102 for v in arr {
1103 if let Some(n) = v.as_u64() {
1104 setup_lines.push(format!("{var_name}.push(value: UInt8({n}))"));
1105 }
1106 }
1107 parts.push((idx, var_name));
1108 }
1109 Some(other) => {
1110 let json_str = serde_json::to_string(other).unwrap_or_default();
1112 let escaped = escape_swift(&json_str);
1113 let var_name = format!("{}Vec", arg.name.to_lower_camel_case());
1114 setup_lines.push(format!("let {var_name} = RustVec<UInt8>()"));
1115 setup_lines.push(format!(
1116 "for _byte in Array(\"{escaped}\".utf8) {{ {var_name}.push(value: _byte) }}"
1117 ));
1118 parts.push((idx, var_name));
1119 }
1120 }
1121 continue;
1122 }
1123
1124 let is_config_arg = arg.name == "config" && arg.arg_type == "json_object";
1130 let is_batch_fn = function_name.starts_with("batch") || function_name.starts_with("Batch");
1131 if is_config_arg && !is_batch_fn {
1132 let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1133 let val = input.get(field);
1134 let json_str = match val {
1135 None | Some(serde_json::Value::Null) => "{}".to_string(),
1136 Some(v) => serde_json::to_string(v).unwrap_or_else(|_| "{}".to_string()),
1137 };
1138 let escaped = escape_swift(&json_str);
1139 let var_name = format!("{}Obj", arg.name.to_lower_camel_case());
1140 let from_json_fn = if let Some(type_name) = options_type {
1142 format!("{}FromJson", type_name.to_lower_camel_case())
1143 } else {
1144 "extractionConfigFromJson".to_string()
1145 };
1146 setup_lines.push(format!("let {var_name} = try {from_json_fn}(\"{escaped}\")"));
1147 parts.push((idx, var_name));
1148 continue;
1149 }
1150
1151 if arg.arg_type == "json_object" && options_via == Some("from_json") {
1158 if let Some(type_name) = options_type {
1159 let resolved_val = super::resolve_field(input, &arg.field);
1160 let json_str = match resolved_val {
1161 serde_json::Value::Null => "{}".to_string(),
1162 v => serde_json::to_string(v).unwrap_or_else(|_| "{}".to_string()),
1163 };
1164 let escaped = escape_swift(&json_str);
1165 let var_name = format!("_{}", arg.name.to_lower_camel_case());
1166 if let Some(handle_expr) = visitor_handle_expr {
1167 let with_visitor_fn = format!("{}FromJsonWithVisitor", type_name.to_lower_camel_case());
1172 let handle_var = format!("_visitorHandle_{}", var_name.trim_start_matches('_'));
1173 setup_lines.push(format!("let {handle_var} = {handle_expr}"));
1174 setup_lines.push(format!(
1175 "let {var_name} = try {with_visitor_fn}(\"{escaped}\", {handle_var})"
1176 ));
1177 } else {
1178 let from_json_fn = format!("{}FromJson", type_name.to_lower_camel_case());
1179 setup_lines.push(format!("let {var_name} = try {from_json_fn}(\"{escaped}\")"));
1180 }
1181 parts.push((idx, var_name));
1182 continue;
1183 }
1184 }
1185
1186 let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1187 let val = input.get(field);
1188 match val {
1189 None | Some(serde_json::Value::Null) if arg.optional => {
1190 if later_emits[idx] {
1194 parts.push((idx, "nil".to_string()));
1195 }
1196 }
1197 None | Some(serde_json::Value::Null) => {
1198 let default_val = match arg.arg_type.as_str() {
1199 "string" => "\"\"".to_string(),
1200 "int" | "integer" => "0".to_string(),
1201 "float" | "number" => "0.0".to_string(),
1202 "bool" | "boolean" => "false".to_string(),
1203 _ => "nil".to_string(),
1204 };
1205 parts.push((idx, default_val));
1206 }
1207 Some(v) => {
1208 parts.push((idx, json_to_swift(v)));
1209 }
1210 }
1211 }
1212
1213 let args_str = parts
1214 .into_iter()
1215 .map(|(idx, val)| format!("{}: {}", args[idx].name, val))
1216 .collect::<Vec<_>>()
1217 .join(", ");
1218 (setup_lines, args_str)
1219}
1220
1221#[allow(clippy::too_many_arguments)]
1222fn render_assertion(
1223 out: &mut String,
1224 assertion: &Assertion,
1225 result_var: &str,
1226 field_resolver: &FieldResolver,
1227 result_is_simple: bool,
1228 result_is_array: bool,
1229 result_is_option: bool,
1230 enum_fields: &HashSet<String>,
1231 is_streaming: bool,
1232) {
1233 let bare_result_is_option = result_is_option && assertion.field.as_deref().filter(|f| !f.is_empty()).is_none();
1238 if let Some(f) = &assertion.field {
1243 let is_streaming_usage_path =
1244 is_streaming && (f == "usage" || (f.starts_with("usage.") || f.starts_with("usage[")));
1245 if !f.is_empty()
1246 && (crate::codegen::streaming_assertions::is_streaming_virtual_field(f) || is_streaming_usage_path)
1247 {
1248 if let Some(expr) =
1249 crate::codegen::streaming_assertions::StreamingFieldResolver::accessor(f, "swift", "chunks")
1250 {
1251 let line = match assertion.assertion_type.as_str() {
1252 "count_min" => {
1253 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1254 format!(" XCTAssertGreaterThanOrEqual(chunks.count, {n})\n")
1255 } else {
1256 String::new()
1257 }
1258 }
1259 "count_equals" => {
1260 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1261 format!(" XCTAssertEqual(chunks.count, {n})\n")
1262 } else {
1263 String::new()
1264 }
1265 }
1266 "equals" => {
1267 if let Some(serde_json::Value::String(s)) = &assertion.value {
1268 let escaped = escape_swift(s);
1269 format!(" XCTAssertEqual({expr}, \"{escaped}\")\n")
1270 } else if let Some(b) = assertion.value.as_ref().and_then(|v| v.as_bool()) {
1271 format!(" XCTAssertEqual({expr}, {b})\n")
1272 } else {
1273 String::new()
1274 }
1275 }
1276 "not_empty" => {
1277 format!(" XCTAssertFalse({expr}.isEmpty, \"expected non-empty\")\n")
1278 }
1279 "is_empty" => {
1280 format!(" XCTAssertTrue({expr}.isEmpty, \"expected empty\")\n")
1281 }
1282 "is_true" => {
1283 format!(" XCTAssertTrue({expr})\n")
1284 }
1285 "is_false" => {
1286 format!(" XCTAssertFalse({expr})\n")
1287 }
1288 "greater_than" => {
1289 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1290 format!(" XCTAssertGreaterThan(chunks.count, {n})\n")
1291 } else {
1292 String::new()
1293 }
1294 }
1295 "contains" => {
1296 if let Some(serde_json::Value::String(s)) = &assertion.value {
1297 let escaped = escape_swift(s);
1298 format!(
1299 " XCTAssertTrue({expr}.contains(\"{escaped}\"), \"expected to contain: {escaped}\")\n"
1300 )
1301 } else {
1302 String::new()
1303 }
1304 }
1305 _ => format!(
1306 " // streaming field '{f}': assertion type '{}' not rendered\n",
1307 assertion.assertion_type
1308 ),
1309 };
1310 if !line.is_empty() {
1311 out.push_str(&line);
1312 }
1313 }
1314 return;
1315 }
1316 }
1317
1318 if let Some(f) = &assertion.field {
1320 if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
1321 let _ = writeln!(out, " // skipped: field '{f}' not available on result type");
1322 return;
1323 }
1324 }
1325
1326 if let Some(f) = &assertion.field {
1331 if !f.is_empty() && field_resolver.tagged_union_split(f).is_some() {
1332 let _ = writeln!(
1333 out,
1334 " // skipped: field '{f}' crosses a tagged-union variant boundary (not expressible in Swift)"
1335 );
1336 return;
1337 }
1338 }
1339
1340 let field_is_enum = assertion
1342 .field
1343 .as_deref()
1344 .is_some_and(|f| enum_fields.contains(f) || enum_fields.contains(field_resolver.resolve(f)));
1345
1346 let field_is_optional = assertion.field.as_deref().is_some_and(|f| {
1347 !f.is_empty() && (field_resolver.is_optional(f) || field_resolver.is_optional(field_resolver.resolve(f)))
1348 });
1349 let field_is_array = assertion.field.as_deref().is_some_and(|f| {
1350 !f.is_empty()
1351 && (field_resolver.is_array(f)
1352 || field_resolver.is_array(field_resolver.resolve(f))
1353 || field_resolver.is_collection_root(f)
1354 || field_resolver.is_collection_root(field_resolver.resolve(f)))
1355 });
1356
1357 let field_expr_raw = if result_is_simple {
1358 result_var.to_string()
1359 } else {
1360 match &assertion.field {
1361 Some(f) if !f.is_empty() => field_resolver.accessor(f, "swift", result_var),
1362 _ => result_var.to_string(),
1363 }
1364 };
1365
1366 let local_suffix = {
1376 use std::hash::{Hash, Hasher};
1377 let mut hasher = std::collections::hash_map::DefaultHasher::new();
1378 assertion.field.hash(&mut hasher);
1379 assertion
1380 .value
1381 .as_ref()
1382 .map(|v| v.to_string())
1383 .unwrap_or_default()
1384 .hash(&mut hasher);
1385 format!(
1386 "{}_{:x}",
1387 assertion.assertion_type.replace(['-', '.'], "_"),
1388 hasher.finish() & 0xffff_ffff,
1389 )
1390 };
1391 let (vec_setup, field_expr, is_map_subscript) = materialise_vec_temporaries(&field_expr_raw, &local_suffix);
1392 let field_uses_traversal = assertion.field.as_deref().is_some_and(|f| f.contains("[]."));
1397 let traversal_skips_field_expr = field_uses_traversal
1398 && matches!(
1399 assertion.assertion_type.as_str(),
1400 "contains" | "not_contains" | "not_empty" | "is_empty"
1401 );
1402 if !traversal_skips_field_expr {
1403 for line in &vec_setup {
1404 let _ = writeln!(out, " {line}");
1405 }
1406 }
1407
1408 let accessor_is_optional = field_expr.contains("?.");
1414 let leaf_is_property_access = {
1422 let trimmed = field_expr.trim_end_matches('?');
1423 let last_segment = trimmed.rsplit_once('.').map(|(_, s)| s).unwrap_or(trimmed);
1425 let last_segment = last_segment.split('[').next().unwrap_or(last_segment);
1426 !last_segment.ends_with(')') && !last_segment.is_empty()
1427 };
1428
1429 let string_expr = if is_map_subscript {
1438 format!("({field_expr} ?? \"\")")
1442 } else if leaf_is_property_access {
1443 if field_is_enum && (field_is_optional || accessor_is_optional) {
1448 format!("(({field_expr})?.rawValue ?? \"\")")
1452 } else if field_is_enum {
1453 format!("{field_expr}.rawValue")
1454 } else if field_is_optional || accessor_is_optional {
1455 format!("({field_expr} ?? \"\")")
1456 } else {
1457 field_expr.to_string()
1458 }
1459 } else if field_is_enum && (field_is_optional || accessor_is_optional) {
1460 format!("({field_expr}?.toString() ?? \"\")")
1463 } else if field_is_enum {
1464 format!("{field_expr}.toString()")
1469 } else if field_is_optional {
1470 format!("({field_expr}?.toString() ?? \"\")")
1472 } else if accessor_is_optional {
1473 format!("({field_expr}.toString() ?? \"\")")
1476 } else {
1477 format!("{field_expr}.toString()")
1478 };
1479
1480 match assertion.assertion_type.as_str() {
1481 "equals" => {
1482 if let Some(expected) = &assertion.value {
1483 let swift_val = json_to_swift(expected);
1484 if expected.is_string() {
1485 if field_is_enum {
1486 let trim_expr =
1490 format!("{string_expr}.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)");
1491 let _ = writeln!(out, " XCTAssertEqual({trim_expr}, {swift_val})");
1492 } else {
1493 let trim_expr =
1498 format!("{string_expr}.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)");
1499 let _ = writeln!(out, " XCTAssertEqual({trim_expr}, {swift_val})");
1500 }
1501 } else {
1502 let _ = writeln!(out, " XCTAssertEqual({field_expr}, {swift_val})");
1503 }
1504 }
1505 }
1506 "contains" => {
1507 if let Some(expected) = &assertion.value {
1508 let swift_val = json_to_swift(expected);
1509 let no_field = assertion.field.as_deref().is_none_or(|f| f.is_empty());
1512 if result_is_simple && result_is_array && no_field {
1513 let _ = writeln!(
1516 out,
1517 " XCTAssertTrue({result_var}.map {{ $0.as_str().toString() }}.contains({swift_val}), \"expected to contain: \\({swift_val})\")"
1518 );
1519 } else {
1520 let traversal_handled = if let Some(f) = assertion.field.as_deref() {
1522 if let Some(dot) = f.find("[].") {
1523 let array_part = &f[..dot];
1524 let elem_part = &f[dot + 3..];
1525 let line = swift_traversal_contains_assert(
1526 array_part,
1527 elem_part,
1528 f,
1529 &swift_val,
1530 result_var,
1531 false,
1532 &format!("expected to contain: \\({swift_val})"),
1533 enum_fields,
1534 field_resolver,
1535 );
1536 let _ = writeln!(out, "{line}");
1537 true
1538 } else {
1539 false
1540 }
1541 } else {
1542 false
1543 };
1544 if !traversal_handled {
1545 let field_is_array = assertion
1547 .field
1548 .as_deref()
1549 .is_some_and(|f| field_resolver.is_array(field_resolver.resolve(f)));
1550 if field_is_array {
1551 let contains_expr =
1552 swift_array_contains_expr(assertion.field.as_deref(), result_var, field_resolver);
1553 let _ = writeln!(
1554 out,
1555 " XCTAssertTrue(({contains_expr} ?? []).contains({swift_val}), \"expected to contain: \\({swift_val})\")"
1556 );
1557 } else if field_is_enum {
1558 let _ = writeln!(
1561 out,
1562 " XCTAssertTrue({string_expr}.contains({swift_val}), \"expected to contain: \\({swift_val})\")"
1563 );
1564 } else {
1565 let _ = writeln!(
1566 out,
1567 " XCTAssertTrue({string_expr}.contains({swift_val}), \"expected to contain: \\({swift_val})\")"
1568 );
1569 }
1570 }
1571 }
1572 }
1573 }
1574 "contains_all" => {
1575 if let Some(values) = &assertion.values {
1576 if let Some(f) = assertion.field.as_deref() {
1578 if let Some(dot) = f.find("[].") {
1579 let array_part = &f[..dot];
1580 let elem_part = &f[dot + 3..];
1581 for val in values {
1582 let swift_val = json_to_swift(val);
1583 let line = swift_traversal_contains_assert(
1584 array_part,
1585 elem_part,
1586 f,
1587 &swift_val,
1588 result_var,
1589 false,
1590 &format!("expected to contain: \\({swift_val})"),
1591 enum_fields,
1592 field_resolver,
1593 );
1594 let _ = writeln!(out, "{line}");
1595 }
1596 } else {
1598 let field_is_array = field_resolver.is_array(field_resolver.resolve(f));
1600 if field_is_array {
1601 let contains_expr =
1602 swift_array_contains_expr(assertion.field.as_deref(), result_var, field_resolver);
1603 for val in values {
1604 let swift_val = json_to_swift(val);
1605 let _ = writeln!(
1606 out,
1607 " XCTAssertTrue(({contains_expr} ?? []).contains({swift_val}), \"expected to contain: \\({swift_val})\")"
1608 );
1609 }
1610 } else if field_is_enum {
1611 for val in values {
1614 let swift_val = json_to_swift(val);
1615 let _ = writeln!(
1616 out,
1617 " XCTAssertTrue({string_expr}.contains({swift_val}), \"expected to contain: \\({swift_val})\")"
1618 );
1619 }
1620 } else {
1621 for val in values {
1622 let swift_val = json_to_swift(val);
1623 let _ = writeln!(
1624 out,
1625 " XCTAssertTrue({string_expr}.contains({swift_val}), \"expected to contain: \\({swift_val})\")"
1626 );
1627 }
1628 }
1629 }
1630 } else {
1631 for val in values {
1633 let swift_val = json_to_swift(val);
1634 let _ = writeln!(
1635 out,
1636 " XCTAssertTrue({string_expr}.contains({swift_val}), \"expected to contain: \\({swift_val})\")"
1637 );
1638 }
1639 }
1640 }
1641 }
1642 "not_contains" => {
1643 if let Some(expected) = &assertion.value {
1644 let swift_val = json_to_swift(expected);
1645 let traversal_handled = if let Some(f) = assertion.field.as_deref() {
1647 if let Some(dot) = f.find("[].") {
1648 let array_part = &f[..dot];
1649 let elem_part = &f[dot + 3..];
1650 let line = swift_traversal_contains_assert(
1651 array_part,
1652 elem_part,
1653 f,
1654 &swift_val,
1655 result_var,
1656 true,
1657 &format!("expected NOT to contain: \\({swift_val})"),
1658 enum_fields,
1659 field_resolver,
1660 );
1661 let _ = writeln!(out, "{line}");
1662 true
1663 } else {
1664 false
1665 }
1666 } else {
1667 false
1668 };
1669 if !traversal_handled {
1670 let _ = writeln!(
1671 out,
1672 " XCTAssertFalse({string_expr}.contains({swift_val}), \"expected NOT to contain: \\({swift_val})\")"
1673 );
1674 }
1675 }
1676 }
1677 "not_empty" => {
1678 let traversal_not_empty_handled = if let Some(f) = assertion.field.as_deref() {
1685 if let Some(dot) = f.find("[].") {
1686 let array_part = &f[..dot];
1687 let elem_part = &f[dot + 3..];
1688 let array_accessor = field_resolver.accessor(array_part, "swift", result_var);
1689 let resolved_full = field_resolver.resolve(f);
1690 let resolved_elem_part = resolved_full
1691 .find("[].")
1692 .map(|d| &resolved_full[d + 3..])
1693 .unwrap_or(elem_part);
1694 let elem_accessor = field_resolver.accessor(resolved_elem_part, "swift", "$0");
1695 let elem_is_enum = enum_fields.contains(f) || enum_fields.contains(resolved_full);
1696 let elem_is_optional = field_resolver.is_optional(resolved_elem_part)
1697 || field_resolver.is_optional(field_resolver.resolve(resolved_elem_part));
1698 let elem_str = if elem_is_enum {
1699 format!("{elem_accessor}.to_string().toString()")
1700 } else if elem_is_optional {
1701 format!("({elem_accessor}?.toString() ?? \"\")")
1702 } else {
1703 format!("{elem_accessor}.toString()")
1704 };
1705 let _ = writeln!(
1706 out,
1707 " XCTAssertTrue({array_accessor}.contains(where: {{ !{elem_str}.isEmpty }}), \"expected non-empty value\")"
1708 );
1709 true
1710 } else {
1711 false
1712 }
1713 } else {
1714 false
1715 };
1716 if !traversal_not_empty_handled {
1717 if bare_result_is_option {
1718 let _ = writeln!(out, " XCTAssertNotNil({result_var}, \"expected non-nil value\")");
1719 } else if field_is_optional {
1720 let _ = writeln!(out, " XCTAssertNotNil({field_expr}, \"expected non-nil value\")");
1721 } else if field_is_array {
1722 let _ = writeln!(
1723 out,
1724 " XCTAssertFalse({field_expr}.isEmpty, \"expected non-empty value\")"
1725 );
1726 } else if result_is_simple {
1727 let _ = writeln!(
1729 out,
1730 " XCTAssertFalse({result_var}.isEmpty, \"expected non-empty value\")"
1731 );
1732 } else {
1733 let count_target = swift_count_target(&field_expr, field_resolver, assertion.field.as_deref());
1748 let len_expr = if accessor_is_optional {
1749 format!("({count_target}.count ?? 0)")
1750 } else {
1751 format!("{count_target}.count")
1752 };
1753 let _ = writeln!(
1754 out,
1755 " XCTAssertGreaterThan({len_expr}, 0, \"expected non-empty value\")"
1756 );
1757 }
1758 }
1759 }
1760 "is_empty" => {
1761 if bare_result_is_option {
1762 let _ = writeln!(out, " XCTAssertNil({result_var}, \"expected nil value\")");
1763 } else if field_is_optional {
1764 let _ = writeln!(out, " XCTAssertNil({field_expr}, \"expected nil value\")");
1765 } else if field_is_array {
1766 let _ = writeln!(
1767 out,
1768 " XCTAssertTrue({field_expr}.isEmpty, \"expected empty value\")"
1769 );
1770 } else {
1771 let count_target = swift_count_target(&field_expr, field_resolver, assertion.field.as_deref());
1775 let len_expr = if accessor_is_optional {
1776 format!("({count_target}.count ?? 0)")
1777 } else {
1778 format!("{count_target}.count")
1779 };
1780 let _ = writeln!(out, " XCTAssertEqual({len_expr}, 0, \"expected empty value\")");
1781 }
1782 }
1783 "contains_any" => {
1784 if let Some(values) = &assertion.values {
1785 let checks: Vec<String> = values
1786 .iter()
1787 .map(|v| {
1788 let swift_val = json_to_swift(v);
1789 format!("{string_expr}.contains({swift_val})")
1790 })
1791 .collect();
1792 let joined = checks.join(" || ");
1793 let _ = writeln!(
1794 out,
1795 " XCTAssertTrue({joined}, \"expected to contain at least one of the specified values\")"
1796 );
1797 }
1798 }
1799 "greater_than" => {
1800 if let Some(val) = &assertion.value {
1801 let swift_val = json_to_swift(val);
1802 let field_is_optional = accessor_is_optional
1805 || assertion.field.as_deref().is_some_and(|f| {
1806 field_resolver.is_optional(f) || field_resolver.is_optional(field_resolver.resolve(f))
1807 });
1808 let compare_expr = if field_is_optional {
1809 format!("({field_expr} ?? 0)")
1810 } else {
1811 field_expr.clone()
1812 };
1813 let _ = writeln!(out, " XCTAssertGreaterThan({compare_expr}, {swift_val})");
1814 }
1815 }
1816 "less_than" => {
1817 if let Some(val) = &assertion.value {
1818 let swift_val = json_to_swift(val);
1819 let field_is_optional = accessor_is_optional
1820 || assertion.field.as_deref().is_some_and(|f| {
1821 field_resolver.is_optional(f) || field_resolver.is_optional(field_resolver.resolve(f))
1822 });
1823 let compare_expr = if field_is_optional {
1824 format!("({field_expr} ?? 0)")
1825 } else {
1826 field_expr.clone()
1827 };
1828 let _ = writeln!(out, " XCTAssertLessThan({compare_expr}, {swift_val})");
1829 }
1830 }
1831 "greater_than_or_equal" => {
1832 if let Some(val) = &assertion.value {
1833 let swift_val = json_to_swift(val);
1834 let field_is_optional = accessor_is_optional
1837 || assertion.field.as_deref().is_some_and(|f| {
1838 field_resolver.is_optional(f) || field_resolver.is_optional(field_resolver.resolve(f))
1839 });
1840 let compare_expr = if field_is_optional {
1841 format!("({field_expr} ?? 0)")
1842 } else {
1843 field_expr.clone()
1844 };
1845 let _ = writeln!(out, " XCTAssertGreaterThanOrEqual({compare_expr}, {swift_val})");
1846 }
1847 }
1848 "less_than_or_equal" => {
1849 if let Some(val) = &assertion.value {
1850 let swift_val = json_to_swift(val);
1851 let field_is_optional = accessor_is_optional
1852 || assertion.field.as_deref().is_some_and(|f| {
1853 field_resolver.is_optional(f) || field_resolver.is_optional(field_resolver.resolve(f))
1854 });
1855 let compare_expr = if field_is_optional {
1856 format!("({field_expr} ?? 0)")
1857 } else {
1858 field_expr.clone()
1859 };
1860 let _ = writeln!(out, " XCTAssertLessThanOrEqual({compare_expr}, {swift_val})");
1861 }
1862 }
1863 "starts_with" => {
1864 if let Some(expected) = &assertion.value {
1865 let swift_val = json_to_swift(expected);
1866 let _ = writeln!(
1867 out,
1868 " XCTAssertTrue({string_expr}.hasPrefix({swift_val}), \"expected to start with: \\({swift_val})\")"
1869 );
1870 }
1871 }
1872 "ends_with" => {
1873 if let Some(expected) = &assertion.value {
1874 let swift_val = json_to_swift(expected);
1875 let _ = writeln!(
1876 out,
1877 " XCTAssertTrue({string_expr}.hasSuffix({swift_val}), \"expected to end with: \\({swift_val})\")"
1878 );
1879 }
1880 }
1881 "min_length" => {
1882 if let Some(val) = &assertion.value {
1883 if let Some(n) = val.as_u64() {
1884 let _ = writeln!(out, " XCTAssertGreaterThanOrEqual({string_expr}.count, {n})");
1887 }
1888 }
1889 }
1890 "max_length" => {
1891 if let Some(val) = &assertion.value {
1892 if let Some(n) = val.as_u64() {
1893 let _ = writeln!(out, " XCTAssertLessThanOrEqual({string_expr}.count, {n})");
1894 }
1895 }
1896 }
1897 "count_min" => {
1898 if let Some(val) = &assertion.value {
1899 if let Some(n) = val.as_u64() {
1900 let count_expr = swift_array_count_expr(assertion.field.as_deref(), result_var, field_resolver);
1904 let _ = writeln!(out, " XCTAssertGreaterThanOrEqual({count_expr}, {n})");
1905 }
1906 }
1907 }
1908 "count_equals" => {
1909 if let Some(val) = &assertion.value {
1910 if let Some(n) = val.as_u64() {
1911 let count_expr = swift_array_count_expr(assertion.field.as_deref(), result_var, field_resolver);
1912 let _ = writeln!(out, " XCTAssertEqual({count_expr}, {n})");
1913 }
1914 }
1915 }
1916 "is_true" => {
1917 let _ = writeln!(out, " XCTAssertTrue({field_expr})");
1918 }
1919 "is_false" => {
1920 let _ = writeln!(out, " XCTAssertFalse({field_expr})");
1921 }
1922 "matches_regex" => {
1923 if let Some(expected) = &assertion.value {
1924 let swift_val = json_to_swift(expected);
1925 let _ = writeln!(
1926 out,
1927 " XCTAssertNotNil({string_expr}.range(of: {swift_val}, options: .regularExpression), \"expected value to match regex: \\({swift_val})\")"
1928 );
1929 }
1930 }
1931 "not_error" => {
1932 }
1934 "error" => {
1935 }
1937 "method_result" => {
1938 let _ = writeln!(out, " // method_result assertions not yet implemented for Swift");
1939 }
1940 other => {
1941 panic!("Swift e2e generator: unsupported assertion type: {other}");
1942 }
1943 }
1944}
1945
1946fn materialise_vec_temporaries(expr: &str, name_suffix: &str) -> (Vec<String>, String, bool) {
1971 let Some(idx) = expr.find("()[") else {
1972 return (Vec::new(), expr.to_string(), false);
1973 };
1974 let after_open = idx + 3; let Some(close_rel) = expr[after_open..].find(']') else {
1976 return (Vec::new(), expr.to_string(), false);
1977 };
1978 let subscript_end = after_open + close_rel; let prefix = &expr[..idx + 2]; let subscript = &expr[idx + 2..=subscript_end]; let tail = &expr[subscript_end + 1..]; let method_dot = expr[..idx].rfind('.').unwrap_or(0);
1983 let method = &expr[method_dot + 1..idx];
1984 let local = format!("_vec_{}_{}", method, name_suffix);
1985
1986 let inner = subscript.trim_start_matches('[').trim_end_matches(']');
1991 let is_string_key = inner.starts_with('"') && inner.ends_with('"');
1992 let setup = if is_string_key {
1993 format!(
1994 "let {local} = (try? JSONSerialization.jsonObject(with: ({prefix}.toString() ?? \"{{}}\").data(using: .utf8)!) as? [String: String]) ?? [:]"
1995 )
1996 } else {
1997 format!("let {local} = {prefix}")
1998 };
1999
2000 let rewritten = format!("{local}{subscript}{tail}");
2001 (vec![setup], rewritten, is_string_key)
2002}
2003
2004fn swift_build_accessor(field: &str, result_var: &str, field_resolver: &FieldResolver) -> (String, bool) {
2007 let resolved = field_resolver.resolve(field);
2008 let parts: Vec<&str> = resolved.split('.').collect();
2009
2010 let mut current_type: Option<String> = field_resolver.swift_root_type().cloned();
2015 let mut via_rust_vec = false;
2020
2021 let mut out = result_var.to_string();
2022 let mut has_optional = false;
2023 let mut path_so_far = String::new();
2024 let total = parts.len();
2025 for (i, part) in parts.iter().enumerate() {
2026 let is_leaf = i == total - 1;
2027 let (field_name, subscript): (&str, Option<&str>) = if let Some(bracket_pos) = part.find('[') {
2031 (&part[..bracket_pos], Some(&part[bracket_pos..]))
2032 } else {
2033 (part, None)
2034 };
2035
2036 if !path_so_far.is_empty() {
2037 path_so_far.push('.');
2038 }
2039 let base_path = {
2043 let mut p = path_so_far.clone();
2044 p.push_str(field_name);
2045 p
2046 };
2047 path_so_far.push_str(part);
2050
2051 let property_syntax = !via_rust_vec && field_resolver.swift_is_first_class(current_type.as_deref());
2055 out.push('.');
2056 out.push_str(&field_name.to_lower_camel_case());
2059 if let Some(sub) = subscript {
2060 let field_is_optional = field_resolver.is_optional(&base_path);
2064 let access = if property_syntax { "" } else { "()" };
2065 if field_is_optional {
2066 out.push_str(&format!("{access}?"));
2067 has_optional = true;
2068 } else {
2069 out.push_str(access);
2070 }
2071 out.push_str(sub);
2072 current_type = field_resolver.swift_advance(current_type.as_deref(), field_name);
2082 if !property_syntax {
2083 via_rust_vec = true;
2084 }
2085 } else {
2086 if !property_syntax {
2087 out.push_str("()");
2088 }
2089 if !is_leaf && field_resolver.is_optional(&base_path) {
2092 out.push('?');
2093 has_optional = true;
2094 }
2095 current_type = field_resolver.swift_advance(current_type.as_deref(), field_name);
2096 }
2097 }
2098 (out, has_optional)
2099}
2100
2101#[allow(clippy::too_many_arguments)]
2123fn swift_traversal_contains_assert(
2124 array_part: &str,
2125 element_part: &str,
2126 full_field: &str,
2127 val_expr: &str,
2128 result_var: &str,
2129 negate: bool,
2130 msg: &str,
2131 enum_fields: &std::collections::HashSet<String>,
2132 field_resolver: &FieldResolver,
2133) -> String {
2134 let array_accessor = field_resolver.accessor(array_part, "swift", result_var);
2135 let resolved_full = field_resolver.resolve(full_field);
2136 let resolved_elem_part = resolved_full
2137 .find("[].")
2138 .map(|d| &resolved_full[d + 3..])
2139 .unwrap_or(element_part);
2140 let elem_accessor = field_resolver.accessor(resolved_elem_part, "swift", "$0");
2141 let elem_is_enum = enum_fields.contains(full_field) || enum_fields.contains(resolved_full);
2142 let elem_is_optional = field_resolver.is_optional(resolved_elem_part)
2143 || field_resolver.is_optional(field_resolver.resolve(resolved_elem_part));
2144 let elem_str = if elem_is_enum {
2145 format!("{elem_accessor}.toString()")
2148 } else if elem_is_optional {
2149 format!("({elem_accessor}?.toString() ?? \"\")")
2150 } else {
2151 format!("{elem_accessor}.toString()")
2152 };
2153 let assert_fn = if negate { "XCTAssertFalse" } else { "XCTAssertTrue" };
2154 format!(" {assert_fn}({array_accessor}.contains(where: {{ {elem_str}.contains({val_expr}) }}), \"{msg}\")")
2155}
2156
2157fn swift_array_contains_expr(field: Option<&str>, result_var: &str, field_resolver: &FieldResolver) -> String {
2158 let Some(f) = field else {
2159 return format!("{result_var}.map {{ $0.as_str().toString() }}");
2160 };
2161 let (accessor, _has_optional) = swift_build_accessor(f, result_var, field_resolver);
2162 format!("{accessor}?.map {{ $0.as_str().toString() }}")
2165}
2166
2167fn swift_array_count_expr(field: Option<&str>, result_var: &str, field_resolver: &FieldResolver) -> String {
2176 let Some(f) = field else {
2177 return format!("{result_var}.count");
2178 };
2179 let (accessor, mut has_optional) = swift_build_accessor(f, result_var, field_resolver);
2180 if field_resolver.is_optional(f) {
2182 has_optional = true;
2183 }
2184 if has_optional {
2185 if accessor.contains("?.") {
2188 format!("{accessor}.count ?? 0")
2189 } else {
2190 format!("({accessor}?.count ?? 0)")
2193 }
2194 } else {
2195 format!("{accessor}.count")
2196 }
2197}
2198
2199fn json_to_swift(value: &serde_json::Value) -> String {
2201 match value {
2202 serde_json::Value::String(s) => format!("\"{}\"", escape_swift(s)),
2203 serde_json::Value::Bool(b) => b.to_string(),
2204 serde_json::Value::Number(n) => n.to_string(),
2205 serde_json::Value::Null => "nil".to_string(),
2206 serde_json::Value::Array(arr) => {
2207 let items: Vec<String> = arr.iter().map(json_to_swift).collect();
2208 format!("[{}]", items.join(", "))
2209 }
2210 serde_json::Value::Object(_) => {
2211 let json_str = serde_json::to_string(value).unwrap_or_default();
2212 format!("\"{}\"", escape_swift(&json_str))
2213 }
2214 }
2215}
2216
2217fn escape_swift(s: &str) -> String {
2219 escape_swift_str(s)
2220}
2221
2222fn swift_count_target(field_expr: &str, field_resolver: &FieldResolver, field: Option<&str>) -> String {
2239 let is_method_call = field_expr.trim_end().ends_with(')');
2240 if !is_method_call {
2241 return field_expr.to_string();
2242 }
2243 if let Some(f) = field
2244 && field_resolver.leaf_is_vec_via_swift_map(field_resolver.resolve(f))
2245 {
2246 return field_expr.to_string();
2247 }
2248 format!("{field_expr}.toString()")
2249}
2250
2251fn swift_call_result_type(call_config: &alef_core::config::e2e::CallConfig) -> Option<String> {
2265 const LOOKUP_LANGS: &[&str] = &["c", "csharp", "java", "kotlin", "go", "php"];
2266 for lang in LOOKUP_LANGS {
2267 if let Some(o) = call_config.overrides.get(*lang)
2268 && let Some(rt) = o.result_type.as_deref()
2269 && !rt.is_empty()
2270 {
2271 return Some(rt.to_string());
2272 }
2273 }
2274 None
2275}
2276
2277fn swift_first_class_field_supported(ty: &alef_core::ir::TypeRef, known_dto_names: &HashSet<String>) -> bool {
2291 use alef_core::ir::TypeRef;
2292 match ty {
2293 TypeRef::Primitive(_) | TypeRef::String => true,
2294 TypeRef::Named(name) => known_dto_names.contains(name),
2295 TypeRef::Vec(inner) | TypeRef::Optional(inner) => swift_first_class_field_supported(inner, known_dto_names),
2296 _ => false,
2297 }
2298}
2299
2300fn build_swift_first_class_map(
2320 type_defs: &[alef_core::ir::TypeDef],
2321 enum_defs: &[alef_core::ir::EnumDef],
2322 e2e_config: &crate::config::E2eConfig,
2323) -> SwiftFirstClassMap {
2324 use alef_core::ir::TypeRef;
2325 let mut field_types: HashMap<String, HashMap<String, String>> = HashMap::new();
2326 let mut vec_field_names: HashSet<String> = HashSet::new();
2327 fn inner_named(ty: &TypeRef) -> Option<String> {
2328 match ty {
2329 TypeRef::Named(n) => Some(n.clone()),
2330 TypeRef::Optional(inner) | TypeRef::Vec(inner) => inner_named(inner),
2331 _ => None,
2332 }
2333 }
2334 fn is_vec_ty(ty: &TypeRef) -> bool {
2335 match ty {
2336 TypeRef::Vec(_) => true,
2337 TypeRef::Optional(inner) => is_vec_ty(inner),
2338 _ => false,
2339 }
2340 }
2341 let mut known_dto_names: HashSet<String> = enum_defs
2344 .iter()
2345 .filter(|e| e.has_serde && e.variants.iter().all(|v| v.fields.is_empty()))
2346 .map(|e| e.name.clone())
2347 .collect();
2348
2349 let candidates: Vec<&alef_core::ir::TypeDef> = type_defs
2355 .iter()
2356 .filter(|td| !td.is_trait && !td.is_opaque && td.has_serde && !td.fields.is_empty())
2357 .collect();
2358
2359 loop {
2360 let prev = known_dto_names.len();
2361 for td in &candidates {
2362 if known_dto_names.contains(&td.name) {
2363 continue;
2364 }
2365 let all_supported = td
2366 .fields
2367 .iter()
2368 .filter(|f| !f.binding_excluded)
2369 .all(|f| swift_first_class_field_supported(&f.ty, &known_dto_names));
2370 if all_supported {
2371 known_dto_names.insert(td.name.clone());
2372 }
2373 }
2374 if known_dto_names.len() == prev {
2375 break;
2376 }
2377 }
2378
2379 let first_class_types: HashSet<String> = candidates
2384 .iter()
2385 .filter(|td| known_dto_names.contains(&td.name))
2386 .map(|td| td.name.clone())
2387 .collect();
2388
2389 for td in type_defs {
2390 let mut td_field_types: HashMap<String, String> = HashMap::new();
2391 for f in &td.fields {
2392 if let Some(named) = inner_named(&f.ty) {
2393 td_field_types.insert(f.name.clone(), named);
2394 }
2395 if is_vec_ty(&f.ty) {
2396 vec_field_names.insert(f.name.clone());
2397 }
2398 }
2399 if !td_field_types.is_empty() {
2400 field_types.insert(td.name.clone(), td_field_types);
2401 }
2402 }
2403 let root_type = if e2e_config.result_fields.is_empty() {
2407 None
2408 } else {
2409 let matches: Vec<&alef_core::ir::TypeDef> = type_defs
2410 .iter()
2411 .filter(|td| {
2412 let names: HashSet<&str> = td.fields.iter().map(|f| f.name.as_str()).collect();
2413 e2e_config.result_fields.iter().all(|rf| names.contains(rf.as_str()))
2414 })
2415 .collect();
2416 if matches.len() == 1 {
2417 Some(matches[0].name.clone())
2418 } else {
2419 None
2420 }
2421 };
2422 SwiftFirstClassMap {
2423 first_class_types,
2424 field_types,
2425 vec_field_names,
2426 root_type,
2427 }
2428}
2429
2430#[cfg(test)]
2431mod tests {
2432 use super::*;
2433 use crate::field_access::FieldResolver;
2434 use std::collections::{HashMap, HashSet};
2435
2436 fn make_resolver_tool_calls() -> FieldResolver {
2437 let mut optional = HashSet::new();
2441 optional.insert("choices.message.tool_calls".to_string());
2442 let mut arrays = HashSet::new();
2443 arrays.insert("choices".to_string());
2444 FieldResolver::new(&HashMap::new(), &optional, &HashSet::new(), &arrays, &HashSet::new())
2445 }
2446
2447 #[test]
2457 fn optional_vec_subscript_does_not_emit_trailing_question_mark_before_next_segment() {
2458 let resolver = make_resolver_tool_calls();
2459 let (accessor, has_optional) =
2460 swift_build_accessor("choices[0].message.tool_calls[0].function.name", "result", &resolver);
2461 assert!(
2464 accessor.contains("toolCalls?[0]"),
2465 "expected `toolCalls?[0]` for optional tool_calls, got: {accessor}"
2466 );
2467 assert!(
2469 !accessor.contains("?[0]?"),
2470 "must not emit trailing `?` after subscript index: {accessor}"
2471 );
2472 assert!(has_optional, "expected has_optional=true for optional field chain");
2474 assert!(
2476 accessor.contains("[0].function"),
2477 "expected `.function` (non-optional) after subscript: {accessor}"
2478 );
2479 }
2480}