alef 0.62.5

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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
//! Kotlin argument construction and setup helpers.

use heck::ToUpperCamelCase;

use crate::core::config::ResolvedCrateConfig;
use crate::e2e::config::ArgMapping;
use crate::e2e::escape::escape_kotlin;
use crate::e2e::fixture::Fixture;

/// Build setup lines and the argument list for the function call.
///
/// Returns `Ok((setup_lines, args_string))`, or an error when a `test_backend` arg
/// cannot be rendered as a compilable expression (missing/unregistered trait, or the
/// resolved backend's stub emitter is unimplemented) — see the `test_backend` branch
/// below for why this must fail loudly rather than degrade to a placeholder. ~keep
///
/// `kotlin_android_style = true` switches the optional-`json_object` default
/// from `OptionsType.builder().build()` to `null`. The Java-facade-backed
/// JVM target emits a Java-style builder for every `json_object` type, but
/// the kotlin_android backend emits plain Kotlin data classes with no
/// `.builder()` companion (every field is declared without a default), so a
/// builder call would not compile. The Android facade signatures declare the
/// optional argument as `T? = null`, making `null` the idiomatic positional
/// default that matches the call arity.
pub(super) struct KotlinArgsContext<'a> {
    pub(super) fixture: &'a Fixture,
    pub(super) class_name: &'a str,
    pub(super) options_type: Option<&'a str>,
    pub(super) fixture_id: &'a str,
    pub(super) kotlin_android_style: bool,
    pub(super) config: &'a ResolvedCrateConfig,
    pub(super) type_defs: &'a [crate::core::ir::TypeDef],
    /// True for a streaming `owner_type` adapter, where the facade exposes the
    /// call as an instance method on the handle rather than as a positional
    /// argument to a static/client call (`engine.streamItems(req)`, not
    /// `Facade.streamItems(engine, req)`). Mirrors
    /// `JavaArgsContext::owner_handle_is_receiver`: the handle's construction
    /// line is still emitted, only its presence in the positional argument
    /// list is skipped. ~keep
    pub(super) owner_handle_is_receiver: bool,
}

