alef 0.82.1

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
//! Java e2e test generator using JUnit 5.
//!
//! Generates `e2e/java/pom.xml` and language-package test classes
//! files from JSON fixtures, driven entirely by `E2eConfig` and `CallConfig`.

use crate::core::backend::GeneratedFile;
use crate::core::config::ResolvedCrateConfig;
use crate::e2e::config::E2eConfig;
use crate::e2e::escape::sanitize_filename;
use crate::e2e::fixture::{Fixture, FixtureGroup};
use anyhow::Result;
use heck::ToUpperCamelCase;
use std::path::PathBuf;

use super::E2eCodegen;
use super::java_mvnw::{MAVEN_WRAPPER_PROPERTIES, MVNW_UNIX, MVNW_WINDOWS};

/// Build the per-route `middleware` value for a java fixture.
///
/// Only CORS is route-scoped in these fixtures (compression, rate-limit, etc.
/// are server-level and wired elsewhere). Its keys are remapped
/// `allow_* -> allowed_*` so the java harness can deserialize the object
/// straight into the binding's `CorsConfig`, mirroring the python/node/ruby
/// emitters. Returns `Null` when the handler declares no CORS middleware, so
/// the harness's `middleware.cors` lookup is a missing node.
fn build_middleware_value(middleware: &Option<crate::e2e::fixture::HttpMiddleware>) -> serde_json::Value {
    let Some(cors) = middleware.as_ref().and_then(|mw| mw.cors.as_ref()) else {
        return serde_json::Value::Null;
    };
    let mut cors_map = serde_json::Map::new();
    cors_map.insert("allowed_origins".to_string(), serde_json::json!(cors.allow_origins));
    cors_map.insert("allowed_methods".to_string(), serde_json::json!(cors.allow_methods));
    cors_map.insert("allowed_headers".to_string(), serde_json::json!(cors.allow_headers));
    if !cors.expose_headers.is_empty() {
        cors_map.insert("expose_headers".to_string(), serde_json::json!(cors.expose_headers));
    }
    if let Some(max_age) = cors.max_age {
        cors_map.insert("max_age".to_string(), serde_json::json!(max_age));
    }
    if cors.allow_credentials {
        cors_map.insert("allow_credentials".to_string(), serde_json::json!(true));
    }
    serde_json::json!({ "cors": serde_json::Value::Object(cors_map) })
}

/// Java e2e code generator.
pub struct JavaCodegen;

