alef 0.80.0

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
use std::collections::HashSet;
use std::path::PathBuf;

use crate::core::config::e2e::CallConfig;
use crate::core::ir::{DefaultValue, EnumDef, EnumVariant, FieldDef, FunctionDef, PrimitiveType, TypeDef, TypeRef};
use crate::e2e::config::E2eConfig;
use crate::e2e::field_access::FieldResolver;
use crate::e2e::fixture::{Assertion, Fixture};

use super::assertion_field_shape::resolve_assertion_field_shape;
use super::go_batch::{GoBatchCase, GoBatchLayout, GoCaseOutcome, run_go_batch};
use super::test_function::{GoTestFunctionContext, render_test_function};

/// Import path of the throwaway module that holds every rendered-assertion case as its own
/// package. One module means one `go test` process for the whole set; separate packages keep
/// each case compiled on its own, so an unused import or a build error still fails only the
/// case that caused it. ~keep
const SHAPE_BATCH_MODULE: &str = "example.com/shapes";

/// Every rendered-assertion case that must compile and run. Asserted as a set against the
/// packages `go test` reports on: a batch that silently selects fewer packages exits 0 and
/// is otherwise indistinguishable from a real pass. ~keep
const RENDERED_SHAPE_CASE_COUNT: usize = 45;

/// A case whose rendered Go cannot build. It shares the batch with the real cases to prove
/// the single invocation still surfaces a failure instead of swallowing it, and that doing
/// so does not disturb the verdict on any other case. ~keep
const BROKEN_SOURCE_CONTROL: &str = "compile_control_broken_source";

const PSEUDO_FIELD_SUFFIXES: [&str; 3] = ["length", "count", "size"];

const PSEUDO_FIELD_ASSERTIONS: [&str; 6] = [
    "greater_than",
    "less_than_or_equal",
    "count_min",
    "count_equals",
    "min_length",
    "max_length",
];

const DATA_INTERFACE_STRING_FAMILIES: [(&str, &str); 5] = [
    ("equals", "value"),
    ("contains", "value"),
    ("contains_all", "value"),
    ("not_contains", "absent"),
    ("contains_any", "value"),
];

const SAMPLE_DATA_INTERFACE: &str = "package sample\ntype Choice interface{}\ntype Envelope struct { Choice Choice }\nfunc Inspect() (*Envelope, error) { return &Envelope{Choice: \"value\"}, nil }\n";

const SAMPLE_RAW_MESSAGE: &str = "package sample\nimport \"encoding/json\"\ntype Envelope struct { Payload *json.RawMessage }\nfunc Inspect() (*Envelope, error) { raw := json.RawMessage(`{\"value\":\"sample\"}`); return &Envelope{Payload: &raw}, nil }\n";

const SAMPLE_LABEL_POINTER: &str = "package sample\ntype Envelope struct { Label *string }\nfunc Inspect() (*Envelope, error) { value := \"sample\"; return &Envelope{Label: &value}, nil }\n";

const SAMPLE_LABEL_NIL: &str = "package sample\ntype Envelope struct { Label *string }\nfunc Inspect() (*Envelope, error) { return &Envelope{Label: nil}, nil }\n";

const SAMPLE_LIMIT_POINTER: &str = "package sample\ntype Envelope struct { Limit *int64 }\nfunc Inspect() (*Envelope, error) { value := int64(5); return &Envelope{Limit: &value}, nil }\n";

/// Package one rendered assertion as a Go package inside the batch module: the sample
/// package under test plus the external test file that exercises it.
fn rendered_case(name: &str, rendered: &str, sample_source: &str) -> GoBatchCase {
    assert!(
        emitted_test_functions(rendered) >= 1,
        "a rendered case must emit at least one Go test function:\n{rendered}"
    );
    let mut imports = vec![
        "\"testing\"".to_owned(),
        format!("sample \"{SHAPE_BATCH_MODULE}/{name}\""),
    ];
    if rendered.contains("strings.") {
        imports.push("\"strings\"".to_owned());
    }
    if rendered.contains("jsonString(") {
        imports.push("\"encoding/json\"".to_owned());
    }
    let assertion_stub = if rendered.contains("assert.") {
        "type assertions struct{}\nvar assert assertions\nfunc (assertions) NotNil(*testing.T, any, ...string) {}\nfunc (assertions) GreaterOrEqual(*testing.T, any, any, ...string) {}\nfunc (assertions) LessOrEqual(*testing.T, any, any, ...string) {}\nfunc (assertions) Equal(*testing.T, any, any, ...string) {}\n"
    } else {
        ""
    };
    let json_stub = if rendered.contains("jsonString(") {
        "func jsonString(t *testing.T, value any) string { t.Helper(); data, err := json.Marshal(value); if err != nil { t.Fatal(err) }; return string(data) }\n"
    } else {
        ""
    };
    let source = format!(
        "package sample_test\nimport ({})\n{assertion_stub}{json_stub}\n{rendered}",
        imports.join("\n")
    );
    GoBatchCase {
        name: name.to_owned(),
        files: vec![
            ("sample.go".to_owned(), sample_source.to_owned()),
            ("shape_test.go".to_owned(), source),
        ],
    }
}