pub(super) fn build_args_and_setup(
    input: &serde_json::Value,
    args: &[ArgMapping],
    context: KotlinArgsContext<'_>,
) -> anyhow::Result<(Vec<String>, String)> {
    let KotlinArgsContext {
        fixture,
        class_name,
        options_type,
        fixture_id,
        kotlin_android_style,
        config,
        type_defs,
        owner_handle_is_receiver,
    } = context;
    if args.is_empty() {
        return Ok((Vec::new(), String::new()));
    }

    let mut setup_lines: Vec<String> = Vec::new();
    let mut parts: Vec<String> = Vec::new();

    for arg in args {
        if arg.arg_type == "mock_url" {
            let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
            let value = input.get(field).unwrap_or(&serde_json::Value::Null);
            if let Some(url) = crate::e2e::codegen::preserved_url_literal(fixture.preserve_input_urls, value) {
                setup_lines.push(format!("val {} = \"{}\"", arg.name, escape_kotlin(url)));
            } else if fixture.has_host_root_route() {
                setup_lines.push(format!(
                    "val {} = System.getProperty(\"mockServer.{fixture_id}\", (System.getProperty(\"mockServerUrl\", System.getenv(\"MOCK_SERVER_URL\") ?: \"\") ?: \"\") + \"/fixtures/{fixture_id}\")",
                    arg.name,
                ));
            } else {
                setup_lines.push(format!(
                    "val {} = (System.getProperty(\"mockServerUrl\", System.getenv(\"MOCK_SERVER_URL\") ?: \"\") ?: \"\") + \"/fixtures/{fixture_id}\"",
                    arg.name,
                ));
            }
            parts.push(arg.name.clone());
            continue;
        }

        if arg.arg_type == "mock_url_list" {
            let value = crate::e2e::codegen::resolve_urls_field(input, &arg.field);
            if let Some(urls) = crate::e2e::codegen::preserved_url_list(fixture.preserve_input_urls, value) {
                let literals = urls
                    .into_iter()
                    .map(|url| format!("\"{}\"", escape_kotlin(url)))
                    .collect::<Vec<_>>()
                    .join(", ");
                setup_lines.push(format!("val {} = listOf({literals})", arg.name));
                parts.push(arg.name.clone());
                continue;
            }
        }

        if arg.arg_type == "handle" {
            let constructor_name = format!("create{}", arg.name.to_upper_camel_case());
            let field = arg.field.strip_prefix("input.").unwrap_or(&arg.field);
            let config_value = input.get(field).unwrap_or(&serde_json::Value::Null);
            if config_value.is_null()
                || config_value.is_object() && config_value.as_object().is_some_and(|o| o.is_empty())
            {
                setup_lines.push(format!("val {} = {class_name}.{constructor_name}(null)", arg.name,));
            } else {
                let json_str = serde_json::to_string(config_value).unwrap_or_default();
                let name = &arg.name;
                if let Some(config_type) = super::test_file::resolve_handle_config_type(arg, options_type, type_defs) {
                    setup_lines.push(format!(
                        "val {name}Config = MAPPER.readValue(\"{}\", {config_type}::class.java)",
                        escape_kotlin(&json_str),
                    ));
                    setup_lines.push(format!(
                        "val {} = {class_name}.{constructor_name}({name}Config)",
                        arg.name,
                        name = name,
                    ));
                } else {
                    setup_lines.push(format!("val {} = {class_name}.{constructor_name}(null)", arg.name,));
                }
            }
            // For a streaming owner_type adapter the handle is the instance-method
            // receiver, not a positional argument — emit its construction but omit
            // it from the call's argument list.
            if owner_handle_is_receiver {
                continue;
            }
            parts.push(arg.name.clone());
            continue;
        }

        if arg.arg_type == "test_backend" {
            let lang = if kotlin_android_style {
                "kotlin_android"
            } else {
                "kotlin"
            };

            // A `test_backend` arg fills a non-null `I{TraitName}` interface parameter.
            // There is no fixture-supplied value to fall back to and no safe default —
            // unlike every other arg branch above, "the trait isn't configured" and
            // "the backend can't build a stub" have no compilable positional value.
            // Fail generation loudly instead of guessing (`null` into a non-null
            // parameter is itself a compile error, not a safe default). ~keep
            let Some(trait_name) = &arg.trait_name else {
                anyhow::bail!(
                    "e2e fixture `{fixture_id}` declares a `test_backend` arg `{}` with no `trait_name` configured; cannot generate a `{lang}` stub without knowing which trait to implement",
                    arg.name
                );
            };
            let Some(trait_bridge) = config.trait_bridges.iter().find(|tb| tb.trait_name == *trait_name) else {
                anyhow::bail!(
                    "e2e fixture `{fixture_id}` requires trait `{trait_name}` for its `test_backend` arg `{}`, but no `[[crates.trait_bridges]]` entry named `{trait_name}` is configured",
                    arg.name
                );
            };

            // Collect methods from both the main trait and its super-trait (if present).
            // The super-trait methods are needed so stubs implement the full interface.
            let mut methods: Vec<&crate::core::ir::MethodDef> = type_defs
                .iter()
                .find(|t| t.name == *trait_name)
                .map(|t| t.methods.iter().collect())
                .unwrap_or_default();

            // If there's a super-trait, also collect its methods.
            if let Some(super_trait) = &trait_bridge.super_trait {
                // Extract the simple name from the full path (e.g., "Plugin" from "sample_core::plugins::Plugin").
                let super_trait_simple = super_trait.rsplit("::").next().unwrap_or(super_trait.as_str());
                if let Some(super_type) = type_defs.iter().find(|t| t.name == super_trait_simple) {
                    for method in &super_type.methods {
                        // Only add if not already present (avoid duplicates).
                        if !methods.iter().any(|m| m.name == method.name) {
                            methods.push(method);
                        }
                    }
                }
            }

            // For kotlin_android, filter out methods whose return type or parameters
            // reference types in the `exclude_types` list.  The binding generator
            // omits those methods from the generated interface, so the test stub
            // must not attempt to implement them.
            if kotlin_android_style {
                let excluded: std::collections::HashSet<&str> = config
                    .kotlin_android
                    .as_ref()
                    .map(|c| c.exclude_types.iter().map(String::as_str).collect())
                    .unwrap_or_default();
                if !excluded.is_empty() {
                    methods.retain(|m| {
                        !excluded.iter().any(|ex| m.return_type.references_named(ex))
                            && m.params
                                .iter()
                                .all(|p| !excluded.iter().any(|ex| p.ty.references_named(ex)))
                    });
                }
            }

            // `emit_test_backend` panics rather than return a placeholder when a
            // language has no real `test_backend` stub generator (e.g. Kotlin JVM
            // today) — see `TestBackendEmission`'s doc comment. ~keep
            let emission = crate::e2e::codegen::emit_test_backend(lang, trait_bridge, &methods, fixture, &[]);
            setup_lines.push(emission.setup_block);
            parts.push(emission.arg_expr);
            continue;
        }

        // Use resolve_field so field = "input" resolves to the whole fixture input.
        let val_resolved = crate::e2e::codegen::resolve_field(input, &arg.field);
        let val: Option<&serde_json::Value> = if val_resolved.is_null() {
            None
        } else {
            Some(val_resolved)
        };
        match val {
            None | Some(serde_json::Value::Null) if arg.optional => {
                // Optional arg with no fixture value: emit positional default so the
                // call has the right arity for the facade.
                //
                // For json_object optional args:
                // - If options_type is set, use `OptionsType()` for kotlin_android (data class
                //   constructor with defaults) or `OptionsType.builder().build()` for Java facade.
                // - If no options_type, infer the type from arg.name and emit default constructor
                //   (e.g., a configured default constructor for an options arg). This handles both Java facade
                //   (which requires non-null) and kotlin_android (which also declares non-null).
                if arg.arg_type == "json_object" {
                    let default_constructor = if let Some(opts_type) = options_type {
                        if kotlin_android_style {
                            format!("{}()", opts_type)
                        } else {
                            format!("{}.builder().build()", opts_type)
                        }
                    } else {
                        // Infer the type from available config types in type_defs.
                        let inferred_type = super::test_file::resolve_handle_config_type(
                            &crate::e2e::config::ArgMapping {
                                name: arg.name.clone(),
                                field: arg.field.clone(),
                                arg_type: "handle".to_string(),
                                optional: arg.optional,
                                owned: false,
                                element_type: None,
                                go_type: None,
                                vec_inner_is_ref: false,
                                trait_name: None,
                            },
                            None,
                            type_defs,
                        )
                        .unwrap_or_else(|| {
                            // Fallback: try the pattern "{field}Config"
                            let candidate = format!("{}Config", arg.name.to_upper_camel_case());
                            if type_defs.iter().any(|t| t.name == candidate) {
                                candidate
                            } else {
                                arg.name.to_upper_camel_case()
                            }
                        });
                        format!("{}()", inferred_type)
                    };
                    parts.push(default_constructor);
                } else {
                    parts.push("null".to_string());
                }
            }
            None | Some(serde_json::Value::Null) => {
                let default_val = match arg.arg_type.as_str() {
                    "string" => "\"\"".to_string(),
                    "int" | "integer" => "0".to_string(),
                    "float" | "number" => "0.0".to_string(),
                    "bool" | "boolean" => "false".to_string(),
                    _ => "null".to_string(),
                };
                parts.push(default_val);
            }
            Some(v) => {
                // Typed arrays carry `element_type` and are materialised as `listOf(...)`.
                // For kotlin_android batch APIs the element type is a binding class
                // (e.g. BatchBytesItem) that wraps multiple fields from JSON objects.
                // For JVM bindings, when element_type is present, deserialize objects via Jackson
                // instead of emitting raw JSON strings.
                if arg.arg_type == "json_object" && v.is_array() && arg.element_type.is_some() {
                    let element_type = arg.element_type.as_deref().unwrap();
                    let mock_base_var = if crate::e2e::codegen::value_contains_mock_url_placeholder(v) {
                        let env_key = crate::e2e::codegen::mock_url_env_key(fixture_id);
                        let base_var = format!("{}MockBaseUrl", arg.name);
                        setup_lines.push(format!(
                            "val {base_var} = System.getProperty(\"mockServer.{fixture_id}\", System.getenv(\"{env_key}\") ?: (System.getProperty(\"mockServerUrl\", System.getenv(\"MOCK_SERVER_URL\") ?: \"\") + \"/fixtures/{fixture_id}\"))"
                        ));
                        Some(base_var)
                    } else {
                        None
                    };
                    let items: Vec<String> = v
                        .as_array()
                        .map(|arr| {
                            arr.iter()
                                .map(|item| {
                                    // For object items, deserialize via Jackson to the element type
                                    if item.is_object() {
                                        let normalized = crate::e2e::codegen::transform_json_keys_for_language(item, "snake_case");
                                        let json_str = serde_json::to_string(&normalized).unwrap_or_default();
                                        let escaped = escape_kotlin(&json_str);
                                        if let Some(base_var) = mock_base_var.as_deref()
                                            && crate::e2e::codegen::value_contains_mock_url_placeholder(item)
                                        {
                                            format!(
                                                "MAPPER.readValue(\"{escaped}\".replace(\"{}\", {base_var}), {element_type}::class.java)",
                                                escape_kotlin(crate::e2e::codegen::MOCK_URL_PLACEHOLDER)
                                            )
                                        } else {
                                            format!("MAPPER.readValue(\"{escaped}\", {element_type}::class.java)")
                                        }
                                    } else if element_type == "String" {
                                        if let Some(raw) = item.as_str()
                                            && let Some(base_var) = mock_base_var.as_deref()
                                            && raw.contains(crate::e2e::codegen::MOCK_URL_PLACEHOLDER)
                                        {
                                            format!(
                                                "\"{}\".replace(\"{}\", {base_var})",
                                                escape_kotlin(raw),
                                                escape_kotlin(crate::e2e::codegen::MOCK_URL_PLACEHOLDER)
                                            )
                                        } else {
                                            super::values::json_to_kotlin(item)
                                        }
                                    } else if let Some(path) = item.as_str() {
                                        // For string items (file paths), construct the element with the path
                                        if kotlin_android_style {
                                            format!(
                                                "{element_type}(java.nio.file.Files.readAllBytes(java.nio.file.Paths.get(\"{}\")), java.nio.charset.StandardCharsets.UTF_8)",
                                                escape_kotlin(path)
                                            )
                                        } else {
                                            // JVM version takes Path objects, not ByteArray
                                            format!(
                                                "{element_type}(java.nio.file.Paths.get(\"{}\"))",
                                                escape_kotlin(path)
                                            )
                                        }
                                    } else {
                                        // Fallback for other literal types
                                        super::values::json_to_kotlin(item)
                                    }
                                })
                                .collect()
                        })
                        .unwrap_or_default();
                    parts.push(format!("listOf({})", items.join(", ")));
                    continue;
                }
                // For json_object args, deserialize via Jackson or use pre-deserialized variable.
                //
                // This is the sole emitter of the `val {arg.name} = MAPPER.readValue(...)`
                // binding for json_object args: it is shared by both the e2e test emitter
                // (test_method.rs) and standalone docs snippets (snippet.rs), and must be
                // fully self-contained for both callers — neither duplicates this logic. ~keep
                if arg.arg_type == "json_object" {
                    if let Some(opts_type) =
                        crate::e2e::codegen::recipe::json_object_constructor_type(arg, options_type, v)
                    {
                        if crate::e2e::codegen::value_contains_mock_url_placeholder(v) {
                            // The mock server's base URL is only known at test run time, so
                            // the placeholder is swapped in via a runtime `.replace(...)`
                            // rather than baked into the literal at codegen time. Doc-file
                            // markers are not combined with this path, mirroring the
                            // config_type-inference branch below. ~keep
                            let json_value = normalize_typed_json(v, opts_type, type_defs);
                            let json_str = serde_json::to_string(&json_value).unwrap_or_default();
                            let env_key = crate::e2e::codegen::mock_url_env_key(fixture_id);
                            let base_var = format!("{}MockBaseUrl", arg.name);
                            let json_var = format!("{}Json", arg.name);
                            setup_lines.push(format!(
                                "val {base_var} = System.getProperty(\"mockServer.{fixture_id}\", System.getenv(\"{env_key}\") ?: ((System.getProperty(\"mockServerUrl\", System.getenv(\"MOCK_SERVER_URL\") ?: \"\") ?: \"\") + \"/fixtures/{fixture_id}\"))"
                            ));
                            setup_lines.push(format!(
                                "val {json_var} = \"{}\".replace(\"{}\", {base_var})",
                                escape_kotlin(&json_str),
                                escape_kotlin(crate::e2e::codegen::MOCK_URL_PLACEHOLDER)
                            ));
                            setup_lines.push(format!(
                                "val {} = MAPPER.readValue({json_var}, {opts_type}::class.java)",
                                arg.name
                            ));
                        } else {
                            let files = fixture.docs_files_for_arg(&arg.field);
                            let mut json_value = v.clone();
                            let file_reads = prepare_docs_file_reads(&mut json_value, &files);
                            json_value = normalize_typed_json(&json_value, opts_type, type_defs);
                            append_docs_file_setup(&mut setup_lines, &arg.name, &json_value, opts_type, &file_reads);
                        }
                        parts.push(arg.name.clone());
                    } else {
                        // Infer the config type and deserialize
                        let config_type = super::test_file::resolve_handle_config_type(
                            &crate::e2e::config::ArgMapping {
                                name: arg.name.clone(),
                                field: arg.field.clone(),
                                arg_type: "handle".to_string(),
                                optional: arg.optional,
                                owned: false,
                                element_type: None,
                                go_type: None,
                                vec_inner_is_ref: false,
                                trait_name: None,
                            },
                            None,
                            type_defs,
                        )
                        .unwrap_or_else(|| {
                            // Fallback to derived type
                            let candidate = format!("{}Config", arg.name.to_upper_camel_case());
                            if type_defs.iter().any(|t| t.name == candidate) {
                                candidate
                            } else {
                                arg.name.to_upper_camel_case()
                            }
                        });

                        // Setup deserialization
                        let files = fixture.docs_files_for_arg(&arg.field);
                        let mut json_value = v.clone();
                        let file_reads = files
                            .iter()
                            .enumerate()
                            .filter_map(|(index, file)| {
                                let marker = format!("__ALEF_DOC_FILE_{index}__");
                                let target = if file.field.is_empty() {
                                    Some(&mut json_value)
                                } else {
                                    json_value.pointer_mut(&file.field)
                                }?;
                                *target = serde_json::Value::String(marker.clone());
                                Some((index, marker, file.path.clone()))
                            })
                            .collect::<Vec<_>>();
                        let json_str = serde_json::to_string(&json_value).unwrap_or_default();
                        let var_name = format!("{}_Config", arg.name);
                        if crate::e2e::codegen::value_contains_mock_url_placeholder(v) {
                            let env_key = crate::e2e::codegen::mock_url_env_key(fixture_id);
                            let base_var = format!("{}MockBaseUrl", arg.name);
                            let json_var = format!("{}Json", var_name);
                            setup_lines.push(format!(
                                "val {base_var} = System.getProperty(\"mockServer.{fixture_id}\", System.getenv(\"{env_key}\") ?: ((System.getProperty(\"mockServerUrl\", System.getenv(\"MOCK_SERVER_URL\") ?: \"\") ?: \"\") + \"/fixtures/{fixture_id}\"))"
                            ));
                            setup_lines.push(format!(
                                "val {json_var} = \"{}\".replace(\"{}\", {base_var})",
                                crate::e2e::escape::escape_kotlin(&json_str),
                                crate::e2e::escape::escape_kotlin(crate::e2e::codegen::MOCK_URL_PLACEHOLDER)
                            ));
                            setup_lines.push(format!(
                                "val {var_name} = MAPPER.readValue({json_var}, {config_type}::class.java)"
                            ));
                        } else if file_reads.is_empty() {
                            setup_lines.push(format!(
                                "val {var_name} = MAPPER.readValue(\"{}\", {config_type}::class.java)",
                                crate::e2e::escape::escape_kotlin(&json_str)
                            ));
                        } else {
                            let replacements = file_reads
                                .iter()
                                .map(|(index, marker, _)| format!(".replace(\"{marker}\", {}File{index})", arg.name))
                                .collect::<String>();
                            for (index, _, path) in &file_reads {
                                setup_lines.push(
                                    crate::e2e::template_env::render(
                                        "kotlin/docs_file_read.jinja",
                                        minijinja::context! {
                                            variable => arg.name,
                                            index => index,
                                            path => escape_kotlin(path),
                                        },
                                    )
                                    .trim_end()
                                    .to_string(),
                                );
                            }
                            setup_lines.push(
                                crate::e2e::template_env::render(
                                    "kotlin/snippet_json_object_setup.jinja",
                                    minijinja::context! {
                                        variable => var_name,
                                        json => escape_kotlin(&json_str),
                                        replacements => replacements,
                                        type_name => config_type,
                                    },
                                )
                                .trim_end()
                                .to_string(),
                            );
                        }
                        parts.push(var_name);
                    }
                    continue;
                }
                // bytes args in Kotlin binding carry a relative file path (e.g. "docx/fake.docx")
                // that the Kotlin API resolves and reads internally.
                // - JVM binding: pass the path string directly
                // - android binding: need to read bytes and wrap in ByteArray
                if arg.arg_type == "bytes" {
                    let val = super::values::json_to_kotlin(v);
                    if kotlin_android_style {
                        // kotlin_android needs ByteArray, not String path
                        // Emit code to read the file as bytes
                        if v.is_string() {
                            parts.push(format!(
                                "java.nio.file.Files.readAllBytes(java.nio.file.Paths.get({val}))"
                            ));
                        } else {
                            parts.push("byteArrayOf()".to_string());
                        }
                    } else {
                        parts.push(val);
                    }
                    continue;
                }
                // file_path args: Kotlin module wraps the Java facade (which takes Path),
                // but kotlin_android has a different signature that takes a plain String.
                if arg.arg_type == "file_path" {
                    let val = super::values::json_to_kotlin(v);
                    if kotlin_android_style {
                        // kotlin_android binding takes a plain String path
                        parts.push(val);
                    } else {
                        // Kotlin (JVM) binding re-exports Java facade which takes java.nio.file.Path
                        parts.push(format!("java.nio.file.Path.of({val})"));
                    }
                    continue;
                }
                parts.push(super::values::json_to_kotlin(v));
            }
        }
    }

    Ok((setup_lines, parts.join(", ")))
}

