alef 0.23.38

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
use super::helpers::{build_php_wrapper_constructor_stmt, format_php_comment, render};
use super::type_mapping::php_type_annotation;
use crate::core::ir::{ApiSurface, EntrypointKind, RegistrationDef, RegistrationVariantStyle, ServiceDef};
use heck::ToSnakeCase;
use minijinja::context;

/// Generate the idiomatic PHP service class (`service.php`).
///
/// Produces a PHP file containing one class per service. Each class exposes:
/// - A constructor mirroring [`ServiceDef::constructor`].
/// - Configurator methods from [`ServiceDef::configurators`].
/// - Registration methods from [`ServiceDef::registrations`].
/// - A `run(...)` method derived from the first [`EntrypointKind::Run`]
///   entrypoint.
pub(in crate::backends::php::gen_bindings) fn gen_service_php(api: &ApiSurface, extension_name: &str) -> String {
    let mut out = String::new();

    out.push_str("<?php\n\n");
    out.push_str("declare(strict_types=1);\n\n");

    // Emit one class per service
    for service in &api.services {
        gen_service_class(&mut out, service, api, extension_name);
    }

    out
}

fn gen_service_class(out: &mut String, service: &ServiceDef, api: &ApiSurface, extension_name: &str) {
    let class_name = &service.name;

    // Class declaration with docblock
    if !service.doc.is_empty() {
        out.push_str(&format_php_comment(&service.doc, 0));
    }
    out.push_str(&render(
        "php_service_class_start.jinja",
        context! { class_name => class_name },
    ));

    // Private registrations storage
    out.push_str("    private array $registrations = [];\n\n");

    // __construct
    {
        let ctor = &service.constructor;
        let mut ctor_params = Vec::new();
        let mut ctor_assigns = Vec::new();

        for p in &ctor.params {
            let annotation = php_type_annotation(&p.ty);
            if p.optional {
                ctor_params.push(format!("?{} ${} = null", annotation, p.name));
            } else {
                ctor_params.push(format!("{} ${}", annotation, p.name));
            }
            // Store constructor param as private property for use in run()
            ctor_assigns.push(p.name.clone());
        }

        let param_sig = ctor_params.join(", ");
        // PHP constructors cannot declare a return type — emitting `: void`
        // is a parse error. The return type is implicit.
        out.push_str(&render(
            "php_service_constructor_start.jinja",
            context! { param_sig => &param_sig },
        ));
        if !ctor.doc.is_empty() {
            out.push_str(&format_php_comment(&ctor.doc, 8));
        }

        // Store constructor args as instance properties
        for arg in &ctor_assigns {
            out.push_str(&render(
                "php_service_property_assignment.jinja",
                context! { name => arg },
            ));
        }
        out.push_str("    }\n\n");
    }

    // Configurator methods
    for method in &service.configurators {
        let mut params = Vec::new();
        for p in &method.params {
            let annotation = php_type_annotation(&p.ty);
            if p.optional {
                params.push(format!("?{} ${} = null", annotation, p.name));
            } else {
                params.push(format!("{} ${}", annotation, p.name));
            }
        }
        let param_sig = params.join(", ");
        let method_name = &method.name;
        out.push_str(&render(
            "php_service_method_start.jinja",
            context! {
                method_name => method_name,
                param_sig => &param_sig,
                return_type => "self",
            },
        ));
        if !method.doc.is_empty() {
            out.push_str(&format_php_comment(&method.doc, 8));
        }

        // Store each configurator param as instance property
        for p in &method.params {
            out.push_str(&render(
                "php_service_property_assignment.jinja",
                context! { name => &p.name },
            ));
        }
        out.push_str("        return $this;\n");
        out.push_str("    }\n\n");
    }

    // Registration methods
    for reg in &service.registrations {
        gen_registration_method(out, reg, service, api, extension_name);
    }

    // Entrypoint methods
    for ep in &service.entrypoints {
        let mut params = Vec::new();
        for p in &ep.params {
            let annotation = php_type_annotation(&p.ty);
            if p.optional {
                params.push(format!("?{} ${} = null", annotation, p.name));
            } else {
                params.push(format!("{} ${}", annotation, p.name));
            }
        }
        let param_sig = params.join(", ");
        let ep_name = &ep.method;

        match ep.kind {
            EntrypointKind::Run => {
                out.push_str(&render(
                    "php_service_method_start.jinja",
                    context! {
                        method_name => ep_name,
                        param_sig => &param_sig,
                        return_type => "void",
                    },
                ));
                if !ep.doc.is_empty() {
                    out.push_str(&format_php_comment(&ep.doc, 8));
                }

                // Build the call to the native run function
                // Convention: native fn is `{snake_service_name}_{entrypoint_name}`
                let native_fn = format!("{service_snake}_{ep_name}", service_snake = class_name.to_snake_case());
                let args = php_service_native_args(&ep.params);
                out.push_str(&render(
                    "php_service_native_call.jinja",
                    context! {
                        native_fn => &native_fn,
                        args => &args,
                    },
                ));
                out.push_str("    }\n\n");
            }
            EntrypointKind::Finalize => {
                let return_annotation = php_type_annotation(&ep.return_type);
                out.push_str(&render(
                    "php_service_method_start.jinja",
                    context! {
                        method_name => ep_name,
                        param_sig => &param_sig,
                        return_type => &return_annotation,
                    },
                ));
                if !ep.doc.is_empty() {
                    out.push_str(&format_php_comment(&ep.doc, 8));
                }

                let native_fn = format!("{service_snake}_{ep_name}", service_snake = class_name.to_snake_case());
                let args = php_service_native_args(&ep.params);
                out.push_str(&render(
                    "php_service_native_return.jinja",
                    context! {
                        native_fn => &native_fn,
                        args => &args,
                    },
                ));
                out.push_str("    }\n\n");
            }
        }
    }

    out.push_str("}\n\n");
}