fn emitted_test_functions(rendered: &str) -> usize {
    rendered.lines().filter(|line| line.starts_with("func Test")).count()
}

fn render_field_assertion(
    field: FieldDef,
    assertion_field: &str,
    enums: &[EnumDef],
    configured_optional: bool,
    assertion_type: &str,
    value: Option<serde_json::Value>,
) -> String {
    let mut optional = HashSet::new();
    if configured_optional {
        optional.insert(field.name.clone());
    }
    let config = E2eConfig {
        call: CallConfig {
            function: "inspect".into(),
            module: "example.com/sample".into(),
            returns_result: true,
            ..Default::default()
        },
        fields_optional: optional,
        ..Default::default()
    };
    let uses_values = matches!(assertion_type, "contains_all" | "contains_any" | "not_contains");
    let values = uses_values.then(|| vec![value.clone().expect("string family value")]);
    let fixture = Fixture {
        id: "field_shape".into(),
        description: "field shape".into(),
        assertions: vec![Assertion {
            assertion_type: assertion_type.into(),
            field: Some(assertion_field.into()),
            value: (!uses_values).then_some(value).flatten(),
            values,
            ..Default::default()
        }],
        ..Default::default()
    };
    render_fixture(config, fixture, field, enums)
}

fn render_fixture(config: E2eConfig, fixture: Fixture, field: FieldDef, enums: &[EnumDef]) -> String {
    let type_defs = vec![TypeDef {
        name: "Envelope".into(),
        fields: vec![field],
        ..Default::default()
    }];
    let functions = vec![FunctionDef {
        name: "inspect".into(),
        return_type: TypeRef::Named("Envelope".into()),
        ..Default::default()
    }];
    let mut output = String::new();
    render_test_function(
        &mut output,
        &fixture,
        GoTestFunctionContext {
            import_alias: "sample",
            e2e_config: &config,
            adapters: &[],
            data_enum_names: &HashSet::new(),
            config: &Default::default(),
            type_defs: &type_defs,
            enums,
            errors: &[],
            functions: &functions,
        },
    );
    output
}

fn data_choice_enum() -> EnumDef {
    EnumDef {
        name: "Choice".into(),
        variants: vec![EnumVariant {
            name: "Value".into(),
            fields: vec![FieldDef {
                name: "value".into(),
                ty: TypeRef::String,
                ..Default::default()
            }],
            ..Default::default()
        }],
        ..Default::default()
    }
}

fn label_field() -> FieldDef {
    FieldDef {
        name: "label".into(),
        ty: TypeRef::String,
        default: Some("default_label".into()),
        typed_default: Some(DefaultValue::StringLiteral("default".into())),
        ..Default::default()
    }
}

fn optional_data_interface_case() -> GoBatchCase {
    let output = render_field_assertion(
        FieldDef {
            name: "choice".into(),
            ty: TypeRef::Named("Choice".into()),
            optional: true,
            ..Default::default()
        },
        "choice",
        &[data_choice_enum()],
        true,
        "is_true",
        None,
    );

    assert!(
        !output.contains("*result.Choice"),
        "sealed interfaces are not pointers:\n{output}"
    );
    rendered_case(
        "optional_data_interface_nullable_not_dereferenced",
        &output,
        SAMPLE_DATA_INTERFACE,
    )
}

