alef 0.79.2

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
use super::*;

/// `not_empty` is the one assertion that silently degrades into a no-op: a check that
/// stringifies before measuring, or that leans on the host language's truthiness, reads
/// as coverage while passing on empty data. Every emitter below must reject an empty
/// collection and an empty string, and must still accept a legitimate `0` / `0.0` / `false`.
#[cfg(test)]
mod not_empty_tests {
    use super::render;

    /// Compare emitted code by token sequence so a template's cosmetic indentation
    /// (which minijinja's whitespace control also influences) cannot mask a behaviour change.
    fn code(text: &str) -> String {
        text.split_whitespace().collect::<Vec<_>>().join(" ")
    }

    #[test]
    fn not_empty_for_python_rejects_empty_sized_values_but_accepts_zero() {
        let rendered = render(
            "python/assertion.jinja",
            minijinja::context! { assertion_type => "not_empty", field_access => "result.content" },
        );
        assert_eq!(
            rendered.trim(),
            "assert result.content is not None and (not hasattr(result.content, \"__len__\") \
             or len(result.content) > 0)"
        );
    }

    #[test]
    fn not_empty_for_php_arrays_measures_the_element_count() {
        let rendered = render(
            "php/assertion.jinja",
            minijinja::context! {
                assertion_type => "not_empty",
                field_expr => "$result->chunks",
                field_is_array => true,
            },
        );
        assert_eq!(
            rendered.trim(),
            "$this->assertGreaterThan(0, count($result->chunks ?? []), 'expected non-empty value');"
        );
    }

    #[test]
    fn not_empty_for_php_scalars_rejects_empty_string_but_accepts_zero() {
        let rendered = render(
            "php/assertion.jinja",
            minijinja::context! {
                assertion_type => "not_empty",
                field_expr => "$result->content",
                field_is_array => false,
            },
        );
        // assertNotEmpty() routes through empty(), which would reject 0, 0.0, "0" and false.
        assert!(!rendered.contains("assertNotEmpty"), "got: {rendered}");
        assert_eq!(
            rendered.trim(),
            "$this->assertNotSame('', $result->content ?? '', 'expected non-empty value');"
        );
    }

    #[test]
    fn not_empty_for_ruby_asks_the_value_not_its_string_form() {
        let rendered = render(
            "ruby/assertion.jinja",
            minijinja::context! { assertion_type => "not_empty", field_expr => "result.content" },
        );
        // `[].to_s` is "[]" — a non-empty string — so the old form could never fail.
        assert!(!rendered.contains(".to_s"), "got: {rendered}");
        assert_eq!(
            rendered.trim(),
            "expect(result.content.respond_to?(:empty?) ? !result.content.empty? : !result.content.nil?).to be(true)"
        );
    }

