alef 0.62.9

Opinionated polyglot binding generator for Rust libraries
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
use super::super::ir_enum::is_enum_path;
use super::super::parse::{
    normalize_indices_to_wildcards, normalize_numeric_indices, parse_path, strip_numeric_indices,
};
use super::super::types::{FieldResolver, PathSegment, StringyField};
use std::collections::HashSet;

impl FieldResolver {
    /// Returns `true` when `fixture_field` (or its resolved alias, or a
    /// normalised form) is configured as a display-as-text field.
    ///
    /// Accepts both the raw fixture field path and the alias-resolved path so
    /// callers don't need to resolve first.
    pub fn is_display_as_text(&self, fixture_field: &str) -> bool {
        if self.display_as_text_fields.is_empty() {
            return false;
        }
        if self.display_as_text_fields.contains(fixture_field) {
            return true;
        }
        let resolved = self.resolve(fixture_field);
        self.display_as_text_fields.contains(resolved)
    }

    /// Resolve a fixture field path to the actual struct path.
    /// Falls back to the field itself if no alias exists.
    pub fn resolve<'a>(&'a self, fixture_field: &'a str) -> &'a str {
        self.aliases
            .get(fixture_field)
            .map(String::as_str)
            .unwrap_or(fixture_field)
    }

    /// True when the leaf segment of `field` is a `Vec<T>` field on any IR type.
    ///
    /// Used by swift codegen to keep `.count` straight on method-call accessors
    /// (`result.output()` returns RustVec — `.count` works directly, no
    /// `.toString()` needed). The check is on the bare leaf name, so it is best-
    /// effort when distinct types share a field name with different kinds.
    pub fn leaf_is_vec_via_swift_map(&self, field: &str) -> bool {
        let leaf = field.split('.').next_back().unwrap_or(field);
        let leaf = leaf.split('[').next().unwrap_or(leaf);
        self.swift_first_class_map.is_vec_field_name(leaf)
    }

    /// IR type backing the Swift result variable, if known. Used by
    /// `swift_build_accessor` to seed its per-segment type cursor.
    pub fn swift_root_type(&self) -> Option<&String> {
        self.swift_first_class_map.root_type.as_ref()
    }

    /// Whether fields on `type_name` should be accessed as Swift properties
    /// (first-class Codable struct → `public let`) vs swift-bridge method calls
    /// (typealias-to-opaque RustBridge class). Mirrors `SwiftFirstClassMap::is_first_class`.
    pub fn swift_is_first_class(&self, type_name: Option<&str>) -> bool {
        self.swift_first_class_map.is_first_class(type_name)
    }

    /// Advance the per-segment type cursor by one field name. Mirrors
    /// `SwiftFirstClassMap::advance`.
    pub fn swift_advance(&self, owner_type: Option<&str>, field_name: &str) -> Option<String> {
        self.swift_first_class_map.advance(owner_type, field_name)
    }

    /// Stringy field accessors recorded for `type_name` in the Swift
    /// first-class map (used by `contains` assertions on `Vec<T>` element
    /// types).
    pub fn swift_stringy_fields(&self, type_name: &str) -> Option<&[StringyField]> {
        self.swift_first_class_map.stringy_fields(type_name)
    }

    /// IR type backing the Dart result variable, if known.
    pub fn dart_root_type(&self) -> Option<&String> {
        self.dart_first_class_map.root_type.as_ref()
    }

    /// Advance the Dart type cursor through a field, returning the target type name.
    pub fn dart_advance(&self, owner_type: Option<&str>, field_name: &str) -> Option<String> {
        self.dart_first_class_map.advance(owner_type, field_name)
    }

    /// Stringy field accessors recorded for `type_name` in the Dart
    /// first-class map (used by `contains` assertions on `Vec<T>` element
    /// types).
    pub fn dart_stringy_fields(&self, type_name: &str) -> Option<&[StringyField]> {
        self.dart_first_class_map.stringy_fields(type_name)
    }