fn required_unresolved_named_case() -> GoBatchCase {
    let output = render_field_assertion(
        FieldDef {
            name: "payload".into(),
            ty: TypeRef::Named("ForeignPayload".into()),
            ..Default::default()
        },
        "payload",
        &[],
        false,
        "contains",
        Some(serde_json::json!("sample")),
    );

    assert!(
        output.contains("*result.Payload"),
        "unresolved named fields are pointers:\n{output}"
    );
    rendered_case(
        "required_unresolved_named_raw_message_pointer",
        &output,
        SAMPLE_RAW_MESSAGE,
    )
}

fn required_default_string_count_case() -> GoBatchCase {
    let output = render_field_assertion(
        label_field(),
        "label",
        &[],
        false,
        "count_min",
        Some(serde_json::json!(1)),
    );

    assert!(output.contains("len(*result.Label)"), "{output}");
    rendered_case("required_default_string_count_pointer", &output, SAMPLE_LABEL_POINTER)
}

fn required_default_number_comparison_case() -> GoBatchCase {
    let output = render_field_assertion(
        FieldDef {
            name: "limit".into(),
            ty: TypeRef::Primitive(PrimitiveType::I64),
            default: Some("default_limit".into()),
            typed_default: Some(DefaultValue::IntLiteral(5)),
            ..Default::default()
        },
        "limit",
        &[],
        false,
        "greater_than",
        Some(serde_json::json!(1)),
    );

    assert!(output.contains("*result.Limit < 2"), "{output}");
    rendered_case(
        "required_default_number_comparison_pointer",
        &output,
        SAMPLE_LIMIT_POINTER,
    )
}

fn pointer_pseudo_field_compiles_case(suffix: &str, assertion_type: &str) -> GoBatchCase {
    let expected = match assertion_type {
        "greater_than" => 0,
        "less_than_or_equal" | "max_length" => 10,
        "count_equals" => 6,
        _ => 1,
    };
    let output = render_field_assertion(
        label_field(),
        &format!("label.{suffix}"),
        &[],
        false,
        assertion_type,
        Some(serde_json::json!(expected)),
    );
    assert!(!output.contains("len(*result.Label) != nil"), "{output}");
    assert!(!output.contains("len(len(*result.Label))"), "{output}");
    rendered_case(
        &format!("pointer_pseudo_{suffix}_{assertion_type}_compiles"),
        &output,
        SAMPLE_LABEL_POINTER,
    )
}

fn pointer_pseudo_field_nil_safe_case(suffix: &str, assertion_type: &str) -> GoBatchCase {
    let expected = match assertion_type {
        "less_than_or_equal" | "max_length" => 10,
        _ => 1,
    };
    let output = render_field_assertion(
        label_field(),
        &format!("label.{suffix}"),
        &[],
        false,
        assertion_type,
        Some(serde_json::json!(expected)),
    );
    rendered_case(
        &format!("pointer_pseudo_{suffix}_{assertion_type}_nil_safe"),
        &output,
        SAMPLE_LABEL_NIL,
    )
}

fn data_interface_string_family_case(assertion_type: &str, expected: &str) -> GoBatchCase {
    let output = render_field_assertion(
        FieldDef {
            name: "choice".into(),
            ty: TypeRef::Named("Choice".into()),
            ..Default::default()
        },
        "choice",
        &[data_choice_enum()],
        false,
        assertion_type,
        Some(serde_json::json!(expected)),
    );
    assert!(output.contains("jsonString(t, result.Choice)"), "{output}");
    rendered_case(
        &format!("data_interface_string_{assertion_type}"),
        &output,
        SAMPLE_DATA_INTERFACE,
    )
}

/// Every case the batch must run, in a stable order. The names double as the batch's case
/// inventory, so each one names the exact fixture it replaced.
fn rendered_shape_cases() -> Vec<GoBatchCase> {
    let mut cases = vec![
        optional_data_interface_case(),
        required_unresolved_named_case(),
        required_default_string_count_case(),
        required_default_number_comparison_case(),
    ];
    for suffix in PSEUDO_FIELD_SUFFIXES {
        for assertion_type in PSEUDO_FIELD_ASSERTIONS {
            cases.push(pointer_pseudo_field_compiles_case(suffix, assertion_type));
            cases.push(pointer_pseudo_field_nil_safe_case(suffix, assertion_type));
        }
    }
    for (assertion_type, expected) in DATA_INTERFACE_STRING_FAMILIES {
        cases.push(data_interface_string_family_case(assertion_type, expected));
    }
    cases
}