    #[test]
    fn not_empty_for_java_measures_collections_instead_of_their_string_form() {
        let rendered = render(
            "java/assertion.jinja",
            minijinja::context! {
                assertion_type => "not_empty",
                field_expr => "java.util.Optional.ofNullable(result.content())",
            },
        );
        assert!(!rendered.contains("toString"), "got: {rendered}");
        assert_eq!(
            code(&rendered),
            code(
                "assertTrue(java.util.Optional.ofNullable(result.content()).filter(value -> switch ((Object) value) {
                case CharSequence text -> !text.isEmpty();
                case java.util.Collection<?> items -> !items.isEmpty();
                case java.util.Map<?, ?> entries -> !entries.isEmpty();
                default -> true;
            }).isPresent(), \"expected non-empty value\");"
            )
        );
    }

    #[test]
    fn not_empty_for_java_concrete_fields_still_use_is_empty() {
        let rendered = render(
            "java/assertion.jinja",
            minijinja::context! { assertion_type => "not_empty", field_expr => "result.content()" },
        );
        assert_eq!(
            code(&rendered),
            code("assertFalse(result.content().isEmpty(), \"expected non-empty value\");")
        );
    }

    #[test]
    fn not_empty_for_csharp_pattern_matches_instead_of_stringifying() {
        let rendered = render(
            "csharp/assertion.jinja",
            minijinja::context! {
                assertion_type => "not_empty",
                field_expr => "result.Content",
                field_needs_json_serialize => false,
                skipped_reason => "",
            },
        );
        // `.ToString()` on a struct yields the type name, and the old `?.` form did not
        // compile for a non-nullable value type.
        assert!(!rendered.contains("ToString"), "got: {rendered}");
        assert_eq!(
            code(&rendered),
            code(
                "Assert.True(((object?)result.Content) switch
            {
                null => false,
                string text => text.Length > 0,
                System.Collections.ICollection items => items.Count > 0,
                _ => true,
            }, \"expected non-empty value\");"
            )
        );
    }

    #[test]
    fn not_empty_for_csharp_collections_still_use_assert_not_empty() {
        let rendered = render(
            "csharp/assertion.jinja",
            minijinja::context! {
                assertion_type => "not_empty",
                field_expr => "result.Chunks",
                field_needs_json_serialize => true,
                skipped_reason => "",
            },
        );
        assert_eq!(code(&rendered), code("Assert.NotEmpty(result.Chunks);"));
    }

    #[test]
    fn not_empty_for_zig_json_rejects_empty_array_and_empty_string() {
        let rendered = render(
            "zig/json_assertion.jinja",
            minijinja::context! { assertion_type => "not_empty", field_expr => "_content" },
        );
        // `!= .null` accepted an empty array and an empty string.
        assert!(!rendered.contains("!= .null"), "got: {rendered}");
        assert_eq!(
            code(&rendered),
            code(
                "{
                const _ne = _content;
                try testing.expect(switch (_ne) {
                    .null => false,
                    .string => |_s| _s.len > 0,
                    .array => |_a| _a.items.len > 0,
                    .object => |_o| _o.count() > 0,
                    else => true,
                });
            }"
            )
        );
    }

    #[test]
    fn not_empty_for_typescript_sizes_strings_and_arrays_and_accepts_zero() {
        let rendered = render(
            "typescript/assertion.jinja",
            minijinja::context! {
                assertion_type => "not_empty",
                field_expr => "result.content",
                field_is_optional => false,
            },
        );
        assert_eq!(
            code(&rendered),
            code(
                "{
                const _v = result.content;
                if (typeof _v === \"string\" || Array.isArray(_v)) {
                    expect(_v.length).toBeGreaterThan(0);
                } else {
                    expect(_v).toBeDefined();
                    expect(_v).not.toBeNull();
                }
            }"
            )
        );
    }
}

#[cfg(test)]
mod template_registration_tests {
    use super::TEMPLATES;
    use std::collections::HashSet;
    use std::path::Path;

    /// `go/harness_main.go.jinja` is read by its own private `minijinja::Environment` in
    /// `render_harness_main` (`src/e2e/codegen/go.rs`), via a local `include_str!` rather than
    /// through this shared `TEMPLATES` registry. That function is currently dead code — its own
    /// doc comment says the server-pattern harness is now emitted by a consumer `Extension` and
    /// alef no longer calls it, kept only pending a dead-code sweep — so the file is genuinely
    /// unreachable through `render()`, but deleting it would break `render_harness_main`'s
    /// `include_str!`, and that's an emitter-side change out of scope here. ~keep
    const ALLOWLISTED_UNREGISTERED: &[&str] = &["go/harness_main.go.jinja"];

    /// `render()` resolves names against `TEMPLATES`, not the filesystem, so a
    /// `.jinja` file added to `templates/` but never wired into this array compiles fine
    /// (`include_str!` only runs for entries that are listed) and panics only once an
    /// emitter reaches it at generation time. Compare by content rather than by
    /// registered key: some backends register a file under a shortened or aliased name,
    /// which is fine, but every file's bytes must appear in `TEMPLATES` somewhere. ~keep
    #[test]
    fn every_template_file_is_registered() {
        let templates_dir = Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/src/e2e/templates"));
        let registered_contents: HashSet<&str> = TEMPLATES.iter().map(|(_, content)| *content).collect();

        let mut unregistered = Vec::new();
        collect_unregistered(templates_dir, templates_dir, &registered_contents, &mut unregistered);
        unregistered.retain(|path| !ALLOWLISTED_UNREGISTERED.contains(&path.as_str()));
        unregistered.sort();
        assert!(
            unregistered.is_empty(),
            "found .jinja file(s) in templates/ whose content is not registered in TEMPLATES: {unregistered:?}"
        );
    }

    fn collect_unregistered(
        root: &Path,
        dir: &Path,
        registered_contents: &HashSet<&str>,
        unregistered: &mut Vec<String>,
    ) {
        for entry in std::fs::read_dir(dir).expect("read templates directory") {
            let entry = entry.expect("read templates directory entry");
            let path = entry.path();
            if path.is_dir() {
                collect_unregistered(root, &path, registered_contents, unregistered);
                continue;
            }
            if path.extension().and_then(|ext| ext.to_str()) != Some("jinja") {
                continue;
            }
            let content = std::fs::read_to_string(&path).expect("read template file");
            if !registered_contents.contains(content.as_str()) {
                let relative = path
                    .strip_prefix(root)
                    .expect("template path under templates root")
                    .to_str()
                    .expect("template path is valid UTF-8")
                    .replace('\\', "/");
                unregistered.push(relative);
            }
        }
    }
}