fn php_service_native_args(params: &[crate::core::ir::ParamDef]) -> String {
    params
        .iter()
        .map(|p| format!("${}", p.name))
        .collect::<Vec<_>>()
        .join(", ")
}

fn gen_registration_method(
    out: &mut String,
    reg: &RegistrationDef,
    _service: &ServiceDef,
    _api: &ApiSurface,
    _extension_name: &str,
) {
    let method_name = &reg.method;

    // Build metadata param signature (excluding the callback param)
    let meta_params: Vec<String> = reg
        .metadata_params
        .iter()
        .map(|p| {
            let annotation = php_type_annotation(&p.ty);
            if p.optional {
                format!("?{} ${} = null", annotation, p.name)
            } else {
                format!("{} ${}", annotation, p.name)
            }
        })
        .collect();

    // For direct registration (non-decorator), also add the callback param
    let mut direct_params = meta_params.clone();
    direct_params.push(format!("callable ${}", reg.callback_param));

    let meta_sig = meta_params.join(", ");
    let direct_sig = direct_params.join(", ");

    // Decorator factory form: returns a closure
    out.push_str(&render(
        "php_service_method_start.jinja",
        context! {
            method_name => method_name,
            param_sig => &meta_sig,
            return_type => "callable",
        },
    ));
    if !reg.doc.is_empty() {
        out.push_str(&format_php_comment(&reg.doc, 8));
    }

    // Build the metadata tuple for storage
    let meta_tuple = if reg.metadata_params.is_empty() {
        "[]".to_owned()
    } else {
        let names: Vec<&str> = reg.metadata_params.iter().map(|p| p.name.as_str()).collect();
        format!(
            "[{}]",
            names.iter().map(|n| format!("${}", n)).collect::<Vec<_>>().join(", ")
        )
    };

    out.push_str(&render(
        "php_service_registration_factory_body.jinja",
        context! {
            callback_param => &reg.callback_param,
            method_name => method_name,
            meta_tuple => &meta_tuple,
        },
    ));
    out.push_str("    }\n\n");

    // Also expose a direct (non-decorator) variant: `register_{method_name}`
    let direct_name = format!("register_{method_name}");
    if direct_name != *method_name {
        out.push_str(&render(
            "php_service_method_start.jinja",
            context! {
                method_name => &direct_name,
                param_sig => &direct_sig,
                return_type => "self",
            },
        ));
        out.push_str(&render(
            "php_service_registration_store.jinja",
            context! {
                method_name => method_name,
                meta_tuple => &meta_tuple,
                callback_param => &reg.callback_param,
            },
        ));
        out.push_str("        return $this;\n");
        out.push_str("    }\n\n");
    }

    // Emit verb-decorator variants (e.g., $app->get(), $app->post())
    for variant in &reg.variants {
        gen_registration_variant(out, variant, reg, method_name);
    }
}