impl E2eCodegen for JavaCodegen {
    fn generate(
        &self,
        groups: &[FixtureGroup],
        e2e_config: &E2eConfig,
        config: &ResolvedCrateConfig,
        type_defs: &[crate::core::ir::TypeDef],
        enums: &[crate::core::ir::EnumDef],
        functions: &[crate::core::ir::FunctionDef],
        errors: &[crate::core::ir::ErrorDef],
    ) -> Result<Vec<GeneratedFile>> {
        let lang = self.language_name();
        let output_base = PathBuf::from(e2e_config.effective_output()).join(lang);

        let mut files = Vec::new();

        // Resolve call config with overrides.
        //
        // The base `module` field is deliberately not read here: `src/e2e/codegen/java/snippet.rs`
        // (the actual per-fixture snippet emitter) resolves the java package from the resolved
        // call's own `overrides.java.module`, falling back to `config.java_package()` -- a
        // config-derived, always-well-formed value -- never the free-text base `module` field.
        // See `crate::e2e::validate_call_module`'s `check_java_module` doc comment for the same
        // fact from the validator side; the two must agree on what java actually consumes. ~keep
        let call = &e2e_config.call;
        let overrides = call.overrides.get(lang);
        let function_name = overrides
            .and_then(|o| o.function.as_ref())
            .cloned()
            .unwrap_or_else(|| call.function.clone());
        let class_name = overrides
            .and_then(|o| o.class.as_ref())
            .cloned()
            .unwrap_or_else(|| config.name.to_upper_camel_case());
        let result_is_simple = overrides.is_some_and(|o| o.result_is_simple);
        let result_var = call.effective_result_var();

        // Resolve package config.
        let java_pkg = e2e_config.resolve_package("java");
        let pkg_name = java_pkg
            .as_ref()
            .and_then(|p| p.name.as_ref())
            .cloned()
            .unwrap_or_else(|| config.name.clone());

        // Resolve Java package info for the dependency.
        let java_group_id = config.java_group_id();
        let binding_pkg = config.java_package();
        let pkg_version = config.resolved_version().unwrap_or_else(|| "0.1.0".to_string());

        // Prepare environment variables for Surefire configuration.
        let mut env_entries: Vec<(String, String)> = e2e_config
            .env
            .iter()
            .map(|(k, v)| (k.clone(), v.clone()))
            .collect::<Vec<_>>();
        env_entries.sort_by(|a, b| a.0.cmp(&b.0));

        // Generate pom.xml.
        // `harness_extras` deps support the alef-generated e2e harness code under
        // `e2e/{lang}/tests/` (Local dep mode). Registry mode emits the published-package
        // test_apps at `test_apps/{lang}/` whose tests only import the under-test package
        // and never need harness-specific dev deps. Injecting harness_extras here drags
        // unused native deps (e.g. upstream `io.github.tree-sitter:jtreesitter`) into
        // Maven downloads, which can break on newer Java versions that the unrelated
        // native build doesn't support yet.
        files.push(GeneratedFile {
            path: output_base.join("pom.xml"),
            content: project::render_pom_xml(
                &pkg_name,
                &java_group_id,
                &pkg_version,
                e2e_config,
                &config.ffi_lib_name(),
                &env_entries,
            ),
            generated_header: false,
        });

        // Maven wrapper: ./mvnw + mvnw.cmd + .mvn/wrapper/maven-wrapper.properties.
        // The wrapper scripts bootstrap-download maven-wrapper.jar from the URL in
        // maven-wrapper.properties on first invocation, so alef does not need to
        // emit the binary jar. The shebang on mvnw triggers 0755 chmod in the
        // file writer.
        files.push(GeneratedFile {
            path: output_base.join("mvnw"),
            content: MVNW_UNIX.to_string(),
            generated_header: false,
        });
        files.push(GeneratedFile {
            path: output_base.join("mvnw.cmd"),
            content: MVNW_WINDOWS.to_string(),
            generated_header: false,
        });
        files.push(GeneratedFile {
            path: output_base
                .join(".mvn")
                .join("wrapper")
                .join("maven-wrapper.properties"),
            content: MAVEN_WRAPPER_PROPERTIES.to_string(),
            generated_header: false,
        });

        // Check if there are HTTP fixtures that need server-pattern harness
        let has_http_fixtures = groups.iter().flat_map(|g| g.fixtures.iter()).any(|f| f.http.is_some());
        let uses_harness = has_http_fixtures && !e2e_config.harness.imports.is_empty();
        // Detect mock-server need from fixture `mock_response` or `http.expected_response`
        // shapes. Mirrors kotlin_android codegen.
        let needs_mock_server = groups
            .iter()
            .flat_map(|g| g.fixtures.iter())
            .any(|f| f.needs_mock_server());

        // Generate test files per category. Path mirrors the configured Java
        // package — `dev.myorg` becomes `dev/myorg`, etc. — so the package
        // declaration in each test file matches its filesystem location.
        let mut test_base = output_base.join("src").join("test").join("java");
        for segment in java_group_id.split('.') {
            test_base = test_base.join(segment);
        }
        let test_base = test_base.join("e2e");

        // When any fixture needs a mock server, emit MockServerListener.java
        // plus its META-INF SPI entry so JUnit Platform discovers and starts
        // the `mock-server` binary once per launcher session. Without these
        // the tests reference `mockServerUrl` but no server runs, and the
        // existing service file (if left over from a prior alef version) points
        // at a class that does not exist on the classpath.
        if needs_mock_server {
            files.push(GeneratedFile {
                path: test_base.join("MockServerListener.java"),
                content: project::render_mock_server_listener(&java_group_id),
                generated_header: true,
            });
            files.push(GeneratedFile {
                path: output_base
                    .join("src")
                    .join("test")
                    .join("resources")
                    .join("META-INF")
                    .join("services")
                    .join("org.junit.platform.launcher.LauncherSessionListener"),
                content: format!("{java_group_id}.e2e.MockServerListener\n"),
                generated_header: false,
            });
        }

        // Emit fixture JSON files to src/test/resources/fixtures/ (avoids 65KB string literal limit)
        let fixtures_resource_base = output_base.join("src").join("test").join("resources").join("fixtures");
        for group in groups {
            for fixture in &group.fixtures {
                if fixture.http.is_none() {
                    continue;
                }
                let http_data = fixture.http.as_ref().unwrap();
                let fixture_json = serde_json::json!({
                    "http": {
                        "handler": {
                            "route": &http_data.handler.route,
                            "method": &http_data.handler.method,
                            "body_schema": http_data.handler.body_schema.clone(),
                            "middleware": build_middleware_value(&http_data.handler.middleware),
                        },
                        "request": {
                            "path": &http_data.request.path,
                        },
                        "expected_response": {
                            "status_code": http_data.expected_response.status_code,
                            "body": &http_data.expected_response.body,
                            "headers": &http_data.expected_response.headers,
                        }
                    }
                });
                let fixture_json_str = serde_json::to_string(&fixture_json).unwrap_or_default();
                files.push(GeneratedFile {
                    path: fixtures_resource_base.join(format!("{}.json", fixture.id)),
                    content: fixture_json_str,
                    generated_header: false,
                });
            }
        }

        // The server-pattern `FixtureLoader.java` and `HarnessMain.java`
        // (SUT-as-server) are delegated to a consumer extension via
        // `Extension::emit_e2e`; alef no longer emits them. The shared test-file
        // `@BeforeAll`/`@AfterAll` harness-spawn seam stays generic in alef.

        // Collect all distinct sealed-union type names declared in `assert_enum_fields`
        // across all call configs for this language.  For each such type we emit a
        // `{TypeName}Display.java` helper that pattern-matches on variants from the IR;
        // projects that declare no `assert_enum_fields` get no extra helper files.
        let sealed_display_types: std::collections::BTreeSet<String> = std::iter::once(&e2e_config.call)
            .chain(e2e_config.calls.values())
            .filter_map(|c| c.overrides.get(lang))
            .flat_map(|o| o.assert_enum_fields.values().cloned())
            .collect();

        for type_name in &sealed_display_types {
            if let Some(enum_def) = enums.iter().find(|e| &e.name == type_name) {
                files.push(GeneratedFile {
                    path: test_base.join(format!("{type_name}Display.java")),
                    content: project::render_sealed_display(type_name, enum_def, type_defs, &java_group_id),
                    generated_header: true,
                });
            }
        }

        // Resolve options_type: prefer Java override, fall back to other languages' options_type.
        // This ensures that when a call declares options_type in C#/Go/Python/PHP but not Java,
        // Java e2e tests still properly deserialize json_object args via JsonUtil.fromJson().
        let options_type = overrides.and_then(|o| o.options_type.clone()).or_else(|| {
            // Inherit from non-Java language overrides (C# first, then C, Go, PHP, Python).
            for cand in ["csharp", "c", "go", "php", "python"] {
                if let Some(o) = e2e_config.call.overrides.get(cand)
                    && let Some(t) = &o.options_type
                {
                    return Some(t.clone());
                }
            }
            None
        });

        // Resolve enum_fields and nested_types from Java override config.
        static EMPTY_ENUM_FIELDS: std::sync::LazyLock<std::collections::HashMap<String, String>> =
            std::sync::LazyLock::new(std::collections::HashMap::new);
        let _enum_fields = overrides.map(|o| &o.enum_fields).unwrap_or(&EMPTY_ENUM_FIELDS);

        // Build effective nested_types from configured overrides (empty by default).
        let mut effective_nested_types: std::collections::HashMap<String, String> = std::collections::HashMap::new();
        if let Some(overrides_map) = overrides.map(|o| &o.nested_types) {
            effective_nested_types.extend(overrides_map.clone());
        }

        // Resolve nested_types_optional from override (defaults to true for backward compatibility).
        let nested_types_optional = overrides.map(|o| o.nested_types_optional).unwrap_or(true);

        for group in groups {
            let active: Vec<&Fixture> = group
                .fixtures
                .iter()
                .filter(|f| super::should_include_fixture(f, lang, e2e_config))
                .collect();

            if active.is_empty() {
                continue;
            }

            let class_file_name = format!("{}Test.java", sanitize_filename(&group.category).to_upper_camel_case());
            let content = test_file::render_test_file(
                &group.category,
                &active,
                &class_name,
                &function_name,
                &java_group_id,
                &binding_pkg,
                result_var,
                &e2e_config.call.args,
                options_type.as_deref(),
                result_is_simple,
                e2e_config,
                &effective_nested_types,
                nested_types_optional,
                &config.adapters,
                config,
                type_defs,
                enums,
                functions,
                errors,
                uses_harness,
            );
            files.push(GeneratedFile {
                path: test_base.join(class_file_name),
                content,
                generated_header: true,
            });
        }

        Ok(files)
    }