fn broken_source_control_case() -> GoBatchCase {
    GoBatchCase {
        name: BROKEN_SOURCE_CONTROL.to_owned(),
        files: vec![
            ("sample.go".to_owned(), "package sample\n".to_owned()),
            (
                "shape_test.go".to_owned(),
                format!(
                    "package sample_test\nimport (\n\"testing\"\nsample \"{SHAPE_BATCH_MODULE}/{BROKEN_SOURCE_CONTROL}\"\n)\nfunc TestBrokenControl(t *testing.T) {{ _ = sample.MissingSymbol }}\n"
                ),
            ),
        ],
    }
}

#[test]
fn rendered_assertion_shapes_compile_and_run_in_one_go_test() {
    let mut cases = rendered_shape_cases();
    assert_eq!(
        cases.len(),
        RENDERED_SHAPE_CASE_COUNT,
        "the rendered-shape inventory changed; update RENDERED_SHAPE_CASE_COUNT deliberately"
    );
    let passing: Vec<String> = cases.iter().map(|case| case.name.clone()).collect();
    let emitted_tests: usize = cases
        .iter()
        .map(|case| {
            case.files
                .iter()
                .map(|(_, content)| emitted_test_functions(content))
                .sum::<usize>()
        })
        .sum();
    cases.push(broken_source_control_case());
    let inventory: Vec<String> = cases.iter().map(|case| case.name.clone()).collect();

    let layout = GoBatchLayout {
        root_files: vec![(
            PathBuf::from("go.mod"),
            format!("module {SHAPE_BATCH_MODULE}\n\ngo 1.24\n"),
        )],
        module_dir: PathBuf::new(),
        module_path: SHAPE_BATCH_MODULE.to_owned(),
        extra_args: Vec::new(),
    };
    let report = run_go_batch(&layout, &cases);

    report.assert_inventory(&inventory);
    for name in &passing {
        report.assert_outcome(name, GoCaseOutcome::Passed);
        assert!(
            report.case(name).test_case_count >= 1,
            "case `{name}` selected no Go test to run:\n{}",
            report.case(name).output
        );
    }
    report.assert_outcome(BROKEN_SOURCE_CONTROL, GoCaseOutcome::Failed);
    report.assert_output_contains(BROKEN_SOURCE_CONTROL, "undefined: sample.MissingSymbol");
    assert!(
        emitted_tests >= RENDERED_SHAPE_CASE_COUNT,
        "every rendered case must contribute at least one Go test: {emitted_tests}"
    );
    assert_eq!(
        report.total_test_cases(),
        emitted_tests,
        "the batch executed a different number of Go tests than it generated"
    );
}

#[test]
fn optional_data_interface_field_is_nullable_but_not_dereferenced() {
    optional_data_interface_case();
}

#[test]
fn required_unresolved_named_field_uses_raw_message_pointer_shape() {
    let types = vec![TypeDef {
        name: "Envelope".into(),
        fields: vec![FieldDef {
            name: "payload".into(),
            ty: TypeRef::Named("ForeignPayload".into()),
            ..Default::default()
        }],
        ..Default::default()
    }];
    let resolver = FieldResolver::new(
        &Default::default(),
        &Default::default(),
        &Default::default(),
        &Default::default(),
        &Default::default(),
    )
    .with_ir_result_fields(
        FieldResolver::ir_result_field_facts_with_enums(&types, &[], "go"),
        Some("Envelope".into()),
    );
    assert_eq!(resolver.target_field_is_pointer("payload"), Some(true));

    required_unresolved_named_case();
}

#[test]
fn optional_vec_assertions_follow_go_slice_shape_over_global_optionality() {
    let config = E2eConfig {
        call: CallConfig {
            function: "inspect".into(),
            module: "example.com/sample".into(),
            returns_result: true,
            ..Default::default()
        },
        fields_optional: HashSet::from(["items".into()]),
        fields_array: HashSet::from(["items".into()]),
        ..Default::default()
    };
    let fixture = Fixture {
        id: "optional_vec_shape".into(),
        assertions: vec![Assertion {
            assertion_type: "min_length".into(),
            field: Some("items".into()),
            value: Some(serde_json::json!(1)),
            ..Default::default()
        }],
        ..Default::default()
    };
    let field = FieldDef {
        name: "items".into(),
        ty: TypeRef::Vec(Box::new(TypeRef::String)),
        optional: true,
        ..Default::default()
    };
    let output = render_fixture(config, fixture, field, &[]);

    assert!(output.contains("len(result.Items)"), "expected slice length:\n{output}");
    assert!(
        !output.contains("len(*result.Items)"),
        "must not dereference slice:\n{output}"
    );
}