fn normalize_typed_json(
    value: &serde_json::Value,
    type_name: &str,
    type_defs: &[crate::core::ir::TypeDef],
) -> serde_json::Value {
    let Some(type_def) = type_defs.iter().find(|candidate| candidate.name == type_name) else {
        return crate::e2e::codegen::transform_json_keys_for_language(value, "snake_case");
    };
    let Some(object) = value.as_object() else {
        return value.clone();
    };
    let mut normalized = serde_json::Map::new();
    for (key, field_value) in object {
        let field = type_def.fields.iter().find(|field| {
            field.name == *key
                || crate::codegen::naming::wire_field_name(
                    &field.name,
                    field.serde_rename.as_deref(),
                    type_def.serde_rename_all.as_deref(),
                ) == *key
        });
        let Some(field) = field else {
            normalized.insert(key.clone(), field_value.clone());
            continue;
        };
        let wire_name = crate::codegen::naming::wire_field_name(
            &field.name,
            field.serde_rename.as_deref(),
            type_def.serde_rename_all.as_deref(),
        );
        normalized.insert(wire_name, normalize_typed_value(field_value, &field.ty, type_defs));
    }
    serde_json::Value::Object(normalized)
}

fn normalize_typed_value(
    value: &serde_json::Value,
    field_type: &crate::core::ir::TypeRef,
    type_defs: &[crate::core::ir::TypeDef],
) -> serde_json::Value {
    match field_type {
        crate::core::ir::TypeRef::Named(name) => normalize_typed_json(value, name, type_defs),
        crate::core::ir::TypeRef::Optional(inner) => normalize_typed_value(value, inner, type_defs),
        crate::core::ir::TypeRef::Vec(inner) => serde_json::Value::Array(
            value
                .as_array()
                .map(|items| {
                    items
                        .iter()
                        .map(|item| normalize_typed_value(item, inner, type_defs))
                        .collect()
                })
                .unwrap_or_default(),
        ),
        _ => value.clone(),
    }
}

