alef 0.25.21

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
//! Verifies that the Rustler backend emits `@moduledoc`, `@typedoc`, and `@doc` heredocs on
//! Elixir DTO modules, enum modules, and per-variant accessors so ExDoc shows complete
//! coverage for the binding.

use alef::backends::rustler::RustlerBackend;
use alef::core::backend::Backend;
use alef::core::config::{ResolvedCrateConfig, new_config::NewAlefConfig};
use alef::core::ir::{ApiSurface, CoreWrapper, EnumDef, EnumVariant, FieldDef, PrimitiveType, TypeDef, TypeRef};

fn make_config(app_name: &str) -> ResolvedCrateConfig {
    let crate_name = app_name.replace('_', "-");
    let toml = format!(
        r#"
[workspace]
languages = ["elixir"]

[[crates]]
name = "{crate_name}"
sources = ["src/lib.rs"]

[crates.elixir]
app_name = "{app_name}"
"#
    );
    let cfg: NewAlefConfig = toml::from_str(&toml).expect("test config must parse");
    cfg.resolve().expect("test config must resolve").remove(0)
}

fn make_field(name: &str, ty: TypeRef, optional: bool, doc: &str) -> FieldDef {
    FieldDef {
        name: name.to_string(),
        ty,
        optional,
        default: None,
        doc: doc.to_string(),
        sanitized: false,
        is_boxed: false,
        type_rust_path: None,
        cfg: None,
        typed_default: None,
        core_wrapper: CoreWrapper::None,
        vec_inner_core_wrapper: CoreWrapper::None,
        newtype_wrapper: None,
        serde_rename: None,
        serde_flatten: false,
        binding_excluded: false,
        binding_exclusion_reason: None,
        original_type: None,
    }
}

fn find_module<'a>(generated: &'a [alef::core::backend::GeneratedFile], needle: &str) -> &'a str {
    let module = generated
        .iter()
        .find(|f| {
            let p = f.path.to_string_lossy();
            p.contains(needle) && p.ends_with(".ex")
        })
        .unwrap_or_else(|| {
            panic!(
                "should generate module containing {needle}; got: {:?}",
                generated
                    .iter()
                    .map(|f| f.path.to_string_lossy().to_string())
                    .collect::<Vec<_>>()
            )
        });
    &module.content
}

#[test]
fn test_struct_module_emits_moduledoc_heredoc_when_doc_present() {
    let struct_def = TypeDef {
        name: "ProcessConfig".to_string(),
        rust_path: "my_crate::ProcessConfig".to_string(),
        original_rust_path: String::new(),
        fields: vec![make_field("name", TypeRef::String, false, "")],
        methods: vec![],
        is_opaque: false,
        is_clone: true,
        is_copy: false,
        is_trait: false,
        has_default: false,
        has_stripped_cfg_fields: false,
        is_return_type: false,
        serde_rename_all: None,
        has_serde: false,
        super_traits: vec![],
        doc: "Configuration for a processing pipeline.\n\nDescribes the input and output channels.".to_string(),
        cfg: None,
        binding_excluded: false,
        binding_exclusion_reason: None,
        is_variant_wrapper: false,
        has_lifetime_params: false,
        version: Default::default(),
    };

    let config = make_config("test_app");
    let api = ApiSurface {
        crate_name: "test-app".to_string(),
        version: "1.0.0".to_string(),
        functions: vec![],
        types: vec![struct_def],
        enums: vec![],
        errors: vec![],
        excluded_type_paths: std::collections::HashMap::new(),
        excluded_trait_names: ::std::collections::HashSet::new(),
        services: vec![],
        handler_contracts: vec![],
        unsupported_public_items: Vec::new(),
    };
    let generated = RustlerBackend.generate_public_api(&api, &config).unwrap();
    let content = find_module(&generated, "process_config");

    assert!(
        content.contains("@moduledoc \"\"\""),
        "multi-line module doc must use heredoc form; got:\n{content}"
    );
    assert!(
        content.contains("Configuration for a processing pipeline."),
        "module doc body must be preserved; got:\n{content}"
    );
    assert!(
        content.contains("Describes the input and output channels."),
        "second paragraph must be preserved; got:\n{content}"
    );
    assert!(
        content.contains("@typedoc"),
        "@typedoc must be emitted; got:\n{content}"
    );
    // @typedoc must come before @type t to be picked up by ExDoc.
    let typedoc_pos = content.find("@typedoc").expect("@typedoc must be present");
    let type_t_pos = content.find("@type t ::").expect("@type t must be present");
    assert!(
        typedoc_pos < type_t_pos,
        "@typedoc must precede @type t; got:\n{content}"
    );
}