#[test]
fn optional_local_has_plain_value_shape() {
    let types = vec![TypeDef {
        name: "Envelope".into(),
        fields: vec![FieldDef {
            name: "title".into(),
            ty: TypeRef::String,
            optional: true,
            ..Default::default()
        }],
        ..Default::default()
    }];
    let resolver = FieldResolver::new(
        &Default::default(),
        &Default::default(),
        &Default::default(),
        &Default::default(),
        &Default::default(),
    )
    .with_ir_result_fields(
        FieldResolver::ir_result_field_facts_with_enums(&types, &[], "go"),
        Some("Envelope".into()),
    );
    let assertion = Assertion {
        assertion_type: "equals".into(),
        field: Some("title".into()),
        value: Some(serde_json::json!("sample")),
        ..Default::default()
    };
    let locals = std::collections::HashMap::from([("title".into(), "title".into())]);
    let shape = resolve_assertion_field_shape(&assertion, &resolver, &locals);

    assert!(!shape.is_optional);
    assert!(!shape.is_pointer);
    assert!(!shape.is_nullable);
}

#[test]
fn required_default_string_count_dereferences_authoritative_pointer() {
    required_default_string_count_case();
}

#[test]
fn required_default_number_comparison_dereferences_authoritative_pointer() {
    required_default_number_comparison_case();
}

#[test]
fn pointer_length_and_count_pseudo_fields_compile_as_scalars() {
    for suffix in PSEUDO_FIELD_SUFFIXES {
        for assertion_type in PSEUDO_FIELD_ASSERTIONS {
            pointer_pseudo_field_compiles_case(suffix, assertion_type);
            pointer_pseudo_field_nil_safe_case(suffix, assertion_type);
        }
    }
}

#[test]
fn data_interface_string_assertion_families_compile_with_wire_json() {
    for (assertion_type, expected) in DATA_INTERFACE_STRING_FAMILIES {
        data_interface_string_family_case(assertion_type, expected);
    }
}

#[test]
fn go_result_shapes_follow_emitted_type_partitions() {
    let (types, enums, excluded) = partitioned_type_fixture();
    let resolver = FieldResolver::new(
        &Default::default(),
        &Default::default(),
        &Default::default(),
        &Default::default(),
        &Default::default(),
    )
    .with_ir_result_fields(
        FieldResolver::go_ir_result_field_facts(&types, &enums, &excluded),
        Some("Envelope".into()),
    );

    for field in ["excluded", "opaque", "visitor", "enum_value"] {
        assert_eq!(resolver.target_field_is_pointer(field), Some(true), "{field}");
    }
}

fn partitioned_type_fixture() -> (Vec<TypeDef>, Vec<EnumDef>, HashSet<String>) {
    let named_field = |name: &str, target: &str| FieldDef {
        name: name.into(),
        ty: TypeRef::Named(target.into()),
        ..Default::default()
    };
    let types = vec![
        TypeDef {
            name: "Envelope".into(),
            fields: vec![
                named_field("excluded", "Excluded"),
                named_field("opaque", "Opaque"),
                named_field("visitor", "VisitorContext"),
                named_field("enum_value", "HiddenChoice"),
            ],
            ..Default::default()
        },
        TypeDef {
            name: "Excluded".into(),
            ..Default::default()
        },
        TypeDef {
            name: "Opaque".into(),
            is_opaque: true,
            ..Default::default()
        },
        TypeDef {
            name: "VisitorContext".into(),
            ..Default::default()
        },
    ];
    let enums = vec![EnumDef {
        name: "HiddenChoice".into(),
        variants: vec![EnumVariant {
            name: "Value".into(),
            ..Default::default()
        }],
        ..Default::default()
    }];
    let excluded = HashSet::from(["Excluded".into(), "VisitorContext".into(), "HiddenChoice".into()]);
    (types, enums, excluded)
}