    /// Check if a resolved field path is optional.
    pub fn is_optional(&self, field: &str) -> bool {
        if self.is_optional_direct(field) {
            return true;
        }
        // Namespace-prefix fallback: paths like `interaction.action_results[0].data`
        // strip the virtual `interaction.` prefix before consulting `optional_fields`,
        // matching the same convention used by `is_valid_for_result`.
        if let Some(suffix) = self.namespace_stripped_path(field)
            && self.is_optional_direct(suffix)
        {
            return true;
        }
        false
    }

    fn is_optional_direct(&self, field: &str) -> bool {
        if self.optional_fields.contains(field) {
            return true;
        }
        let index_normalized = normalize_numeric_indices(field);
        if index_normalized != field && self.optional_fields.contains(index_normalized.as_str()) {
            return true;
        }
        // Also check with all numeric indices stripped: "choices[0].message.tool_calls"
        // should match optional_fields entry "choices.message.tool_calls".
        let de_indexed = strip_numeric_indices(field);
        if de_indexed != field && self.optional_fields.contains(de_indexed.as_str()) {
            return true;
        }
        let normalized = field.replace("[].", ".");
        if normalized != field && self.optional_fields.contains(normalized.as_str()) {
            return true;
        }
        for af in &self.array_fields {
            if let Some(rest) = field.strip_prefix(af.as_str())
                && let Some(rest) = rest.strip_prefix('.')
            {
                let with_bracket = format!("{af}[].{rest}");
                if self.optional_fields.contains(with_bracket.as_str()) {
                    return true;
                }
            }
        }
        false
    }

    /// Check whether a single bare JSON key (not a dotted path) may be entirely absent from
    /// the wire format, per [`Self::with_wire_optional_fields`].
    ///
    /// Callers that walk a parsed JSON tree segment-by-segment (currently the Zig e2e
    /// generator) should consult this once per `.get(key)` step, not once for the whole
    /// resolved path: `wire_optional_fields` is IR-derived from bare field names, with no
    /// notion of nesting depth, so matching happens per key the same way the field was
    /// recorded — unlike [`Self::is_optional`], which matches config-declared, fully
    /// dotted paths.
    pub fn is_wire_optional_key(&self, key: &str) -> bool {
        self.wire_optional_fields.contains(key)
    }

    /// Check if a fixture field has an explicit alias mapping.
    pub fn has_alias(&self, fixture_field: &str) -> bool {
        self.aliases.contains_key(fixture_field)
    }

    /// Check whether `field_name` is configured as an explicit result field.
    ///
    /// Returns true only when the caller has populated `result_fields` AND the
    /// field name is present. Empty `result_fields` always returns false — use
    /// `is_valid_for_result` for the default-allow semantics.
    pub fn has_explicit_field(&self, field_name: &str) -> bool {
        if self.result_fields.is_empty() {
            return false;
        }
        self.result_fields.contains(field_name)
    }