#[test]
fn test_struct_module_emits_moduledoc_false_when_doc_empty() {
    let struct_def = TypeDef {
        name: "Anon".to_string(),
        rust_path: "my_crate::Anon".to_string(),
        original_rust_path: String::new(),
        fields: vec![make_field("v", TypeRef::Primitive(PrimitiveType::U32), false, "")],
        methods: vec![],
        is_opaque: false,
        is_clone: true,
        is_copy: false,
        is_trait: false,
        has_default: false,
        has_stripped_cfg_fields: false,
        is_return_type: false,
        serde_rename_all: None,
        has_serde: false,
        super_traits: vec![],
        doc: String::new(),
        cfg: None,
        binding_excluded: false,
        binding_exclusion_reason: None,
        is_variant_wrapper: false,
        has_lifetime_params: false,
        version: Default::default(),
    };
    let config = make_config("test_app");
    let api = ApiSurface {
        crate_name: "test-app".to_string(),
        version: "1.0.0".to_string(),
        functions: vec![],
        types: vec![struct_def],
        enums: vec![],
        errors: vec![],
        excluded_type_paths: std::collections::HashMap::new(),
        excluded_trait_names: ::std::collections::HashSet::new(),
        services: vec![],
        handler_contracts: vec![],
        unsupported_public_items: Vec::new(),
    };
    let generated = RustlerBackend.generate_public_api(&api, &config).unwrap();
    let content = find_module(&generated, "anon");
    assert!(
        content.contains("@moduledoc false"),
        "docless module must emit @moduledoc false; got:\n{content}"
    );
    assert!(
        !content.contains("@typedoc"),
        "docless module must not emit @typedoc; got:\n{content}"
    );
}

#[test]
fn test_unit_enum_module_emits_doc_on_each_variant_accessor() {
    let enum_def = EnumDef {
        name: "Severity".to_string(),
        rust_path: "my_crate::Severity".to_string(),
        original_rust_path: String::new(),
        variants: vec![
            EnumVariant {
                name: "Error".into(),
                fields: vec![],
                doc: "A blocking issue.".into(),
                is_default: false,
                serde_rename: None,
                binding_excluded: false,
                binding_exclusion_reason: None,
                is_tuple: false,
                originally_had_data_fields: false,
                cfg: None,
                version: Default::default(),
            },
            EnumVariant {
                name: "Warning".into(),
                fields: vec![],
                doc: "A non-blocking caveat.".into(),
                is_default: false,
                serde_rename: None,
                binding_excluded: false,
                binding_exclusion_reason: None,
                is_tuple: false,
                originally_had_data_fields: false,
                cfg: None,
                version: Default::default(),
            },
        ],
        doc: "Severity levels for diagnostics.".into(),
        cfg: None,
        is_copy: false,
        has_serde: false,
        serde_tag: None,
        serde_untagged: false,
        serde_rename_all: None,
        binding_excluded: false,
        binding_exclusion_reason: None,
        excluded_variants: vec![],
        version: Default::default(),
    };
    let config = make_config("test_app");
    let api = ApiSurface {
        crate_name: "test-app".to_string(),
        version: "1.0.0".to_string(),
        functions: vec![],
        types: vec![],
        enums: vec![enum_def],
        errors: vec![],
        excluded_type_paths: std::collections::HashMap::new(),
        excluded_trait_names: ::std::collections::HashSet::new(),
        services: vec![],
        handler_contracts: vec![],
        unsupported_public_items: Vec::new(),
    };
    let generated = RustlerBackend.generate_public_api(&api, &config).unwrap();
    let content = find_module(&generated, "severity");

    assert!(
        content.contains("@moduledoc"),
        "enum module must emit @moduledoc; got:\n{content}"
    );
    assert!(
        content.contains("Severity levels for diagnostics."),
        "enum @moduledoc body must be preserved; got:\n{content}"
    );
    assert!(
        content.contains("@typedoc"),
        "unit enum should emit @typedoc on @type t; got:\n{content}"
    );
    assert!(
        content.contains("A blocking issue."),
        "Error variant doc must appear in @doc above accessor; got:\n{content}"
    );
    assert!(
        content.contains("A non-blocking caveat."),
        "Warning variant doc must appear in @doc above accessor; got:\n{content}"
    );
    // Verify @doc precedes the corresponding @spec/def pair.
    let doc_pos = content.find("A blocking issue.").unwrap();
    let def_error_pos = content
        .find("def error,")
        .unwrap_or_else(|| content.find("def error ").unwrap_or(usize::MAX));
    assert!(
        doc_pos < def_error_pos,
        "@doc must precede def for variant accessor; got:\n{content}"
    );
}