    fn render_snippet_body(
        &self,
        fixture: &Fixture,
        e2e_config: &E2eConfig,
        config: &ResolvedCrateConfig,
        type_defs: &[crate::core::ir::TypeDef],
        _enums: &[crate::core::ir::EnumDef],
    ) -> Result<String> {
        Ok(snippet::render_snippet_body(fixture, e2e_config, config, type_defs))
    }

    fn render_snippet_body_with_functions(
        &self,
        fixture: &Fixture,
        e2e_config: &E2eConfig,
        config: &ResolvedCrateConfig,
        type_defs: &[crate::core::ir::TypeDef],
        enums: &[crate::core::ir::EnumDef],
        functions: &[crate::core::ir::FunctionDef],
        _errors: &[crate::core::ir::ErrorDef],
    ) -> Result<String> {
        Ok(snippet::render_snippet_body_with_ir(
            fixture, e2e_config, config, type_defs, enums, functions,
        ))
    }

    fn language_name(&self) -> &'static str {
        "java"
    }
}

mod args;
mod assertion_wildcard;
mod assertions;
mod enum_lowering;
mod field_shape;
mod http;
mod payload_union_gate;
mod project;
mod snippet;
mod stubs;
mod test_file;
mod test_method;
mod values;
mod visitor;

pub use stubs::emit_test_backend;

#[cfg(test)]
mod assertion_enum_field_classification_tests;
#[cfg(test)]
mod assertion_indentation_layout_tests;
#[cfg(test)]
mod assertion_object_shape_tests;
#[cfg(test)]
mod assertion_union_enum_field_classification_tests;
#[cfg(test)]
mod assertion_wildcard_element_tests;
#[cfg(test)]
mod enum_field_classification_tests;
#[cfg(test)]
mod enum_return_type_tests;
#[cfg(test)]
mod loop_binding_tests;
#[cfg(test)]
mod not_error_bare_option_tests;
#[cfg(test)]
mod optional_collection_default_agreement_tests;
#[cfg(test)]
mod payload_union_family_tests;
#[cfg(test)]
mod sealed_display_wire_name_tests;
#[cfg(test)]
mod super_trait_stub_lifecycle_tests;
#[cfg(test)]
mod tests;
#[cfg(test)]
mod void_not_error_call_tests;