/// Emit a verb-decorator variant method(s) based on the registration style.
///
/// - `VerbDecorator`: Emit only the direct method form (e.g., `get(path, handler): App`)
/// - `Builder`: Emit only the decorator-factory form (e.g., `getDecorator(path): Closure`)
/// - `Hybrid`: Emit both direct method and decorator-factory
///
/// When the variant has a `wrapper_call`, the method constructs the wrapper
/// object and delegates to the base registration method instead of writing
/// directly to `$this->registrations[]`.
fn gen_registration_variant(
    out: &mut String,
    variant: &crate::core::ir::RegistrationVariant,
    reg: &RegistrationDef,
    base_method: &str,
) {
    let variant_name = variant.name.to_lowercase();
    let callback_param = &reg.callback_param;

    // Build the parameter list for metadata (non-callback) params
    let meta_params: Vec<String> = variant
        .signature_params
        .iter()
        .map(|p| {
            let annotation = php_type_annotation(&p.ty);
            if p.optional {
                format!("?{} ${} = null", annotation, p.name)
            } else {
                format!("{} ${}", annotation, p.name)
            }
        })
        .collect();

    // Build the full parameter list for direct method (metadata + callback)
    let mut direct_params = meta_params.clone();
    direct_params.push(format!("callable ${callback_param}"));

    let meta_sig = meta_params.join(", ");
    let direct_sig = direct_params.join(", ");

    // When the variant has a wrapper_call, the body constructs the wrapper
    // object and delegates to the base method.  Otherwise, fall back to the
    // legacy computed call_args path.
    let wrapper_stmt = build_php_wrapper_constructor_stmt(variant);

    // Compute the base registration call arguments (used when wrapper_call is absent)
    let mut call_args: Vec<String> = Vec::new();
    for base_param in &reg.metadata_params {
        if let Some(override_) = variant.overrides.iter().find(|o| o.param_name == base_param.name) {
            call_args.push(override_.value_expr.clone());
        } else if let Some(sig_param) = variant.signature_params.iter().find(|s| s.name == base_param.name) {
            call_args.push(format!("${}", sig_param.name));
        }
    }
    let call_sig = call_args.join(", ");

    // Pre-compute the method bodies to avoid multiple mutable borrows of `out`.
    let direct_body = if let Some(ref stmt) = wrapper_stmt {
        let metadata_param = &variant.wrapper_call.as_ref().unwrap().metadata_param;
        format!("        {stmt}\n        return $this->{base_method}(${metadata_param}, ${callback_param});\n")
    } else {
        let vars = call_args
            .iter()
            .filter_map(|arg| if arg.starts_with('$') { Some(arg.clone()) } else { None })
            .collect::<Vec<_>>()
            .join(", ");
        render(
            "php_service_variant_direct_body.jinja",
            context! {
                base_method => base_method,
                vars => &vars,
                callback_param => callback_param,
            },
        )
    };

    let factory_body = if let Some(ref stmt) = wrapper_stmt {
        let metadata_param = &variant.wrapper_call.as_ref().unwrap().metadata_param;
        render(
            "php_service_variant_wrapper_factory_body.jinja",
            context! {
                callback_param => callback_param,
                stmt => stmt,
                base_method => base_method,
                metadata_param => metadata_param,
            },
        )
    } else {
        render(
            "php_service_variant_factory_body.jinja",
            context! {
                callback_param => callback_param,
                base_method => base_method,
                call_sig => &call_sig,
            },
        )
    };

    match variant.style {
        RegistrationVariantStyle::VerbDecorator => {
            // Emit direct method: $app->get(path, handler): App
            out.push_str(&render(
                "php_service_method_start.jinja",
                context! {
                    method_name => &variant_name,
                    param_sig => &direct_sig,
                    return_type => "self",
                },
            ));
            if let Some(doc) = &variant.doc {
                out.push_str(&format_php_comment(doc, 8));
            }
            out.push_str(&direct_body);
            out.push_str("    }\n\n");
        }

        RegistrationVariantStyle::Builder => {
            // Emit decorator factory: $app->getDecorator(path): Closure
            let factory_name = format!("{variant_name}Decorator");
            out.push_str(&render(
                "php_service_method_start.jinja",
                context! {
                    method_name => &factory_name,
                    param_sig => &meta_sig,
                    return_type => "Closure",
                },
            ));
            if let Some(doc) = &variant.doc {
                out.push_str(&format_php_comment(doc, 8));
            }
            out.push_str(&factory_body);
            out.push_str("    }\n\n");
        }

        RegistrationVariantStyle::Hybrid => {
            // 1. Direct method: $app->get(path, handler): App
            out.push_str(&render(
                "php_service_method_start.jinja",
                context! {
                    method_name => &variant_name,
                    param_sig => &direct_sig,
                    return_type => "self",
                },
            ));
            if let Some(doc) = &variant.doc {
                out.push_str(&format_php_comment(doc, 8));
            }
            out.push_str(&direct_body);
            out.push_str("    }\n\n");

            // 2. Decorator factory: $app->getDecorator(path): Closure
            let factory_name = format!("{variant_name}Decorator");
            out.push_str(&render(
                "php_service_method_start.jinja",
                context! {
                    method_name => &factory_name,
                    param_sig => &meta_sig,
                    return_type => "Closure",
                },
            ));
            if let Some(doc) = &variant.doc {
                out.push_str(&format_php_comment(doc, 8));
            }
            out.push_str(&factory_body);
            out.push_str("    }\n\n");
        }
    }
}