fn prepare_docs_file_reads(
    value: &mut serde_json::Value,
    files: &[crate::e2e::fixture::FixtureDocsFileInput],
) -> Vec<(usize, String, String)> {
    files
        .iter()
        .enumerate()
        .filter_map(|(index, file)| {
            let marker = format!("__ALEF_DOC_FILE_{index}__");
            let target = if file.field.is_empty() {
                Some(&mut *value)
            } else {
                value.pointer_mut(&file.field)
            }?;
            *target = serde_json::Value::String(marker.clone());
            Some((index, marker, file.path.clone()))
        })
        .collect()
}

fn append_docs_file_setup(
    setup_lines: &mut Vec<String>,
    variable: &str,
    value: &serde_json::Value,
    type_name: &str,
    file_reads: &[(usize, String, String)],
) {
    let replacements = file_reads
        .iter()
        .map(|(index, marker, _)| format!(".replace(\"{marker}\", {variable}File{index})"))
        .collect::<String>();
    for (index, _, path) in file_reads {
        setup_lines.push(
            crate::e2e::template_env::render(
                "kotlin/docs_file_read.jinja",
                minijinja::context! { variable => variable, index => index, path => escape_kotlin(path) },
            )
            .trim_end()
            .to_string(),
        );
    }
    let json = serde_json::to_string(value).unwrap_or_default();
    setup_lines.push(
        crate::e2e::template_env::render(
            "kotlin/snippet_json_object_setup.jinja",
            minijinja::context! {
                variable => variable,
                json => escape_kotlin(&json),
                replacements => replacements,
                type_name => type_name,
            },
        )
        .trim_end()
        .to_string(),
    );
}