    /// Check whether a fixture field path is valid for the configured result type.
    ///
    /// The IR is authoritative whenever it recognizes the resolved path's first segment
    /// as a real struct field name (populated via [`Self::with_ir_fields`]):
    /// reachable-through-the-binding wins regardless of `result_fields`, and
    /// known-excluded-from-the-binding loses regardless of `result_fields`. `result_fields`
    /// is a hand-maintained allowlist with no automatic connection to the real struct, and
    /// it can drift in BOTH directions at once — one shipped config was found with a field
    /// genuinely exposed via a real getter missing from `result_fields` (silently
    /// downgrading every assertion on it to a "not available" comment) *and*, in the same
    /// list, a field that carries `#[serde(skip)]` with no getter still listed as
    /// available (which would generate a passing-looking assertion against an attribute
    /// that doesn't exist at runtime). Neither direction is fixable by trusting
    /// `result_fields` harder or consulting more hand-maintained config — the IR is the
    /// only signal here that isn't itself hand-maintained per fixture. ~keep
    ///
    /// When the IR has never heard of the first segment at all — a virtual namespace
    /// prefix like `"browser."`, a streaming/synthetic pseudo-field, or simply because the
    /// codegen call site hasn't wired IR data in via `with_ir_fields` — this falls back to
    /// the config-only check: the resolved path's first segment is in `result_fields`, or
    /// the path uses a single virtual namespace prefix (e.g. `"browser."`, `"interaction."`)
    /// whose second segment IS in `result_fields`, or (last resort, see
    /// [`Self::is_known_via_sibling_field_config`]) another per-field config map already
    /// references the field even though `result_fields` doesn't.
    pub fn is_valid_for_result(&self, fixture_field: &str) -> bool {
        let resolved = self.resolve(fixture_field);
        let first_segment = resolved.split('.').next().unwrap_or(resolved);
        let first_segment = first_segment.split('[').next().unwrap_or(first_segment);

        // IR oracle: only consulted for names the IR actually recognizes. A name it has
        // never seen (namespace prefixes, synthetic fields, or simply no IR data wired up)
        // falls through to the config-only checks below unaffected.
        if self.ir_reachable_fields.contains(first_segment) {
            return true;
        }
        if self.ir_known_excluded_fields.contains(first_segment) {
            return false;
        }

        if self.result_fields.is_empty() {
            return true;
        }
        if self.result_fields.contains(first_segment) {
            return true;
        }
        // Namespace-prefix fallback: if the first segment is NOT a known result field
        // but stripping it yields a path whose own first segment IS a known result
        // field, treat the path as valid.  This supports fixture field paths like
        // `"browser.browser_used"` where `"browser"` is a virtual grouping prefix
        // and the real field is `"browser_used"`.
        if let Some(suffix) = self.namespace_stripped_path(resolved) {
            let suffix_first = suffix.split('.').next().unwrap_or(suffix);
            let suffix_first = suffix_first.split('[').next().unwrap_or(suffix_first);
            if self.result_fields.contains(suffix_first) {
                return true;
            }
        }
        self.is_known_via_sibling_field_config(fixture_field, resolved)
    }

    /// True when `fixture_field` (or its alias-resolved path) is referenced by one of
    /// the other per-field config maps (`fields`, `fields_optional`, `fields_array`,
    /// `fields_method_calls`) even though it is absent from `result_fields`.
    ///
    /// Last-resort fallback for codegen call sites that haven't wired IR data in via
    /// `with_ir_fields` (`is_valid_for_result` only reaches this once the IR has had, and
    /// declined, the chance to answer). These maps only make sense to populate for a field
    /// that genuinely exists on the result type — an alias target, an optionality flag, an
    /// array marker, or a method-call accessor all require the config author to have
    /// looked at the real struct. A field that is truly unavailable (no getter generated
    /// for it at all) has nothing to configure here, so this check does not make
    /// unavailable fields pass — it only rescues fields the config demonstrably already
    /// knows about. ~keep
    fn is_known_via_sibling_field_config(&self, fixture_field: &str, resolved: &str) -> bool {
        self.aliases.contains_key(fixture_field)
            || self.is_optional_direct(resolved)
            || self.is_array(resolved)
            || self.method_calls.contains(resolved)
    }