#[test]
fn test_data_enum_module_emits_typedoc_on_each_variant_alias() {
    let enum_def = EnumDef {
        name: "Diagnostic".to_string(),
        rust_path: "my_crate::Diagnostic".to_string(),
        original_rust_path: String::new(),
        variants: vec![
            EnumVariant {
                name: "Error".into(),
                fields: vec![FieldDef {
                    name: "msg".into(),
                    ty: TypeRef::String,
                    optional: false,
                    default: None,
                    doc: String::new(),
                    sanitized: false,
                    is_boxed: false,
                    type_rust_path: None,
                    cfg: None,
                    typed_default: None,
                    core_wrapper: CoreWrapper::None,
                    vec_inner_core_wrapper: CoreWrapper::None,
                    newtype_wrapper: None,
                    serde_rename: None,
                    serde_flatten: false,
                    binding_excluded: false,
                    binding_exclusion_reason: None,
                    original_type: None,
                }],
                doc: "Hard failure diagnostic.".into(),
                is_default: false,
                serde_rename: None,
                binding_excluded: false,
                binding_exclusion_reason: None,
                is_tuple: false,
                originally_had_data_fields: false,
                cfg: None,
                version: Default::default(),
            },
            EnumVariant {
                name: "Warning".into(),
                fields: vec![FieldDef {
                    name: "msg".into(),
                    ty: TypeRef::String,
                    optional: false,
                    default: None,
                    doc: String::new(),
                    sanitized: false,
                    is_boxed: false,
                    type_rust_path: None,
                    cfg: None,
                    typed_default: None,
                    core_wrapper: CoreWrapper::None,
                    vec_inner_core_wrapper: CoreWrapper::None,
                    newtype_wrapper: None,
                    serde_rename: None,
                    serde_flatten: false,
                    binding_excluded: false,
                    binding_exclusion_reason: None,
                    original_type: None,
                }],
                doc: "Soft warning diagnostic.".into(),
                is_default: false,
                serde_rename: None,
                binding_excluded: false,
                binding_exclusion_reason: None,
                is_tuple: false,
                originally_had_data_fields: false,
                cfg: None,
                version: Default::default(),
            },
        ],
        doc: "All diagnostic variants emitted by the analyzer.".into(),
        cfg: None,
        is_copy: false,
        has_serde: false,
        serde_tag: None,
        serde_untagged: false,
        serde_rename_all: None,
        binding_excluded: false,
        binding_exclusion_reason: None,
        excluded_variants: vec![],
        version: Default::default(),
    };
    let config = make_config("test_app");
    let api = ApiSurface {
        crate_name: "test-app".to_string(),
        version: "1.0.0".to_string(),
        functions: vec![],
        types: vec![],
        enums: vec![enum_def],
        errors: vec![],
        excluded_type_paths: std::collections::HashMap::new(),
        excluded_trait_names: ::std::collections::HashSet::new(),
        services: vec![],
        handler_contracts: vec![],
        unsupported_public_items: Vec::new(),
    };
    let generated = RustlerBackend.generate_public_api(&api, &config).unwrap();
    let content = find_module(&generated, "diagnostic");

    assert!(
        content.contains("All diagnostic variants emitted by the analyzer."),
        "data-enum @moduledoc body must be preserved; got:\n{content}"
    );
    assert!(
        content.contains("Hard failure diagnostic."),
        "Error variant doc must appear in @typedoc above type alias; got:\n{content}"
    );
    assert!(
        content.contains("Soft warning diagnostic."),
        "Warning variant doc must appear in @typedoc above type alias; got:\n{content}"
    );
    // The @typedoc for a variant must precede the corresponding @type alias line.
    let typedoc_idx = content.find("Hard failure diagnostic.").unwrap();
    let alias_idx = content
        .find("@type error ::")
        .or_else(|| content.find("@type :\"Error\" ::"))
        .expect("variant type alias must be present");
    assert!(
        typedoc_idx < alias_idx,
        "variant @typedoc must precede its @type alias; got:\n{content}"
    );
}