1pub const STREAMING_VIRTUAL_FIELDS: &[&str] = &[
34 "chunks",
35 "chunks.length",
36 "stream_content",
37 "stream_complete",
38 "no_chunks_after_done",
39 "tool_calls",
40 "finish_reason",
41 "stream.has_page_event",
46 "stream.has_error_event",
47 "stream.has_complete_event",
48 "stream.event_count_min",
49];
50
51const STREAMING_VIRTUAL_ROOTS: &[&str] = &["tool_calls", "finish_reason"];
61
62pub fn is_streaming_virtual_field(field: &str) -> bool {
70 if STREAMING_VIRTUAL_FIELDS.contains(&field) {
71 return true;
72 }
73 for root in STREAMING_VIRTUAL_ROOTS {
75 if field.len() > root.len() && field.starts_with(root) {
76 let rest = &field[root.len()..];
77 if rest.starts_with('[') || rest.starts_with('.') {
78 return true;
79 }
80 }
81 }
82 false
83}
84
85fn split_streaming_deep_path(field: &str) -> Option<(&str, &str)> {
91 for root in STREAMING_VIRTUAL_ROOTS {
92 if field.len() > root.len() && field.starts_with(root) {
93 let rest = &field[root.len()..];
94 if rest.starts_with('[') || rest.starts_with('.') {
95 return Some((root, rest));
96 }
97 }
98 }
99 None
100}
101
102const STREAMING_ONLY_AUTO_DETECT_FIELDS: &[&str] = &[
109 "chunks",
110 "chunks.length",
111 "stream_content",
112 "stream_complete",
113 "no_chunks_after_done",
114 "stream.has_page_event",
115 "stream.has_error_event",
116 "stream.has_complete_event",
117 "stream.event_count_min",
118];
119
120pub fn resolve_is_streaming(fixture: &crate::fixture::Fixture, call_streaming: Option<bool>) -> bool {
132 if let Some(forced) = call_streaming {
133 return forced;
134 }
135 fixture.is_streaming_mock()
136 || fixture.assertions.iter().any(|a| {
137 a.field
138 .as_deref()
139 .is_some_and(|f| !f.is_empty() && STREAMING_ONLY_AUTO_DETECT_FIELDS.contains(&f))
140 })
141}
142
143pub struct StreamingFieldResolver;
145
146impl StreamingFieldResolver {
147 pub fn accessor(field: &str, lang: &str, chunks_var: &str) -> Option<String> {
161 Self::accessor_with_module_qualifier(field, lang, chunks_var, None)
162 }
163
164 pub fn accessor_with_module_qualifier(
174 field: &str,
175 lang: &str,
176 chunks_var: &str,
177 module_qualifier: Option<&str>,
178 ) -> Option<String> {
179 Self::accessor_with_streaming_context(field, lang, chunks_var, module_qualifier, Some("CrawlEvent"))
182 }
183
184 pub fn accessor_with_streaming_context(
194 field: &str,
195 lang: &str,
196 chunks_var: &str,
197 module_qualifier: Option<&str>,
198 item_type: Option<&str>,
199 ) -> Option<String> {
200 match field {
201 "chunks" => Some(match lang {
202 "zig" => format!("{chunks_var}.items"),
204 "php" => format!("${chunks_var}"),
207 _ => chunks_var.to_string(),
208 }),
209
210 "chunks.length" => Some(match lang {
211 "rust" => format!("{chunks_var}.len()"),
212 "go" => format!("len({chunks_var})"),
213 "python" => format!("len({chunks_var})"),
214 "php" => format!("count(${chunks_var})"),
215 "elixir" => format!("length({chunks_var})"),
216 "kotlin" => format!("{chunks_var}.size"),
218 "zig" => format!("{chunks_var}.items.len"),
220 "swift" => format!("{chunks_var}.count"),
222 _ => format!("{chunks_var}.length"),
224 }),
225
226 "stream_content" => Some(match lang {
227 "rust" => {
228 format!(
229 "{chunks_var}.iter().map(|c| c.choices.first().and_then(|ch| ch.delta.content.as_deref()).unwrap_or(\"\")).collect::<String>()"
230 )
231 }
232 "go" => {
233 format!(
235 "func() string {{ var s string; for _, c := range {chunks_var} {{ if len(c.Choices) > 0 && c.Choices[0].Delta.Content != nil {{ s += *c.Choices[0].Delta.Content }} }}; return s }}()"
236 )
237 }
238 "java" => {
239 format!(
240 "{chunks_var}.stream().map(c -> c.choices().stream().findFirst().map(ch -> ch.delta().content() != null ? ch.delta().content() : \"\").orElse(\"\")).collect(java.util.stream.Collectors.joining())"
241 )
242 }
243 "php" => {
244 format!("implode('', array_map(fn($c) => $c->choices[0]->delta->content ?? '', ${chunks_var}))")
245 }
246 "kotlin" => {
247 format!(
250 "{chunks_var}.joinToString(\"\") {{ it.choices()?.firstOrNull()?.delta()?.content() ?: \"\" }}"
251 )
252 }
253 "kotlin_android" => {
254 format!("{chunks_var}.joinToString(\"\") {{ it.choices?.firstOrNull()?.delta?.content ?: \"\" }}")
256 }
257 "elixir" => {
258 format!(
262 "{chunks_var} |> Enum.map(fn c -> (Enum.at(c.choices, 0) || %{{}}) |> Map.get(:delta, %{{}}) |> Map.get(:content, \"\") end) |> Enum.join(\"\")"
263 )
264 }
265 "python" => {
266 format!("\"\".join(c.choices[0].delta.content or \"\" for c in {chunks_var} if c.choices)")
267 }
268 "zig" => {
269 format!("{chunks_var}_content.items")
272 }
273 "swift" => {
279 format!(
280 "{chunks_var}.map {{ c in c.choices.first.flatMap {{ ch in ch.delta.content }} ?? \"\" }}.joined()"
281 )
282 }
283 _ => {
285 format!("{chunks_var}.map((c: any) => c.choices?.[0]?.delta?.content ?? '').join('')")
286 }
287 }),
288
289 "stream_complete" => Some(match lang {
290 "rust" => {
291 format!(
292 "{chunks_var}.last().and_then(|c| c.choices.first()).and_then(|ch| ch.finish_reason.as_ref()).is_some()"
293 )
294 }
295 "go" => {
296 format!(
297 "func() bool {{ if len({chunks_var}) == 0 {{ return false }}; last := {chunks_var}[len({chunks_var})-1]; return len(last.Choices) > 0 && last.Choices[0].FinishReason != nil }}()"
298 )
299 }
300 "java" => {
301 format!(
302 "!{chunks_var}.isEmpty() && {chunks_var}.get({chunks_var}.size()-1).choices().stream().findFirst().flatMap(ch -> java.util.Optional.ofNullable(ch.finishReason())).isPresent()"
303 )
304 }
305 "php" => {
306 format!("!empty(${chunks_var}) && isset(end(${chunks_var})->choices[0]->finishReason)")
310 }
311 "kotlin" => {
312 format!(
314 "{chunks_var}.isNotEmpty() && {chunks_var}.last().choices()?.firstOrNull()?.finishReason() != null"
315 )
316 }
317 "kotlin_android" => {
318 format!(
320 "{chunks_var}.isNotEmpty() && {chunks_var}.last().choices?.firstOrNull()?.finishReason != null"
321 )
322 }
323 "python" => {
324 format!("bool({chunks_var}) and {chunks_var}[-1].choices[0].finish_reason is not None")
325 }
326 "elixir" => {
327 format!("Enum.at(List.last({chunks_var}).choices, 0).finish_reason != nil")
328 }
329 "zig" => {
332 format!("{chunks_var}.items.len > 0")
333 }
334 "swift" => {
338 format!("!{chunks_var}.isEmpty && {chunks_var}.last!.choices.first?.finishReason != nil")
339 }
340 _ => {
342 format!(
343 "{chunks_var}.length > 0 && {chunks_var}[{chunks_var}.length - 1].choices?.[0]?.finishReason != null"
344 )
345 }
346 }),
347
348 "no_chunks_after_done" => Some(match lang {
352 "rust" => "true".to_string(),
353 "go" => "true".to_string(),
354 "java" => "true".to_string(),
355 "php" => "true".to_string(),
356 _ => "true".to_string(),
357 }),
358
359 "stream.has_page_event" => item_type
374 .and_then(|ty| has_event_variant_accessor(lang, chunks_var, EventVariant::Page, ty, module_qualifier)),
375 "stream.has_error_event" => item_type
376 .and_then(|ty| has_event_variant_accessor(lang, chunks_var, EventVariant::Error, ty, module_qualifier)),
377 "stream.has_complete_event" => item_type.and_then(|ty| {
378 has_event_variant_accessor(lang, chunks_var, EventVariant::Complete, ty, module_qualifier)
379 }),
380
381 "stream.event_count_min" => Self::accessor("chunks.length", lang, chunks_var),
385
386 "tool_calls" => Some(match lang {
387 "rust" => {
388 format!(
389 "{chunks_var}.iter().flat_map(|c| c.choices.iter().flat_map(|ch| ch.delta.tool_calls.iter().flatten())).collect::<Vec<_>>()"
390 )
391 }
392 "go" => {
393 format!(
397 "func() []pkg.StreamToolCall {{ var tc []pkg.StreamToolCall; for _, c := range {chunks_var} {{ for _, ch := range c.Choices {{ tc = append(tc, ch.Delta.ToolCalls...) }} }}; return tc }}()"
398 )
399 }
400 "java" => {
401 format!(
402 "{chunks_var}.stream().flatMap(c -> c.choices().stream()).flatMap(ch -> ch.delta().toolCalls() != null ? ch.delta().toolCalls().stream() : java.util.stream.Stream.empty()).toList()"
403 )
404 }
405 "php" => {
406 format!(
409 "array_merge(...array_map(fn($c) => $c->choices[0]->delta->toolCalls ?? [], ${chunks_var}))"
410 )
411 }
412 "kotlin" => {
413 format!(
415 "{chunks_var}.flatMap {{ c -> c.choices()?.flatMap {{ ch -> ch.delta()?.toolCalls() ?: emptyList() }} ?: emptyList() }}"
416 )
417 }
418 "kotlin_android" => {
419 format!(
421 "{chunks_var}.flatMap {{ c -> c.choices?.flatMap {{ ch -> ch.delta?.toolCalls ?: emptyList() }} ?: emptyList() }}"
422 )
423 }
424 "python" => {
425 format!(
426 "[t for c in {chunks_var} for ch in (c.choices or []) for t in (ch.delta.tool_calls or [])]"
427 )
428 }
429 "elixir" => {
430 format!(
431 "{chunks_var} |> Enum.flat_map(fn c -> (List.first(c.choices) || %{{}}).delta |> Map.get(:tool_calls, []) end)"
432 )
433 }
434 "zig" => {
436 format!("{chunks_var}.items")
437 }
438 "swift" => {
442 format!(
443 "{chunks_var}.flatMap {{ c -> [StreamToolCall] in guard let ch = c.choices.first, let tcs = ch.delta.toolCalls else {{ return [] }}; return tcs }}"
444 )
445 }
446 _ => {
447 format!("{chunks_var}.flatMap((c: any) => c.choices?.[0]?.delta?.toolCalls ?? [])")
448 }
449 }),
450
451 "finish_reason" => Some(match lang {
452 "rust" => {
453 format!(
456 "{chunks_var}.last().and_then(|c| c.choices.first()).and_then(|ch| ch.finish_reason.as_ref()).map(|v| v.to_string()).unwrap_or_default()"
457 )
458 }
459 "go" => {
460 format!(
463 "func() string {{ if len({chunks_var}) == 0 {{ return \"\" }}; last := {chunks_var}[len({chunks_var})-1]; if len(last.Choices) > 0 && last.Choices[0].FinishReason != nil {{ return string(*last.Choices[0].FinishReason) }}; return \"\" }}()"
464 )
465 }
466 "java" => {
467 format!(
471 "({chunks_var}.isEmpty() ? null : {chunks_var}.get({chunks_var}.size()-1).choices().stream().findFirst().map(ch -> ch.finishReason() == null ? null : ch.finishReason().getValue()).orElse(null))"
472 )
473 }
474 "php" => {
475 format!("(!empty(${chunks_var}) ? (end(${chunks_var})->choices[0]->finishReason ?? null) : null)")
478 }
479 "kotlin" => {
480 format!(
483 "(if ({chunks_var}.isEmpty()) null else {chunks_var}.last().choices()?.firstOrNull()?.finishReason()?.getValue())"
484 )
485 }
486 "kotlin_android" => {
487 format!(
489 "(if ({chunks_var}.isEmpty()) null else {chunks_var}.last().choices?.firstOrNull()?.finishReason?.name?.lowercase())"
490 )
491 }
492 "python" => {
493 format!(
497 "(str({chunks_var}[-1].choices[0].finish_reason) if {chunks_var} and {chunks_var}[-1].choices else None)"
498 )
499 }
500 "elixir" => {
501 format!("Enum.at(List.last({chunks_var}).choices, 0).finish_reason")
502 }
503 "zig" => {
506 format!(
507 "(blk: {{ if ({chunks_var}.items.len == 0) break :blk \"\"; var _lcp = std.json.parseFromSlice(std.json.Value, std.heap.c_allocator, {chunks_var}.items[{chunks_var}.items.len - 1], .{{}}) catch break :blk \"\"; defer _lcp.deinit(); if (_lcp.value.object.get(\"choices\")) |_lchs| if (_lchs.array.items.len > 0) if (_lchs.array.items[0].object.get(\"finish_reason\")) |_fr| if (_fr == .string) break :blk _fr.string; break :blk \"\"; }})"
508 )
509 }
510 "swift" => {
515 format!("({chunks_var}.isEmpty ? nil : {chunks_var}.last!.choices.first?.finishReason?.rawValue)")
516 }
517 _ => {
518 format!(
519 "{chunks_var}.length > 0 ? {chunks_var}[{chunks_var}.length - 1].choices?.[0]?.finishReason : undefined"
520 )
521 }
522 }),
523
524 "usage" => Some(match lang {
529 "python" => {
530 format!("({chunks_var}[-1].usage if {chunks_var} else None)")
534 }
535 "rust" => {
536 format!("{chunks_var}.last().and_then(|c| c.usage.as_ref())")
537 }
538 "go" => {
539 format!(
540 "func() interface{{}} {{ if len({chunks_var}) == 0 {{ return nil }}; return {chunks_var}[len({chunks_var})-1].Usage }}()"
541 )
542 }
543 "java" => {
544 format!("({chunks_var}.isEmpty() ? null : {chunks_var}.get({chunks_var}.size()-1).usage())")
545 }
546 "kotlin" => {
547 format!("(if ({chunks_var}.isEmpty()) null else {chunks_var}.last().usage())")
548 }
549 "kotlin_android" => {
550 format!("(if ({chunks_var}.isEmpty()) null else {chunks_var}.last().usage)")
552 }
553 "php" => {
554 format!("(!empty(${chunks_var}) ? end(${chunks_var})->usage ?? null : null)")
555 }
556 "elixir" => {
557 format!("(if length({chunks_var}) > 0, do: List.last({chunks_var}).usage, else: nil)")
558 }
559 "swift" => {
562 format!("({chunks_var}.isEmpty ? nil : {chunks_var}.last!.usage)")
563 }
564 _ => {
565 format!("({chunks_var}.length > 0 ? {chunks_var}[{chunks_var}.length - 1].usage : undefined)")
566 }
567 }),
568
569 _ => {
570 if let Some((root, tail)) = split_streaming_deep_path(field) {
574 if lang == "rust" && root == "tool_calls" {
578 return Some(render_rust_tool_calls_deep(chunks_var, tail));
579 }
580 if lang == "swift" && root == "tool_calls" {
584 let root_expr = Self::accessor(root, lang, chunks_var)?;
585 return Some(render_swift_tool_calls_deep(&root_expr, tail));
586 }
587 if lang == "zig" && root == "tool_calls" {
594 return None;
595 }
596 let root_expr = Self::accessor(root, lang, chunks_var)?;
597 Some(render_deep_tail(&root_expr, tail, lang))
598 } else {
599 None
600 }
601 }
602 }
603 }
604
605 pub fn collect_snippet(lang: &str, stream_var: &str, chunks_var: &str) -> Option<String> {
611 match lang {
612 "rust" => Some(format!(
613 "let {chunks_var}: Vec<_> = tokio_stream::StreamExt::collect::<Vec<_>>({stream_var}).await\n .into_iter()\n .map(|r| r.expect(\"stream item failed\"))\n .collect();"
614 )),
615 "go" => Some(format!(
616 "var {chunks_var} []pkg.ChatCompletionChunk\n\tfor chunk := range {stream_var} {{\n\t\t{chunks_var} = append({chunks_var}, chunk)\n\t}}"
617 )),
618 "java" => Some(format!(
619 "var {chunks_var} = new java.util.ArrayList<ChatCompletionChunk>();\n var _it = {stream_var}.iterator();\n while (_it.hasNext()) {{ {chunks_var}.add(_it.next()); }}"
620 )),
621 "php" => Some(format!(
631 "$__camel = function ($v) use (&$__camel) {{ \
632 if (is_array($v)) {{ \
633 $out = []; \
634 foreach ($v as $k => $vv) {{ \
635 $key = is_string($k) ? lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', $k)))) : $k; \
636 $out[$key] = $__camel($vv); \
637 }} \
638 return (array_keys($out) === range(0, count($out) - 1)) ? $out : (object) $out; \
639 }} \
640 if (is_object($v)) {{ \
641 $out = new \\stdClass(); \
642 foreach (get_object_vars($v) as $k => $vv) {{ \
643 $key = lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', $k)))); \
644 $out->{{$key}} = $__camel($vv); \
645 }} \
646 return $out; \
647 }} \
648 return $v; \
649 }};\n \
650 $__decode_chunk = fn($c) => $__camel(is_string($c) ? json_decode($c, true) : (is_array($c) || is_object($c) ? json_decode(json_encode($c), true) : $c));\n \
651 ${chunks_var} = is_string(${stream_var}) \
652 ? array_map($__decode_chunk, (array)(json_decode(${stream_var}, true) ?: [])) \
653 : (is_array(${stream_var}) \
654 ? array_map($__decode_chunk, ${stream_var}) \
655 : array_map($__decode_chunk, iterator_to_array(${stream_var})));"
656 )),
657 "python" => Some(format!(
658 "{chunks_var} = []\n async for chunk in {stream_var}:\n {chunks_var}.append(chunk)"
659 )),
660 "kotlin" => {
661 Some(format!("val {chunks_var} = {stream_var}.asSequence().toList()"))
664 }
665 "kotlin_android" => {
666 Some(format!("val {chunks_var} = {stream_var}.toList()"))
669 }
670 "elixir" => Some(format!("{chunks_var} = Enum.to_list({stream_var})")),
671 "wasm" => Some(format!(
678 "const {chunks_var}: any[] = [];\n while (true) {{ const _chunk = await {stream_var}.next(); if (_chunk == null) break; {chunks_var}.push(_chunk); }}"
679 )),
680 "node" | "typescript" => Some(format!(
681 "const {chunks_var}: any[] = [];\n for await (const _chunk of {stream_var}) {{ {chunks_var}.push(_chunk); }}"
682 )),
683 "swift" => {
684 Some(format!(
689 "var {chunks_var}: [ChatCompletionChunk] = []\n for try await _chunk in {stream_var} {{ {chunks_var}.append(_chunk) }}"
690 ))
691 }
692 "zig" => Some(Self::collect_snippet_zig(stream_var, chunks_var, "module", "ffi")),
693 _ => None,
694 }
695 }
696
697 pub fn collect_snippet_zig(stream_var: &str, chunks_var: &str, module_name: &str, ffi_prefix: &str) -> String {
699 let stream_next = format!("{ffi_prefix}_default_client_chat_stream_next");
700 let chunk_to_json = format!("{ffi_prefix}_chat_completion_chunk_to_json");
701 let chunk_free = format!("{ffi_prefix}_chat_completion_chunk_free");
702 let free_string = format!("{ffi_prefix}_free_string");
703
704 format!(
711 concat!(
712 "var {chunks_var}: std.ArrayList([]u8) = .empty;
713",
714 " defer {{
715",
716 " for ({chunks_var}.items) |_cj| std.heap.c_allocator.free(_cj);
717",
718 " {chunks_var}.deinit(std.heap.c_allocator);
719",
720 " }}
721",
722 " var {chunks_var}_content: std.ArrayList(u8) = .empty;
723",
724 " defer {chunks_var}_content.deinit(std.heap.c_allocator);
725",
726 " while (true) {{
727",
728 " const _nc = {module_name}.c.{stream_next}({stream_var});
729",
730 " if (_nc == null) break;
731",
732 " const _np = {module_name}.c.{chunk_to_json}(_nc);
733",
734 " {module_name}.c.{chunk_free}(_nc);
735",
736 " if (_np == null) continue;
737",
738 " const _ns = std.mem.span(_np);
739",
740 " const _nj = try std.heap.c_allocator.dupe(u8, _ns);
741",
742 " {module_name}.c.{free_string}(_np);
743",
744 " if (std.json.parseFromSlice(std.json.Value, std.heap.c_allocator, _nj, .{{}})) |_cp| {{
745",
746 " defer _cp.deinit();
747",
748 " if (_cp.value.object.get(\"choices\")) |_chs|
749",
750 " if (_chs.array.items.len > 0)
751",
752 " if (_chs.array.items[0].object.get(\"delta\")) |_dl|
753",
754 " if (_dl.object.get(\"content\")) |_ct|
755",
756 " if (_ct == .string) try {chunks_var}_content.appendSlice(std.heap.c_allocator, _ct.string);
757",
758 " }} else |_| {{}}
759",
760 " try {chunks_var}.append(std.heap.c_allocator, _nj);
761",
762 " }}"
763 ),
764 chunks_var = chunks_var,
765 stream_var = stream_var,
766 module_name = module_name,
767 stream_next = stream_next,
768 chunk_to_json = chunk_to_json,
769 chunk_free = chunk_free,
770 free_string = free_string,
771 )
772 }
773}
774
775#[derive(Debug, Clone, Copy)]
777enum EventVariant {
778 Page,
779 Error,
780 Complete,
781}
782
783impl EventVariant {
784 fn tag(self) -> &'static str {
786 match self {
787 EventVariant::Page => "page",
788 EventVariant::Error => "error",
789 EventVariant::Complete => "complete",
790 }
791 }
792
793 fn upper_camel(self) -> &'static str {
796 match self {
797 EventVariant::Page => "Page",
798 EventVariant::Error => "Error",
799 EventVariant::Complete => "Complete",
800 }
801 }
802}
803
804fn has_event_variant_accessor(
815 lang: &str,
816 chunks_var: &str,
817 variant: EventVariant,
818 item_type: &str,
819 module_qualifier: Option<&str>,
820) -> Option<String> {
821 let tag = variant.tag();
822 let camel = variant.upper_camel();
823 match lang {
824 "python" => Some(format!("any(e.type == \"{tag}\" for e in {chunks_var})")),
826 "node" | "typescript" => Some(format!("{chunks_var}.some((e: any) => e?.type === \"{tag}\")")),
829 "ruby" => Some(format!("{chunks_var}.any? {{ |e| e.{tag}? }}")),
831 "go" => Some(format!(
835 "func() bool {{ for _, e := range {chunks_var} {{ if _, _ok := e.(pkg.{item_type}{camel}); _ok {{ return true }} }}; return false }}()"
836 )),
837 "java" => Some(format!(
839 "{chunks_var}.stream().anyMatch(e -> e instanceof {item_type}.{camel})"
840 )),
841 "csharp" => module_qualifier.map(|ns| format!("{chunks_var}.Any(e => e is global::{ns}.{item_type}.{camel})")),
844 "swift" => Some(format!(
848 "{chunks_var}.contains(where: {{ e in if case .{tag} = e {{ return true }} else {{ return false }} }})"
849 )),
850 "elixir" => Some(format!(
852 "Enum.any?({chunks_var}, fn e -> Map.get(e, :type) == :{tag} end)"
853 )),
854 "kotlin" => Some(format!("{chunks_var}.any {{ it is {item_type}.{camel} }}")),
856 "kotlin_android" => Some(format!("{chunks_var}.any {{ it is {item_type}.{camel} }}")),
858 "dart" => Some(format!("{chunks_var}.any((e) => e is {item_type}_{camel})")),
860 "zig" => Some(format!(
865 "blk: {{ for ({chunks_var}.items) |_e| {{ if (std.mem.indexOf(u8, _e, \"\\\"type\\\":\\\"{tag}\\\"\") != null) break :blk true; }} break :blk false; }}"
866 )),
867 "rust" => module_qualifier.map(|crate_name| {
871 format!("{chunks_var}.iter().any(|e| matches!(e, {crate_name}::{item_type}::{camel} {{ .. }}))")
872 }),
873 "php" | "wasm" => None,
877 _ => None,
878 }
879}
880
881fn render_swift_tool_calls_deep(root_expr: &str, tail: &str) -> String {
893 use heck::ToLowerCamelCase;
894 let segs = parse_tail(tail);
895 let mut expr = root_expr.to_string();
896 let mut prev_is_optional = false;
904 for seg in &segs {
905 match seg {
906 TailSeg::Index(n) => {
907 expr = format!("({expr})[{n}]");
908 prev_is_optional = false;
909 }
910 TailSeg::Field(f) => {
911 let prop = f.to_lower_camel_case();
912 let sep = if prev_is_optional { "?." } else { "." };
913 expr = format!("{expr}{sep}{prop}");
914 prev_is_optional = true;
918 }
919 }
920 }
921 expr
922}
923
924fn render_rust_tool_calls_deep(chunks_var: &str, tail: &str) -> String {
928 let segs = parse_tail(tail);
929 let idx = segs.iter().find_map(|s| match s {
931 TailSeg::Index(n) => Some(*n),
932 _ => None,
933 });
934 let field_segs: Vec<&str> = segs
935 .iter()
936 .filter_map(|s| match s {
937 TailSeg::Field(f) => Some(f.as_str()),
938 _ => None,
939 })
940 .collect();
941
942 let base = format!(
943 "{chunks_var}.iter().flat_map(|c| c.choices.iter().flat_map(|ch| ch.delta.tool_calls.iter().flatten()))"
944 );
945 let with_nth = match idx {
946 Some(n) => format!("{base}.nth({n})"),
947 None => base,
948 };
949
950 let mut expr = with_nth;
953 for (i, f) in field_segs.iter().enumerate() {
954 let is_leaf = i == field_segs.len() - 1;
955 if is_leaf {
956 expr = format!("{expr}.and_then(|x| x.{f}.as_deref())");
957 } else {
958 expr = format!("{expr}.and_then(|x| x.{f}.as_ref())");
959 }
960 }
961 format!("{expr}.unwrap_or(\"\")")
962}
963
964#[derive(Debug, PartialEq)]
969enum TailSeg {
970 Index(usize),
971 Field(String),
972}
973
974fn parse_tail(tail: &str) -> Vec<TailSeg> {
975 let mut segs = Vec::new();
976 let mut rest = tail;
977 while !rest.is_empty() {
978 if let Some(inner) = rest.strip_prefix('[') {
979 if let Some(close) = inner.find(']') {
981 let idx_str = &inner[..close];
982 if let Ok(idx) = idx_str.parse::<usize>() {
983 segs.push(TailSeg::Index(idx));
984 }
985 rest = &inner[close + 1..];
986 } else {
987 break;
988 }
989 } else if let Some(inner) = rest.strip_prefix('.') {
990 let end = inner.find(['.', '[']).unwrap_or(inner.len());
992 segs.push(TailSeg::Field(inner[..end].to_string()));
993 rest = &inner[end..];
994 } else {
995 break;
996 }
997 }
998 segs
999}
1000
1001fn render_deep_tail(root_expr: &str, tail: &str, lang: &str) -> String {
1004 use heck::{ToLowerCamelCase, ToPascalCase};
1005
1006 let segs = parse_tail(tail);
1007 let mut out = root_expr.to_string();
1008
1009 for seg in &segs {
1010 match (seg, lang) {
1011 (TailSeg::Index(n), "rust") => {
1012 out = format!("({out})[{n}]");
1013 }
1014 (TailSeg::Index(n), "java") => {
1015 out = format!("({out}).get({n})");
1016 }
1017 (TailSeg::Index(n), "kotlin") => {
1018 if *n == 0 {
1019 out = format!("({out}).first()");
1020 } else {
1021 out = format!("({out}).get({n})");
1022 }
1023 }
1024 (TailSeg::Index(n), "kotlin_android") => {
1025 if *n == 0 {
1026 out = format!("({out}).first()");
1027 } else {
1028 out = format!("({out})[{n}]");
1029 }
1030 }
1031 (TailSeg::Index(n), "elixir") => {
1032 out = format!("Enum.at({out}, {n})");
1033 }
1034 (TailSeg::Index(n), "zig") => {
1035 out = format!("({out}).items[{n}]");
1036 }
1037 (TailSeg::Index(n), "php") => {
1038 out = format!("({out})[{n}]");
1039 }
1040 (TailSeg::Index(n), _) => {
1041 out = format!("({out})[{n}]");
1043 }
1044 (TailSeg::Field(f), "rust") => {
1045 use heck::ToSnakeCase;
1046 out.push('.');
1047 out.push_str(&f.to_snake_case());
1048 }
1049 (TailSeg::Field(f), "go") => {
1050 use alef_codegen::naming::to_go_name;
1051 out.push('.');
1052 out.push_str(&to_go_name(f));
1053 }
1054 (TailSeg::Field(f), "java") => {
1055 out.push('.');
1056 out.push_str(&f.to_lower_camel_case());
1057 out.push_str("()");
1058 }
1059 (TailSeg::Field(f), "kotlin") => {
1060 out.push_str("?.");
1066 out.push_str(&f.to_lower_camel_case());
1067 out.push_str("()");
1068 }
1069 (TailSeg::Field(f), "kotlin_android") => {
1070 out.push_str("?.");
1072 out.push_str(&f.to_lower_camel_case());
1073 }
1074 (TailSeg::Field(f), "csharp") => {
1075 out.push('.');
1076 out.push_str(&f.to_pascal_case());
1077 }
1078 (TailSeg::Field(f), "php") => {
1079 out.push_str("->");
1084 out.push_str(f);
1085 }
1086 (TailSeg::Field(f), "elixir") => {
1087 out.push('.');
1088 out.push_str(f);
1089 }
1090 (TailSeg::Field(f), "zig") => {
1091 out.push('.');
1092 out.push_str(f);
1093 }
1094 (TailSeg::Field(f), "python") | (TailSeg::Field(f), "ruby") => {
1095 out.push('.');
1096 out.push_str(f);
1097 }
1098 (TailSeg::Field(f), _) => {
1100 out.push('.');
1101 out.push_str(&f.to_lower_camel_case());
1102 }
1103 }
1104 }
1105
1106 out
1107}
1108
1109#[cfg(test)]
1110mod tests {
1111 use super::*;
1112
1113 #[test]
1114 fn is_streaming_virtual_field_recognizes_all_fields() {
1115 for field in STREAMING_VIRTUAL_FIELDS {
1116 assert!(
1117 is_streaming_virtual_field(field),
1118 "field '{field}' not recognized as streaming virtual"
1119 );
1120 }
1121 }
1122
1123 #[test]
1124 fn is_streaming_virtual_field_rejects_real_fields() {
1125 assert!(!is_streaming_virtual_field("content"));
1126 assert!(!is_streaming_virtual_field("choices"));
1127 assert!(!is_streaming_virtual_field("model"));
1128 assert!(!is_streaming_virtual_field(""));
1129 }
1130
1131 #[test]
1132 fn is_streaming_virtual_field_rejects_non_root_paths_with_matching_tail() {
1133 assert!(!is_streaming_virtual_field("choices[0].finish_reason"));
1138 assert!(!is_streaming_virtual_field("choices[0].message.content"));
1139 assert!(!is_streaming_virtual_field("data[0].embedding"));
1140 }
1141
1142 #[test]
1143 fn is_streaming_virtual_field_does_not_match_usage() {
1144 assert!(!is_streaming_virtual_field("usage"));
1148 assert!(!is_streaming_virtual_field("usage.total_tokens"));
1149 assert!(!is_streaming_virtual_field("usage.prompt_tokens"));
1150 }
1151
1152 #[test]
1153 fn accessor_chunks_returns_var_name() {
1154 assert_eq!(
1155 StreamingFieldResolver::accessor("chunks", "rust", "chunks"),
1156 Some("chunks".to_string())
1157 );
1158 assert_eq!(
1159 StreamingFieldResolver::accessor("chunks", "node", "chunks"),
1160 Some("chunks".to_string())
1161 );
1162 }
1163
1164 #[test]
1165 fn accessor_chunks_length_uses_language_idiom() {
1166 let rust = StreamingFieldResolver::accessor("chunks.length", "rust", "chunks").unwrap();
1167 assert!(rust.contains(".len()"), "rust: {rust}");
1168
1169 let go = StreamingFieldResolver::accessor("chunks.length", "go", "chunks").unwrap();
1170 assert!(go.starts_with("len("), "go: {go}");
1171
1172 let node = StreamingFieldResolver::accessor("chunks.length", "node", "chunks").unwrap();
1173 assert!(node.contains(".length"), "node: {node}");
1174
1175 let php = StreamingFieldResolver::accessor("chunks.length", "php", "chunks").unwrap();
1176 assert!(php.starts_with("count("), "php: {php}");
1177 }
1178
1179 #[test]
1180 fn accessor_chunks_length_zig_uses_items_len() {
1181 let zig = StreamingFieldResolver::accessor("chunks.length", "zig", "chunks").unwrap();
1182 assert_eq!(zig, "chunks.items.len", "zig chunks.length: {zig}");
1183 }
1184
1185 #[test]
1186 fn accessor_stream_content_zig_uses_content_items() {
1187 let zig = StreamingFieldResolver::accessor("stream_content", "zig", "chunks").unwrap();
1188 assert_eq!(zig, "chunks_content.items", "zig stream_content: {zig}");
1189 }
1190
1191 #[test]
1192 fn collect_snippet_zig_drains_via_ffi() {
1193 let snip = StreamingFieldResolver::collect_snippet("zig", "_stream_handle", "chunks").unwrap();
1194 assert!(snip.contains("std.ArrayList([]u8)"), "zig collect: {snip}");
1195 assert!(snip.contains("chat_stream_next(_stream_handle)"), "zig collect: {snip}");
1196 assert!(snip.contains("chunks_content"), "zig collect: {snip}");
1197 assert!(
1198 snip.contains("chunks.append(std.heap.c_allocator"),
1199 "zig collect: {snip}"
1200 );
1201 assert!(snip.contains(".empty;"), "zig collect (Zig 0.16 unmanaged): {snip}");
1202 }
1203
1204 #[test]
1205 fn accessor_stream_content_rust_uses_iterator() {
1206 let expr = StreamingFieldResolver::accessor("stream_content", "rust", "chunks").unwrap();
1207 assert!(expr.contains(".collect::<String>()"), "rust stream_content: {expr}");
1208 }
1209
1210 #[test]
1211 fn accessor_no_chunks_after_done_returns_true() {
1212 for lang in ["rust", "go", "java", "php", "node", "wasm", "elixir"] {
1213 let expr = StreamingFieldResolver::accessor("no_chunks_after_done", lang, "chunks").unwrap();
1214 assert_eq!(expr, "true", "lang {lang}: expected 'true', got '{expr}'");
1215 }
1216 }
1217
1218 #[test]
1219 fn accessor_elixir_chunks_length_uses_length_function() {
1220 let expr = StreamingFieldResolver::accessor("chunks.length", "elixir", "chunks").unwrap();
1221 assert_eq!(expr, "length(chunks)", "elixir chunks.length: {expr}");
1222 }
1223
1224 #[test]
1225 fn accessor_elixir_stream_content_uses_pipe() {
1226 let expr = StreamingFieldResolver::accessor("stream_content", "elixir", "chunks").unwrap();
1227 assert!(expr.contains("|> Enum.join"), "elixir stream_content: {expr}");
1228 assert!(expr.contains("|> Enum.map"), "elixir stream_content: {expr}");
1229 assert!(
1231 !expr.contains("choices[0]"),
1232 "elixir stream_content must not use bracket access on list: {expr}"
1233 );
1234 assert!(
1235 expr.contains("Enum.at("),
1236 "elixir stream_content must use Enum.at for list index: {expr}"
1237 );
1238 }
1239
1240 #[test]
1241 fn accessor_elixir_stream_complete_uses_list_last() {
1242 let expr = StreamingFieldResolver::accessor("stream_complete", "elixir", "chunks").unwrap();
1243 assert!(expr.contains("List.last(chunks)"), "elixir stream_complete: {expr}");
1244 assert!(expr.contains("finish_reason != nil"), "elixir stream_complete: {expr}");
1245 assert!(
1247 !expr.contains("choices[0]"),
1248 "elixir stream_complete must not use bracket access on list: {expr}"
1249 );
1250 assert!(
1251 expr.contains("Enum.at("),
1252 "elixir stream_complete must use Enum.at for list index: {expr}"
1253 );
1254 }
1255
1256 #[test]
1257 fn accessor_elixir_finish_reason_uses_list_last() {
1258 let expr = StreamingFieldResolver::accessor("finish_reason", "elixir", "chunks").unwrap();
1259 assert!(expr.contains("List.last(chunks)"), "elixir finish_reason: {expr}");
1260 assert!(expr.contains("finish_reason"), "elixir finish_reason: {expr}");
1261 assert!(
1263 !expr.contains("choices[0]"),
1264 "elixir finish_reason must not use bracket access on list: {expr}"
1265 );
1266 assert!(
1267 expr.contains("Enum.at("),
1268 "elixir finish_reason must use Enum.at for list index: {expr}"
1269 );
1270 }
1271
1272 #[test]
1273 fn collect_snippet_elixir_uses_enum_to_list() {
1274 let snip = StreamingFieldResolver::collect_snippet("elixir", "result", "chunks").unwrap();
1275 assert!(snip.contains("Enum.to_list(result)"), "elixir: {snip}");
1276 assert!(snip.contains("chunks ="), "elixir: {snip}");
1277 }
1278
1279 #[test]
1280 fn collect_snippet_rust_uses_tokio_stream() {
1281 let snip = StreamingFieldResolver::collect_snippet("rust", "result", "chunks").unwrap();
1282 assert!(snip.contains("tokio_stream::StreamExt::collect"), "rust: {snip}");
1283 assert!(snip.contains("let chunks"), "rust: {snip}");
1284 assert!(snip.contains(".expect("), "rust must unwrap Result items: {snip}");
1286 }
1287
1288 #[test]
1289 fn collect_snippet_go_drains_channel() {
1290 let snip = StreamingFieldResolver::collect_snippet("go", "stream", "chunks").unwrap();
1291 assert!(snip.contains("for chunk := range stream"), "go: {snip}");
1292 }
1293
1294 #[test]
1295 fn collect_snippet_java_uses_iterator() {
1296 let snip = StreamingFieldResolver::collect_snippet("java", "result", "chunks").unwrap();
1297 assert!(
1300 snip.contains(".iterator()"),
1301 "java snippet must call .iterator() on stream: {snip}"
1302 );
1303 assert!(snip.contains("hasNext()"), "java: {snip}");
1304 assert!(snip.contains(".next()"), "java: {snip}");
1305 }
1306
1307 #[test]
1308 fn collect_snippet_php_decodes_json_or_iterates() {
1309 let snip = StreamingFieldResolver::collect_snippet("php", "result", "chunks").unwrap();
1310 assert!(snip.contains("json_decode"), "php must decode JSON: {snip}");
1315 assert!(
1316 snip.contains("iterator_to_array"),
1317 "php must keep iterator_to_array fallback: {snip}"
1318 );
1319 assert!(snip.contains("$chunks ="), "php must bind $chunks: {snip}");
1320 }
1321
1322 #[test]
1323 fn collect_snippet_node_uses_for_await() {
1324 let snip = StreamingFieldResolver::collect_snippet("node", "result", "chunks").unwrap();
1325 assert!(snip.contains("for await"), "node: {snip}");
1326 }
1327
1328 #[test]
1329 fn collect_snippet_python_uses_async_for() {
1330 let snip = StreamingFieldResolver::collect_snippet("python", "result", "chunks").unwrap();
1331 assert!(snip.contains("async for chunk in result"), "python: {snip}");
1332 assert!(snip.contains("chunks.append(chunk)"), "python: {snip}");
1333 }
1334
1335 #[test]
1336 fn accessor_stream_content_python_uses_join() {
1337 let expr = StreamingFieldResolver::accessor("stream_content", "python", "chunks").unwrap();
1338 assert!(expr.contains("\"\".join("), "python stream_content: {expr}");
1339 assert!(expr.contains("c.choices"), "python stream_content: {expr}");
1340 }
1341
1342 #[test]
1343 fn accessor_stream_complete_python_uses_finish_reason() {
1344 let expr = StreamingFieldResolver::accessor("stream_complete", "python", "chunks").unwrap();
1345 assert!(
1346 expr.contains("finish_reason is not None"),
1347 "python stream_complete: {expr}"
1348 );
1349 }
1350
1351 #[test]
1352 fn accessor_finish_reason_python_uses_last_chunk() {
1353 let expr = StreamingFieldResolver::accessor("finish_reason", "python", "chunks").unwrap();
1354 assert!(expr.contains("chunks[-1]"), "python finish_reason: {expr}");
1355 assert!(
1357 expr.starts_with("(str(") || expr.contains("str(chunks"),
1358 "python finish_reason must wrap in str(): {expr}"
1359 );
1360 }
1361
1362 #[test]
1363 fn accessor_tool_calls_python_uses_list_comprehension() {
1364 let expr = StreamingFieldResolver::accessor("tool_calls", "python", "chunks").unwrap();
1365 assert!(expr.contains("for c in chunks"), "python tool_calls: {expr}");
1366 assert!(expr.contains("tool_calls"), "python tool_calls: {expr}");
1367 }
1368
1369 #[test]
1370 fn accessor_usage_python_uses_last_chunk() {
1371 let expr = StreamingFieldResolver::accessor("usage", "python", "chunks").unwrap();
1372 assert!(
1373 expr.contains("chunks[-1].usage"),
1374 "python usage: expected chunks[-1].usage, got: {expr}"
1375 );
1376 }
1377
1378 #[test]
1379 fn accessor_usage_total_tokens_does_not_route_via_chunks() {
1380 assert!(StreamingFieldResolver::accessor("usage.total_tokens", "python", "chunks").is_none());
1384 }
1385
1386 #[test]
1387 fn accessor_unknown_field_returns_none() {
1388 assert_eq!(
1389 StreamingFieldResolver::accessor("nonexistent_field", "rust", "chunks"),
1390 None
1391 );
1392 }
1393
1394 #[test]
1399 fn is_streaming_virtual_field_recognizes_deep_tool_calls_paths() {
1400 assert!(
1401 is_streaming_virtual_field("tool_calls[0].function.name"),
1402 "tool_calls[0].function.name should be recognized"
1403 );
1404 assert!(
1405 is_streaming_virtual_field("tool_calls[0].id"),
1406 "tool_calls[0].id should be recognized"
1407 );
1408 assert!(
1409 is_streaming_virtual_field("tool_calls[1].function.arguments"),
1410 "tool_calls[1].function.arguments should be recognized"
1411 );
1412 assert!(is_streaming_virtual_field("tool_calls"));
1414 assert!(!is_streaming_virtual_field("tool_calls_extra.name"));
1416 assert!(!is_streaming_virtual_field("nonexistent[0].field"));
1417 }
1418
1419 #[test]
1426 fn deep_tool_calls_function_name_snapshot_rust_kotlin_ts() {
1427 let field = "tool_calls[0].function.name";
1428
1429 let rust = StreamingFieldResolver::accessor(field, "rust", "chunks").unwrap();
1430 assert!(
1434 rust.contains(".nth(0)"),
1435 "rust deep tool_calls: expected .nth(0) iterator index, got: {rust}"
1436 );
1437 assert!(
1438 rust.contains("x.function.as_ref()"),
1439 "rust deep tool_calls: expected Option-aware function access, got: {rust}"
1440 );
1441 assert!(
1442 rust.contains("x.name.as_deref()"),
1443 "rust deep tool_calls: expected Option-aware name leaf, got: {rust}"
1444 );
1445 assert!(
1446 !rust.contains("// skipped"),
1447 "rust deep tool_calls: must not emit skip comment, got: {rust}"
1448 );
1449
1450 let kotlin = StreamingFieldResolver::accessor(field, "kotlin", "chunks").unwrap();
1451 assert!(
1453 kotlin.contains(".first()"),
1454 "kotlin deep tool_calls: expected .first() for index 0, got: {kotlin}"
1455 );
1456 assert!(
1457 kotlin.contains(".function()"),
1458 "kotlin deep tool_calls: expected .function() method call, got: {kotlin}"
1459 );
1460 assert!(
1461 kotlin.contains(".name()"),
1462 "kotlin deep tool_calls: expected .name() method call, got: {kotlin}"
1463 );
1464
1465 let ts = StreamingFieldResolver::accessor(field, "node", "chunks").unwrap();
1466 assert!(
1468 ts.contains("[0]"),
1469 "ts/node deep tool_calls: expected [0] index, got: {ts}"
1470 );
1471 assert!(
1472 ts.contains(".function"),
1473 "ts/node deep tool_calls: expected .function segment, got: {ts}"
1474 );
1475 assert!(
1476 ts.contains(".name"),
1477 "ts/node deep tool_calls: expected .name segment, got: {ts}"
1478 );
1479 }
1480
1481 #[test]
1482 fn deep_tool_calls_id_snapshot_all_langs() {
1483 let field = "tool_calls[0].id";
1484
1485 let rust = StreamingFieldResolver::accessor(field, "rust", "chunks").unwrap();
1486 assert!(rust.contains(".nth(0)"), "rust: {rust}");
1487 assert!(rust.contains("x.id.as_deref()"), "rust: {rust}");
1488
1489 let go = StreamingFieldResolver::accessor(field, "go", "chunks").unwrap();
1490 assert!(go.contains("[0]"), "go: {go}");
1491 assert!(go.contains(".ID"), "go: expected .ID initialism, got: {go}");
1493
1494 let python = StreamingFieldResolver::accessor(field, "python", "chunks").unwrap();
1495 assert!(python.contains("[0]"), "python: {python}");
1496 assert!(python.contains(".id"), "python: {python}");
1497
1498 let php = StreamingFieldResolver::accessor(field, "php", "chunks").unwrap();
1499 assert!(php.contains("[0]"), "php: {php}");
1500 assert!(php.contains("->id"), "php: expected ->id, got: {php}");
1501
1502 let java = StreamingFieldResolver::accessor(field, "java", "chunks").unwrap();
1503 assert!(java.contains(".get(0)"), "java: expected .get(0), got: {java}");
1504 assert!(java.contains(".id()"), "java: expected .id() method call, got: {java}");
1505
1506 let csharp = StreamingFieldResolver::accessor(field, "csharp", "chunks").unwrap();
1507 assert!(csharp.contains("[0]"), "csharp: {csharp}");
1508 assert!(
1509 csharp.contains(".Id"),
1510 "csharp: expected .Id (PascalCase), got: {csharp}"
1511 );
1512
1513 let elixir = StreamingFieldResolver::accessor(field, "elixir", "chunks").unwrap();
1514 assert!(elixir.contains("Enum.at("), "elixir: expected Enum.at(, got: {elixir}");
1515 assert!(elixir.contains(".id"), "elixir: {elixir}");
1516 }
1517
1518 #[test]
1519 fn deep_tool_calls_function_name_snapshot_python_elixir_zig() {
1520 let field = "tool_calls[0].function.name";
1521
1522 let python = StreamingFieldResolver::accessor(field, "python", "chunks").unwrap();
1523 assert!(python.contains("[0]"), "python: {python}");
1524 assert!(python.contains(".function"), "python: {python}");
1525 assert!(python.contains(".name"), "python: {python}");
1526
1527 let elixir = StreamingFieldResolver::accessor(field, "elixir", "chunks").unwrap();
1528 assert!(elixir.contains("Enum.at("), "elixir: {elixir}");
1530 assert!(elixir.contains(".function"), "elixir: {elixir}");
1531 assert!(elixir.contains(".name"), "elixir: {elixir}");
1532
1533 assert!(
1537 StreamingFieldResolver::accessor(field, "zig", "chunks").is_none(),
1538 "zig: expected None for deep tool_calls path"
1539 );
1540 }
1541
1542 #[test]
1543 fn parse_tail_parses_index_then_field_segments() {
1544 let segs = parse_tail("[0].function.name");
1545 assert_eq!(segs.len(), 3, "expected 3 segments, got: {segs:?}");
1546 assert_eq!(segs[0], TailSeg::Index(0));
1547 assert_eq!(segs[1], TailSeg::Field("function".to_string()));
1548 assert_eq!(segs[2], TailSeg::Field("name".to_string()));
1549 }
1550
1551 #[test]
1552 fn parse_tail_parses_simple_index_field() {
1553 let segs = parse_tail("[0].id");
1554 assert_eq!(segs.len(), 2, "expected 2 segments, got: {segs:?}");
1555 assert_eq!(segs[0], TailSeg::Index(0));
1556 assert_eq!(segs[1], TailSeg::Field("id".to_string()));
1557 }
1558
1559 #[test]
1560 fn parse_tail_handles_nonzero_index() {
1561 let segs = parse_tail("[2].function.arguments");
1562 assert_eq!(segs[0], TailSeg::Index(2));
1563 assert_eq!(segs[1], TailSeg::Field("function".to_string()));
1564 assert_eq!(segs[2], TailSeg::Field("arguments".to_string()));
1565 }
1566
1567 #[test]
1572 fn accessor_chunks_length_swift_uses_count() {
1573 let swift = StreamingFieldResolver::accessor("chunks.length", "swift", "chunks").unwrap();
1574 assert_eq!(swift, "chunks.count", "swift chunks.length: {swift}");
1575 }
1576
1577 #[test]
1578 fn accessor_stream_content_swift_uses_swift_closures() {
1579 let expr = StreamingFieldResolver::accessor("stream_content", "swift", "chunks").unwrap();
1580 assert!(
1582 expr.contains("{ c in"),
1583 "swift stream_content must use Swift closure syntax, got: {expr}"
1584 );
1585 assert!(
1586 !expr.contains("=>"),
1587 "swift stream_content must not contain JS arrow `=>`, got: {expr}"
1588 );
1589 assert!(
1591 expr.contains("c.choices"),
1592 "swift stream_content must use property access for choices, got: {expr}"
1593 );
1594 assert!(
1595 expr.contains("ch.delta"),
1596 "swift stream_content must use property access for delta, got: {expr}"
1597 );
1598 assert!(
1599 expr.contains("ch.delta.content"),
1600 "swift stream_content must use property access for content, got: {expr}"
1601 );
1602 assert!(
1604 !expr.contains(".toString()"),
1605 "swift stream_content must NOT wrap first-class String fields with .toString(), got: {expr}"
1606 );
1607 assert!(
1608 expr.contains(".joined()"),
1609 "swift stream_content must join with .joined(), got: {expr}"
1610 );
1611 assert!(
1613 !expr.contains(".length"),
1614 "swift stream_content must not use JS .length, got: {expr}"
1615 );
1616 assert!(
1617 !expr.contains(".join("),
1618 "swift stream_content must not use JS .join(, got: {expr}"
1619 );
1620 }
1621
1622 #[test]
1623 fn accessor_stream_complete_swift_uses_swift_syntax() {
1624 let expr = StreamingFieldResolver::accessor("stream_complete", "swift", "chunks").unwrap();
1625 assert!(
1627 expr.contains("isEmpty"),
1628 "swift stream_complete must use .isEmpty, got: {expr}"
1629 );
1630 assert!(
1631 expr.contains(".last!"),
1632 "swift stream_complete must use .last!, got: {expr}"
1633 );
1634 assert!(
1636 expr.contains(".choices.first"),
1637 "swift stream_complete must use property access on choices, got: {expr}"
1638 );
1639 assert!(
1640 expr.contains("finishReason"),
1641 "swift stream_complete must reference lowerCamelCase finishReason, got: {expr}"
1642 );
1643 assert!(
1644 !expr.contains(".length"),
1645 "swift stream_complete must not use JS .length, got: {expr}"
1646 );
1647 assert!(
1648 !expr.contains("!= null"),
1649 "swift stream_complete must not use JS `!= null`, got: {expr}"
1650 );
1651 }
1652
1653 #[test]
1654 fn accessor_tool_calls_swift_uses_swift_flatmap() {
1655 let expr = StreamingFieldResolver::accessor("tool_calls", "swift", "chunks").unwrap();
1656 assert!(
1658 !expr.contains("=>"),
1659 "swift tool_calls must not contain JS arrow `=>`, got: {expr}"
1660 );
1661 assert!(
1662 expr.contains("flatMap"),
1663 "swift tool_calls must use flatMap, got: {expr}"
1664 );
1665 assert!(
1667 expr.contains("c.choices.first"),
1668 "swift tool_calls must use property access on choices, got: {expr}"
1669 );
1670 assert!(
1671 expr.contains("ch.delta.toolCalls"),
1672 "swift tool_calls must use lowerCamelCase toolCalls property, got: {expr}"
1673 );
1674 }
1675
1676 #[test]
1677 fn accessor_tool_calls_deep_path_swift_uses_method_calls_with_optional_chain() {
1678 let expr = StreamingFieldResolver::accessor("tool_calls[0].function.name", "swift", "chunks").unwrap();
1684 assert!(
1685 expr.contains("[0].function"),
1686 "swift deep tool_calls must use plain `.function` directly after array index (non-optional), got: {expr}"
1687 );
1688 assert!(
1689 expr.contains("?.name"),
1690 "swift deep tool_calls must use ?.name property access, got: {expr}"
1691 );
1692 assert!(
1693 !expr.contains(".toString()"),
1694 "swift deep tool_calls must NOT wrap first-class String fields with .toString(), got: {expr}"
1695 );
1696 assert!(
1697 !expr.contains("=>"),
1698 "swift deep tool_calls must not use JS arrow syntax, got: {expr}"
1699 );
1700 }
1701
1702 #[test]
1703 fn accessor_finish_reason_swift_uses_swift_syntax() {
1704 let expr = StreamingFieldResolver::accessor("finish_reason", "swift", "chunks").unwrap();
1705 assert!(
1707 expr.contains("isEmpty"),
1708 "swift finish_reason must use .isEmpty, got: {expr}"
1709 );
1710 assert!(
1711 expr.contains(".last!"),
1712 "swift finish_reason must use .last!, got: {expr}"
1713 );
1714 assert!(
1715 expr.contains("finishReason"),
1716 "swift finish_reason must use lowerCamelCase finishReason property, got: {expr}"
1717 );
1718 assert!(
1720 expr.contains(".rawValue"),
1721 "swift finish_reason must read enum .rawValue, got: {expr}"
1722 );
1723 assert!(
1724 !expr.contains("undefined"),
1725 "swift finish_reason must not use JS `undefined`, got: {expr}"
1726 );
1727 assert!(
1728 !expr.contains(".length"),
1729 "swift finish_reason must not use JS .length, got: {expr}"
1730 );
1731 }
1732
1733 #[test]
1734 fn accessor_usage_swift_uses_swift_syntax() {
1735 let expr = StreamingFieldResolver::accessor("usage", "swift", "chunks").unwrap();
1736 assert!(expr.contains("isEmpty"), "swift usage must use .isEmpty, got: {expr}");
1738 assert!(expr.contains(".last!"), "swift usage must use .last!, got: {expr}");
1739 assert!(
1741 expr.contains(".usage"),
1742 "swift usage must reference .usage property, got: {expr}"
1743 );
1744 assert!(
1745 !expr.contains("usage()"),
1746 "swift usage must NOT use method-call syntax, got: {expr}"
1747 );
1748 assert!(
1749 !expr.contains("undefined"),
1750 "swift usage must not use JS `undefined`, got: {expr}"
1751 );
1752 assert!(
1753 !expr.contains(".length"),
1754 "swift usage must not use JS .length, got: {expr}"
1755 );
1756 }
1757
1758 #[test]
1763 fn kotlin_android_collect_snippet_uses_flow_to_list() {
1764 let snip = StreamingFieldResolver::collect_snippet("kotlin_android", "result", "chunks").unwrap();
1765 assert!(
1767 snip.contains("result.toList()"),
1768 "kotlin_android collect must use Flow.toList(), got: {snip}"
1769 );
1770 assert!(
1771 !snip.contains("asSequence()"),
1772 "kotlin_android collect must NOT use asSequence(), got: {snip}"
1773 );
1774 }
1775
1776 #[test]
1777 fn kotlin_android_stream_content_uses_property_access() {
1778 let expr = StreamingFieldResolver::accessor("stream_content", "kotlin_android", "chunks").unwrap();
1779 assert!(
1780 expr.contains(".choices"),
1781 "kotlin_android stream_content must use .choices property, got: {expr}"
1782 );
1783 assert!(
1784 !expr.contains(".choices()"),
1785 "kotlin_android stream_content must NOT use .choices() getter, got: {expr}"
1786 );
1787 assert!(
1788 expr.contains(".delta"),
1789 "kotlin_android stream_content must use .delta property, got: {expr}"
1790 );
1791 assert!(
1792 !expr.contains(".delta()"),
1793 "kotlin_android stream_content must NOT use .delta() getter, got: {expr}"
1794 );
1795 assert!(
1796 expr.contains(".content"),
1797 "kotlin_android stream_content must use .content property, got: {expr}"
1798 );
1799 assert!(
1800 !expr.contains(".content()"),
1801 "kotlin_android stream_content must NOT use .content() getter, got: {expr}"
1802 );
1803 }
1804
1805 #[test]
1806 fn kotlin_android_finish_reason_uses_name_lowercase_not_get_value() {
1807 let expr = StreamingFieldResolver::accessor("finish_reason", "kotlin_android", "chunks").unwrap();
1808 assert!(
1809 expr.contains(".finishReason"),
1810 "kotlin_android finish_reason must use .finishReason property, got: {expr}"
1811 );
1812 assert!(
1813 !expr.contains(".finishReason()"),
1814 "kotlin_android finish_reason must NOT use .finishReason() getter, got: {expr}"
1815 );
1816 assert!(
1817 expr.contains(".name"),
1818 "kotlin_android finish_reason must use .name for enum wire value, got: {expr}"
1819 );
1820 assert!(
1821 expr.contains(".lowercase()"),
1822 "kotlin_android finish_reason must use .lowercase(), got: {expr}"
1823 );
1824 assert!(
1825 !expr.contains(".getValue()"),
1826 "kotlin_android finish_reason must NOT use .getValue(), got: {expr}"
1827 );
1828 }
1829
1830 #[test]
1831 fn kotlin_android_usage_uses_property_access() {
1832 let expr = StreamingFieldResolver::accessor("usage", "kotlin_android", "chunks").unwrap();
1833 assert!(
1834 expr.contains(".usage"),
1835 "kotlin_android usage must use .usage property, got: {expr}"
1836 );
1837 assert!(
1838 !expr.contains(".usage()"),
1839 "kotlin_android usage must NOT use .usage() getter, got: {expr}"
1840 );
1841 }
1842
1843 #[test]
1844 fn kotlin_android_deep_tool_calls_uses_property_access() {
1845 let expr = StreamingFieldResolver::accessor("tool_calls[0].function.name", "kotlin_android", "chunks").unwrap();
1846 assert!(
1847 expr.contains(".function"),
1848 "kotlin_android deep tool_calls must use .function property, got: {expr}"
1849 );
1850 assert!(
1851 !expr.contains(".function()"),
1852 "kotlin_android deep tool_calls must NOT use .function() getter, got: {expr}"
1853 );
1854 assert!(
1855 expr.contains(".name"),
1856 "kotlin_android deep tool_calls must use .name property, got: {expr}"
1857 );
1858 assert!(
1859 !expr.contains(".name()"),
1860 "kotlin_android deep tool_calls must NOT use .name() getter, got: {expr}"
1861 );
1862 }
1863}