    /// If `path`'s first dot-separated segment is NOT in `result_fields` and
    /// contains no `[…]` indexing (i.e. it looks like a pure namespace label),
    /// return the remainder of the path after that first segment.  Returns `None`
    /// when the first segment already matches a result field or when stripping it
    /// would leave an empty string.
    pub fn namespace_stripped_path<'a>(&self, path: &'a str) -> Option<&'a str> {
        // When the consumer hasn't configured `result_fields`, there is no way
        // to tell a virtual namespace prefix (e.g. `interaction.action_results`)
        // from a real nested-struct field path (e.g. `metrics.total_lines`).
        // Defaulting to "strip" was lossy — every dotted field path was reduced
        // to its leaf segment, so backends (notably the C e2e codegen) emitted
        // accessors against the wrong parent type. Opt the stripping in only
        // when the consumer explicitly listed the top-level result fields.
        if self.result_fields.is_empty() {
            return None;
        }
        let dot_pos = path.find('.')?;
        let first = &path[..dot_pos];
        // Only strip if the first segment contains no brackets (i.e. is a bare
        // label, not an array access like `pages[0]`).
        if first.contains('[') {
            return None;
        }
        // Only strip if the first segment is NOT itself a known result field —
        // real fields should never be treated as namespace prefixes.
        if self.result_fields.contains(first) {
            return None;
        }
        let suffix = &path[dot_pos + 1..];
        if suffix.is_empty() { None } else { Some(suffix) }
    }

    /// Check if a resolved field is an array/Vec type.
    pub fn is_array(&self, field: &str) -> bool {
        self.array_fields.contains(field)
    }

    /// Check whether `field` (a raw or already-resolved fixture path) is
    /// configured as a `fields_json_scalar` entry — i.e. its Kotlin type is
    /// an untyped JSON scalar (`Any?`, from `Option<serde_json::Value>`)
    /// rather than `Option<String>`, so `.orEmpty()` is undefined on it.
    ///
    /// Consults `json_scalar_fields` (a per-call resolved set, not stored on
    /// the resolver) against every spelling `fields_optional`/`is_optional`
    /// already treats as interchangeable — bracket-wildcard (`a[].b`) and
    /// fully de-indexed (`a.b`) — and, mirroring `is_optional`'s namespace
    /// fallback, against the path with a virtual grouping prefix (e.g.
    /// `interaction.`) stripped. Fixture field paths like
    /// `interaction.action_results[0].data` resolve to the struct path
    /// `action_results[0].data` for accessor generation via
    /// `namespace_stripped_path`; the same stripped path must be consulted
    /// here so `fields_json_scalar` entries configured against the struct
    /// path (not the virtual fixture namespace) are honored.
    pub fn is_json_scalar(&self, field: &str, json_scalar_fields: &HashSet<String>) -> bool {
        if Self::matches_json_scalar_spelling(field, json_scalar_fields) {
            return true;
        }
        let resolved = self.resolve(field);
        if resolved != field && Self::matches_json_scalar_spelling(resolved, json_scalar_fields) {
            return true;
        }
        self.namespace_stripped_path(resolved)
            .is_some_and(|stripped| Self::matches_json_scalar_spelling(stripped, json_scalar_fields))
    }

    fn matches_json_scalar_spelling(path: &str, json_scalar_fields: &HashSet<String>) -> bool {
        if json_scalar_fields.contains(path) {
            return true;
        }
        let normalized = normalize_indices_to_wildcards(path);
        if normalized != path && json_scalar_fields.contains(normalized.as_str()) {
            return true;
        }
        let de_indexed = strip_numeric_indices(path);
        de_indexed != path && json_scalar_fields.contains(de_indexed.as_str())
    }

    /// Check whether `field` is enum-typed: an explicit `fields_enum` config entry (exact or
    /// alias-resolved) always wins, and — when the config is silent — the IR-derived
    /// classification (`with_ir_enum_map`) gets the final say. See `ir_enum` module docs for
    /// why the IR check has to walk the whole path rather than matching on the leaf name
    /// alone.
    pub fn is_enum(&self, field: &str) -> bool {
        let resolved = self.resolve(field);
        if self.enum_fields.contains(field) || self.enum_fields.contains(resolved) {
            return true;
        }
        is_enum_path(&self.ir_enum_map, resolved)
    }

    /// Check if a field name is the root of a collection type (i.e., the field
    /// itself returns a `Vec`/array, even though it is not in `fields_array`
    /// directly).
    ///
    /// `fields_array` tracks traversal paths like `choices[0].message.tool_calls`
    /// — the array element paths — not the bare collection accessor (`choices`).
    /// `fields_optional` may also contain paths like `data[0].url` that reveal
    /// `data` is a collection root.
    ///
    /// Returns `true` when any entry in `array_fields` or `optional_fields`
    /// starts with `{field}[`, indicating that `field` is the top-level
    /// collection getter.
    pub fn is_collection_root(&self, field: &str) -> bool {
        let prefix = format!("{field}[");
        self.array_fields.iter().any(|af| af.starts_with(&prefix))
            || self.optional_fields.iter().any(|of| of.starts_with(&prefix))
    }

    /// Check if a resolved field path traverses a tagged-union variant.
    ///
    /// Returns `Some((prefix, variant, suffix))` where:
    /// - `prefix` is the path up to (but not including) the tagged-union field
    ///   (e.g., `"metadata.format"`)
    /// - `variant` is the tagged-union accessor segment
    ///   (e.g., `"excel"`)
    /// - `suffix` is the remaining path after the variant
    ///   (e.g., `"sheet_count"`)
    ///
    /// Returns `None` if no tagged-union segment exists in the path.
    pub fn tagged_union_split(&self, fixture_field: &str) -> Option<(String, String, String)> {
        let resolved = self.resolve(fixture_field);
        let segments: Vec<&str> = resolved.split('.').collect();
        let mut path_so_far = String::new();
        for (i, seg) in segments.iter().enumerate() {
            if !path_so_far.is_empty() {
                path_so_far.push('.');
            }
            path_so_far.push_str(seg);
            if self.method_calls.contains(&path_so_far) {
                // Everything before the last segment of path_so_far is the prefix.
                let prefix = segments[..i].join(".");
                let variant = (*seg).to_string();
                let suffix = segments[i + 1..].join(".");
                return Some((prefix, variant, suffix));
            }
        }
        None
    }

    /// Split a bracket-wildcard path (`foo[].bar`) into its array-root path and
    /// element sub-path, or `None` when the path has no wildcard.
    ///
    /// A wildcard means "every element", so callers render an any-element
    /// construct over the array root rather than an accessor into one index.
    /// Build the element side with `accessor(&element, lang, "<lambda param>")`
    /// — passing the closure parameter as the result var is what lets a nested
    /// element sub-path resolve against the loop variable instead of the result.
    ///
    /// Alias resolution happens BEFORE the split, so a renamed sub-field lands on
    /// the element side; the raw split is only a fallback for when resolution drops
    /// the marker. Explicit numeric indices (`choices[0].message`) return `None` and
    /// keep their existing index-preserving path through `accessor`. ~keep
    ///
    /// The split is NOT recursive: it consumes the FIRST `[].` only. A doubly-nested path
    /// (`pages[].links[].url`) therefore returns an element sub-path that still carries a
    /// wildcard, and handing that to `accessor` lowers the inner `[]` to index 0 (see
    /// `parse_path`) — the caller's loop covers `pages` while the assertion inside it silently
    /// reads `links[0]`. Gate the element sub-path with
    /// `crate::e2e::codegen::field_skip::nested_wildcard_skip_line` before building an
    /// accessor from it. ~keep
    pub fn wildcard_split(&self, fixture_field: &str) -> Option<(String, String)> {
        let raw_dot = fixture_field.find("[].")?;
        let resolved = self.resolve(fixture_field);
        match resolved.find("[].") {
            Some(dot) => Some((resolved[..dot].to_string(), resolved[dot + 3..].to_string())),
            None => Some((
                fixture_field[..raw_dot].to_string(),
                fixture_field[raw_dot + 3..].to_string(),
            )),
        }
    }

    /// Check if a resolved field path contains a non-numeric map access.
    pub fn has_map_access(&self, fixture_field: &str) -> bool {
        let resolved = self.resolve(fixture_field);
        let segments = parse_path(resolved);
        segments.iter().any(|s| {
            if let PathSegment::MapAccess { key, .. } = s {
                !key.chars().all(|c| c.is_ascii_digit())
            } else {
                false
            }
        })
    }
}