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 {
867 format!("try await {function_name}({args_str})")
868 } else {
869 format!("try {function_name}({args_str})")
870 };
871 (None, expr)
872 };
873 let _ = function_name;
875
876 if is_async {
877 let _ = writeln!(out, " func test{method_name}() async throws {{");
878 } else {
879 let _ = writeln!(out, " func test{method_name}() throws {{");
880 }
881 let _ = writeln!(out, " // {description}");
882
883 if expects_error {
884 if is_async {
888 let _ = writeln!(out, " do {{");
893 for line in &setup_lines {
894 let _ = writeln!(out, " {line}");
895 }
896 if let Some(setup) = &call_setup {
897 let _ = writeln!(out, " {setup}");
898 }
899 let _ = writeln!(out, " _ = {call_expr}");
900 let _ = writeln!(out, " XCTFail(\"expected to throw\")");
901 let _ = writeln!(out, " }} catch {{");
902 let _ = writeln!(out, " // success");
903 let _ = writeln!(out, " }}");
904 } else {
905 let _ = writeln!(out, " do {{");
912 for line in &setup_lines {
913 let _ = writeln!(out, " {line}");
914 }
915 if let Some(setup) = &call_setup {
916 let _ = writeln!(out, " {setup}");
917 }
918 let _ = writeln!(out, " _ = {call_expr}");
919 let _ = writeln!(out, " XCTFail(\"expected to throw\")");
920 let _ = writeln!(out, " }} catch {{");
921 let _ = writeln!(out, " // success");
922 let _ = writeln!(out, " }}");
923 }
924 let _ = writeln!(out, " }}");
925 return;
926 }
927
928 for line in &setup_lines {
929 let _ = writeln!(out, " {line}");
930 }
931
932 if let Some(setup) = &call_setup {
934 let _ = writeln!(out, " {setup}");
935 }
936
937 let _ = writeln!(out, " let {result_var} = {call_expr}");
938
939 if !collect_snippet.is_empty() {
942 for line in collect_snippet.lines() {
943 let _ = writeln!(out, " {line}");
944 }
945 }
946
947 let fixture_root_type: Option<String> = swift_call_result_type(call_config);
952 let fixture_resolver = field_resolver.with_swift_root_type(fixture_root_type);
953
954 for assertion in &fixture.assertions {
955 let mut assertion_out = String::new();
956 render_assertion(
957 &mut assertion_out,
958 assertion,
959 result_var,
960 &fixture_resolver,
961 result_is_simple,
962 result_is_array,
963 result_is_option,
964 &effective_enum_fields,
965 is_streaming,
966 );
967 for unqualified in ["StreamToolCall", "ToolCall"] {
975 assertion_out =
976 assertion_out.replace(&format!("[{unqualified}]"), &format!("[{module_name}.{unqualified}]"));
977 }
978 out.push_str(&assertion_out);
979 }
980
981 let _ = writeln!(out, " }}");
982}
983
984#[allow(clippy::too_many_arguments)]
985fn build_args_and_setup(
999 input: &serde_json::Value,
1000 args: &[crate::config::ArgMapping],
1001 fixture_id: &str,
1002 has_host_root_route: bool,
1003 function_name: &str,
1004 options_via: Option<&str>,
1005 options_type: Option<&str>,
1006 handle_config_fn: Option<&str>,
1007 visitor_handle_expr: Option<&str>,
1008) -> (Vec<String>, String) {
1009 if args.is_empty() {
1010 return (Vec::new(), String::new());
1011 }
1012
1013 let mut setup_lines: Vec<String> = Vec::new();
1014 let mut parts: Vec<String> = Vec::new();
1015
1016 let later_emits: Vec<bool> = (0..args.len())
1021 .map(|i| {
1022 args.iter().skip(i + 1).any(|a| {
1023 let f = a.field.strip_prefix("input.").unwrap_or(&a.field);
1024 let v = input.get(f);
1025 let has_value = matches!(v, Some(x) if !x.is_null());
1026 has_value || !a.optional || (a.arg_type == "json_object" && a.name == "config")
1027 })
1028 })
1029 .collect();
1030
1031 for (idx, arg) in args.iter().enumerate() {
1032 if arg.arg_type == "mock_url" {
1033 let env_key = format!("MOCK_SERVER_{}", fixture_id.to_ascii_uppercase().replace('-', "_"));
1034 let url_expr = if has_host_root_route {
1035 format!(
1036 "ProcessInfo.processInfo.environment[\"{env_key}\"] ?? (ProcessInfo.processInfo.environment[\"MOCK_SERVER_URL\"]! + \"/fixtures/{fixture_id}\")"
1037 )
1038 } else {
1039 format!("ProcessInfo.processInfo.environment[\"MOCK_SERVER_URL\"]! + \"/fixtures/{fixture_id}\"")
1040 };
1041 setup_lines.push(format!("let {} = {url_expr}", arg.name));
1042 parts.push(arg.name.clone());
1043 continue;
1044 }
1045
1046 if arg.arg_type == "handle" {
1047 let var_name = format!("{}Obj", arg.name.to_lower_camel_case());
1048 let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1049 let config_val = input.get(field);
1050 let has_config = config_val
1051 .is_some_and(|v| !(v.is_null() || v.is_object() && v.as_object().is_some_and(|o| o.is_empty())));
1052 if has_config {
1053 if let Some(from_json_fn) = handle_config_fn {
1054 let json_str = serde_json::to_string(config_val.unwrap()).unwrap_or_default();
1055 let escaped = escape_swift_str(&json_str);
1056 let config_var = format!("{}Config", arg.name.to_lower_camel_case());
1057 setup_lines.push(format!("let {config_var} = try {from_json_fn}(\"{escaped}\")"));
1058 setup_lines.push(format!("let {var_name} = try createEngine({config_var})"));
1059 } else {
1060 setup_lines.push(format!("let {var_name} = try createEngine(nil)"));
1061 }
1062 } else {
1063 setup_lines.push(format!("let {var_name} = try createEngine(nil)"));
1064 }
1065 parts.push(var_name);
1066 continue;
1067 }
1068
1069 if arg.arg_type == "bytes" {
1074 let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1075 let val = input.get(field);
1076 match val {
1077 None | Some(serde_json::Value::Null) if arg.optional => {
1078 if later_emits[idx] {
1079 parts.push("nil".to_string());
1080 }
1081 }
1082 None | Some(serde_json::Value::Null) => {
1083 let var_name = format!("{}Vec", arg.name.to_lower_camel_case());
1084 setup_lines.push(format!("let {var_name} = RustVec<UInt8>()"));
1085 parts.push(var_name);
1086 }
1087 Some(serde_json::Value::String(s)) => {
1088 let escaped = escape_swift(s);
1089 let var_name = format!("{}Vec", arg.name.to_lower_camel_case());
1090 let data_var = format!("{}Data", arg.name.to_lower_camel_case());
1091 setup_lines.push(format!(
1092 "let {data_var} = try Data(contentsOf: URL(fileURLWithPath: \"{escaped}\"))"
1093 ));
1094 setup_lines.push(format!("let {var_name} = RustVec<UInt8>()"));
1095 setup_lines.push(format!("for _byte in {data_var} {{ {var_name}.push(value: _byte) }}"));
1096 parts.push(var_name);
1097 }
1098 Some(serde_json::Value::Array(arr)) => {
1099 let var_name = format!("{}Vec", arg.name.to_lower_camel_case());
1100 setup_lines.push(format!("let {var_name} = RustVec<UInt8>()"));
1101 for v in arr {
1102 if let Some(n) = v.as_u64() {
1103 setup_lines.push(format!("{var_name}.push(value: UInt8({n}))"));
1104 }
1105 }
1106 parts.push(var_name);
1107 }
1108 Some(other) => {
1109 let json_str = serde_json::to_string(other).unwrap_or_default();
1111 let escaped = escape_swift(&json_str);
1112 let var_name = format!("{}Vec", arg.name.to_lower_camel_case());
1113 setup_lines.push(format!("let {var_name} = RustVec<UInt8>()"));
1114 setup_lines.push(format!(
1115 "for _byte in Array(\"{escaped}\".utf8) {{ {var_name}.push(value: _byte) }}"
1116 ));
1117 parts.push(var_name);
1118 }
1119 }
1120 continue;
1121 }
1122
1123 let is_config_arg = arg.name == "config" && arg.arg_type == "json_object";
1129 let is_batch_fn = function_name.starts_with("batch") || function_name.starts_with("Batch");
1130 if is_config_arg && !is_batch_fn {
1131 let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1132 let val = input.get(field);
1133 let json_str = match val {
1134 None | Some(serde_json::Value::Null) => "{}".to_string(),
1135 Some(v) => serde_json::to_string(v).unwrap_or_else(|_| "{}".to_string()),
1136 };
1137 let escaped = escape_swift(&json_str);
1138 let var_name = format!("{}Obj", arg.name.to_lower_camel_case());
1139 let from_json_fn = if let Some(type_name) = options_type {
1141 format!("{}FromJson", type_name.to_lower_camel_case())
1142 } else {
1143 "extractionConfigFromJson".to_string()
1144 };
1145 setup_lines.push(format!("let {var_name} = try {from_json_fn}(\"{escaped}\")"));
1146 parts.push(var_name);
1147 continue;
1148 }
1149
1150 if arg.arg_type == "json_object" && options_via == Some("from_json") {
1157 if let Some(type_name) = options_type {
1158 let resolved_val = super::resolve_field(input, &arg.field);
1159 let json_str = match resolved_val {
1160 serde_json::Value::Null => "{}".to_string(),
1161 v => serde_json::to_string(v).unwrap_or_else(|_| "{}".to_string()),
1162 };
1163 let escaped = escape_swift(&json_str);
1164 let var_name = format!("_{}", arg.name.to_lower_camel_case());
1165 if let Some(handle_expr) = visitor_handle_expr {
1166 let with_visitor_fn = format!("{}FromJsonWithVisitor", type_name.to_lower_camel_case());
1171 let handle_var = format!("_visitorHandle_{}", var_name.trim_start_matches('_'));
1172 setup_lines.push(format!("let {handle_var} = {handle_expr}"));
1173 setup_lines.push(format!(
1174 "let {var_name} = try {with_visitor_fn}(\"{escaped}\", {handle_var})"
1175 ));
1176 } else {
1177 let from_json_fn = format!("{}FromJson", type_name.to_lower_camel_case());
1178 setup_lines.push(format!("let {var_name} = try {from_json_fn}(\"{escaped}\")"));
1179 }
1180 parts.push(var_name);
1181 continue;
1182 }
1183 }
1184
1185 let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
1186 let val = input.get(field);
1187 match val {
1188 None | Some(serde_json::Value::Null) if arg.optional => {
1189 if later_emits[idx] {
1193 parts.push("nil".to_string());
1194 }
1195 }
1196 None | Some(serde_json::Value::Null) => {
1197 let default_val = match arg.arg_type.as_str() {
1198 "string" => "\"\"".to_string(),
1199 "int" | "integer" => "0".to_string(),
1200 "float" | "number" => "0.0".to_string(),
1201 "bool" | "boolean" => "false".to_string(),
1202 _ => "nil".to_string(),
1203 };
1204 parts.push(default_val);
1205 }
1206 Some(v) => {
1207 parts.push(json_to_swift(v));
1208 }
1209 }
1210 }
1211
1212 (setup_lines, parts.join(", "))
1213}
1214
1215#[allow(clippy::too_many_arguments)]
1216fn render_assertion(
1217 out: &mut String,
1218 assertion: &Assertion,
1219 result_var: &str,
1220 field_resolver: &FieldResolver,
1221 result_is_simple: bool,
1222 result_is_array: bool,
1223 result_is_option: bool,
1224 enum_fields: &HashSet<String>,
1225 is_streaming: bool,
1226) {
1227 let bare_result_is_option = result_is_option && assertion.field.as_deref().filter(|f| !f.is_empty()).is_none();
1232 if let Some(f) = &assertion.field {
1237 let is_streaming_usage_path =
1238 is_streaming && (f == "usage" || (f.starts_with("usage.") || f.starts_with("usage[")));
1239 if !f.is_empty()
1240 && (crate::codegen::streaming_assertions::is_streaming_virtual_field(f) || is_streaming_usage_path)
1241 {
1242 if let Some(expr) =
1243 crate::codegen::streaming_assertions::StreamingFieldResolver::accessor(f, "swift", "chunks")
1244 {
1245 let line = match assertion.assertion_type.as_str() {
1246 "count_min" => {
1247 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1248 format!(" XCTAssertGreaterThanOrEqual(chunks.count, {n})\n")
1249 } else {
1250 String::new()
1251 }
1252 }
1253 "count_equals" => {
1254 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1255 format!(" XCTAssertEqual(chunks.count, {n})\n")
1256 } else {
1257 String::new()
1258 }
1259 }
1260 "equals" => {
1261 if let Some(serde_json::Value::String(s)) = &assertion.value {
1262 let escaped = escape_swift(s);
1263 format!(" XCTAssertEqual({expr}, \"{escaped}\")\n")
1264 } else if let Some(b) = assertion.value.as_ref().and_then(|v| v.as_bool()) {
1265 format!(" XCTAssertEqual({expr}, {b})\n")
1266 } else {
1267 String::new()
1268 }
1269 }
1270 "not_empty" => {
1271 format!(" XCTAssertFalse({expr}.isEmpty, \"expected non-empty\")\n")
1272 }
1273 "is_empty" => {
1274 format!(" XCTAssertTrue({expr}.isEmpty, \"expected empty\")\n")
1275 }
1276 "is_true" => {
1277 format!(" XCTAssertTrue({expr})\n")
1278 }
1279 "is_false" => {
1280 format!(" XCTAssertFalse({expr})\n")
1281 }
1282 "greater_than" => {
1283 if let Some(n) = assertion.value.as_ref().and_then(|v| v.as_u64()) {
1284 format!(" XCTAssertGreaterThan(chunks.count, {n})\n")
1285 } else {
1286 String::new()
1287 }
1288 }
1289 "contains" => {
1290 if let Some(serde_json::Value::String(s)) = &assertion.value {
1291 let escaped = escape_swift(s);
1292 format!(
1293 " XCTAssertTrue({expr}.contains(\"{escaped}\"), \"expected to contain: {escaped}\")\n"
1294 )
1295 } else {
1296 String::new()
1297 }
1298 }
1299 _ => format!(
1300 " // streaming field '{f}': assertion type '{}' not rendered\n",
1301 assertion.assertion_type
1302 ),
1303 };
1304 if !line.is_empty() {
1305 out.push_str(&line);
1306 }
1307 }
1308 return;
1309 }
1310 }
1311
1312 if let Some(f) = &assertion.field {
1314 if !f.is_empty() && !field_resolver.is_valid_for_result(f) {
1315 let _ = writeln!(out, " // skipped: field '{f}' not available on result type");
1316 return;
1317 }
1318 }
1319
1320 if let Some(f) = &assertion.field {
1325 if !f.is_empty() && field_resolver.tagged_union_split(f).is_some() {
1326 let _ = writeln!(
1327 out,
1328 " // skipped: field '{f}' crosses a tagged-union variant boundary (not expressible in Swift)"
1329 );
1330 return;
1331 }
1332 }
1333
1334 let field_is_enum = assertion
1336 .field
1337 .as_deref()
1338 .is_some_and(|f| enum_fields.contains(f) || enum_fields.contains(field_resolver.resolve(f)));
1339
1340 let field_is_optional = assertion.field.as_deref().is_some_and(|f| {
1341 !f.is_empty() && (field_resolver.is_optional(f) || field_resolver.is_optional(field_resolver.resolve(f)))
1342 });
1343 let field_is_array = assertion.field.as_deref().is_some_and(|f| {
1344 !f.is_empty()
1345 && (field_resolver.is_array(f)
1346 || field_resolver.is_array(field_resolver.resolve(f))
1347 || field_resolver.is_collection_root(f)
1348 || field_resolver.is_collection_root(field_resolver.resolve(f)))
1349 });
1350
1351 let field_expr_raw = if result_is_simple {
1352 result_var.to_string()
1353 } else {
1354 match &assertion.field {
1355 Some(f) if !f.is_empty() => field_resolver.accessor(f, "swift", result_var),
1356 _ => result_var.to_string(),
1357 }
1358 };
1359
1360 let local_suffix = {
1370 use std::hash::{Hash, Hasher};
1371 let mut hasher = std::collections::hash_map::DefaultHasher::new();
1372 assertion.field.hash(&mut hasher);
1373 assertion
1374 .value
1375 .as_ref()
1376 .map(|v| v.to_string())
1377 .unwrap_or_default()
1378 .hash(&mut hasher);
1379 format!(
1380 "{}_{:x}",
1381 assertion.assertion_type.replace(['-', '.'], "_"),
1382 hasher.finish() & 0xffff_ffff,
1383 )
1384 };
1385 let (vec_setup, field_expr, is_map_subscript) = materialise_vec_temporaries(&field_expr_raw, &local_suffix);
1386 let field_uses_traversal = assertion.field.as_deref().is_some_and(|f| f.contains("[]."));
1391 let traversal_skips_field_expr = field_uses_traversal
1392 && matches!(
1393 assertion.assertion_type.as_str(),
1394 "contains" | "not_contains" | "not_empty" | "is_empty"
1395 );
1396 if !traversal_skips_field_expr {
1397 for line in &vec_setup {
1398 let _ = writeln!(out, " {line}");
1399 }
1400 }
1401
1402 let accessor_is_optional = field_expr.contains("?.");
1408 let leaf_is_property_access = {
1416 let trimmed = field_expr.trim_end_matches('?');
1417 let last_segment = trimmed.rsplit_once('.').map(|(_, s)| s).unwrap_or(trimmed);
1419 let last_segment = last_segment.split('[').next().unwrap_or(last_segment);
1420 !last_segment.ends_with(')') && !last_segment.is_empty()
1421 };
1422
1423 let string_expr = if is_map_subscript {
1432 format!("({field_expr} ?? \"\")")
1436 } else if leaf_is_property_access {
1437 if field_is_enum && (field_is_optional || accessor_is_optional) {
1442 format!("(({field_expr})?.rawValue ?? \"\")")
1446 } else if field_is_enum {
1447 format!("{field_expr}.rawValue")
1448 } else if field_is_optional || accessor_is_optional {
1449 format!("({field_expr} ?? \"\")")
1450 } else {
1451 field_expr.to_string()
1452 }
1453 } else if field_is_enum && (field_is_optional || accessor_is_optional) {
1454 format!("({field_expr}?.toString() ?? \"\")")
1457 } else if field_is_enum {
1458 format!("{field_expr}.toString()")
1463 } else if field_is_optional {
1464 format!("({field_expr}?.toString() ?? \"\")")
1466 } else if accessor_is_optional {
1467 format!("({field_expr}.toString() ?? \"\")")
1470 } else {
1471 format!("{field_expr}.toString()")
1472 };
1473
1474 match assertion.assertion_type.as_str() {
1475 "equals" => {
1476 if let Some(expected) = &assertion.value {
1477 let swift_val = json_to_swift(expected);
1478 if expected.is_string() {
1479 if field_is_enum {
1480 let trim_expr =
1484 format!("{string_expr}.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)");
1485 let _ = writeln!(out, " XCTAssertEqual({trim_expr}, {swift_val})");
1486 } else {
1487 let trim_expr =
1492 format!("{string_expr}.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)");
1493 let _ = writeln!(out, " XCTAssertEqual({trim_expr}, {swift_val})");
1494 }
1495 } else {
1496 let _ = writeln!(out, " XCTAssertEqual({field_expr}, {swift_val})");
1497 }
1498 }
1499 }
1500 "contains" => {
1501 if let Some(expected) = &assertion.value {
1502 let swift_val = json_to_swift(expected);
1503 let no_field = assertion.field.as_deref().is_none_or(|f| f.is_empty());
1506 if result_is_simple && result_is_array && no_field {
1507 let _ = writeln!(
1510 out,
1511 " XCTAssertTrue({result_var}.map {{ $0.as_str().toString() }}.contains({swift_val}), \"expected to contain: \\({swift_val})\")"
1512 );
1513 } else {
1514 let traversal_handled = if let Some(f) = assertion.field.as_deref() {
1516 if let Some(dot) = f.find("[].") {
1517 let array_part = &f[..dot];
1518 let elem_part = &f[dot + 3..];
1519 let line = swift_traversal_contains_assert(
1520 array_part,
1521 elem_part,
1522 f,
1523 &swift_val,
1524 result_var,
1525 false,
1526 &format!("expected to contain: \\({swift_val})"),
1527 enum_fields,
1528 field_resolver,
1529 );
1530 let _ = writeln!(out, "{line}");
1531 true
1532 } else {
1533 false
1534 }
1535 } else {
1536 false
1537 };
1538 if !traversal_handled {
1539 let field_is_array = assertion
1541 .field
1542 .as_deref()
1543 .is_some_and(|f| field_resolver.is_array(field_resolver.resolve(f)));
1544 if field_is_array {
1545 let contains_expr =
1546 swift_array_contains_expr(assertion.field.as_deref(), result_var, field_resolver);
1547 let _ = writeln!(
1548 out,
1549 " XCTAssertTrue(({contains_expr} ?? []).contains({swift_val}), \"expected to contain: \\({swift_val})\")"
1550 );
1551 } else if field_is_enum {
1552 let _ = writeln!(
1555 out,
1556 " XCTAssertTrue({string_expr}.contains({swift_val}), \"expected to contain: \\({swift_val})\")"
1557 );
1558 } else {
1559 let _ = writeln!(
1560 out,
1561 " XCTAssertTrue({string_expr}.contains({swift_val}), \"expected to contain: \\({swift_val})\")"
1562 );
1563 }
1564 }
1565 }
1566 }
1567 }
1568 "contains_all" => {
1569 if let Some(values) = &assertion.values {
1570 if let Some(f) = assertion.field.as_deref() {
1572 if let Some(dot) = f.find("[].") {
1573 let array_part = &f[..dot];
1574 let elem_part = &f[dot + 3..];
1575 for val in values {
1576 let swift_val = json_to_swift(val);
1577 let line = swift_traversal_contains_assert(
1578 array_part,
1579 elem_part,
1580 f,
1581 &swift_val,
1582 result_var,
1583 false,
1584 &format!("expected to contain: \\({swift_val})"),
1585 enum_fields,
1586 field_resolver,
1587 );
1588 let _ = writeln!(out, "{line}");
1589 }
1590 } else {
1592 let field_is_array = field_resolver.is_array(field_resolver.resolve(f));
1594 if field_is_array {
1595 let contains_expr =
1596 swift_array_contains_expr(assertion.field.as_deref(), result_var, field_resolver);
1597 for val in values {
1598 let swift_val = json_to_swift(val);
1599 let _ = writeln!(
1600 out,
1601 " XCTAssertTrue(({contains_expr} ?? []).contains({swift_val}), \"expected to contain: \\({swift_val})\")"
1602 );
1603 }
1604 } else if field_is_enum {
1605 for val in values {
1608 let swift_val = json_to_swift(val);
1609 let _ = writeln!(
1610 out,
1611 " XCTAssertTrue({string_expr}.contains({swift_val}), \"expected to contain: \\({swift_val})\")"
1612 );
1613 }
1614 } else {
1615 for val in values {
1616 let swift_val = json_to_swift(val);
1617 let _ = writeln!(
1618 out,
1619 " XCTAssertTrue({string_expr}.contains({swift_val}), \"expected to contain: \\({swift_val})\")"
1620 );
1621 }
1622 }
1623 }
1624 } else {
1625 for val in values {
1627 let swift_val = json_to_swift(val);
1628 let _ = writeln!(
1629 out,
1630 " XCTAssertTrue({string_expr}.contains({swift_val}), \"expected to contain: \\({swift_val})\")"
1631 );
1632 }
1633 }
1634 }
1635 }
1636 "not_contains" => {
1637 if let Some(expected) = &assertion.value {
1638 let swift_val = json_to_swift(expected);
1639 let traversal_handled = if let Some(f) = assertion.field.as_deref() {
1641 if let Some(dot) = f.find("[].") {
1642 let array_part = &f[..dot];
1643 let elem_part = &f[dot + 3..];
1644 let line = swift_traversal_contains_assert(
1645 array_part,
1646 elem_part,
1647 f,
1648 &swift_val,
1649 result_var,
1650 true,
1651 &format!("expected NOT to contain: \\({swift_val})"),
1652 enum_fields,
1653 field_resolver,
1654 );
1655 let _ = writeln!(out, "{line}");
1656 true
1657 } else {
1658 false
1659 }
1660 } else {
1661 false
1662 };
1663 if !traversal_handled {
1664 let _ = writeln!(
1665 out,
1666 " XCTAssertFalse({string_expr}.contains({swift_val}), \"expected NOT to contain: \\({swift_val})\")"
1667 );
1668 }
1669 }
1670 }
1671 "not_empty" => {
1672 let traversal_not_empty_handled = if let Some(f) = assertion.field.as_deref() {
1679 if let Some(dot) = f.find("[].") {
1680 let array_part = &f[..dot];
1681 let elem_part = &f[dot + 3..];
1682 let array_accessor = field_resolver.accessor(array_part, "swift", result_var);
1683 let resolved_full = field_resolver.resolve(f);
1684 let resolved_elem_part = resolved_full
1685 .find("[].")
1686 .map(|d| &resolved_full[d + 3..])
1687 .unwrap_or(elem_part);
1688 let elem_accessor = field_resolver.accessor(resolved_elem_part, "swift", "$0");
1689 let elem_is_enum = enum_fields.contains(f) || enum_fields.contains(resolved_full);
1690 let elem_is_optional = field_resolver.is_optional(resolved_elem_part)
1691 || field_resolver.is_optional(field_resolver.resolve(resolved_elem_part));
1692 let elem_str = if elem_is_enum {
1693 format!("{elem_accessor}.to_string().toString()")
1694 } else if elem_is_optional {
1695 format!("({elem_accessor}?.toString() ?? \"\")")
1696 } else {
1697 format!("{elem_accessor}.toString()")
1698 };
1699 let _ = writeln!(
1700 out,
1701 " XCTAssertTrue({array_accessor}.contains(where: {{ !{elem_str}.isEmpty }}), \"expected non-empty value\")"
1702 );
1703 true
1704 } else {
1705 false
1706 }
1707 } else {
1708 false
1709 };
1710 if !traversal_not_empty_handled {
1711 if bare_result_is_option {
1712 let _ = writeln!(out, " XCTAssertNotNil({result_var}, \"expected non-nil value\")");
1713 } else if field_is_optional {
1714 let _ = writeln!(out, " XCTAssertNotNil({field_expr}, \"expected non-nil value\")");
1715 } else if field_is_array {
1716 let _ = writeln!(
1717 out,
1718 " XCTAssertFalse({field_expr}.isEmpty, \"expected non-empty value\")"
1719 );
1720 } else if result_is_simple {
1721 let _ = writeln!(
1723 out,
1724 " XCTAssertFalse({result_var}.isEmpty, \"expected non-empty value\")"
1725 );
1726 } else {
1727 let count_target = swift_count_target(&field_expr, field_resolver, assertion.field.as_deref());
1742 let len_expr = if accessor_is_optional {
1743 format!("({count_target}.count ?? 0)")
1744 } else {
1745 format!("{count_target}.count")
1746 };
1747 let _ = writeln!(
1748 out,
1749 " XCTAssertGreaterThan({len_expr}, 0, \"expected non-empty value\")"
1750 );
1751 }
1752 }
1753 }
1754 "is_empty" => {
1755 if bare_result_is_option {
1756 let _ = writeln!(out, " XCTAssertNil({result_var}, \"expected nil value\")");
1757 } else if field_is_optional {
1758 let _ = writeln!(out, " XCTAssertNil({field_expr}, \"expected nil value\")");
1759 } else if field_is_array {
1760 let _ = writeln!(
1761 out,
1762 " XCTAssertTrue({field_expr}.isEmpty, \"expected empty value\")"
1763 );
1764 } else {
1765 let count_target = swift_count_target(&field_expr, field_resolver, assertion.field.as_deref());
1769 let len_expr = if accessor_is_optional {
1770 format!("({count_target}.count ?? 0)")
1771 } else {
1772 format!("{count_target}.count")
1773 };
1774 let _ = writeln!(out, " XCTAssertEqual({len_expr}, 0, \"expected empty value\")");
1775 }
1776 }
1777 "contains_any" => {
1778 if let Some(values) = &assertion.values {
1779 let checks: Vec<String> = values
1780 .iter()
1781 .map(|v| {
1782 let swift_val = json_to_swift(v);
1783 format!("{string_expr}.contains({swift_val})")
1784 })
1785 .collect();
1786 let joined = checks.join(" || ");
1787 let _ = writeln!(
1788 out,
1789 " XCTAssertTrue({joined}, \"expected to contain at least one of the specified values\")"
1790 );
1791 }
1792 }
1793 "greater_than" => {
1794 if let Some(val) = &assertion.value {
1795 let swift_val = json_to_swift(val);
1796 let field_is_optional = accessor_is_optional
1799 || assertion.field.as_deref().is_some_and(|f| {
1800 field_resolver.is_optional(f) || field_resolver.is_optional(field_resolver.resolve(f))
1801 });
1802 let compare_expr = if field_is_optional {
1803 format!("({field_expr} ?? 0)")
1804 } else {
1805 field_expr.clone()
1806 };
1807 let _ = writeln!(out, " XCTAssertGreaterThan({compare_expr}, {swift_val})");
1808 }
1809 }
1810 "less_than" => {
1811 if let Some(val) = &assertion.value {
1812 let swift_val = json_to_swift(val);
1813 let field_is_optional = accessor_is_optional
1814 || assertion.field.as_deref().is_some_and(|f| {
1815 field_resolver.is_optional(f) || field_resolver.is_optional(field_resolver.resolve(f))
1816 });
1817 let compare_expr = if field_is_optional {
1818 format!("({field_expr} ?? 0)")
1819 } else {
1820 field_expr.clone()
1821 };
1822 let _ = writeln!(out, " XCTAssertLessThan({compare_expr}, {swift_val})");
1823 }
1824 }
1825 "greater_than_or_equal" => {
1826 if let Some(val) = &assertion.value {
1827 let swift_val = json_to_swift(val);
1828 let field_is_optional = accessor_is_optional
1831 || assertion.field.as_deref().is_some_and(|f| {
1832 field_resolver.is_optional(f) || field_resolver.is_optional(field_resolver.resolve(f))
1833 });
1834 let compare_expr = if field_is_optional {
1835 format!("({field_expr} ?? 0)")
1836 } else {
1837 field_expr.clone()
1838 };
1839 let _ = writeln!(out, " XCTAssertGreaterThanOrEqual({compare_expr}, {swift_val})");
1840 }
1841 }
1842 "less_than_or_equal" => {
1843 if let Some(val) = &assertion.value {
1844 let swift_val = json_to_swift(val);
1845 let field_is_optional = accessor_is_optional
1846 || assertion.field.as_deref().is_some_and(|f| {
1847 field_resolver.is_optional(f) || field_resolver.is_optional(field_resolver.resolve(f))
1848 });
1849 let compare_expr = if field_is_optional {
1850 format!("({field_expr} ?? 0)")
1851 } else {
1852 field_expr.clone()
1853 };
1854 let _ = writeln!(out, " XCTAssertLessThanOrEqual({compare_expr}, {swift_val})");
1855 }
1856 }
1857 "starts_with" => {
1858 if let Some(expected) = &assertion.value {
1859 let swift_val = json_to_swift(expected);
1860 let _ = writeln!(
1861 out,
1862 " XCTAssertTrue({string_expr}.hasPrefix({swift_val}), \"expected to start with: \\({swift_val})\")"
1863 );
1864 }
1865 }
1866 "ends_with" => {
1867 if let Some(expected) = &assertion.value {
1868 let swift_val = json_to_swift(expected);
1869 let _ = writeln!(
1870 out,
1871 " XCTAssertTrue({string_expr}.hasSuffix({swift_val}), \"expected to end with: \\({swift_val})\")"
1872 );
1873 }
1874 }
1875 "min_length" => {
1876 if let Some(val) = &assertion.value {
1877 if let Some(n) = val.as_u64() {
1878 let _ = writeln!(out, " XCTAssertGreaterThanOrEqual({string_expr}.count, {n})");
1881 }
1882 }
1883 }
1884 "max_length" => {
1885 if let Some(val) = &assertion.value {
1886 if let Some(n) = val.as_u64() {
1887 let _ = writeln!(out, " XCTAssertLessThanOrEqual({string_expr}.count, {n})");
1888 }
1889 }
1890 }
1891 "count_min" => {
1892 if let Some(val) = &assertion.value {
1893 if let Some(n) = val.as_u64() {
1894 let count_expr = swift_array_count_expr(assertion.field.as_deref(), result_var, field_resolver);
1898 let _ = writeln!(out, " XCTAssertGreaterThanOrEqual({count_expr}, {n})");
1899 }
1900 }
1901 }
1902 "count_equals" => {
1903 if let Some(val) = &assertion.value {
1904 if let Some(n) = val.as_u64() {
1905 let count_expr = swift_array_count_expr(assertion.field.as_deref(), result_var, field_resolver);
1906 let _ = writeln!(out, " XCTAssertEqual({count_expr}, {n})");
1907 }
1908 }
1909 }
1910 "is_true" => {
1911 let _ = writeln!(out, " XCTAssertTrue({field_expr})");
1912 }
1913 "is_false" => {
1914 let _ = writeln!(out, " XCTAssertFalse({field_expr})");
1915 }
1916 "matches_regex" => {
1917 if let Some(expected) = &assertion.value {
1918 let swift_val = json_to_swift(expected);
1919 let _ = writeln!(
1920 out,
1921 " XCTAssertNotNil({string_expr}.range(of: {swift_val}, options: .regularExpression), \"expected value to match regex: \\({swift_val})\")"
1922 );
1923 }
1924 }
1925 "not_error" => {
1926 }
1928 "error" => {
1929 }
1931 "method_result" => {
1932 let _ = writeln!(out, " // method_result assertions not yet implemented for Swift");
1933 }
1934 other => {
1935 panic!("Swift e2e generator: unsupported assertion type: {other}");
1936 }
1937 }
1938}
1939
1940fn materialise_vec_temporaries(expr: &str, name_suffix: &str) -> (Vec<String>, String, bool) {
1965 let Some(idx) = expr.find("()[") else {
1966 return (Vec::new(), expr.to_string(), false);
1967 };
1968 let after_open = idx + 3; let Some(close_rel) = expr[after_open..].find(']') else {
1970 return (Vec::new(), expr.to_string(), false);
1971 };
1972 let subscript_end = after_open + close_rel; 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);
1977 let method = &expr[method_dot + 1..idx];
1978 let local = format!("_vec_{}_{}", method, name_suffix);
1979
1980 let inner = subscript.trim_start_matches('[').trim_end_matches(']');
1985 let is_string_key = inner.starts_with('"') && inner.ends_with('"');
1986 let setup = if is_string_key {
1987 format!(
1988 "let {local} = (try? JSONSerialization.jsonObject(with: ({prefix}.toString() ?? \"{{}}\").data(using: .utf8)!) as? [String: String]) ?? [:]"
1989 )
1990 } else {
1991 format!("let {local} = {prefix}")
1992 };
1993
1994 let rewritten = format!("{local}{subscript}{tail}");
1995 (vec![setup], rewritten, is_string_key)
1996}
1997
1998fn swift_build_accessor(field: &str, result_var: &str, field_resolver: &FieldResolver) -> (String, bool) {
2001 let resolved = field_resolver.resolve(field);
2002 let parts: Vec<&str> = resolved.split('.').collect();
2003
2004 let mut current_type: Option<String> = field_resolver.swift_root_type().cloned();
2009 let mut via_rust_vec = false;
2014
2015 let mut out = result_var.to_string();
2016 let mut has_optional = false;
2017 let mut path_so_far = String::new();
2018 let total = parts.len();
2019 for (i, part) in parts.iter().enumerate() {
2020 let is_leaf = i == total - 1;
2021 let (field_name, subscript): (&str, Option<&str>) = if let Some(bracket_pos) = part.find('[') {
2025 (&part[..bracket_pos], Some(&part[bracket_pos..]))
2026 } else {
2027 (part, None)
2028 };
2029
2030 if !path_so_far.is_empty() {
2031 path_so_far.push('.');
2032 }
2033 let base_path = {
2037 let mut p = path_so_far.clone();
2038 p.push_str(field_name);
2039 p
2040 };
2041 path_so_far.push_str(part);
2044
2045 let property_syntax = !via_rust_vec && field_resolver.swift_is_first_class(current_type.as_deref());
2049 out.push('.');
2050 out.push_str(&field_name.to_lower_camel_case());
2053 if let Some(sub) = subscript {
2054 let field_is_optional = field_resolver.is_optional(&base_path);
2058 let access = if property_syntax { "" } else { "()" };
2059 if field_is_optional {
2060 out.push_str(&format!("{access}?"));
2061 has_optional = true;
2062 } else {
2063 out.push_str(access);
2064 }
2065 out.push_str(sub);
2066 current_type = field_resolver.swift_advance(current_type.as_deref(), field_name);
2076 if !property_syntax {
2077 via_rust_vec = true;
2078 }
2079 } else {
2080 if !property_syntax {
2081 out.push_str("()");
2082 }
2083 if !is_leaf && field_resolver.is_optional(&base_path) {
2086 out.push('?');
2087 has_optional = true;
2088 }
2089 current_type = field_resolver.swift_advance(current_type.as_deref(), field_name);
2090 }
2091 }
2092 (out, has_optional)
2093}
2094
2095#[allow(clippy::too_many_arguments)]
2117fn swift_traversal_contains_assert(
2118 array_part: &str,
2119 element_part: &str,
2120 full_field: &str,
2121 val_expr: &str,
2122 result_var: &str,
2123 negate: bool,
2124 msg: &str,
2125 enum_fields: &std::collections::HashSet<String>,
2126 field_resolver: &FieldResolver,
2127) -> String {
2128 let array_accessor = field_resolver.accessor(array_part, "swift", result_var);
2129 let resolved_full = field_resolver.resolve(full_field);
2130 let resolved_elem_part = resolved_full
2131 .find("[].")
2132 .map(|d| &resolved_full[d + 3..])
2133 .unwrap_or(element_part);
2134 let elem_accessor = field_resolver.accessor(resolved_elem_part, "swift", "$0");
2135 let elem_is_enum = enum_fields.contains(full_field) || enum_fields.contains(resolved_full);
2136 let elem_is_optional = field_resolver.is_optional(resolved_elem_part)
2137 || field_resolver.is_optional(field_resolver.resolve(resolved_elem_part));
2138 let elem_str = if elem_is_enum {
2139 format!("{elem_accessor}.toString()")
2142 } else if elem_is_optional {
2143 format!("({elem_accessor}?.toString() ?? \"\")")
2144 } else {
2145 format!("{elem_accessor}.toString()")
2146 };
2147 let assert_fn = if negate { "XCTAssertFalse" } else { "XCTAssertTrue" };
2148 format!(" {assert_fn}({array_accessor}.contains(where: {{ {elem_str}.contains({val_expr}) }}), \"{msg}\")")
2149}
2150
2151fn swift_array_contains_expr(field: Option<&str>, result_var: &str, field_resolver: &FieldResolver) -> String {
2152 let Some(f) = field else {
2153 return format!("{result_var}.map {{ $0.as_str().toString() }}");
2154 };
2155 let (accessor, _has_optional) = swift_build_accessor(f, result_var, field_resolver);
2156 format!("{accessor}?.map {{ $0.as_str().toString() }}")
2159}
2160
2161fn swift_array_count_expr(field: Option<&str>, result_var: &str, field_resolver: &FieldResolver) -> String {
2170 let Some(f) = field else {
2171 return format!("{result_var}.count");
2172 };
2173 let (accessor, mut has_optional) = swift_build_accessor(f, result_var, field_resolver);
2174 if field_resolver.is_optional(f) {
2176 has_optional = true;
2177 }
2178 if has_optional {
2179 if accessor.contains("?.") {
2182 format!("{accessor}.count ?? 0")
2183 } else {
2184 format!("({accessor}?.count ?? 0)")
2187 }
2188 } else {
2189 format!("{accessor}.count")
2190 }
2191}
2192
2193fn json_to_swift(value: &serde_json::Value) -> String {
2195 match value {
2196 serde_json::Value::String(s) => format!("\"{}\"", escape_swift(s)),
2197 serde_json::Value::Bool(b) => b.to_string(),
2198 serde_json::Value::Number(n) => n.to_string(),
2199 serde_json::Value::Null => "nil".to_string(),
2200 serde_json::Value::Array(arr) => {
2201 let items: Vec<String> = arr.iter().map(json_to_swift).collect();
2202 format!("[{}]", items.join(", "))
2203 }
2204 serde_json::Value::Object(_) => {
2205 let json_str = serde_json::to_string(value).unwrap_or_default();
2206 format!("\"{}\"", escape_swift(&json_str))
2207 }
2208 }
2209}
2210
2211fn escape_swift(s: &str) -> String {
2213 escape_swift_str(s)
2214}
2215
2216fn swift_count_target(field_expr: &str, field_resolver: &FieldResolver, field: Option<&str>) -> String {
2233 let is_method_call = field_expr.trim_end().ends_with(')');
2234 if !is_method_call {
2235 return field_expr.to_string();
2236 }
2237 if let Some(f) = field
2238 && field_resolver.leaf_is_vec_via_swift_map(field_resolver.resolve(f))
2239 {
2240 return field_expr.to_string();
2241 }
2242 format!("{field_expr}.toString()")
2243}
2244
2245fn swift_call_result_type(call_config: &alef_core::config::e2e::CallConfig) -> Option<String> {
2259 const LOOKUP_LANGS: &[&str] = &["c", "csharp", "java", "kotlin", "go", "php"];
2260 for lang in LOOKUP_LANGS {
2261 if let Some(o) = call_config.overrides.get(*lang)
2262 && let Some(rt) = o.result_type.as_deref()
2263 && !rt.is_empty()
2264 {
2265 return Some(rt.to_string());
2266 }
2267 }
2268 None
2269}
2270
2271fn swift_first_class_field_supported(ty: &alef_core::ir::TypeRef, known_dto_names: &HashSet<String>) -> bool {
2285 use alef_core::ir::TypeRef;
2286 match ty {
2287 TypeRef::Primitive(_) | TypeRef::String => true,
2288 TypeRef::Named(name) => known_dto_names.contains(name),
2289 TypeRef::Vec(inner) | TypeRef::Optional(inner) => swift_first_class_field_supported(inner, known_dto_names),
2290 _ => false,
2291 }
2292}
2293
2294fn build_swift_first_class_map(
2314 type_defs: &[alef_core::ir::TypeDef],
2315 enum_defs: &[alef_core::ir::EnumDef],
2316 e2e_config: &crate::config::E2eConfig,
2317) -> SwiftFirstClassMap {
2318 use alef_core::ir::TypeRef;
2319 let mut field_types: HashMap<String, HashMap<String, String>> = HashMap::new();
2320 let mut vec_field_names: HashSet<String> = HashSet::new();
2321 fn inner_named(ty: &TypeRef) -> Option<String> {
2322 match ty {
2323 TypeRef::Named(n) => Some(n.clone()),
2324 TypeRef::Optional(inner) | TypeRef::Vec(inner) => inner_named(inner),
2325 _ => None,
2326 }
2327 }
2328 fn is_vec_ty(ty: &TypeRef) -> bool {
2329 match ty {
2330 TypeRef::Vec(_) => true,
2331 TypeRef::Optional(inner) => is_vec_ty(inner),
2332 _ => false,
2333 }
2334 }
2335 let mut known_dto_names: HashSet<String> = enum_defs
2338 .iter()
2339 .filter(|e| e.has_serde && e.variants.iter().all(|v| v.fields.is_empty()))
2340 .map(|e| e.name.clone())
2341 .collect();
2342
2343 let candidates: Vec<&alef_core::ir::TypeDef> = type_defs
2349 .iter()
2350 .filter(|td| !td.is_trait && !td.is_opaque && td.has_serde && !td.fields.is_empty())
2351 .collect();
2352
2353 loop {
2354 let prev = known_dto_names.len();
2355 for td in &candidates {
2356 if known_dto_names.contains(&td.name) {
2357 continue;
2358 }
2359 let all_supported = td
2360 .fields
2361 .iter()
2362 .filter(|f| !f.binding_excluded)
2363 .all(|f| swift_first_class_field_supported(&f.ty, &known_dto_names));
2364 if all_supported {
2365 known_dto_names.insert(td.name.clone());
2366 }
2367 }
2368 if known_dto_names.len() == prev {
2369 break;
2370 }
2371 }
2372
2373 let first_class_types: HashSet<String> = candidates
2378 .iter()
2379 .filter(|td| known_dto_names.contains(&td.name))
2380 .map(|td| td.name.clone())
2381 .collect();
2382
2383 for td in type_defs {
2384 let mut td_field_types: HashMap<String, String> = HashMap::new();
2385 for f in &td.fields {
2386 if let Some(named) = inner_named(&f.ty) {
2387 td_field_types.insert(f.name.clone(), named);
2388 }
2389 if is_vec_ty(&f.ty) {
2390 vec_field_names.insert(f.name.clone());
2391 }
2392 }
2393 if !td_field_types.is_empty() {
2394 field_types.insert(td.name.clone(), td_field_types);
2395 }
2396 }
2397 let root_type = if e2e_config.result_fields.is_empty() {
2401 None
2402 } else {
2403 let matches: Vec<&alef_core::ir::TypeDef> = type_defs
2404 .iter()
2405 .filter(|td| {
2406 let names: HashSet<&str> = td.fields.iter().map(|f| f.name.as_str()).collect();
2407 e2e_config.result_fields.iter().all(|rf| names.contains(rf.as_str()))
2408 })
2409 .collect();
2410 if matches.len() == 1 {
2411 Some(matches[0].name.clone())
2412 } else {
2413 None
2414 }
2415 };
2416 SwiftFirstClassMap {
2417 first_class_types,
2418 field_types,
2419 vec_field_names,
2420 root_type,
2421 }
2422}
2423
2424#[cfg(test)]
2425mod tests {
2426 use super::*;
2427 use crate::field_access::FieldResolver;
2428 use std::collections::{HashMap, HashSet};
2429
2430 fn make_resolver_tool_calls() -> FieldResolver {
2431 let mut optional = HashSet::new();
2435 optional.insert("choices.message.tool_calls".to_string());
2436 let mut arrays = HashSet::new();
2437 arrays.insert("choices".to_string());
2438 FieldResolver::new(&HashMap::new(), &optional, &HashSet::new(), &arrays, &HashSet::new())
2439 }
2440
2441 #[test]
2451 fn optional_vec_subscript_does_not_emit_trailing_question_mark_before_next_segment() {
2452 let resolver = make_resolver_tool_calls();
2453 let (accessor, has_optional) =
2454 swift_build_accessor("choices[0].message.tool_calls[0].function.name", "result", &resolver);
2455 assert!(
2458 accessor.contains("toolCalls?[0]"),
2459 "expected `toolCalls?[0]` for optional tool_calls, got: {accessor}"
2460 );
2461 assert!(
2463 !accessor.contains("?[0]?"),
2464 "must not emit trailing `?` after subscript index: {accessor}"
2465 );
2466 assert!(has_optional, "expected has_optional=true for optional field chain");
2468 assert!(
2470 accessor.contains("[0].function"),
2471 "expected `.function` (non-optional) after subscript: {accessor}"
2472 );
2473 }
2474}