/// A synthetic assertion is appended to the output with a bare `push_str`, so the template
/// — not the caller — owns its line terminator. `trim_blocks` already eats the newline that
/// follows a block tag, so a branch that also closes with `{%- endif %}` renders a bare
/// fragment with no newline at either end, and whatever the next emitter writes lands on the
/// same physical line. That is harmless between two statements and destructive after a
/// comment, which swallows the statement that follows it. Observed in a downstream consumer's
/// generated PHP smoke suite, where two skip comments shared one physical line.
#[cfg(test)]
mod synthetic_assertion_line_discipline {
    use super::render;

    const KIND_KEYED_TEMPLATES: [&str; 3] = [
        "php/synthetic_assertion.jinja",
        "java/synthetic_assertion.jinja",
        "r/synthetic_assertion.jinja",
    ];

    fn skip_comment(template: &str) -> String {
        if template == "typescript/synthetic_assertion.jinja" {
            return render(
                template,
                minijinja::context! {
                    assertion_type => "unsupported_by_this_backend",
                    field_name => "metadata.format.excel.sheet_count",
                },
            );
        }
        render(
            template,
            minijinja::context! {
                assertion_kind => "skipped",
                assertion_type => "unsupported_by_this_backend",
                field_name => "metadata.format.excel.sheet_count",
            },
        )
    }

    fn every_template() -> Vec<&'static str> {
        let mut templates = KIND_KEYED_TEMPLATES.to_vec();
        templates.push("typescript/synthetic_assertion.jinja");
        templates
    }

    #[test]
    fn a_skip_comment_terminates_its_own_line() {
        for template in every_template() {
            let rendered = skip_comment(template);
            assert!(
                rendered.contains("skipped:"),
                "{template} rendered no skip comment: {rendered:?}"
            );
            assert!(
                rendered.ends_with('\n'),
                "{template} left its comment unterminated: {rendered:?}"
            );
            assert_eq!(
                rendered.matches('\n').count(),
                1,
                "{template} did not render exactly one line: {rendered:?}"
            );
        }
    }

    /// The defect is *concatenation*, so the assertion has to be made on two appended
    /// renders. Checking a single render in isolation is the vacuous version of this test:
    /// it passes whether or not the fragment can collide with its successor.
    #[test]
    fn two_appended_skip_comments_do_not_share_a_physical_line() {
        for template in every_template() {
            let mut out = String::new();
            out.push_str(&skip_comment(template));
            out.push_str(&skip_comment(template));
            assert_eq!(
                out.lines().count(),
                2,
                "{template} merged two appended assertions onto one line: {out:?}"
            );
        }
    }

    /// Positive control: the branches that emit real code must still emit it, unchanged
    /// apart from now owning their terminator.
    #[test]
    fn a_rendered_assertion_still_emits_its_statement_on_one_line() {
        let php = render(
            "php/synthetic_assertion.jinja",
            minijinja::context! {
                assertion_kind => "chunks_content",
                assertion_type => "is_true",
                pred => "$carry",
                field_name => "chunks_have_content",
            },
        );
        assert_eq!(php, "        $this->assertTrue($carry);\n");

        let java = render(
            "java/synthetic_assertion.jinja",
            minijinja::context! {
                assertion_kind => "chunks_content",
                assertion_type => "is_true",
                pred => "carry",
                field_name => "chunks_have_content",
            },
        );
        assert_eq!(java, "        assertTrue(carry, \"expected true\");\n");
    }

    /// A statement followed by a comment is the destructive ordering: without a terminator
    /// the comment starts on the statement's line, and every later emitter is commented out.
    #[test]
    fn a_comment_appended_after_a_statement_starts_its_own_line() {
        let mut out = String::new();
        out.push_str(&render(
            "php/synthetic_assertion.jinja",
            minijinja::context! {
                assertion_kind => "chunks_content",
                assertion_type => "is_true",
                pred => "$carry",
                field_name => "chunks_have_content",
            },
        ));
        out.push_str(&skip_comment("php/synthetic_assertion.jinja"));

        let lines: Vec<&str> = out.lines().collect();
        assert_eq!(lines.len(), 2, "statement and comment shared a line: {out:?}");
        assert!(!lines[0].contains("//"), "the statement was commented out: {out:?}");
        assert!(
            lines[1].trim_start().starts_with("//"),
            "unexpected second line: {out:?}"
        );
    }
}