Skip to main content

alef_e2e/codegen/
streaming_assertions.rs

1//! Shared streaming-virtual-fields module for e2e test codegen.
2//!
3//! Chat-stream fixtures assert on "virtual" fields that don't exist on the
4//! stream result type itself — `chunks`, `chunks.length`, `stream_content`,
5//! `stream_complete`, `no_chunks_after_done`, `tool_calls`, `finish_reason`.
6//! These fields resolve against the *collected* list of chunks produced by
7//! draining the stream.
8//!
9//! [`StreamingFieldResolver`] provides two entry points:
10//! - [`StreamingFieldResolver::accessor`] — the language-specific expression
11//!   for a virtual field given a local variable that holds the collected list.
12//! - [`StreamingFieldResolver::collect_snippet`] — the language-specific
13//!   code snippet that drains a stream variable into the collected list.
14//!
15//! ## Convention
16//!
17//! The `chunks_var` parameter is the local variable name that holds the
18//! collected list (default: `"chunks"`).  The `stream_var` parameter is the
19//! result variable produced by the stream call (default: `"result"`).
20//!
21//! The set of streaming-virtual field names handled by this module:
22//! - `chunks`              → the collected list itself
23//! - `chunks.length`       → length/count of the collected list
24//! - `stream_content`      → concatenation of all delta content strings
25//! - `stream_complete`     → boolean — last chunk has a non-null finish_reason
26//! - `no_chunks_after_done` → structural invariant (true by construction for
27//!   channel/iterator-based APIs once the channel is closed; emitted as
28//!   `assert!(true)` / `assertTrue` for languages without post-DONE chunk plumbing)
29//! - `tool_calls`          → flat list of tool_calls from all chunk deltas
30//! - `finish_reason`       → finish_reason string from the last chunk
31
32/// The set of field names treated as streaming-virtual fields.
33pub 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    // Crawl-stream event-variant predicates: resolve against the collected
42    // `chunks` list where each item is a tagged-union CrawlEvent (`page` /
43    // `error` / `complete`). `event_count_min` is a synonym for the chunk
44    // count, used with `greater_than_or_equal` to assert "at least N events".
45    "stream.has_page_event",
46    "stream.has_error_event",
47    "stream.has_complete_event",
48    "stream.event_count_min",
49];
50
51/// The set of streaming-virtual root names that may have deep-path continuations.
52///
53/// A field like `tool_calls[0].function.name` starts with `tool_calls` and has
54/// a continuation `[0].function.name`. These are handled by
55/// [`StreamingFieldResolver::accessor`] via the deep-path logic.
56///
57/// `usage` is a stream-level root: `usage.total_tokens` resolves against the
58/// last chunk that carried a usage payload (accessed via the collected chunks
59/// list). Python accessor: `(chunks[-1].usage if chunks else None)`.
60const STREAMING_VIRTUAL_ROOTS: &[&str] = &["tool_calls", "finish_reason"];
61
62/// Returns `true` when `field` is a streaming-virtual field name, including
63/// deep-nested paths that start with a known streaming-virtual root.
64///
65/// Examples that return `true`:
66/// - `"tool_calls"` (exact root)
67/// - `"tool_calls[0].function.name"` (deep path)
68/// - `"tool_calls[0].id"` (deep path)
69pub fn is_streaming_virtual_field(field: &str) -> bool {
70    if STREAMING_VIRTUAL_FIELDS.contains(&field) {
71        return true;
72    }
73    // Check deep-path prefixes: `tool_calls[…` or `tool_calls.`
74    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
85/// Split a field path into `(root, tail)` when it starts with a streaming-virtual
86/// root and has a continuation.
87///
88/// Returns `None` when the field is an exact root match (no tail) or is not a
89/// streaming-virtual root at all.
90fn 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
102/// Field names that unambiguously imply a streaming test (no overlap with
103/// non-streaming response shapes). `usage`, `tool_calls`, and `finish_reason`
104/// are intentionally excluded — they exist on non-streaming responses too
105/// (`usage.total_tokens` on ChatCompletionResponse, `choices[0].finish_reason`,
106/// etc.) and would otherwise drag non-streaming fixtures into streaming
107/// codegen.
108const 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
120/// Resolve whether a fixture should be treated as streaming, honoring the
121/// call-level three-valued opt-in/out (`CallConfig::streaming`):
122///
123/// - `Some(true)` → forced streaming.
124/// - `Some(false)` → forced non-streaming (skip the auto-detect even when an
125///   assertion references a streaming-virtual-field name like `chunks`).
126/// - `None` → auto-detect: streaming iff the fixture has a streaming mock
127///   (`mock_response.stream_chunks`) or any assertion references one of the
128///   unambiguous streaming-only field names.
129///
130/// All backends should use this helper so the opt-out is respected uniformly.
131pub 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
143/// Shared streaming-virtual-fields resolver for e2e test codegen.
144pub struct StreamingFieldResolver;
145
146impl StreamingFieldResolver {
147    /// Returns the language-specific expression for a streaming-virtual field,
148    /// given `chunks_var` (the collected-list local name) and `lang`.
149    ///
150    /// Returns `None` when the field name is not a known streaming-virtual
151    /// field or the language has no streaming support.
152    ///
153    /// `module_qualifier` carries the per-project module/crate name used by the
154    /// Rust and C# `stream.has_*_event` branches to construct the streaming
155    /// union type path. Pass the cargo crate name (snake_case) for Rust callers
156    /// and the C# namespace (PascalCase) for C# callers. When `None` is
157    /// supplied for those branches, the accessor returns `None` so the call
158    /// site can skip the assertion rather than emit code referencing an unknown
159    /// type.
160    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    /// Same as [`Self::accessor`] but accepts a per-project module qualifier
165    /// for the `stream.has_*_event` branches that emit a streaming union type
166    /// path.
167    ///
168    /// This is a backward-compatible wrapper; it forwards to
169    /// [`Self::accessor_with_streaming_context`] with the legacy default item
170    /// type `"CrawlEvent"` so existing callers continue to emit correct code for
171    /// kreuzcrawl without changes. Consumers whose streaming union type differs
172    /// should call [`Self::accessor_with_streaming_context`] directly.
173    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        // Pass the legacy default item type so the `stream.has_*_event` branches
180        // continue to work for callers that predate the generic API.
181        Self::accessor_with_streaming_context(field, lang, chunks_var, module_qualifier, Some("CrawlEvent"))
182    }
183
184    /// Same as [`Self::accessor_with_module_qualifier`] but also accepts the
185    /// unqualified name of the streaming union item type (e.g. `"CrawlEvent"`
186    /// for kreuzcrawl, or any other tagged-union name a consumer defines).
187    ///
188    /// When `item_type` is `None` the `stream.has_*_event` branches fall back
189    /// to the legacy default supplied by the originating consumer — callers
190    /// that do not know their item type should pass `None` and the function
191    /// returns `None` for those branches, so the assertion is skipped rather
192    /// than emitting a reference to an unknown type.
193    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 ArrayList does not expose .len directly; must use .items
203                "zig" => format!("{chunks_var}.items"),
204                // PHP variables require `$` sigil — bareword `chunks` is parsed as a
205                // constant reference and triggers "Undefined constant" errors.
206                "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 List.size is a property (not .length)
217                "kotlin" => format!("{chunks_var}.size"),
218                // zig: chunks_var is ArrayList([]u8); use .items.len
219                "zig" => format!("{chunks_var}.items.len"),
220                // Swift Array uses .count (Collection protocol)
221                "swift" => format!("{chunks_var}.count"),
222                // node/wasm/typescript use .length
223                _ => 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                    // Go: chunks is []pkg.ChatCompletionChunk
234                    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                    // Kotlin: chunks is List<ChatCompletionChunk> (Java records via typealias).
248                    // choices() / delta() / content() are Java record accessor methods.
249                    format!(
250                        "{chunks_var}.joinToString(\"\") {{ it.choices()?.firstOrNull()?.delta()?.content() ?: \"\" }}"
251                    )
252                }
253                "kotlin_android" => {
254                    // kotlin-android: data classes use Kotlin property access (no parens).
255                    format!("{chunks_var}.joinToString(\"\") {{ it.choices?.firstOrNull()?.delta?.content ?: \"\" }}")
256                }
257                "elixir" => {
258                    // StreamDelta has all fields optional with skip_serializing_if, so
259                    // absent fields are not present as keys in the Jason-decoded map.
260                    // Use Map.get with defaults to avoid KeyError on absent :content.
261                    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                    // Zig: `{chunks_var}_content` is a `std.ArrayList(u8)` populated by
270                    // the collect snippet. `.items` gives a `[]u8` slice of the content.
271                    format!("{chunks_var}_content.items")
272                }
273                // Swift: chunks is [<Module>.ChatCompletionChunk] (first-class
274                // Codable struct emitted by alef-backend-swift). choices is
275                // `[StreamChoice]` (property), delta is `StreamDelta` (property),
276                // content is `String?` (property). No `.toString()` wrapping —
277                // first-class fields are already native Swift values.
278                "swift" => {
279                    format!(
280                        "{chunks_var}.map {{ c in c.choices.first.flatMap {{ ch in ch.delta.content }} ?? \"\" }}.joined()"
281                    )
282                }
283                // node/wasm/typescript
284                _ => {
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                    // PHP streaming chunks come from `json_decode` of the binding's JSON
307                    // string return. The PHP binding serializes with rename_all = "camelCase",
308                    // so use `finishReason` (camelCase) to match the emitted JSON keys.
309                    format!("!empty(${chunks_var}) && isset(end(${chunks_var})->choices[0]->finishReason)")
310                }
311                "kotlin" => {
312                    // Kotlin: use isNotEmpty() + last() + safe-call chain
313                    format!(
314                        "{chunks_var}.isNotEmpty() && {chunks_var}.last().choices()?.firstOrNull()?.finishReason() != null"
315                    )
316                }
317                "kotlin_android" => {
318                    // kotlin-android: data classes use Kotlin property access (no parens).
319                    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: the collect snippet exhausts the stream; check last chunk JSON
330                // was collected (chunks.items is non-empty) as a proxy for completion.
331                "zig" => {
332                    format!("{chunks_var}.items.len > 0")
333                }
334                // Swift: chunks is [<Module>.ChatCompletionChunk] first-class
335                // struct. `choices` is `[StreamChoice]` (property), `finishReason`
336                // is `FinishReason?` (property, camelCase).
337                "swift" => {
338                    format!("!{chunks_var}.isEmpty && {chunks_var}.last!.choices.first?.finishReason != nil")
339                }
340                // node/wasm/typescript
341                _ => {
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 is a structural invariant: once the stream
349            // closes (channel drained / iterator exhausted), no further chunks
350            // can arrive.  We assert `true` as a compile-time proof of intent.
351            "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            // Streaming union event-variant predicates.
360            //
361            // Each chunk is a tagged union whose concrete type name is given by
362            // `item_type` (e.g. `"CrawlEvent"` for kreuzcrawl). The accessor
363            // returns a language-native boolean expression that is `true` iff
364            // any chunk in the collected list matches the named variant.
365            //
366            // When `item_type` is `None` the helper returns `None` so the
367            // assertion is silently skipped — callers must supply the type name
368            // to emit working code.
369            //
370            // PHP and WASM intentionally return `None`: PHP's crawl-stream is
371            // exposed as eager JSON (see `chunks_var` collect_snippet) and WASM
372            // does not support streaming on `wasm32` targets.
373            "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            // event_count_min is the collected chunks count — used with
382            // `greater_than_or_equal` assertions on the chunk count.  Mirrors
383            // `chunks.length` per-language.
384            "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                    // StreamDelta.ToolCalls is `[]StreamToolCall` (slice, not pointer).
394                    // Return the typed slice so deep-path accessors like `tool_calls[0].function.name`
395                    // can index and access typed fields.
396                    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                    // PHP streaming chunks are json_decoded stdClass. The PHP binding
407                    // serializes with rename_all = "camelCase", so use `toolCalls`.
408                    format!(
409                        "array_merge(...array_map(fn($c) => $c->choices[0]->delta->toolCalls ?? [], ${chunks_var}))"
410                    )
411                }
412                "kotlin" => {
413                    // Kotlin: flatten tool_calls from all chunk deltas into one list
414                    format!(
415                        "{chunks_var}.flatMap {{ c -> c.choices()?.flatMap {{ ch -> ch.delta()?.toolCalls() ?: emptyList() }} ?: emptyList() }}"
416                    )
417                }
418                "kotlin_android" => {
419                    // kotlin-android: data classes use Kotlin property access (no parens).
420                    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: tool_calls count from all chunk deltas
435                "zig" => {
436                    format!("{chunks_var}.items")
437                }
438                // Swift: chunks is [<Module>.ChatCompletionChunk] first-class
439                // Codable struct. choices is `[StreamChoice]`, delta is
440                // `StreamDelta`, toolCalls is `[StreamToolCall]?`.
441                "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                    // ChatCompletionChunk's finish_reason is Option<FinishReason> (enum, not
454                    // String). Display impl writes the JSON wire form (e.g. "tool_calls").
455                    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                    // FinishReason is a typed alias (`type FinishReason string`) in bindings,
461                    // so cast to string explicitly to match the assertion target type.
462                    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                    // FinishReason.getValue() returns the JSON wire string (e.g. "tool_calls").
468                    // Without it, assertEquals(String, FinishReason) fails because Object.equals
469                    // doesn't cross types even when toString() matches.
470                    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                    // PHP streaming chunks are json_decoded stdClass. The PHP binding
476                    // serializes with rename_all = "camelCase", so use `finishReason`.
477                    format!("(!empty(${chunks_var}) ? (end(${chunks_var})->choices[0]->finishReason ?? null) : null)")
478                }
479                "kotlin" => {
480                    // Returns the string value of the finish_reason enum from the last chunk.
481                    // FinishReason.getValue() returns the JSON wire string (e.g. "tool_calls").
482                    format!(
483                        "(if ({chunks_var}.isEmpty()) null else {chunks_var}.last().choices()?.firstOrNull()?.finishReason()?.getValue())"
484                    )
485                }
486                "kotlin_android" => {
487                    // kotlin-android: plain Kotlin enum class uses .name.lowercase() for wire string.
488                    format!(
489                        "(if ({chunks_var}.isEmpty()) null else {chunks_var}.last().choices?.firstOrNull()?.finishReason?.name?.lowercase())"
490                    )
491                }
492                "python" => {
493                    // FinishReason is a PyO3 enum object, not a plain string.
494                    // Wrap in str() so callers can do `.strip()` / string comparisons
495                    // without `AttributeError: 'FinishReason' has no attribute 'strip'`.
496                    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: finish_reason from the last chunk's JSON via an inline labeled block.
504                // Returns `[]const u8` (unwrapped with orelse "" for expectEqualStrings).
505                "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: first-class `StreamChoice.finishReason: FinishReason?`
511                // where FinishReason is a Codable Swift enum with `String` raw
512                // values matching serde wire strings. `.rawValue` yields e.g.
513                // "tool_calls" for cross-language fixture parity.
514                "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` is a stream-level virtual root: resolves against the last
525            // chunk that carried a usage payload.  Deep paths like `usage.total_tokens`
526            // are handled by the deep-path logic in the `_` arm below (root=`usage`,
527            // tail=`.total_tokens`), which calls this base accessor and appends the tail.
528            "usage" => Some(match lang {
529                "python" => {
530                    // Access the last chunk's usage object (may be None).
531                    // Deep paths like usage.total_tokens are rendered as:
532                    //   (chunks[-1].usage if chunks else None).total_tokens
533                    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                    // kotlin-android: data classes use Kotlin property access (no parens).
551                    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: first-class `ChatCompletionChunk.usage: Usage?`
560                // (Codable struct property — no method call).
561                "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                // Deep-path: e.g. `tool_calls[0].function.name`
571                // Split into root + tail, get the root's inline expression, then
572                // render the tail (index + fields) in a per-language style on top.
573                if let Some((root, tail)) = split_streaming_deep_path(field) {
574                    // Rust needs Option-aware chaining for the StreamToolCall fields
575                    // (function/id are Option<...>). The generic tail renderer can't
576                    // infer Option-wrapping, so we emit rust-specific idiom here.
577                    if lang == "rust" && root == "tool_calls" {
578                        return Some(render_rust_tool_calls_deep(chunks_var, tail));
579                    }
580                    // Swift: StreamToolCallRef fields are swift-bridge methods returning
581                    // Optional.  The generic render_deep_tail doesn't know to add `()`
582                    // or optional-chain with `?.`, so use a dedicated renderer.
583                    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                    // Zig stores stream chunks as JSON strings (`[]const u8`) in
588                    // `chunks: ArrayList([]u8)`, not typed `ChatCompletionChunk`
589                    // records. A deep `tool_calls[N].function.name` access would
590                    // require parsing each chunk's JSON inline — rather than
591                    // emit code that won't compile, signal "unsupported" so the
592                    // assertion is skipped at the call site.
593                    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    /// Returns the language-specific stream-collect-into-list snippet that
606    /// produces `chunks_var` from `stream_var`.
607    ///
608    /// Returns `None` when the language has no streaming collect support or
609    /// when the collect snippet cannot be expressed generically.
610    pub fn collect_snippet(lang: &str, stream_var: &str, chunks_var: &str) -> Option<String> {
611        Self::collect_snippet_typed(lang, stream_var, chunks_var, None)
612    }
613
614    /// Collect stream into a list, with optional item_type for languages that need the concrete type.
615    ///
616    /// When item_type is None, defaults to ChatCompletionChunk for backward compatibility with
617    /// liter-llm. For other projects like kreuzcrawl, item_type should be provided (e.g., "CrawlEvent").
618    pub fn collect_snippet_typed(
619        lang: &str,
620        stream_var: &str,
621        chunks_var: &str,
622        item_type: Option<&str>,
623    ) -> Option<String> {
624        let item_type = item_type.unwrap_or("ChatCompletionChunk");
625        match lang {
626            "rust" => Some(format!(
627                "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();"
628            )),
629            "go" => Some(format!(
630                "var {chunks_var} []pkg.{item_type}\n\tfor chunk := range {stream_var} {{\n\t\t{chunks_var} = append({chunks_var}, chunk)\n\t}}"
631            )),
632            "java" => Some(format!(
633                "var {chunks_var} = new java.util.ArrayList<{item_type}>();\n        var _it = {stream_var}.iterator();\n        while (_it.hasNext()) {{ {chunks_var}.add(_it.next()); }}"
634            )),
635            // PHP binding's chat_stream returns Vec<String> (each element is a
636            // JSON-serialized chunk) because ext-php-rs can't expose Rust
637            // iterators directly. Decode each element and recursively
638            // camelCase the keys so accessor chains like
639            // `$c->choices[0]->delta->finishReason` resolve against what the
640            // non-streaming PHP binding returns (camelCase getters). Three
641            // input shapes are tolerated: (a) array of JSON strings — the
642            // current binding; (b) single concatenated JSON — older binding
643            // output; (c) a real iterator — future binding upgrade.
644            "php" => Some(format!(
645                "$__camel = function ($v) use (&$__camel) {{ \
646                    if (is_array($v)) {{ \
647                        $out = []; \
648                        foreach ($v as $k => $vv) {{ \
649                            $key = is_string($k) ? lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', $k)))) : $k; \
650                            $out[$key] = $__camel($vv); \
651                        }} \
652                        return (array_keys($out) === range(0, count($out) - 1)) ? $out : (object) $out; \
653                    }} \
654                    if (is_object($v)) {{ \
655                        $out = new \\stdClass(); \
656                        foreach (get_object_vars($v) as $k => $vv) {{ \
657                            $key = lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', $k)))); \
658                            $out->{{$key}} = $__camel($vv); \
659                        }} \
660                        return $out; \
661                    }} \
662                    return $v; \
663                }};\n        \
664                $__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        \
665                ${chunks_var} = is_string(${stream_var}) \
666                    ? array_map($__decode_chunk, (array)(json_decode(${stream_var}, true) ?: [])) \
667                    : (is_array(${stream_var}) \
668                        ? array_map($__decode_chunk, ${stream_var}) \
669                        : array_map($__decode_chunk, iterator_to_array(${stream_var})));"
670            )),
671            "python" => Some(format!(
672                "{chunks_var} = []\n    async for chunk in {stream_var}:\n        {chunks_var}.append(chunk)"
673            )),
674            "kotlin" => {
675                // Kotlin: chatStream returns Iterator<ChatCompletionChunk> (from Java bridge).
676                // Drain into a Kotlin List using asSequence().toList().
677                Some(format!("val {chunks_var} = {stream_var}.asSequence().toList()"))
678            }
679            "kotlin_android" => {
680                // kotlin-android: chatStream returns Flow<ChatCompletionChunk> (kotlinx.coroutines).
681                // Collect inside a runBlocking coroutine scope using Flow.toList().
682                Some(format!("val {chunks_var} = {stream_var}.toList()"))
683            }
684            "elixir" => Some(format!("{chunks_var} = Enum.to_list({stream_var})")),
685            // WASM's chatStream returns a hand-rolled `ChatStreamIterator`
686            // struct that exposes `next()` returning `Promise<chunk | null>`,
687            // not a JS async iterable. wasm-bindgen does not auto-emit the
688            // `Symbol.asyncIterator` protocol, so `for await` on this object
689            // throws `TypeError: stream is not async iterable`. Drain via an
690            // explicit while/next() loop instead.
691            "wasm" => Some(format!(
692                "const {chunks_var}: any[] = [];\n    while (true) {{ const _chunk = await {stream_var}.next(); if (_chunk == null) break; {chunks_var}.push(_chunk); }}"
693            )),
694            "node" | "typescript" => Some(format!(
695                "const {chunks_var}: any[] = [];\n    for await (const _chunk of {stream_var}) {{ {chunks_var}.push(_chunk); }}"
696            )),
697            "swift" => {
698                // Swift's chat-stream wrapper returns AsyncThrowingStream<ChunkType, Error>,
699                // so consumers drain it with `for try await chunk in stream { ... }`. The
700                // chunk type is decoded from the bridge-boundary JSON inside the wrapper —
701                // here we just collect the typed Swift values.
702                Some(format!(
703                    "var {chunks_var}: [ChatCompletionChunk] = []\n        for try await _chunk in {stream_var} {{ {chunks_var}.append(_chunk) }}"
704                ))
705            }
706            "zig" => Some(Self::collect_snippet_zig(stream_var, chunks_var, "module", "ffi")),
707            _ => None,
708        }
709    }
710
711    /// Render Zig's streaming collect snippet using the configured module and FFI prefix.
712    pub fn collect_snippet_zig(stream_var: &str, chunks_var: &str, module_name: &str, ffi_prefix: &str) -> String {
713        let stream_next = format!("{ffi_prefix}_default_client_chat_stream_next");
714        let chunk_to_json = format!("{ffi_prefix}_chat_completion_chunk_to_json");
715        let chunk_free = format!("{ffi_prefix}_chat_completion_chunk_free");
716        let free_string = format!("{ffi_prefix}_free_string");
717
718        // Zig 0.16: ArrayList is unmanaged — no stored allocator.
719        // Use `.empty` to initialize, pass `std.heap.c_allocator` to each mutation.
720        // `stream_var` is the opaque stream handle obtained via `_start`.
721        // We collect every chunk's JSON string into `chunks_var: ArrayList([]u8)`
722        // and concatenate delta content into `{chunks_var}_content: ArrayList(u8)`.
723        // Accessors use `.items.len` and `{chunks_var}_content.items` on these lists.
724        format!(
725            concat!(
726                "var {chunks_var}: std.ArrayList([]u8) = .empty;
727",
728                "    defer {{
729",
730                "        for ({chunks_var}.items) |_cj| std.heap.c_allocator.free(_cj);
731",
732                "        {chunks_var}.deinit(std.heap.c_allocator);
733",
734                "    }}
735",
736                "    var {chunks_var}_content: std.ArrayList(u8) = .empty;
737",
738                "    defer {chunks_var}_content.deinit(std.heap.c_allocator);
739",
740                "    while (true) {{
741",
742                "        const _nc = {module_name}.c.{stream_next}({stream_var});
743",
744                "        if (_nc == null) break;
745",
746                "        const _np = {module_name}.c.{chunk_to_json}(_nc);
747",
748                "        {module_name}.c.{chunk_free}(_nc);
749",
750                "        if (_np == null) continue;
751",
752                "        const _ns = std.mem.span(_np);
753",
754                "        const _nj = try std.heap.c_allocator.dupe(u8, _ns);
755",
756                "        {module_name}.c.{free_string}(_np);
757",
758                "        if (std.json.parseFromSlice(std.json.Value, std.heap.c_allocator, _nj, .{{}})) |_cp| {{
759",
760                "            defer _cp.deinit();
761",
762                "            if (_cp.value.object.get(\"choices\")) |_chs|
763",
764                "                if (_chs.array.items.len > 0)
765",
766                "                    if (_chs.array.items[0].object.get(\"delta\")) |_dl|
767",
768                "                        if (_dl.object.get(\"content\")) |_ct|
769",
770                "                            if (_ct == .string) try {chunks_var}_content.appendSlice(std.heap.c_allocator, _ct.string);
771",
772                "        }} else |_| {{}}
773",
774                "        try {chunks_var}.append(std.heap.c_allocator, _nj);
775",
776                "    }}"
777            ),
778            chunks_var = chunks_var,
779            stream_var = stream_var,
780            module_name = module_name,
781            stream_next = stream_next,
782            chunk_to_json = chunk_to_json,
783            chunk_free = chunk_free,
784            free_string = free_string,
785        )
786    }
787}
788
789/// Identifies a `CrawlEvent` variant for `stream.has_*_event` accessors.
790#[derive(Debug, Clone, Copy)]
791enum EventVariant {
792    Page,
793    Error,
794    Complete,
795}
796
797impl EventVariant {
798    /// Lower-case JSON-wire tag value for the `type` discriminator.
799    fn tag(self) -> &'static str {
800        match self {
801            EventVariant::Page => "page",
802            EventVariant::Error => "error",
803            EventVariant::Complete => "complete",
804        }
805    }
806
807    /// Upper-camel variant name as used in most language bindings
808    /// (e.g. `CrawlEvent_Page`, `CrawlEventPage`, `CrawlEvent.Page`).
809    fn upper_camel(self) -> &'static str {
810        match self {
811            EventVariant::Page => "Page",
812            EventVariant::Error => "Error",
813            EventVariant::Complete => "Complete",
814        }
815    }
816}
817
818/// Emit a language-native boolean expression that is `true` iff any chunk in
819/// `chunks_var` matches the given streaming-union variant.
820///
821/// `item_type` is the unqualified name of the streaming union type (e.g.
822/// `"CrawlEvent"` for kreuzcrawl).  `module_qualifier` is the per-project
823/// module/namespace prefix required by Rust and C# to form a fully-qualified
824/// type path.
825///
826/// Returns `None` for languages where typed streaming-union matching is not
827/// expressible (PHP — eager-JSON, WASM — no streaming on wasm32).
828fn has_event_variant_accessor(
829    lang: &str,
830    chunks_var: &str,
831    variant: EventVariant,
832    item_type: &str,
833    module_qualifier: Option<&str>,
834) -> Option<String> {
835    let tag = variant.tag();
836    let camel = variant.upper_camel();
837    match lang {
838        // Python: tagged-union exposes `.type` returning the lower-case wire tag.
839        "python" => Some(format!("any(e.type == \"{tag}\" for e in {chunks_var})")),
840        // Node / TypeScript: deserialized union objects expose a `type`
841        // discriminator field with the lower-case wire tag.
842        "node" | "typescript" => Some(format!("{chunks_var}.some((e: any) => e?.type === \"{tag}\")")),
843        // Ruby: each variant class exposes `<tag>?` predicates.
844        "ruby" => Some(format!("{chunks_var}.any? {{ |e| e.{tag}? }}")),
845        // Go: variants are concrete struct types ({item_type}{Camel}) that
846        // implement the {item_type} interface.  Use a type switch via an
847        // anonymous IIFE so the accessor remains an expression.
848        "go" => Some(format!(
849            "func() bool {{ for _, e := range {chunks_var} {{ if _, _ok := e.(pkg.{item_type}{camel}); _ok {{ return true }} }}; return false }}()"
850        )),
851        // Java: sealed interface {item_type} with nested records.
852        "java" => Some(format!(
853            "{chunks_var}.stream().anyMatch(e -> e instanceof {item_type}.{camel})"
854        )),
855        // C#: abstract record {item_type} with nested sealed records.
856        // The qualifier is the project's C# namespace (e.g. `Kreuzcrawl`).
857        "csharp" => module_qualifier.map(|ns| format!("{chunks_var}.Any(e => e is global::{ns}.{item_type}.{camel})")),
858        // Swift: enum {item_type} with associated values.  `if case .<tag> = e`
859        // is a statement, not an expression — wrap in a `contains(where:)` call
860        // with a switch-returning-bool closure.
861        "swift" => Some(format!(
862            "{chunks_var}.contains(where: {{ e in if case .{tag} = e {{ return true }} else {{ return false }} }})"
863        )),
864        // Elixir: each event is a map with a `:type` atom discriminator.
865        "elixir" => Some(format!(
866            "Enum.any?({chunks_var}, fn e -> Map.get(e, :type) == :{tag} end)"
867        )),
868        // Kotlin (Java records via typealias): same shape as Java.
869        "kotlin" => Some(format!("{chunks_var}.any {{ it is {item_type}.{camel} }}")),
870        // kotlin-android: native sealed class with the same nested variants.
871        "kotlin_android" => Some(format!("{chunks_var}.any {{ it is {item_type}.{camel} }}")),
872        // Dart (freezed): variants are {item_type}_{Camel} (underscored).
873        "dart" => Some(format!("{chunks_var}.any((e) => e is {item_type}_{camel})")),
874        // Zig: collected chunks are JSON strings (see Zig collect_snippet); check
875        // for the wire-format `"type":"<tag>"` substring on any item.  Substring
876        // matching is safe because the JSON is produced by the FFI marshaller
877        // with a fixed key ordering and the tag values do not collide.
878        "zig" => Some(format!(
879            "blk: {{ for ({chunks_var}.items) |_e| {{ if (std.mem.indexOf(u8, _e, \"\\\"type\\\":\\\"{tag}\\\"\") != null) break :blk true; }} break :blk false; }}"
880        )),
881        // Rust: {item_type} is a tagged enum (`#[serde(tag = "type")]`).
882        // Use `matches!` for the predicate so we don't bind the variant payload.
883        // The qualifier is the project's cargo crate name (snake_case).
884        "rust" => module_qualifier.map(|crate_name| {
885            format!("{chunks_var}.iter().any(|e| matches!(e, {crate_name}::{item_type}::{camel} {{ .. }}))")
886        }),
887        // PHP: crawl-stream is delivered as eager JSON (see PHP collect_snippet)
888        // and the PHP binding does not expose typed union objects.
889        // WASM: streaming is unavailable on wasm32 targets.
890        "php" | "wasm" => None,
891        _ => None,
892    }
893}
894
895/// Render a Swift deep accessor for `tool_calls[N]...` paths.
896///
897/// The flat tool_calls array is `[StreamToolCallRef]`.  Each element is a
898/// swift-bridge opaque ref: the first field after an index (e.g. `function`)
899/// is accessed with `.method()` (direct call on the non-optional ref).
900/// All subsequent fields use `?.method()` (optional chaining) because each
901/// intermediate method returns `Optional`.  The string leaf appends
902/// `?.toString()` to convert `RustString?` to `String?`.
903///
904/// Example: `[0].function.name`
905///   → `(root)[0].function()?.name()?.toString()`
906fn render_swift_tool_calls_deep(root_expr: &str, tail: &str) -> String {
907    use heck::ToLowerCamelCase;
908    let segs = parse_tail(tail);
909    let mut expr = root_expr.to_string();
910    // First-class `StreamToolCall` struct: every field is a Codable Swift
911    // property (no parens). Index access on `[StreamToolCall]` returns the
912    // element directly (non-optional). Subsequent `Optional` properties chain
913    // with `?.`. Track whether the prior segment yielded a non-optional value:
914    // - after `Index`, the element is non-optional → next field uses `.`
915    // - after the first optional property access (`?.`), every subsequent
916    //   field also uses `?.` (chained optional)
917    let mut prev_is_optional = false;
918    for seg in &segs {
919        match seg {
920            TailSeg::Index(n) => {
921                expr = format!("({expr})[{n}]");
922                prev_is_optional = false;
923            }
924            TailSeg::Field(f) => {
925                let prop = f.to_lower_camel_case();
926                let sep = if prev_is_optional { "?." } else { "." };
927                expr = format!("{expr}{sep}{prop}");
928                // All `StreamToolCall` fields (function/id/arguments) are
929                // `Optional<...>` in the first-class binding, so chaining
930                // henceforth uses `?.`.
931                prev_is_optional = true;
932            }
933        }
934    }
935    expr
936}
937
938/// Render a rust deep accessor for `tool_calls[N]...` paths over the flattened
939/// stream-chunk tool_calls iterator. Handles Option-wrapped fields by chaining
940/// `as_ref().and_then(...)` so the final value is a `&str` (for name/id/arguments).
941fn render_rust_tool_calls_deep(chunks_var: &str, tail: &str) -> String {
942    let segs = parse_tail(tail);
943    // Locate index segment (rust uses .nth(n) on the iterator instead of [N] on a Vec)
944    let idx = segs.iter().find_map(|s| match s {
945        TailSeg::Index(n) => Some(*n),
946        _ => None,
947    });
948    let field_segs: Vec<&str> = segs
949        .iter()
950        .filter_map(|s| match s {
951            TailSeg::Field(f) => Some(f.as_str()),
952            _ => None,
953        })
954        .collect();
955
956    let base = format!(
957        "{chunks_var}.iter().flat_map(|c| c.choices.iter().flat_map(|ch| ch.delta.tool_calls.iter().flatten()))"
958    );
959    let with_nth = match idx {
960        Some(n) => format!("{base}.nth({n})"),
961        None => base,
962    };
963
964    // Chain Option-aware field access. Every field on StreamToolCall is Option<...>;
965    // the leaf (String fields) uses `.as_deref()` to project to `&str`.
966    let mut expr = with_nth;
967    for (i, f) in field_segs.iter().enumerate() {
968        let is_leaf = i == field_segs.len() - 1;
969        if is_leaf {
970            expr = format!("{expr}.and_then(|x| x.{f}.as_deref())");
971        } else {
972            expr = format!("{expr}.and_then(|x| x.{f}.as_ref())");
973        }
974    }
975    format!("{expr}.unwrap_or(\"\")")
976}
977
978/// Parse a deep-path tail (e.g. `[0].function.name`) into structured segments.
979///
980/// The tail always starts with either `[N]` (array index) or `.field`.
981/// Returns a list of segments: `TailSeg::Index(N)` or `TailSeg::Field(name)`.
982#[derive(Debug, PartialEq)]
983enum TailSeg {
984    Index(usize),
985    Field(String),
986}
987
988fn parse_tail(tail: &str) -> Vec<TailSeg> {
989    let mut segs = Vec::new();
990    let mut rest = tail;
991    while !rest.is_empty() {
992        if let Some(inner) = rest.strip_prefix('[') {
993            // Array index: `[N]`
994            if let Some(close) = inner.find(']') {
995                let idx_str = &inner[..close];
996                if let Ok(idx) = idx_str.parse::<usize>() {
997                    segs.push(TailSeg::Index(idx));
998                }
999                rest = &inner[close + 1..];
1000            } else {
1001                break;
1002            }
1003        } else if let Some(inner) = rest.strip_prefix('.') {
1004            // Field name: up to next `.` or `[`
1005            let end = inner.find(['.', '[']).unwrap_or(inner.len());
1006            segs.push(TailSeg::Field(inner[..end].to_string()));
1007            rest = &inner[end..];
1008        } else {
1009            break;
1010        }
1011    }
1012    segs
1013}
1014
1015/// Render the full deep accessor expression by appending per-language tail
1016/// segments onto `root_expr`.
1017fn render_deep_tail(root_expr: &str, tail: &str, lang: &str) -> String {
1018    use heck::{ToLowerCamelCase, ToPascalCase};
1019
1020    let segs = parse_tail(tail);
1021    let mut out = root_expr.to_string();
1022
1023    for seg in &segs {
1024        match (seg, lang) {
1025            (TailSeg::Index(n), "rust") => {
1026                out = format!("({out})[{n}]");
1027            }
1028            (TailSeg::Index(n), "java") => {
1029                out = format!("({out}).get({n})");
1030            }
1031            (TailSeg::Index(n), "kotlin") => {
1032                if *n == 0 {
1033                    out = format!("({out}).first()");
1034                } else {
1035                    out = format!("({out}).get({n})");
1036                }
1037            }
1038            (TailSeg::Index(n), "kotlin_android") => {
1039                if *n == 0 {
1040                    out = format!("({out}).first()");
1041                } else {
1042                    out = format!("({out})[{n}]");
1043                }
1044            }
1045            (TailSeg::Index(n), "elixir") => {
1046                out = format!("Enum.at({out}, {n})");
1047            }
1048            (TailSeg::Index(n), "zig") => {
1049                out = format!("({out}).items[{n}]");
1050            }
1051            (TailSeg::Index(n), "php") => {
1052                out = format!("({out})[{n}]");
1053            }
1054            (TailSeg::Index(n), _) => {
1055                // rust-like for go (but we handle Field differently), python, node, ts, kotlin, etc.
1056                out = format!("({out})[{n}]");
1057            }
1058            (TailSeg::Field(f), "rust") => {
1059                use heck::ToSnakeCase;
1060                out.push('.');
1061                out.push_str(&f.to_snake_case());
1062            }
1063            (TailSeg::Field(f), "go") => {
1064                use alef_codegen::naming::to_go_name;
1065                out.push('.');
1066                out.push_str(&to_go_name(f));
1067            }
1068            (TailSeg::Field(f), "java") => {
1069                out.push('.');
1070                out.push_str(&f.to_lower_camel_case());
1071                out.push_str("()");
1072            }
1073            (TailSeg::Field(f), "kotlin") => {
1074                // Use safe-call `?.` for all field accessors in Kotlin deep paths.
1075                // All streaming tool-call sub-fields (`function`, `id`, `name`,
1076                // `arguments`) are nullable in the generated Java records, so `?.`
1077                // is always correct here and prevents "non-null asserted call on
1078                // nullable receiver" compile errors.
1079                out.push_str("?.");
1080                out.push_str(&f.to_lower_camel_case());
1081                out.push_str("()");
1082            }
1083            (TailSeg::Field(f), "kotlin_android") => {
1084                // kotlin-android: Kotlin data classes use property access (no parens).
1085                out.push_str("?.");
1086                out.push_str(&f.to_lower_camel_case());
1087            }
1088            (TailSeg::Field(f), "csharp") => {
1089                out.push('.');
1090                out.push_str(&f.to_pascal_case());
1091            }
1092            (TailSeg::Field(f), "php") => {
1093                // Streaming PHP accessors operate on json_decoded stdClass with
1094                // snake_case property names (JSON wire format), not the camelCase
1095                // properties exposed on the PHP wrapper class. Use the raw field
1096                // name verbatim.
1097                out.push_str("->");
1098                out.push_str(f);
1099            }
1100            (TailSeg::Field(f), "elixir") => {
1101                out.push('.');
1102                out.push_str(f);
1103            }
1104            (TailSeg::Field(f), "zig") => {
1105                out.push('.');
1106                out.push_str(f);
1107            }
1108            (TailSeg::Field(f), "python") | (TailSeg::Field(f), "ruby") => {
1109                out.push('.');
1110                out.push_str(f);
1111            }
1112            // node, wasm, typescript, kotlin, dart, swift all use camelCase
1113            (TailSeg::Field(f), _) => {
1114                out.push('.');
1115                out.push_str(&f.to_lower_camel_case());
1116            }
1117        }
1118    }
1119
1120    out
1121}
1122
1123#[cfg(test)]
1124mod tests {
1125    use super::*;
1126
1127    #[test]
1128    fn is_streaming_virtual_field_recognizes_all_fields() {
1129        for field in STREAMING_VIRTUAL_FIELDS {
1130            assert!(
1131                is_streaming_virtual_field(field),
1132                "field '{field}' not recognized as streaming virtual"
1133            );
1134        }
1135    }
1136
1137    #[test]
1138    fn is_streaming_virtual_field_rejects_real_fields() {
1139        assert!(!is_streaming_virtual_field("content"));
1140        assert!(!is_streaming_virtual_field("choices"));
1141        assert!(!is_streaming_virtual_field("model"));
1142        assert!(!is_streaming_virtual_field(""));
1143    }
1144
1145    #[test]
1146    fn is_streaming_virtual_field_rejects_non_root_paths_with_matching_tail() {
1147        // Regression: prior impl matched any field whose chars-after-root-len started
1148        // with `[` or `.` — without checking that the field actually starts with the
1149        // root token. `choices[0].finish_reason` therefore falsely matched root
1150        // `tool_calls` because byte 10 onward is `.finish_reason`.
1151        assert!(!is_streaming_virtual_field("choices[0].finish_reason"));
1152        assert!(!is_streaming_virtual_field("choices[0].message.content"));
1153        assert!(!is_streaming_virtual_field("data[0].embedding"));
1154    }
1155
1156    #[test]
1157    fn is_streaming_virtual_field_does_not_match_usage() {
1158        // `usage` is intentionally NOT a streaming-virtual root: chat/embed
1159        // responses carry `usage.total_tokens` at the response root, so treating
1160        // it as virtual would drag non-streaming tests into the chunks accessor.
1161        assert!(!is_streaming_virtual_field("usage"));
1162        assert!(!is_streaming_virtual_field("usage.total_tokens"));
1163        assert!(!is_streaming_virtual_field("usage.prompt_tokens"));
1164    }
1165
1166    #[test]
1167    fn accessor_chunks_returns_var_name() {
1168        assert_eq!(
1169            StreamingFieldResolver::accessor("chunks", "rust", "chunks"),
1170            Some("chunks".to_string())
1171        );
1172        assert_eq!(
1173            StreamingFieldResolver::accessor("chunks", "node", "chunks"),
1174            Some("chunks".to_string())
1175        );
1176    }
1177
1178    #[test]
1179    fn accessor_chunks_length_uses_language_idiom() {
1180        let rust = StreamingFieldResolver::accessor("chunks.length", "rust", "chunks").unwrap();
1181        assert!(rust.contains(".len()"), "rust: {rust}");
1182
1183        let go = StreamingFieldResolver::accessor("chunks.length", "go", "chunks").unwrap();
1184        assert!(go.starts_with("len("), "go: {go}");
1185
1186        let node = StreamingFieldResolver::accessor("chunks.length", "node", "chunks").unwrap();
1187        assert!(node.contains(".length"), "node: {node}");
1188
1189        let php = StreamingFieldResolver::accessor("chunks.length", "php", "chunks").unwrap();
1190        assert!(php.starts_with("count("), "php: {php}");
1191    }
1192
1193    #[test]
1194    fn accessor_chunks_length_zig_uses_items_len() {
1195        let zig = StreamingFieldResolver::accessor("chunks.length", "zig", "chunks").unwrap();
1196        assert_eq!(zig, "chunks.items.len", "zig chunks.length: {zig}");
1197    }
1198
1199    #[test]
1200    fn accessor_stream_content_zig_uses_content_items() {
1201        let zig = StreamingFieldResolver::accessor("stream_content", "zig", "chunks").unwrap();
1202        assert_eq!(zig, "chunks_content.items", "zig stream_content: {zig}");
1203    }
1204
1205    #[test]
1206    fn collect_snippet_zig_drains_via_ffi() {
1207        let snip = StreamingFieldResolver::collect_snippet("zig", "_stream_handle", "chunks").unwrap();
1208        assert!(snip.contains("std.ArrayList([]u8)"), "zig collect: {snip}");
1209        assert!(snip.contains("chat_stream_next(_stream_handle)"), "zig collect: {snip}");
1210        assert!(snip.contains("chunks_content"), "zig collect: {snip}");
1211        assert!(
1212            snip.contains("chunks.append(std.heap.c_allocator"),
1213            "zig collect: {snip}"
1214        );
1215        assert!(snip.contains(".empty;"), "zig collect (Zig 0.16 unmanaged): {snip}");
1216    }
1217
1218    #[test]
1219    fn accessor_stream_content_rust_uses_iterator() {
1220        let expr = StreamingFieldResolver::accessor("stream_content", "rust", "chunks").unwrap();
1221        assert!(expr.contains(".collect::<String>()"), "rust stream_content: {expr}");
1222    }
1223
1224    #[test]
1225    fn accessor_no_chunks_after_done_returns_true() {
1226        for lang in ["rust", "go", "java", "php", "node", "wasm", "elixir"] {
1227            let expr = StreamingFieldResolver::accessor("no_chunks_after_done", lang, "chunks").unwrap();
1228            assert_eq!(expr, "true", "lang {lang}: expected 'true', got '{expr}'");
1229        }
1230    }
1231
1232    #[test]
1233    fn accessor_elixir_chunks_length_uses_length_function() {
1234        let expr = StreamingFieldResolver::accessor("chunks.length", "elixir", "chunks").unwrap();
1235        assert_eq!(expr, "length(chunks)", "elixir chunks.length: {expr}");
1236    }
1237
1238    #[test]
1239    fn accessor_elixir_stream_content_uses_pipe() {
1240        let expr = StreamingFieldResolver::accessor("stream_content", "elixir", "chunks").unwrap();
1241        assert!(expr.contains("|> Enum.join"), "elixir stream_content: {expr}");
1242        assert!(expr.contains("|> Enum.map"), "elixir stream_content: {expr}");
1243        // Elixir lists do not support bracket access — must use Enum.at, never choices[0]
1244        assert!(
1245            !expr.contains("choices[0]"),
1246            "elixir stream_content must not use bracket access on list: {expr}"
1247        );
1248        assert!(
1249            expr.contains("Enum.at("),
1250            "elixir stream_content must use Enum.at for list index: {expr}"
1251        );
1252    }
1253
1254    #[test]
1255    fn accessor_elixir_stream_complete_uses_list_last() {
1256        let expr = StreamingFieldResolver::accessor("stream_complete", "elixir", "chunks").unwrap();
1257        assert!(expr.contains("List.last(chunks)"), "elixir stream_complete: {expr}");
1258        assert!(expr.contains("finish_reason != nil"), "elixir stream_complete: {expr}");
1259        // Elixir lists do not support bracket access — must use Enum.at, never choices[0]
1260        assert!(
1261            !expr.contains("choices[0]"),
1262            "elixir stream_complete must not use bracket access on list: {expr}"
1263        );
1264        assert!(
1265            expr.contains("Enum.at("),
1266            "elixir stream_complete must use Enum.at for list index: {expr}"
1267        );
1268    }
1269
1270    #[test]
1271    fn accessor_elixir_finish_reason_uses_list_last() {
1272        let expr = StreamingFieldResolver::accessor("finish_reason", "elixir", "chunks").unwrap();
1273        assert!(expr.contains("List.last(chunks)"), "elixir finish_reason: {expr}");
1274        assert!(expr.contains("finish_reason"), "elixir finish_reason: {expr}");
1275        // Elixir lists do not support bracket access — must use Enum.at, never choices[0]
1276        assert!(
1277            !expr.contains("choices[0]"),
1278            "elixir finish_reason must not use bracket access on list: {expr}"
1279        );
1280        assert!(
1281            expr.contains("Enum.at("),
1282            "elixir finish_reason must use Enum.at for list index: {expr}"
1283        );
1284    }
1285
1286    #[test]
1287    fn collect_snippet_elixir_uses_enum_to_list() {
1288        let snip = StreamingFieldResolver::collect_snippet("elixir", "result", "chunks").unwrap();
1289        assert!(snip.contains("Enum.to_list(result)"), "elixir: {snip}");
1290        assert!(snip.contains("chunks ="), "elixir: {snip}");
1291    }
1292
1293    #[test]
1294    fn collect_snippet_rust_uses_tokio_stream() {
1295        let snip = StreamingFieldResolver::collect_snippet("rust", "result", "chunks").unwrap();
1296        assert!(snip.contains("tokio_stream::StreamExt::collect"), "rust: {snip}");
1297        assert!(snip.contains("let chunks"), "rust: {snip}");
1298        // Items are Result<ChatCompletionChunk, _> — unwrap so chunks is Vec<ChatCompletionChunk>
1299        assert!(snip.contains(".expect("), "rust must unwrap Result items: {snip}");
1300    }
1301
1302    #[test]
1303    fn collect_snippet_go_drains_channel() {
1304        let snip = StreamingFieldResolver::collect_snippet("go", "stream", "chunks").unwrap();
1305        assert!(snip.contains("for chunk := range stream"), "go: {snip}");
1306    }
1307
1308    #[test]
1309    fn collect_snippet_java_uses_iterator() {
1310        let snip = StreamingFieldResolver::collect_snippet("java", "result", "chunks").unwrap();
1311        // Must call .iterator() on the Stream<T> before using hasNext()/next() —
1312        // Stream does not implement those methods directly.
1313        assert!(
1314            snip.contains(".iterator()"),
1315            "java snippet must call .iterator() on stream: {snip}"
1316        );
1317        assert!(snip.contains("hasNext()"), "java: {snip}");
1318        assert!(snip.contains(".next()"), "java: {snip}");
1319    }
1320
1321    #[test]
1322    fn collect_snippet_php_decodes_json_or_iterates() {
1323        let snip = StreamingFieldResolver::collect_snippet("php", "result", "chunks").unwrap();
1324        // PHP binding's chat_stream_async returns a JSON string today; collect-snippet
1325        // decodes it.  iterator_to_array is retained as the fallback branch so a
1326        // future binding that exposes a real iterator continues to work without
1327        // regenerating the e2e tests.
1328        assert!(snip.contains("json_decode"), "php must decode JSON: {snip}");
1329        assert!(
1330            snip.contains("iterator_to_array"),
1331            "php must keep iterator_to_array fallback: {snip}"
1332        );
1333        assert!(snip.contains("$chunks ="), "php must bind $chunks: {snip}");
1334    }
1335
1336    #[test]
1337    fn collect_snippet_node_uses_for_await() {
1338        let snip = StreamingFieldResolver::collect_snippet("node", "result", "chunks").unwrap();
1339        assert!(snip.contains("for await"), "node: {snip}");
1340    }
1341
1342    #[test]
1343    fn collect_snippet_python_uses_async_for() {
1344        let snip = StreamingFieldResolver::collect_snippet("python", "result", "chunks").unwrap();
1345        assert!(snip.contains("async for chunk in result"), "python: {snip}");
1346        assert!(snip.contains("chunks.append(chunk)"), "python: {snip}");
1347    }
1348
1349    #[test]
1350    fn accessor_stream_content_python_uses_join() {
1351        let expr = StreamingFieldResolver::accessor("stream_content", "python", "chunks").unwrap();
1352        assert!(expr.contains("\"\".join("), "python stream_content: {expr}");
1353        assert!(expr.contains("c.choices"), "python stream_content: {expr}");
1354    }
1355
1356    #[test]
1357    fn accessor_stream_complete_python_uses_finish_reason() {
1358        let expr = StreamingFieldResolver::accessor("stream_complete", "python", "chunks").unwrap();
1359        assert!(
1360            expr.contains("finish_reason is not None"),
1361            "python stream_complete: {expr}"
1362        );
1363    }
1364
1365    #[test]
1366    fn accessor_finish_reason_python_uses_last_chunk() {
1367        let expr = StreamingFieldResolver::accessor("finish_reason", "python", "chunks").unwrap();
1368        assert!(expr.contains("chunks[-1]"), "python finish_reason: {expr}");
1369        // Must wrap in str() so FinishReason enum objects support .strip() comparisons
1370        assert!(
1371            expr.starts_with("(str(") || expr.contains("str(chunks"),
1372            "python finish_reason must wrap in str(): {expr}"
1373        );
1374    }
1375
1376    #[test]
1377    fn accessor_tool_calls_python_uses_list_comprehension() {
1378        let expr = StreamingFieldResolver::accessor("tool_calls", "python", "chunks").unwrap();
1379        assert!(expr.contains("for c in chunks"), "python tool_calls: {expr}");
1380        assert!(expr.contains("tool_calls"), "python tool_calls: {expr}");
1381    }
1382
1383    #[test]
1384    fn accessor_usage_python_uses_last_chunk() {
1385        let expr = StreamingFieldResolver::accessor("usage", "python", "chunks").unwrap();
1386        assert!(
1387            expr.contains("chunks[-1].usage"),
1388            "python usage: expected chunks[-1].usage, got: {expr}"
1389        );
1390    }
1391
1392    #[test]
1393    fn accessor_usage_total_tokens_does_not_route_via_chunks() {
1394        // `usage` is intentionally NOT a streaming-virtual root (it overlaps the
1395        // non-streaming response shape). The accessor must return None so the
1396        // assertion falls through to the normal field-path codegen.
1397        assert!(StreamingFieldResolver::accessor("usage.total_tokens", "python", "chunks").is_none());
1398    }
1399
1400    #[test]
1401    fn accessor_unknown_field_returns_none() {
1402        assert_eq!(
1403            StreamingFieldResolver::accessor("nonexistent_field", "rust", "chunks"),
1404            None
1405        );
1406    }
1407
1408    // -----------------------------------------------------------------------
1409    // Deep-path tests: tool_calls[0].function.name and tool_calls[0].id
1410    // -----------------------------------------------------------------------
1411
1412    #[test]
1413    fn is_streaming_virtual_field_recognizes_deep_tool_calls_paths() {
1414        assert!(
1415            is_streaming_virtual_field("tool_calls[0].function.name"),
1416            "tool_calls[0].function.name should be recognized"
1417        );
1418        assert!(
1419            is_streaming_virtual_field("tool_calls[0].id"),
1420            "tool_calls[0].id should be recognized"
1421        );
1422        assert!(
1423            is_streaming_virtual_field("tool_calls[1].function.arguments"),
1424            "tool_calls[1].function.arguments should be recognized"
1425        );
1426        // bare root still recognized
1427        assert!(is_streaming_virtual_field("tool_calls"));
1428        // unrelated deep path must NOT be recognized
1429        assert!(!is_streaming_virtual_field("tool_calls_extra.name"));
1430        assert!(!is_streaming_virtual_field("nonexistent[0].field"));
1431    }
1432
1433    /// Snapshot: `tool_calls[0].function.name` for Rust, Kotlin, TypeScript.
1434    ///
1435    /// These three languages cover the main accessor styles:
1436    /// - Rust: snake_case field, explicit `[0]` index on collected Vec
1437    /// - Kotlin: camelCase method calls with `.first()` for index 0
1438    /// - TypeScript/Node: camelCase properties with `[0]` bracket
1439    #[test]
1440    fn deep_tool_calls_function_name_snapshot_rust_kotlin_ts() {
1441        let field = "tool_calls[0].function.name";
1442
1443        let rust = StreamingFieldResolver::accessor(field, "rust", "chunks").unwrap();
1444        // Rust: Option-aware chain over the iterator — `.nth(0)` then `.and_then`
1445        // on each Option-wrapped field (function is Option<StreamFunctionCall>,
1446        // name is Option<String>). Final `.unwrap_or("")` yields `&str`.
1447        assert!(
1448            rust.contains(".nth(0)"),
1449            "rust deep tool_calls: expected .nth(0) iterator index, got: {rust}"
1450        );
1451        assert!(
1452            rust.contains("x.function.as_ref()"),
1453            "rust deep tool_calls: expected Option-aware function access, got: {rust}"
1454        );
1455        assert!(
1456            rust.contains("x.name.as_deref()"),
1457            "rust deep tool_calls: expected Option-aware name leaf, got: {rust}"
1458        );
1459        assert!(
1460            !rust.contains("// skipped"),
1461            "rust deep tool_calls: must not emit skip comment, got: {rust}"
1462        );
1463
1464        let kotlin = StreamingFieldResolver::accessor(field, "kotlin", "chunks").unwrap();
1465        // Kotlin: uses .first() for index 0, then .function().name()
1466        assert!(
1467            kotlin.contains(".first()"),
1468            "kotlin deep tool_calls: expected .first() for index 0, got: {kotlin}"
1469        );
1470        assert!(
1471            kotlin.contains(".function()"),
1472            "kotlin deep tool_calls: expected .function() method call, got: {kotlin}"
1473        );
1474        assert!(
1475            kotlin.contains(".name()"),
1476            "kotlin deep tool_calls: expected .name() method call, got: {kotlin}"
1477        );
1478
1479        let ts = StreamingFieldResolver::accessor(field, "node", "chunks").unwrap();
1480        // TypeScript/Node: uses [0] then .function.name (camelCase)
1481        assert!(
1482            ts.contains("[0]"),
1483            "ts/node deep tool_calls: expected [0] index, got: {ts}"
1484        );
1485        assert!(
1486            ts.contains(".function"),
1487            "ts/node deep tool_calls: expected .function segment, got: {ts}"
1488        );
1489        assert!(
1490            ts.contains(".name"),
1491            "ts/node deep tool_calls: expected .name segment, got: {ts}"
1492        );
1493    }
1494
1495    #[test]
1496    fn deep_tool_calls_id_snapshot_all_langs() {
1497        let field = "tool_calls[0].id";
1498
1499        let rust = StreamingFieldResolver::accessor(field, "rust", "chunks").unwrap();
1500        assert!(rust.contains(".nth(0)"), "rust: {rust}");
1501        assert!(rust.contains("x.id.as_deref()"), "rust: {rust}");
1502
1503        let go = StreamingFieldResolver::accessor(field, "go", "chunks").unwrap();
1504        assert!(go.contains("[0]"), "go: {go}");
1505        // Go: ID is a well-known initialism → uppercase
1506        assert!(go.contains(".ID"), "go: expected .ID initialism, got: {go}");
1507
1508        let python = StreamingFieldResolver::accessor(field, "python", "chunks").unwrap();
1509        assert!(python.contains("[0]"), "python: {python}");
1510        assert!(python.contains(".id"), "python: {python}");
1511
1512        let php = StreamingFieldResolver::accessor(field, "php", "chunks").unwrap();
1513        assert!(php.contains("[0]"), "php: {php}");
1514        assert!(php.contains("->id"), "php: expected ->id, got: {php}");
1515
1516        let java = StreamingFieldResolver::accessor(field, "java", "chunks").unwrap();
1517        assert!(java.contains(".get(0)"), "java: expected .get(0), got: {java}");
1518        assert!(java.contains(".id()"), "java: expected .id() method call, got: {java}");
1519
1520        let csharp = StreamingFieldResolver::accessor(field, "csharp", "chunks").unwrap();
1521        assert!(csharp.contains("[0]"), "csharp: {csharp}");
1522        assert!(
1523            csharp.contains(".Id"),
1524            "csharp: expected .Id (PascalCase), got: {csharp}"
1525        );
1526
1527        let elixir = StreamingFieldResolver::accessor(field, "elixir", "chunks").unwrap();
1528        assert!(elixir.contains("Enum.at("), "elixir: expected Enum.at(, got: {elixir}");
1529        assert!(elixir.contains(".id"), "elixir: {elixir}");
1530    }
1531
1532    #[test]
1533    fn deep_tool_calls_function_name_snapshot_python_elixir_zig() {
1534        let field = "tool_calls[0].function.name";
1535
1536        let python = StreamingFieldResolver::accessor(field, "python", "chunks").unwrap();
1537        assert!(python.contains("[0]"), "python: {python}");
1538        assert!(python.contains(".function"), "python: {python}");
1539        assert!(python.contains(".name"), "python: {python}");
1540
1541        let elixir = StreamingFieldResolver::accessor(field, "elixir", "chunks").unwrap();
1542        // Elixir: Enum.at(…, 0).function.name
1543        assert!(elixir.contains("Enum.at("), "elixir: {elixir}");
1544        assert!(elixir.contains(".function"), "elixir: {elixir}");
1545        assert!(elixir.contains(".name"), "elixir: {elixir}");
1546
1547        // Zig stores chunks as JSON strings, not typed records — deep
1548        // tool_calls paths are unsupported and resolve to None so the
1549        // assertion site can skip them.
1550        assert!(
1551            StreamingFieldResolver::accessor(field, "zig", "chunks").is_none(),
1552            "zig: expected None for deep tool_calls path"
1553        );
1554    }
1555
1556    #[test]
1557    fn parse_tail_parses_index_then_field_segments() {
1558        let segs = parse_tail("[0].function.name");
1559        assert_eq!(segs.len(), 3, "expected 3 segments, got: {segs:?}");
1560        assert_eq!(segs[0], TailSeg::Index(0));
1561        assert_eq!(segs[1], TailSeg::Field("function".to_string()));
1562        assert_eq!(segs[2], TailSeg::Field("name".to_string()));
1563    }
1564
1565    #[test]
1566    fn parse_tail_parses_simple_index_field() {
1567        let segs = parse_tail("[0].id");
1568        assert_eq!(segs.len(), 2, "expected 2 segments, got: {segs:?}");
1569        assert_eq!(segs[0], TailSeg::Index(0));
1570        assert_eq!(segs[1], TailSeg::Field("id".to_string()));
1571    }
1572
1573    #[test]
1574    fn parse_tail_handles_nonzero_index() {
1575        let segs = parse_tail("[2].function.arguments");
1576        assert_eq!(segs[0], TailSeg::Index(2));
1577        assert_eq!(segs[1], TailSeg::Field("function".to_string()));
1578        assert_eq!(segs[2], TailSeg::Field("arguments".to_string()));
1579    }
1580
1581    // -----------------------------------------------------------------------
1582    // Swift-specific accessor tests
1583    // -----------------------------------------------------------------------
1584
1585    #[test]
1586    fn accessor_chunks_length_swift_uses_count() {
1587        let swift = StreamingFieldResolver::accessor("chunks.length", "swift", "chunks").unwrap();
1588        assert_eq!(swift, "chunks.count", "swift chunks.length: {swift}");
1589    }
1590
1591    #[test]
1592    fn accessor_stream_content_swift_uses_swift_closures() {
1593        let expr = StreamingFieldResolver::accessor("stream_content", "swift", "chunks").unwrap();
1594        // Must use Swift closure syntax (`{ ... }`) not JS arrow (`=>`)
1595        assert!(
1596            expr.contains("{ c in"),
1597            "swift stream_content must use Swift closure syntax, got: {expr}"
1598        );
1599        assert!(
1600            !expr.contains("=>"),
1601            "swift stream_content must not contain JS arrow `=>`, got: {expr}"
1602        );
1603        // Fields are accessed as first-class Codable struct properties (no parens).
1604        assert!(
1605            expr.contains("c.choices"),
1606            "swift stream_content must use property access for choices, got: {expr}"
1607        );
1608        assert!(
1609            expr.contains("ch.delta"),
1610            "swift stream_content must use property access for delta, got: {expr}"
1611        );
1612        assert!(
1613            expr.contains("ch.delta.content"),
1614            "swift stream_content must use property access for content, got: {expr}"
1615        );
1616        // First-class Codable struct fields are native Swift strings — no .toString() wrap.
1617        assert!(
1618            !expr.contains(".toString()"),
1619            "swift stream_content must NOT wrap first-class String fields with .toString(), got: {expr}"
1620        );
1621        assert!(
1622            expr.contains(".joined()"),
1623            "swift stream_content must join with .joined(), got: {expr}"
1624        );
1625        // Must not use JS .length or .join('')
1626        assert!(
1627            !expr.contains(".length"),
1628            "swift stream_content must not use JS .length, got: {expr}"
1629        );
1630        assert!(
1631            !expr.contains(".join("),
1632            "swift stream_content must not use JS .join(, got: {expr}"
1633        );
1634    }
1635
1636    #[test]
1637    fn accessor_stream_complete_swift_uses_swift_syntax() {
1638        let expr = StreamingFieldResolver::accessor("stream_complete", "swift", "chunks").unwrap();
1639        // Must use Swift isEmpty / last! syntax, not JS .length
1640        assert!(
1641            expr.contains("isEmpty"),
1642            "swift stream_complete must use .isEmpty, got: {expr}"
1643        );
1644        assert!(
1645            expr.contains(".last!"),
1646            "swift stream_complete must use .last!, got: {expr}"
1647        );
1648        // Property access for first-class fields (no parens, camelCase).
1649        assert!(
1650            expr.contains(".choices.first"),
1651            "swift stream_complete must use property access on choices, got: {expr}"
1652        );
1653        assert!(
1654            expr.contains("finishReason"),
1655            "swift stream_complete must reference lowerCamelCase finishReason, got: {expr}"
1656        );
1657        assert!(
1658            !expr.contains(".length"),
1659            "swift stream_complete must not use JS .length, got: {expr}"
1660        );
1661        assert!(
1662            !expr.contains("!= null"),
1663            "swift stream_complete must not use JS `!= null`, got: {expr}"
1664        );
1665    }
1666
1667    #[test]
1668    fn accessor_tool_calls_swift_uses_swift_flatmap() {
1669        let expr = StreamingFieldResolver::accessor("tool_calls", "swift", "chunks").unwrap();
1670        // Must use Swift closure syntax, not JS arrow
1671        assert!(
1672            !expr.contains("=>"),
1673            "swift tool_calls must not contain JS arrow `=>`, got: {expr}"
1674        );
1675        assert!(
1676            expr.contains("flatMap"),
1677            "swift tool_calls must use flatMap, got: {expr}"
1678        );
1679        // First-class struct property access (no parens, lowerCamelCase).
1680        assert!(
1681            expr.contains("c.choices.first"),
1682            "swift tool_calls must use property access on choices, got: {expr}"
1683        );
1684        assert!(
1685            expr.contains("ch.delta.toolCalls"),
1686            "swift tool_calls must use lowerCamelCase toolCalls property, got: {expr}"
1687        );
1688    }
1689
1690    #[test]
1691    fn accessor_tool_calls_deep_path_swift_uses_method_calls_with_optional_chain() {
1692        // `tool_calls[0].function.name`: StreamToolCall is a first-class Codable
1693        // struct, so deep fields use lowerCamelCase property access. The first
1694        // field segment after `[N]` is non-optional (array index yields a value),
1695        // so `.function` uses plain `.`; subsequent segments chain with `?.`
1696        // because `function` itself is `Optional<StreamFunctionCall>`.
1697        let expr = StreamingFieldResolver::accessor("tool_calls[0].function.name", "swift", "chunks").unwrap();
1698        assert!(
1699            expr.contains("[0].function"),
1700            "swift deep tool_calls must use plain `.function` directly after array index (non-optional), got: {expr}"
1701        );
1702        assert!(
1703            expr.contains("?.name"),
1704            "swift deep tool_calls must use ?.name property access, got: {expr}"
1705        );
1706        assert!(
1707            !expr.contains(".toString()"),
1708            "swift deep tool_calls must NOT wrap first-class String fields with .toString(), got: {expr}"
1709        );
1710        assert!(
1711            !expr.contains("=>"),
1712            "swift deep tool_calls must not use JS arrow syntax, got: {expr}"
1713        );
1714    }
1715
1716    #[test]
1717    fn accessor_finish_reason_swift_uses_swift_syntax() {
1718        let expr = StreamingFieldResolver::accessor("finish_reason", "swift", "chunks").unwrap();
1719        // Must use Swift isEmpty / last! syntax, not JS .length / undefined
1720        assert!(
1721            expr.contains("isEmpty"),
1722            "swift finish_reason must use .isEmpty, got: {expr}"
1723        );
1724        assert!(
1725            expr.contains(".last!"),
1726            "swift finish_reason must use .last!, got: {expr}"
1727        );
1728        assert!(
1729            expr.contains("finishReason"),
1730            "swift finish_reason must use lowerCamelCase finishReason property, got: {expr}"
1731        );
1732        // First-class Swift enum: use .rawValue for the serde wire string, not .toString().
1733        assert!(
1734            expr.contains(".rawValue"),
1735            "swift finish_reason must read enum .rawValue, got: {expr}"
1736        );
1737        assert!(
1738            !expr.contains("undefined"),
1739            "swift finish_reason must not use JS `undefined`, got: {expr}"
1740        );
1741        assert!(
1742            !expr.contains(".length"),
1743            "swift finish_reason must not use JS .length, got: {expr}"
1744        );
1745    }
1746
1747    #[test]
1748    fn accessor_usage_swift_uses_swift_syntax() {
1749        let expr = StreamingFieldResolver::accessor("usage", "swift", "chunks").unwrap();
1750        // Must use Swift isEmpty / last! syntax, not JS .length / undefined
1751        assert!(expr.contains("isEmpty"), "swift usage must use .isEmpty, got: {expr}");
1752        assert!(expr.contains(".last!"), "swift usage must use .last!, got: {expr}");
1753        // First-class Codable property access (no parens).
1754        assert!(
1755            expr.contains(".usage"),
1756            "swift usage must reference .usage property, got: {expr}"
1757        );
1758        assert!(
1759            !expr.contains("usage()"),
1760            "swift usage must NOT use method-call syntax, got: {expr}"
1761        );
1762        assert!(
1763            !expr.contains("undefined"),
1764            "swift usage must not use JS `undefined`, got: {expr}"
1765        );
1766        assert!(
1767            !expr.contains(".length"),
1768            "swift usage must not use JS .length, got: {expr}"
1769        );
1770    }
1771
1772    // ---------------------------------------------------------------------------
1773    // Bug regression: kotlin_android streaming assertions use property access
1774    // ---------------------------------------------------------------------------
1775
1776    #[test]
1777    fn kotlin_android_collect_snippet_uses_flow_to_list() {
1778        let snip = StreamingFieldResolver::collect_snippet("kotlin_android", "result", "chunks").unwrap();
1779        // Flow.toList() — not Iterator.asSequence().toList()
1780        assert!(
1781            snip.contains("result.toList()"),
1782            "kotlin_android collect must use Flow.toList(), got: {snip}"
1783        );
1784        assert!(
1785            !snip.contains("asSequence()"),
1786            "kotlin_android collect must NOT use asSequence(), got: {snip}"
1787        );
1788    }
1789
1790    #[test]
1791    fn kotlin_android_stream_content_uses_property_access() {
1792        let expr = StreamingFieldResolver::accessor("stream_content", "kotlin_android", "chunks").unwrap();
1793        assert!(
1794            expr.contains(".choices"),
1795            "kotlin_android stream_content must use .choices property, got: {expr}"
1796        );
1797        assert!(
1798            !expr.contains(".choices()"),
1799            "kotlin_android stream_content must NOT use .choices() getter, got: {expr}"
1800        );
1801        assert!(
1802            expr.contains(".delta"),
1803            "kotlin_android stream_content must use .delta property, got: {expr}"
1804        );
1805        assert!(
1806            !expr.contains(".delta()"),
1807            "kotlin_android stream_content must NOT use .delta() getter, got: {expr}"
1808        );
1809        assert!(
1810            expr.contains(".content"),
1811            "kotlin_android stream_content must use .content property, got: {expr}"
1812        );
1813        assert!(
1814            !expr.contains(".content()"),
1815            "kotlin_android stream_content must NOT use .content() getter, got: {expr}"
1816        );
1817    }
1818
1819    #[test]
1820    fn kotlin_android_finish_reason_uses_name_lowercase_not_get_value() {
1821        let expr = StreamingFieldResolver::accessor("finish_reason", "kotlin_android", "chunks").unwrap();
1822        assert!(
1823            expr.contains(".finishReason"),
1824            "kotlin_android finish_reason must use .finishReason property, got: {expr}"
1825        );
1826        assert!(
1827            !expr.contains(".finishReason()"),
1828            "kotlin_android finish_reason must NOT use .finishReason() getter, got: {expr}"
1829        );
1830        assert!(
1831            expr.contains(".name"),
1832            "kotlin_android finish_reason must use .name for enum wire value, got: {expr}"
1833        );
1834        assert!(
1835            expr.contains(".lowercase()"),
1836            "kotlin_android finish_reason must use .lowercase(), got: {expr}"
1837        );
1838        assert!(
1839            !expr.contains(".getValue()"),
1840            "kotlin_android finish_reason must NOT use .getValue(), got: {expr}"
1841        );
1842    }
1843
1844    #[test]
1845    fn kotlin_android_usage_uses_property_access() {
1846        let expr = StreamingFieldResolver::accessor("usage", "kotlin_android", "chunks").unwrap();
1847        assert!(
1848            expr.contains(".usage"),
1849            "kotlin_android usage must use .usage property, got: {expr}"
1850        );
1851        assert!(
1852            !expr.contains(".usage()"),
1853            "kotlin_android usage must NOT use .usage() getter, got: {expr}"
1854        );
1855    }
1856
1857    #[test]
1858    fn kotlin_android_deep_tool_calls_uses_property_access() {
1859        let expr = StreamingFieldResolver::accessor("tool_calls[0].function.name", "kotlin_android", "chunks").unwrap();
1860        assert!(
1861            expr.contains(".function"),
1862            "kotlin_android deep tool_calls must use .function property, got: {expr}"
1863        );
1864        assert!(
1865            !expr.contains(".function()"),
1866            "kotlin_android deep tool_calls must NOT use .function() getter, got: {expr}"
1867        );
1868        assert!(
1869            expr.contains(".name"),
1870            "kotlin_android deep tool_calls must use .name property, got: {expr}"
1871        );
1872        assert!(
1873            !expr.contains(".name()"),
1874            "kotlin_android deep tool_calls must NOT use .name() getter, got: {expr}"
1875        );
1876    }
1877}