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> {
153 match field {
154 "chunks" => Some(match lang {
155 "zig" => format!("{chunks_var}.items"),
157 "php" => format!("${chunks_var}"),
160 _ => chunks_var.to_string(),
161 }),
162
163 "chunks.length" => Some(match lang {
164 "rust" => format!("{chunks_var}.len()"),
165 "go" => format!("len({chunks_var})"),
166 "python" => format!("len({chunks_var})"),
167 "php" => format!("count(${chunks_var})"),
168 "elixir" => format!("length({chunks_var})"),
169 "kotlin" => format!("{chunks_var}.size"),
171 "zig" => format!("{chunks_var}.items.len"),
173 "swift" => format!("{chunks_var}.count"),
175 _ => format!("{chunks_var}.length"),
177 }),
178
179 "stream_content" => Some(match lang {
180 "rust" => {
181 format!(
182 "{chunks_var}.iter().map(|c| c.choices.first().and_then(|ch| ch.delta.content.as_deref()).unwrap_or(\"\")).collect::<String>()"
183 )
184 }
185 "go" => {
186 format!(
188 "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 }}()"
189 )
190 }
191 "java" => {
192 format!(
193 "{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())"
194 )
195 }
196 "php" => {
197 format!("implode('', array_map(fn($c) => $c->choices[0]->delta->content ?? '', ${chunks_var}))")
198 }
199 "kotlin" => {
200 format!(
203 "{chunks_var}.joinToString(\"\") {{ it.choices()?.firstOrNull()?.delta()?.content() ?: \"\" }}"
204 )
205 }
206 "kotlin_android" => {
207 format!("{chunks_var}.joinToString(\"\") {{ it.choices?.firstOrNull()?.delta?.content ?: \"\" }}")
209 }
210 "elixir" => {
211 format!(
215 "{chunks_var} |> Enum.map(fn c -> (Enum.at(c.choices, 0) || %{{}}) |> Map.get(:delta, %{{}}) |> Map.get(:content, \"\") end) |> Enum.join(\"\")"
216 )
217 }
218 "python" => {
219 format!("\"\".join(c.choices[0].delta.content or \"\" for c in {chunks_var} if c.choices)")
220 }
221 "zig" => {
222 format!("{chunks_var}_content.items")
225 }
226 "swift" => {
230 format!(
231 "{chunks_var}.map {{ c in c.choices().first.flatMap {{ ch in ch.delta().content()?.toString() }} ?? \"\" }}.joined()"
232 )
233 }
234 _ => {
236 format!("{chunks_var}.map((c: any) => c.choices?.[0]?.delta?.content ?? '').join('')")
237 }
238 }),
239
240 "stream_complete" => Some(match lang {
241 "rust" => {
242 format!(
243 "{chunks_var}.last().and_then(|c| c.choices.first()).and_then(|ch| ch.finish_reason.as_ref()).is_some()"
244 )
245 }
246 "go" => {
247 format!(
248 "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 }}()"
249 )
250 }
251 "java" => {
252 format!(
253 "!{chunks_var}.isEmpty() && {chunks_var}.get({chunks_var}.size()-1).choices().stream().findFirst().flatMap(ch -> java.util.Optional.ofNullable(ch.finishReason())).isPresent()"
254 )
255 }
256 "php" => {
257 format!("!empty(${chunks_var}) && isset(end(${chunks_var})->choices[0]->finishReason)")
261 }
262 "kotlin" => {
263 format!(
265 "{chunks_var}.isNotEmpty() && {chunks_var}.last().choices()?.firstOrNull()?.finishReason() != null"
266 )
267 }
268 "kotlin_android" => {
269 format!(
271 "{chunks_var}.isNotEmpty() && {chunks_var}.last().choices?.firstOrNull()?.finishReason != null"
272 )
273 }
274 "python" => {
275 format!("bool({chunks_var}) and {chunks_var}[-1].choices[0].finish_reason is not None")
276 }
277 "elixir" => {
278 format!("Enum.at(List.last({chunks_var}).choices, 0).finish_reason != nil")
279 }
280 "zig" => {
283 format!("{chunks_var}.items.len > 0")
284 }
285 "swift" => {
289 format!("!{chunks_var}.isEmpty && {chunks_var}.last!.choices().first?.finish_reason() != nil")
290 }
291 _ => {
293 format!(
294 "{chunks_var}.length > 0 && {chunks_var}[{chunks_var}.length - 1].choices?.[0]?.finishReason != null"
295 )
296 }
297 }),
298
299 "no_chunks_after_done" => Some(match lang {
303 "rust" => "true".to_string(),
304 "go" => "true".to_string(),
305 "java" => "true".to_string(),
306 "php" => "true".to_string(),
307 _ => "true".to_string(),
308 }),
309
310 "stream.has_page_event" => has_event_variant_accessor(lang, chunks_var, EventVariant::Page),
320 "stream.has_error_event" => has_event_variant_accessor(lang, chunks_var, EventVariant::Error),
321 "stream.has_complete_event" => has_event_variant_accessor(lang, chunks_var, EventVariant::Complete),
322
323 "stream.event_count_min" => Self::accessor("chunks.length", lang, chunks_var),
327
328 "tool_calls" => Some(match lang {
329 "rust" => {
330 format!(
331 "{chunks_var}.iter().flat_map(|c| c.choices.iter().flat_map(|ch| ch.delta.tool_calls.iter().flatten())).collect::<Vec<_>>()"
332 )
333 }
334 "go" => {
335 format!(
339 "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 }}()"
340 )
341 }
342 "java" => {
343 format!(
344 "{chunks_var}.stream().flatMap(c -> c.choices().stream()).flatMap(ch -> ch.delta().toolCalls() != null ? ch.delta().toolCalls().stream() : java.util.stream.Stream.empty()).toList()"
345 )
346 }
347 "php" => {
348 format!(
351 "array_merge(...array_map(fn($c) => $c->choices[0]->delta->toolCalls ?? [], ${chunks_var}))"
352 )
353 }
354 "kotlin" => {
355 format!(
357 "{chunks_var}.flatMap {{ c -> c.choices()?.flatMap {{ ch -> ch.delta()?.toolCalls() ?: emptyList() }} ?: emptyList() }}"
358 )
359 }
360 "kotlin_android" => {
361 format!(
363 "{chunks_var}.flatMap {{ c -> c.choices?.flatMap {{ ch -> ch.delta?.toolCalls ?: emptyList() }} ?: emptyList() }}"
364 )
365 }
366 "python" => {
367 format!(
368 "[t for c in {chunks_var} for ch in (c.choices or []) for t in (ch.delta.tool_calls or [])]"
369 )
370 }
371 "elixir" => {
372 format!(
373 "{chunks_var} |> Enum.flat_map(fn c -> (List.first(c.choices) || %{{}}).delta |> Map.get(:tool_calls, []) end)"
374 )
375 }
376 "zig" => {
378 format!("{chunks_var}.items")
379 }
380 "swift" => {
387 format!(
388 "{chunks_var}.flatMap {{ c -> [StreamToolCallRef] in guard let ch = c.choices().first, let tcs = ch.delta().tool_calls() else {{ return [] }}; return Array(tcs) }}"
389 )
390 }
391 _ => {
392 format!("{chunks_var}.flatMap((c: any) => c.choices?.[0]?.delta?.toolCalls ?? [])")
393 }
394 }),
395
396 "finish_reason" => Some(match lang {
397 "rust" => {
398 format!(
401 "{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()"
402 )
403 }
404 "go" => {
405 format!(
408 "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 \"\" }}()"
409 )
410 }
411 "java" => {
412 format!(
416 "({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))"
417 )
418 }
419 "php" => {
420 format!("(!empty(${chunks_var}) ? (end(${chunks_var})->choices[0]->finishReason ?? null) : null)")
423 }
424 "kotlin" => {
425 format!(
428 "(if ({chunks_var}.isEmpty()) null else {chunks_var}.last().choices()?.firstOrNull()?.finishReason()?.getValue())"
429 )
430 }
431 "kotlin_android" => {
432 format!(
434 "(if ({chunks_var}.isEmpty()) null else {chunks_var}.last().choices?.firstOrNull()?.finishReason?.name?.lowercase())"
435 )
436 }
437 "python" => {
438 format!(
442 "(str({chunks_var}[-1].choices[0].finish_reason) if {chunks_var} and {chunks_var}[-1].choices else None)"
443 )
444 }
445 "elixir" => {
446 format!("Enum.at(List.last({chunks_var}).choices, 0).finish_reason")
447 }
448 "zig" => {
451 format!(
452 "(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 \"\"; }})"
453 )
454 }
455 "swift" => {
459 format!(
460 "({chunks_var}.isEmpty ? nil : {chunks_var}.last!.choices().first?.finish_reason()?.toString())"
461 )
462 }
463 _ => {
464 format!(
465 "{chunks_var}.length > 0 ? {chunks_var}[{chunks_var}.length - 1].choices?.[0]?.finishReason : undefined"
466 )
467 }
468 }),
469
470 "usage" => Some(match lang {
475 "python" => {
476 format!("({chunks_var}[-1].usage if {chunks_var} else None)")
480 }
481 "rust" => {
482 format!("{chunks_var}.last().and_then(|c| c.usage.as_ref())")
483 }
484 "go" => {
485 format!(
486 "func() interface{{}} {{ if len({chunks_var}) == 0 {{ return nil }}; return {chunks_var}[len({chunks_var})-1].Usage }}()"
487 )
488 }
489 "java" => {
490 format!("({chunks_var}.isEmpty() ? null : {chunks_var}.get({chunks_var}.size()-1).usage())")
491 }
492 "kotlin" => {
493 format!("(if ({chunks_var}.isEmpty()) null else {chunks_var}.last().usage())")
494 }
495 "kotlin_android" => {
496 format!("(if ({chunks_var}.isEmpty()) null else {chunks_var}.last().usage)")
498 }
499 "php" => {
500 format!("(!empty(${chunks_var}) ? end(${chunks_var})->usage ?? null : null)")
501 }
502 "elixir" => {
503 format!("(if length({chunks_var}) > 0, do: List.last({chunks_var}).usage, else: nil)")
504 }
505 "swift" => {
507 format!("({chunks_var}.isEmpty ? nil : {chunks_var}.last!.usage())")
508 }
509 _ => {
510 format!("({chunks_var}.length > 0 ? {chunks_var}[{chunks_var}.length - 1].usage : undefined)")
511 }
512 }),
513
514 _ => {
515 if let Some((root, tail)) = split_streaming_deep_path(field) {
519 if lang == "rust" && root == "tool_calls" {
523 return Some(render_rust_tool_calls_deep(chunks_var, tail));
524 }
525 if lang == "swift" && root == "tool_calls" {
529 let root_expr = Self::accessor(root, lang, chunks_var)?;
530 return Some(render_swift_tool_calls_deep(&root_expr, tail));
531 }
532 if lang == "zig" && root == "tool_calls" {
539 return None;
540 }
541 let root_expr = Self::accessor(root, lang, chunks_var)?;
542 Some(render_deep_tail(&root_expr, tail, lang))
543 } else {
544 None
545 }
546 }
547 }
548 }
549
550 pub fn collect_snippet(lang: &str, stream_var: &str, chunks_var: &str) -> Option<String> {
556 match lang {
557 "rust" => Some(format!(
558 "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();"
559 )),
560 "go" => Some(format!(
561 "var {chunks_var} []pkg.ChatCompletionChunk\n\tfor chunk := range {stream_var} {{\n\t\t{chunks_var} = append({chunks_var}, chunk)\n\t}}"
562 )),
563 "java" => Some(format!(
564 "var {chunks_var} = new java.util.ArrayList<ChatCompletionChunk>();\n var _it = {stream_var}.iterator();\n while (_it.hasNext()) {{ {chunks_var}.add(_it.next()); }}"
565 )),
566 "php" => Some(format!(
573 "${chunks_var} = is_string(${stream_var}) ? (json_decode(${stream_var}) ?: []) : iterator_to_array(${stream_var});"
574 )),
575 "python" => Some(format!(
576 "{chunks_var} = []\n async for chunk in {stream_var}:\n {chunks_var}.append(chunk)"
577 )),
578 "kotlin" => {
579 Some(format!("val {chunks_var} = {stream_var}.asSequence().toList()"))
582 }
583 "kotlin_android" => {
584 Some(format!("val {chunks_var} = {stream_var}.toList()"))
587 }
588 "elixir" => Some(format!("{chunks_var} = Enum.to_list({stream_var})")),
589 "node" | "wasm" | "typescript" => Some(format!(
590 "const {chunks_var}: any[] = [];\n for await (const _chunk of {stream_var}) {{ {chunks_var}.push(_chunk); }}"
591 )),
592 "swift" => {
593 Some(format!(
598 "var {chunks_var}: [ChatCompletionChunk] = []\n for try await _chunk in {stream_var} {{ {chunks_var}.append(_chunk) }}"
599 ))
600 }
601 "zig" => Some(Self::collect_snippet_zig(stream_var, chunks_var, "module", "ffi")),
602 _ => None,
603 }
604 }
605
606 pub fn collect_snippet_zig(stream_var: &str, chunks_var: &str, module_name: &str, ffi_prefix: &str) -> String {
608 let stream_next = format!("{ffi_prefix}_default_client_chat_stream_next");
609 let chunk_to_json = format!("{ffi_prefix}_chat_completion_chunk_to_json");
610 let chunk_free = format!("{ffi_prefix}_chat_completion_chunk_free");
611 let free_string = format!("{ffi_prefix}_free_string");
612
613 format!(
620 concat!(
621 "var {chunks_var}: std.ArrayList([]u8) = .empty;
622",
623 " defer {{
624",
625 " for ({chunks_var}.items) |_cj| std.heap.c_allocator.free(_cj);
626",
627 " {chunks_var}.deinit(std.heap.c_allocator);
628",
629 " }}
630",
631 " var {chunks_var}_content: std.ArrayList(u8) = .empty;
632",
633 " defer {chunks_var}_content.deinit(std.heap.c_allocator);
634",
635 " while (true) {{
636",
637 " const _nc = {module_name}.c.{stream_next}({stream_var});
638",
639 " if (_nc == null) break;
640",
641 " const _np = {module_name}.c.{chunk_to_json}(_nc);
642",
643 " {module_name}.c.{chunk_free}(_nc);
644",
645 " if (_np == null) continue;
646",
647 " const _ns = std.mem.span(_np);
648",
649 " const _nj = try std.heap.c_allocator.dupe(u8, _ns);
650",
651 " {module_name}.c.{free_string}(_np);
652",
653 " if (std.json.parseFromSlice(std.json.Value, std.heap.c_allocator, _nj, .{{}})) |_cp| {{
654",
655 " defer _cp.deinit();
656",
657 " if (_cp.value.object.get(\"choices\")) |_chs|
658",
659 " if (_chs.array.items.len > 0)
660",
661 " if (_chs.array.items[0].object.get(\"delta\")) |_dl|
662",
663 " if (_dl.object.get(\"content\")) |_ct|
664",
665 " if (_ct == .string) try {chunks_var}_content.appendSlice(std.heap.c_allocator, _ct.string);
666",
667 " }} else |_| {{}}
668",
669 " try {chunks_var}.append(std.heap.c_allocator, _nj);
670",
671 " }}"
672 ),
673 chunks_var = chunks_var,
674 stream_var = stream_var,
675 module_name = module_name,
676 stream_next = stream_next,
677 chunk_to_json = chunk_to_json,
678 chunk_free = chunk_free,
679 free_string = free_string,
680 )
681 }
682}
683
684#[derive(Debug, Clone, Copy)]
686enum EventVariant {
687 Page,
688 Error,
689 Complete,
690}
691
692impl EventVariant {
693 fn tag(self) -> &'static str {
695 match self {
696 EventVariant::Page => "page",
697 EventVariant::Error => "error",
698 EventVariant::Complete => "complete",
699 }
700 }
701
702 fn upper_camel(self) -> &'static str {
705 match self {
706 EventVariant::Page => "Page",
707 EventVariant::Error => "Error",
708 EventVariant::Complete => "Complete",
709 }
710 }
711}
712
713fn has_event_variant_accessor(lang: &str, chunks_var: &str, variant: EventVariant) -> Option<String> {
719 let tag = variant.tag();
720 let camel = variant.upper_camel();
721 match lang {
722 "python" => Some(format!("any(e.type == \"{tag}\" for e in {chunks_var})")),
724 "node" | "typescript" => Some(format!("{chunks_var}.some((e: any) => e?.type === \"{tag}\")")),
727 "ruby" => Some(format!("{chunks_var}.any? {{ |e| e.{tag}? }}")),
729 "go" => Some(format!(
733 "func() bool {{ for _, e := range {chunks_var} {{ if _, _ok := e.(pkg.CrawlEvent{camel}); _ok {{ return true }} }}; return false }}()"
734 )),
735 "java" => Some(format!(
737 "{chunks_var}.stream().anyMatch(e -> e instanceof CrawlEvent.{camel})"
738 )),
739 "csharp" => Some(format!(
741 "{chunks_var}.Any(e => e is global::Kreuzcrawl.CrawlEvent.{camel})"
742 )),
743 "swift" => Some(format!(
747 "{chunks_var}.contains(where: {{ e in if case .{tag} = e {{ return true }} else {{ return false }} }})"
748 )),
749 "elixir" => Some(format!(
751 "Enum.any?({chunks_var}, fn e -> Map.get(e, :type) == :{tag} end)"
752 )),
753 "kotlin" => Some(format!("{chunks_var}.any {{ it is CrawlEvent.{camel} }}")),
755 "kotlin_android" => Some(format!("{chunks_var}.any {{ it is CrawlEvent.{camel} }}")),
757 "dart" => Some(format!("{chunks_var}.any((e) => e is CrawlEvent_{camel})")),
760 "zig" => Some(format!(
765 "blk: {{ for ({chunks_var}.items) |_e| {{ if (std.mem.indexOf(u8, _e, \"\\\"type\\\":\\\"{tag}\\\"\") != null) break :blk true; }} break :blk false; }}"
766 )),
767 "rust" => Some(format!(
772 "{chunks_var}.iter().any(|e| matches!(e, kreuzcrawl::CrawlEvent::{camel} {{ .. }}))"
773 )),
774 "php" | "wasm" => None,
778 _ => None,
779 }
780}
781
782fn render_swift_tool_calls_deep(root_expr: &str, tail: &str) -> String {
794 use heck::ToLowerCamelCase;
795 let segs = parse_tail(tail);
796 let mut expr = root_expr.to_string();
797 let last_field_idx = segs.iter().rposition(|s| matches!(s, TailSeg::Field(_)));
798 let mut prev_was_index = false;
801
802 for (i, seg) in segs.iter().enumerate() {
803 match seg {
804 TailSeg::Index(n) => {
805 expr = format!("({expr})[{n}]");
806 prev_was_index = true;
807 }
808 TailSeg::Field(f) => {
809 let method = f.to_lower_camel_case();
810 let is_last = Some(i) == last_field_idx;
811 let chain = if prev_was_index { "." } else { "?." };
812 if is_last {
813 expr = format!("{expr}{chain}{method}()?.toString()");
815 } else {
816 expr = format!("{expr}{chain}{method}()");
818 }
819 prev_was_index = false;
820 }
821 }
822 }
823 expr
824}
825
826fn render_rust_tool_calls_deep(chunks_var: &str, tail: &str) -> String {
830 let segs = parse_tail(tail);
831 let idx = segs.iter().find_map(|s| match s {
833 TailSeg::Index(n) => Some(*n),
834 _ => None,
835 });
836 let field_segs: Vec<&str> = segs
837 .iter()
838 .filter_map(|s| match s {
839 TailSeg::Field(f) => Some(f.as_str()),
840 _ => None,
841 })
842 .collect();
843
844 let base = format!(
845 "{chunks_var}.iter().flat_map(|c| c.choices.iter().flat_map(|ch| ch.delta.tool_calls.iter().flatten()))"
846 );
847 let with_nth = match idx {
848 Some(n) => format!("{base}.nth({n})"),
849 None => base,
850 };
851
852 let mut expr = with_nth;
855 for (i, f) in field_segs.iter().enumerate() {
856 let is_leaf = i == field_segs.len() - 1;
857 if is_leaf {
858 expr = format!("{expr}.and_then(|x| x.{f}.as_deref())");
859 } else {
860 expr = format!("{expr}.and_then(|x| x.{f}.as_ref())");
861 }
862 }
863 format!("{expr}.unwrap_or(\"\")")
864}
865
866#[derive(Debug, PartialEq)]
871enum TailSeg {
872 Index(usize),
873 Field(String),
874}
875
876fn parse_tail(tail: &str) -> Vec<TailSeg> {
877 let mut segs = Vec::new();
878 let mut rest = tail;
879 while !rest.is_empty() {
880 if let Some(inner) = rest.strip_prefix('[') {
881 if let Some(close) = inner.find(']') {
883 let idx_str = &inner[..close];
884 if let Ok(idx) = idx_str.parse::<usize>() {
885 segs.push(TailSeg::Index(idx));
886 }
887 rest = &inner[close + 1..];
888 } else {
889 break;
890 }
891 } else if let Some(inner) = rest.strip_prefix('.') {
892 let end = inner.find(['.', '[']).unwrap_or(inner.len());
894 segs.push(TailSeg::Field(inner[..end].to_string()));
895 rest = &inner[end..];
896 } else {
897 break;
898 }
899 }
900 segs
901}
902
903fn render_deep_tail(root_expr: &str, tail: &str, lang: &str) -> String {
906 use heck::{ToLowerCamelCase, ToPascalCase};
907
908 let segs = parse_tail(tail);
909 let mut out = root_expr.to_string();
910
911 for seg in &segs {
912 match (seg, lang) {
913 (TailSeg::Index(n), "rust") => {
914 out = format!("({out})[{n}]");
915 }
916 (TailSeg::Index(n), "java") => {
917 out = format!("({out}).get({n})");
918 }
919 (TailSeg::Index(n), "kotlin") => {
920 if *n == 0 {
921 out = format!("({out}).first()");
922 } else {
923 out = format!("({out}).get({n})");
924 }
925 }
926 (TailSeg::Index(n), "kotlin_android") => {
927 if *n == 0 {
928 out = format!("({out}).first()");
929 } else {
930 out = format!("({out})[{n}]");
931 }
932 }
933 (TailSeg::Index(n), "elixir") => {
934 out = format!("Enum.at({out}, {n})");
935 }
936 (TailSeg::Index(n), "zig") => {
937 out = format!("({out}).items[{n}]");
938 }
939 (TailSeg::Index(n), "php") => {
940 out = format!("({out})[{n}]");
941 }
942 (TailSeg::Index(n), _) => {
943 out = format!("({out})[{n}]");
945 }
946 (TailSeg::Field(f), "rust") => {
947 use heck::ToSnakeCase;
948 out.push('.');
949 out.push_str(&f.to_snake_case());
950 }
951 (TailSeg::Field(f), "go") => {
952 use alef_codegen::naming::to_go_name;
953 out.push('.');
954 out.push_str(&to_go_name(f));
955 }
956 (TailSeg::Field(f), "java") => {
957 out.push('.');
958 out.push_str(&f.to_lower_camel_case());
959 out.push_str("()");
960 }
961 (TailSeg::Field(f), "kotlin") => {
962 out.push_str("?.");
968 out.push_str(&f.to_lower_camel_case());
969 out.push_str("()");
970 }
971 (TailSeg::Field(f), "kotlin_android") => {
972 out.push_str("?.");
974 out.push_str(&f.to_lower_camel_case());
975 }
976 (TailSeg::Field(f), "csharp") => {
977 out.push('.');
978 out.push_str(&f.to_pascal_case());
979 }
980 (TailSeg::Field(f), "php") => {
981 out.push_str("->");
986 out.push_str(f);
987 }
988 (TailSeg::Field(f), "elixir") => {
989 out.push('.');
990 out.push_str(f);
991 }
992 (TailSeg::Field(f), "zig") => {
993 out.push('.');
994 out.push_str(f);
995 }
996 (TailSeg::Field(f), "python") | (TailSeg::Field(f), "ruby") => {
997 out.push('.');
998 out.push_str(f);
999 }
1000 (TailSeg::Field(f), _) => {
1002 out.push('.');
1003 out.push_str(&f.to_lower_camel_case());
1004 }
1005 }
1006 }
1007
1008 out
1009}
1010
1011#[cfg(test)]
1012mod tests {
1013 use super::*;
1014
1015 #[test]
1016 fn is_streaming_virtual_field_recognizes_all_fields() {
1017 for field in STREAMING_VIRTUAL_FIELDS {
1018 assert!(
1019 is_streaming_virtual_field(field),
1020 "field '{field}' not recognized as streaming virtual"
1021 );
1022 }
1023 }
1024
1025 #[test]
1026 fn is_streaming_virtual_field_rejects_real_fields() {
1027 assert!(!is_streaming_virtual_field("content"));
1028 assert!(!is_streaming_virtual_field("choices"));
1029 assert!(!is_streaming_virtual_field("model"));
1030 assert!(!is_streaming_virtual_field(""));
1031 }
1032
1033 #[test]
1034 fn is_streaming_virtual_field_rejects_non_root_paths_with_matching_tail() {
1035 assert!(!is_streaming_virtual_field("choices[0].finish_reason"));
1040 assert!(!is_streaming_virtual_field("choices[0].message.content"));
1041 assert!(!is_streaming_virtual_field("data[0].embedding"));
1042 }
1043
1044 #[test]
1045 fn is_streaming_virtual_field_does_not_match_usage() {
1046 assert!(!is_streaming_virtual_field("usage"));
1050 assert!(!is_streaming_virtual_field("usage.total_tokens"));
1051 assert!(!is_streaming_virtual_field("usage.prompt_tokens"));
1052 }
1053
1054 #[test]
1055 fn accessor_chunks_returns_var_name() {
1056 assert_eq!(
1057 StreamingFieldResolver::accessor("chunks", "rust", "chunks"),
1058 Some("chunks".to_string())
1059 );
1060 assert_eq!(
1061 StreamingFieldResolver::accessor("chunks", "node", "chunks"),
1062 Some("chunks".to_string())
1063 );
1064 }
1065
1066 #[test]
1067 fn accessor_chunks_length_uses_language_idiom() {
1068 let rust = StreamingFieldResolver::accessor("chunks.length", "rust", "chunks").unwrap();
1069 assert!(rust.contains(".len()"), "rust: {rust}");
1070
1071 let go = StreamingFieldResolver::accessor("chunks.length", "go", "chunks").unwrap();
1072 assert!(go.starts_with("len("), "go: {go}");
1073
1074 let node = StreamingFieldResolver::accessor("chunks.length", "node", "chunks").unwrap();
1075 assert!(node.contains(".length"), "node: {node}");
1076
1077 let php = StreamingFieldResolver::accessor("chunks.length", "php", "chunks").unwrap();
1078 assert!(php.starts_with("count("), "php: {php}");
1079 }
1080
1081 #[test]
1082 fn accessor_chunks_length_zig_uses_items_len() {
1083 let zig = StreamingFieldResolver::accessor("chunks.length", "zig", "chunks").unwrap();
1084 assert_eq!(zig, "chunks.items.len", "zig chunks.length: {zig}");
1085 }
1086
1087 #[test]
1088 fn accessor_stream_content_zig_uses_content_items() {
1089 let zig = StreamingFieldResolver::accessor("stream_content", "zig", "chunks").unwrap();
1090 assert_eq!(zig, "chunks_content.items", "zig stream_content: {zig}");
1091 }
1092
1093 #[test]
1094 fn collect_snippet_zig_drains_via_ffi() {
1095 let snip = StreamingFieldResolver::collect_snippet("zig", "_stream_handle", "chunks").unwrap();
1096 assert!(snip.contains("std.ArrayList([]u8)"), "zig collect: {snip}");
1097 assert!(snip.contains("chat_stream_next(_stream_handle)"), "zig collect: {snip}");
1098 assert!(snip.contains("chunks_content"), "zig collect: {snip}");
1099 assert!(
1100 snip.contains("chunks.append(std.heap.c_allocator"),
1101 "zig collect: {snip}"
1102 );
1103 assert!(snip.contains(".empty;"), "zig collect (Zig 0.16 unmanaged): {snip}");
1104 }
1105
1106 #[test]
1107 fn accessor_stream_content_rust_uses_iterator() {
1108 let expr = StreamingFieldResolver::accessor("stream_content", "rust", "chunks").unwrap();
1109 assert!(expr.contains(".collect::<String>()"), "rust stream_content: {expr}");
1110 }
1111
1112 #[test]
1113 fn accessor_no_chunks_after_done_returns_true() {
1114 for lang in ["rust", "go", "java", "php", "node", "wasm", "elixir"] {
1115 let expr = StreamingFieldResolver::accessor("no_chunks_after_done", lang, "chunks").unwrap();
1116 assert_eq!(expr, "true", "lang {lang}: expected 'true', got '{expr}'");
1117 }
1118 }
1119
1120 #[test]
1121 fn accessor_elixir_chunks_length_uses_length_function() {
1122 let expr = StreamingFieldResolver::accessor("chunks.length", "elixir", "chunks").unwrap();
1123 assert_eq!(expr, "length(chunks)", "elixir chunks.length: {expr}");
1124 }
1125
1126 #[test]
1127 fn accessor_elixir_stream_content_uses_pipe() {
1128 let expr = StreamingFieldResolver::accessor("stream_content", "elixir", "chunks").unwrap();
1129 assert!(expr.contains("|> Enum.join"), "elixir stream_content: {expr}");
1130 assert!(expr.contains("|> Enum.map"), "elixir stream_content: {expr}");
1131 assert!(
1133 !expr.contains("choices[0]"),
1134 "elixir stream_content must not use bracket access on list: {expr}"
1135 );
1136 assert!(
1137 expr.contains("Enum.at("),
1138 "elixir stream_content must use Enum.at for list index: {expr}"
1139 );
1140 }
1141
1142 #[test]
1143 fn accessor_elixir_stream_complete_uses_list_last() {
1144 let expr = StreamingFieldResolver::accessor("stream_complete", "elixir", "chunks").unwrap();
1145 assert!(expr.contains("List.last(chunks)"), "elixir stream_complete: {expr}");
1146 assert!(expr.contains("finish_reason != nil"), "elixir stream_complete: {expr}");
1147 assert!(
1149 !expr.contains("choices[0]"),
1150 "elixir stream_complete must not use bracket access on list: {expr}"
1151 );
1152 assert!(
1153 expr.contains("Enum.at("),
1154 "elixir stream_complete must use Enum.at for list index: {expr}"
1155 );
1156 }
1157
1158 #[test]
1159 fn accessor_elixir_finish_reason_uses_list_last() {
1160 let expr = StreamingFieldResolver::accessor("finish_reason", "elixir", "chunks").unwrap();
1161 assert!(expr.contains("List.last(chunks)"), "elixir finish_reason: {expr}");
1162 assert!(expr.contains("finish_reason"), "elixir finish_reason: {expr}");
1163 assert!(
1165 !expr.contains("choices[0]"),
1166 "elixir finish_reason must not use bracket access on list: {expr}"
1167 );
1168 assert!(
1169 expr.contains("Enum.at("),
1170 "elixir finish_reason must use Enum.at for list index: {expr}"
1171 );
1172 }
1173
1174 #[test]
1175 fn collect_snippet_elixir_uses_enum_to_list() {
1176 let snip = StreamingFieldResolver::collect_snippet("elixir", "result", "chunks").unwrap();
1177 assert!(snip.contains("Enum.to_list(result)"), "elixir: {snip}");
1178 assert!(snip.contains("chunks ="), "elixir: {snip}");
1179 }
1180
1181 #[test]
1182 fn collect_snippet_rust_uses_tokio_stream() {
1183 let snip = StreamingFieldResolver::collect_snippet("rust", "result", "chunks").unwrap();
1184 assert!(snip.contains("tokio_stream::StreamExt::collect"), "rust: {snip}");
1185 assert!(snip.contains("let chunks"), "rust: {snip}");
1186 assert!(snip.contains(".expect("), "rust must unwrap Result items: {snip}");
1188 }
1189
1190 #[test]
1191 fn collect_snippet_go_drains_channel() {
1192 let snip = StreamingFieldResolver::collect_snippet("go", "stream", "chunks").unwrap();
1193 assert!(snip.contains("for chunk := range stream"), "go: {snip}");
1194 }
1195
1196 #[test]
1197 fn collect_snippet_java_uses_iterator() {
1198 let snip = StreamingFieldResolver::collect_snippet("java", "result", "chunks").unwrap();
1199 assert!(
1202 snip.contains(".iterator()"),
1203 "java snippet must call .iterator() on stream: {snip}"
1204 );
1205 assert!(snip.contains("hasNext()"), "java: {snip}");
1206 assert!(snip.contains(".next()"), "java: {snip}");
1207 }
1208
1209 #[test]
1210 fn collect_snippet_php_decodes_json_or_iterates() {
1211 let snip = StreamingFieldResolver::collect_snippet("php", "result", "chunks").unwrap();
1212 assert!(snip.contains("json_decode"), "php must decode JSON: {snip}");
1217 assert!(
1218 snip.contains("iterator_to_array"),
1219 "php must keep iterator_to_array fallback: {snip}"
1220 );
1221 assert!(snip.contains("$chunks ="), "php must bind $chunks: {snip}");
1222 }
1223
1224 #[test]
1225 fn collect_snippet_node_uses_for_await() {
1226 let snip = StreamingFieldResolver::collect_snippet("node", "result", "chunks").unwrap();
1227 assert!(snip.contains("for await"), "node: {snip}");
1228 }
1229
1230 #[test]
1231 fn collect_snippet_python_uses_async_for() {
1232 let snip = StreamingFieldResolver::collect_snippet("python", "result", "chunks").unwrap();
1233 assert!(snip.contains("async for chunk in result"), "python: {snip}");
1234 assert!(snip.contains("chunks.append(chunk)"), "python: {snip}");
1235 }
1236
1237 #[test]
1238 fn accessor_stream_content_python_uses_join() {
1239 let expr = StreamingFieldResolver::accessor("stream_content", "python", "chunks").unwrap();
1240 assert!(expr.contains("\"\".join("), "python stream_content: {expr}");
1241 assert!(expr.contains("c.choices"), "python stream_content: {expr}");
1242 }
1243
1244 #[test]
1245 fn accessor_stream_complete_python_uses_finish_reason() {
1246 let expr = StreamingFieldResolver::accessor("stream_complete", "python", "chunks").unwrap();
1247 assert!(
1248 expr.contains("finish_reason is not None"),
1249 "python stream_complete: {expr}"
1250 );
1251 }
1252
1253 #[test]
1254 fn accessor_finish_reason_python_uses_last_chunk() {
1255 let expr = StreamingFieldResolver::accessor("finish_reason", "python", "chunks").unwrap();
1256 assert!(expr.contains("chunks[-1]"), "python finish_reason: {expr}");
1257 assert!(
1259 expr.starts_with("(str(") || expr.contains("str(chunks"),
1260 "python finish_reason must wrap in str(): {expr}"
1261 );
1262 }
1263
1264 #[test]
1265 fn accessor_tool_calls_python_uses_list_comprehension() {
1266 let expr = StreamingFieldResolver::accessor("tool_calls", "python", "chunks").unwrap();
1267 assert!(expr.contains("for c in chunks"), "python tool_calls: {expr}");
1268 assert!(expr.contains("tool_calls"), "python tool_calls: {expr}");
1269 }
1270
1271 #[test]
1272 fn accessor_usage_python_uses_last_chunk() {
1273 let expr = StreamingFieldResolver::accessor("usage", "python", "chunks").unwrap();
1274 assert!(
1275 expr.contains("chunks[-1].usage"),
1276 "python usage: expected chunks[-1].usage, got: {expr}"
1277 );
1278 }
1279
1280 #[test]
1281 fn accessor_usage_total_tokens_does_not_route_via_chunks() {
1282 assert!(StreamingFieldResolver::accessor("usage.total_tokens", "python", "chunks").is_none());
1286 }
1287
1288 #[test]
1289 fn accessor_unknown_field_returns_none() {
1290 assert_eq!(
1291 StreamingFieldResolver::accessor("nonexistent_field", "rust", "chunks"),
1292 None
1293 );
1294 }
1295
1296 #[test]
1301 fn is_streaming_virtual_field_recognizes_deep_tool_calls_paths() {
1302 assert!(
1303 is_streaming_virtual_field("tool_calls[0].function.name"),
1304 "tool_calls[0].function.name should be recognized"
1305 );
1306 assert!(
1307 is_streaming_virtual_field("tool_calls[0].id"),
1308 "tool_calls[0].id should be recognized"
1309 );
1310 assert!(
1311 is_streaming_virtual_field("tool_calls[1].function.arguments"),
1312 "tool_calls[1].function.arguments should be recognized"
1313 );
1314 assert!(is_streaming_virtual_field("tool_calls"));
1316 assert!(!is_streaming_virtual_field("tool_calls_extra.name"));
1318 assert!(!is_streaming_virtual_field("nonexistent[0].field"));
1319 }
1320
1321 #[test]
1328 fn deep_tool_calls_function_name_snapshot_rust_kotlin_ts() {
1329 let field = "tool_calls[0].function.name";
1330
1331 let rust = StreamingFieldResolver::accessor(field, "rust", "chunks").unwrap();
1332 assert!(
1336 rust.contains(".nth(0)"),
1337 "rust deep tool_calls: expected .nth(0) iterator index, got: {rust}"
1338 );
1339 assert!(
1340 rust.contains("x.function.as_ref()"),
1341 "rust deep tool_calls: expected Option-aware function access, got: {rust}"
1342 );
1343 assert!(
1344 rust.contains("x.name.as_deref()"),
1345 "rust deep tool_calls: expected Option-aware name leaf, got: {rust}"
1346 );
1347 assert!(
1348 !rust.contains("// skipped"),
1349 "rust deep tool_calls: must not emit skip comment, got: {rust}"
1350 );
1351
1352 let kotlin = StreamingFieldResolver::accessor(field, "kotlin", "chunks").unwrap();
1353 assert!(
1355 kotlin.contains(".first()"),
1356 "kotlin deep tool_calls: expected .first() for index 0, got: {kotlin}"
1357 );
1358 assert!(
1359 kotlin.contains(".function()"),
1360 "kotlin deep tool_calls: expected .function() method call, got: {kotlin}"
1361 );
1362 assert!(
1363 kotlin.contains(".name()"),
1364 "kotlin deep tool_calls: expected .name() method call, got: {kotlin}"
1365 );
1366
1367 let ts = StreamingFieldResolver::accessor(field, "node", "chunks").unwrap();
1368 assert!(
1370 ts.contains("[0]"),
1371 "ts/node deep tool_calls: expected [0] index, got: {ts}"
1372 );
1373 assert!(
1374 ts.contains(".function"),
1375 "ts/node deep tool_calls: expected .function segment, got: {ts}"
1376 );
1377 assert!(
1378 ts.contains(".name"),
1379 "ts/node deep tool_calls: expected .name segment, got: {ts}"
1380 );
1381 }
1382
1383 #[test]
1384 fn deep_tool_calls_id_snapshot_all_langs() {
1385 let field = "tool_calls[0].id";
1386
1387 let rust = StreamingFieldResolver::accessor(field, "rust", "chunks").unwrap();
1388 assert!(rust.contains(".nth(0)"), "rust: {rust}");
1389 assert!(rust.contains("x.id.as_deref()"), "rust: {rust}");
1390
1391 let go = StreamingFieldResolver::accessor(field, "go", "chunks").unwrap();
1392 assert!(go.contains("[0]"), "go: {go}");
1393 assert!(go.contains(".ID"), "go: expected .ID initialism, got: {go}");
1395
1396 let python = StreamingFieldResolver::accessor(field, "python", "chunks").unwrap();
1397 assert!(python.contains("[0]"), "python: {python}");
1398 assert!(python.contains(".id"), "python: {python}");
1399
1400 let php = StreamingFieldResolver::accessor(field, "php", "chunks").unwrap();
1401 assert!(php.contains("[0]"), "php: {php}");
1402 assert!(php.contains("->id"), "php: expected ->id, got: {php}");
1403
1404 let java = StreamingFieldResolver::accessor(field, "java", "chunks").unwrap();
1405 assert!(java.contains(".get(0)"), "java: expected .get(0), got: {java}");
1406 assert!(java.contains(".id()"), "java: expected .id() method call, got: {java}");
1407
1408 let csharp = StreamingFieldResolver::accessor(field, "csharp", "chunks").unwrap();
1409 assert!(csharp.contains("[0]"), "csharp: {csharp}");
1410 assert!(
1411 csharp.contains(".Id"),
1412 "csharp: expected .Id (PascalCase), got: {csharp}"
1413 );
1414
1415 let elixir = StreamingFieldResolver::accessor(field, "elixir", "chunks").unwrap();
1416 assert!(elixir.contains("Enum.at("), "elixir: expected Enum.at(, got: {elixir}");
1417 assert!(elixir.contains(".id"), "elixir: {elixir}");
1418 }
1419
1420 #[test]
1421 fn deep_tool_calls_function_name_snapshot_python_elixir_zig() {
1422 let field = "tool_calls[0].function.name";
1423
1424 let python = StreamingFieldResolver::accessor(field, "python", "chunks").unwrap();
1425 assert!(python.contains("[0]"), "python: {python}");
1426 assert!(python.contains(".function"), "python: {python}");
1427 assert!(python.contains(".name"), "python: {python}");
1428
1429 let elixir = StreamingFieldResolver::accessor(field, "elixir", "chunks").unwrap();
1430 assert!(elixir.contains("Enum.at("), "elixir: {elixir}");
1432 assert!(elixir.contains(".function"), "elixir: {elixir}");
1433 assert!(elixir.contains(".name"), "elixir: {elixir}");
1434
1435 assert!(
1439 StreamingFieldResolver::accessor(field, "zig", "chunks").is_none(),
1440 "zig: expected None for deep tool_calls path"
1441 );
1442 }
1443
1444 #[test]
1445 fn parse_tail_parses_index_then_field_segments() {
1446 let segs = parse_tail("[0].function.name");
1447 assert_eq!(segs.len(), 3, "expected 3 segments, got: {segs:?}");
1448 assert_eq!(segs[0], TailSeg::Index(0));
1449 assert_eq!(segs[1], TailSeg::Field("function".to_string()));
1450 assert_eq!(segs[2], TailSeg::Field("name".to_string()));
1451 }
1452
1453 #[test]
1454 fn parse_tail_parses_simple_index_field() {
1455 let segs = parse_tail("[0].id");
1456 assert_eq!(segs.len(), 2, "expected 2 segments, got: {segs:?}");
1457 assert_eq!(segs[0], TailSeg::Index(0));
1458 assert_eq!(segs[1], TailSeg::Field("id".to_string()));
1459 }
1460
1461 #[test]
1462 fn parse_tail_handles_nonzero_index() {
1463 let segs = parse_tail("[2].function.arguments");
1464 assert_eq!(segs[0], TailSeg::Index(2));
1465 assert_eq!(segs[1], TailSeg::Field("function".to_string()));
1466 assert_eq!(segs[2], TailSeg::Field("arguments".to_string()));
1467 }
1468
1469 #[test]
1474 fn accessor_chunks_length_swift_uses_count() {
1475 let swift = StreamingFieldResolver::accessor("chunks.length", "swift", "chunks").unwrap();
1476 assert_eq!(swift, "chunks.count", "swift chunks.length: {swift}");
1477 }
1478
1479 #[test]
1480 fn accessor_stream_content_swift_uses_swift_closures() {
1481 let expr = StreamingFieldResolver::accessor("stream_content", "swift", "chunks").unwrap();
1482 assert!(
1484 expr.contains("{ c in"),
1485 "swift stream_content must use Swift closure syntax, got: {expr}"
1486 );
1487 assert!(
1488 !expr.contains("=>"),
1489 "swift stream_content must not contain JS arrow `=>`, got: {expr}"
1490 );
1491 assert!(
1493 expr.contains("choices()"),
1494 "swift stream_content must use .choices() method call, got: {expr}"
1495 );
1496 assert!(
1497 expr.contains("delta()"),
1498 "swift stream_content must use .delta() method call, got: {expr}"
1499 );
1500 assert!(
1501 expr.contains("content()"),
1502 "swift stream_content must use .content() method call, got: {expr}"
1503 );
1504 assert!(
1505 expr.contains(".toString()"),
1506 "swift stream_content must convert RustString via .toString(), got: {expr}"
1507 );
1508 assert!(
1509 expr.contains(".joined()"),
1510 "swift stream_content must join with .joined(), got: {expr}"
1511 );
1512 assert!(
1514 !expr.contains(".length"),
1515 "swift stream_content must not use JS .length, got: {expr}"
1516 );
1517 assert!(
1518 !expr.contains(".join("),
1519 "swift stream_content must not use JS .join(, got: {expr}"
1520 );
1521 }
1522
1523 #[test]
1524 fn accessor_stream_complete_swift_uses_swift_syntax() {
1525 let expr = StreamingFieldResolver::accessor("stream_complete", "swift", "chunks").unwrap();
1526 assert!(
1528 expr.contains("isEmpty"),
1529 "swift stream_complete must use .isEmpty, got: {expr}"
1530 );
1531 assert!(
1532 expr.contains(".last!"),
1533 "swift stream_complete must use .last!, got: {expr}"
1534 );
1535 assert!(
1536 expr.contains("choices()"),
1537 "swift stream_complete must use .choices() method call, got: {expr}"
1538 );
1539 assert!(
1540 expr.contains("finish_reason()"),
1541 "swift stream_complete must use .finish_reason(), got: {expr}"
1542 );
1543 assert!(
1544 !expr.contains(".length"),
1545 "swift stream_complete must not use JS .length, got: {expr}"
1546 );
1547 assert!(
1548 !expr.contains("!= null"),
1549 "swift stream_complete must not use JS `!= null`, got: {expr}"
1550 );
1551 }
1552
1553 #[test]
1554 fn accessor_tool_calls_swift_uses_swift_flatmap() {
1555 let expr = StreamingFieldResolver::accessor("tool_calls", "swift", "chunks").unwrap();
1556 assert!(
1558 !expr.contains("=>"),
1559 "swift tool_calls must not contain JS arrow `=>`, got: {expr}"
1560 );
1561 assert!(
1562 expr.contains("flatMap"),
1563 "swift tool_calls must use flatMap, got: {expr}"
1564 );
1565 assert!(
1566 expr.contains("choices()"),
1567 "swift tool_calls must use .choices() method call, got: {expr}"
1568 );
1569 assert!(
1570 expr.contains("delta()"),
1571 "swift tool_calls must use .delta() method call, got: {expr}"
1572 );
1573 assert!(
1574 expr.contains("tool_calls()"),
1575 "swift tool_calls must use .tool_calls() method call, got: {expr}"
1576 );
1577 }
1578
1579 #[test]
1580 fn accessor_tool_calls_deep_path_swift_uses_method_calls_with_optional_chain() {
1581 let expr = StreamingFieldResolver::accessor("tool_calls[0].function.name", "swift", "chunks").unwrap();
1585 assert!(
1586 expr.contains("function()"),
1587 "swift deep tool_calls must use .function() method call, got: {expr}"
1588 );
1589 assert!(
1590 expr.contains("name()"),
1591 "swift deep tool_calls must use .name() method call, got: {expr}"
1592 );
1593 assert!(
1594 expr.contains(".toString()"),
1595 "swift deep tool_calls must convert RustString via .toString(), got: {expr}"
1596 );
1597 assert!(
1598 !expr.contains("=>"),
1599 "swift deep tool_calls must not use JS arrow syntax, got: {expr}"
1600 );
1601 }
1602
1603 #[test]
1604 fn accessor_finish_reason_swift_uses_swift_syntax() {
1605 let expr = StreamingFieldResolver::accessor("finish_reason", "swift", "chunks").unwrap();
1606 assert!(
1608 expr.contains("isEmpty"),
1609 "swift finish_reason must use .isEmpty, got: {expr}"
1610 );
1611 assert!(
1612 expr.contains(".last!"),
1613 "swift finish_reason must use .last!, got: {expr}"
1614 );
1615 assert!(
1616 expr.contains("finish_reason()"),
1617 "swift finish_reason must use .finish_reason() method call, got: {expr}"
1618 );
1619 assert!(
1620 expr.contains(".toString()"),
1621 "swift finish_reason must convert RustString via .toString(), got: {expr}"
1622 );
1623 assert!(
1624 !expr.contains("undefined"),
1625 "swift finish_reason must not use JS `undefined`, got: {expr}"
1626 );
1627 assert!(
1628 !expr.contains(".length"),
1629 "swift finish_reason must not use JS .length, got: {expr}"
1630 );
1631 }
1632
1633 #[test]
1634 fn accessor_usage_swift_uses_swift_syntax() {
1635 let expr = StreamingFieldResolver::accessor("usage", "swift", "chunks").unwrap();
1636 assert!(expr.contains("isEmpty"), "swift usage must use .isEmpty, got: {expr}");
1638 assert!(expr.contains(".last!"), "swift usage must use .last!, got: {expr}");
1639 assert!(
1640 expr.contains("usage()"),
1641 "swift usage must use .usage() method call, got: {expr}"
1642 );
1643 assert!(
1644 !expr.contains("undefined"),
1645 "swift usage must not use JS `undefined`, got: {expr}"
1646 );
1647 assert!(
1648 !expr.contains(".length"),
1649 "swift usage must not use JS .length, got: {expr}"
1650 );
1651 }
1652
1653 #[test]
1658 fn kotlin_android_collect_snippet_uses_flow_to_list() {
1659 let snip = StreamingFieldResolver::collect_snippet("kotlin_android", "result", "chunks").unwrap();
1660 assert!(
1662 snip.contains("result.toList()"),
1663 "kotlin_android collect must use Flow.toList(), got: {snip}"
1664 );
1665 assert!(
1666 !snip.contains("asSequence()"),
1667 "kotlin_android collect must NOT use asSequence(), got: {snip}"
1668 );
1669 }
1670
1671 #[test]
1672 fn kotlin_android_stream_content_uses_property_access() {
1673 let expr = StreamingFieldResolver::accessor("stream_content", "kotlin_android", "chunks").unwrap();
1674 assert!(
1675 expr.contains(".choices"),
1676 "kotlin_android stream_content must use .choices property, got: {expr}"
1677 );
1678 assert!(
1679 !expr.contains(".choices()"),
1680 "kotlin_android stream_content must NOT use .choices() getter, got: {expr}"
1681 );
1682 assert!(
1683 expr.contains(".delta"),
1684 "kotlin_android stream_content must use .delta property, got: {expr}"
1685 );
1686 assert!(
1687 !expr.contains(".delta()"),
1688 "kotlin_android stream_content must NOT use .delta() getter, got: {expr}"
1689 );
1690 assert!(
1691 expr.contains(".content"),
1692 "kotlin_android stream_content must use .content property, got: {expr}"
1693 );
1694 assert!(
1695 !expr.contains(".content()"),
1696 "kotlin_android stream_content must NOT use .content() getter, got: {expr}"
1697 );
1698 }
1699
1700 #[test]
1701 fn kotlin_android_finish_reason_uses_name_lowercase_not_get_value() {
1702 let expr = StreamingFieldResolver::accessor("finish_reason", "kotlin_android", "chunks").unwrap();
1703 assert!(
1704 expr.contains(".finishReason"),
1705 "kotlin_android finish_reason must use .finishReason property, got: {expr}"
1706 );
1707 assert!(
1708 !expr.contains(".finishReason()"),
1709 "kotlin_android finish_reason must NOT use .finishReason() getter, got: {expr}"
1710 );
1711 assert!(
1712 expr.contains(".name"),
1713 "kotlin_android finish_reason must use .name for enum wire value, got: {expr}"
1714 );
1715 assert!(
1716 expr.contains(".lowercase()"),
1717 "kotlin_android finish_reason must use .lowercase(), got: {expr}"
1718 );
1719 assert!(
1720 !expr.contains(".getValue()"),
1721 "kotlin_android finish_reason must NOT use .getValue(), got: {expr}"
1722 );
1723 }
1724
1725 #[test]
1726 fn kotlin_android_usage_uses_property_access() {
1727 let expr = StreamingFieldResolver::accessor("usage", "kotlin_android", "chunks").unwrap();
1728 assert!(
1729 expr.contains(".usage"),
1730 "kotlin_android usage must use .usage property, got: {expr}"
1731 );
1732 assert!(
1733 !expr.contains(".usage()"),
1734 "kotlin_android usage must NOT use .usage() getter, got: {expr}"
1735 );
1736 }
1737
1738 #[test]
1739 fn kotlin_android_deep_tool_calls_uses_property_access() {
1740 let expr = StreamingFieldResolver::accessor("tool_calls[0].function.name", "kotlin_android", "chunks").unwrap();
1741 assert!(
1742 expr.contains(".function"),
1743 "kotlin_android deep tool_calls must use .function property, got: {expr}"
1744 );
1745 assert!(
1746 !expr.contains(".function()"),
1747 "kotlin_android deep tool_calls must NOT use .function() getter, got: {expr}"
1748 );
1749 assert!(
1750 expr.contains(".name"),
1751 "kotlin_android deep tool_calls must use .name property, got: {expr}"
1752 );
1753 assert!(
1754 !expr.contains(".name()"),
1755 "kotlin_android deep tool_calls must NOT use .name() getter, got: {expr}"
1756 );
1757 }
1758}