Skip to main content

alef_backend_php/gen_bindings/
mod.rs

1mod functions;
2mod helpers;
3mod types;
4
5use crate::type_map::PhpMapper;
6use ahash::AHashSet;
7use alef_codegen::builder::RustFileBuilder;
8use alef_codegen::conversions::ConversionConfig;
9use alef_codegen::generators::RustBindingConfig;
10use alef_codegen::generators::{self, AsyncPattern};
11use alef_core::backend::{Backend, BuildConfig, Capabilities, GeneratedFile};
12use alef_core::config::{AlefConfig, Language, detect_serde_available, resolve_output_dir};
13use alef_core::ir::ApiSurface;
14use alef_core::ir::{PrimitiveType, TypeRef};
15use heck::{ToLowerCamelCase, ToPascalCase};
16use std::path::PathBuf;
17
18use functions::{gen_async_function, gen_function};
19use helpers::{
20    gen_enum_tainted_from_binding_to_core, gen_serde_bridge_from, gen_tokio_runtime, has_enum_named_field,
21    references_named_type,
22};
23use types::{gen_enum_constants, gen_opaque_struct_methods, gen_php_struct, gen_struct_methods};
24
25pub struct PhpBackend;
26
27impl PhpBackend {
28    fn binding_config(core_import: &str, has_serde: bool) -> RustBindingConfig<'_> {
29        RustBindingConfig {
30            struct_attrs: &["php_class"],
31            field_attrs: &[],
32            struct_derives: &["Clone"],
33            method_block_attr: Some("php_impl"),
34            constructor_attr: "",
35            static_attr: None,
36            function_attr: "#[php_function]",
37            enum_attrs: &[],
38            enum_derives: &[],
39            needs_signature: false,
40            signature_prefix: "",
41            signature_suffix: "",
42            core_import,
43            async_pattern: AsyncPattern::TokioBlockOn,
44            has_serde,
45            type_name_prefix: "",
46            option_duration_on_defaults: true,
47        }
48    }
49}
50
51impl Backend for PhpBackend {
52    fn name(&self) -> &str {
53        "php"
54    }
55
56    fn language(&self) -> Language {
57        Language::Php
58    }
59
60    fn capabilities(&self) -> Capabilities {
61        Capabilities {
62            supports_async: true,
63            supports_classes: true,
64            supports_enums: true,
65            supports_option: true,
66            supports_result: true,
67            ..Capabilities::default()
68        }
69    }
70
71    fn generate_bindings(&self, api: &ApiSurface, config: &AlefConfig) -> anyhow::Result<Vec<GeneratedFile>> {
72        let enum_names = api.enums.iter().map(|e| e.name.clone()).collect();
73        let mapper = PhpMapper { enum_names };
74        let core_import = config.core_import();
75
76        let output_dir = resolve_output_dir(
77            config.output.php.as_ref(),
78            &config.crate_config.name,
79            "crates/{name}-php/src/",
80        );
81        let has_serde = detect_serde_available(&output_dir);
82        let cfg = Self::binding_config(&core_import, has_serde);
83
84        // Build the inner module content (types, methods, conversions)
85        let mut builder = RustFileBuilder::new();
86        builder.add_import("ext_php_rs::prelude::*");
87
88        // Import serde_json when available (needed for serde-based param conversion)
89        if has_serde {
90            builder.add_import("serde_json");
91        }
92
93        // Import traits needed for trait method dispatch
94        for trait_path in generators::collect_trait_imports(api) {
95            builder.add_import(&trait_path);
96        }
97
98        // Only import HashMap when Map-typed fields or returns are present
99        let has_maps = api.types.iter().any(|t| {
100            t.fields
101                .iter()
102                .any(|f| matches!(&f.ty, alef_core::ir::TypeRef::Map(_, _)))
103        }) || api
104            .functions
105            .iter()
106            .any(|f| matches!(&f.return_type, alef_core::ir::TypeRef::Map(_, _)));
107        if has_maps {
108            builder.add_import("std::collections::HashMap");
109        }
110
111        // Custom module declarations
112        let custom_mods = config.custom_modules.for_language(Language::Php);
113        for module in custom_mods {
114            builder.add_item(&format!("pub mod {module};"));
115        }
116
117        // Check if any function or method is async
118        let has_async =
119            api.functions.iter().any(|f| f.is_async) || api.types.iter().any(|t| t.methods.iter().any(|m| m.is_async));
120
121        if has_async {
122            builder.add_item(&gen_tokio_runtime());
123        }
124
125        // Check if we have opaque types and add Arc import if needed
126        let opaque_types: AHashSet<String> = api
127            .types
128            .iter()
129            .filter(|t| t.is_opaque)
130            .map(|t| t.name.clone())
131            .collect();
132        if !opaque_types.is_empty() {
133            builder.add_import("std::sync::Arc");
134        }
135
136        for typ in &api.types {
137            if typ.is_opaque {
138                builder.add_item(&generators::gen_opaque_struct(typ, &cfg));
139                builder.add_item(&gen_opaque_struct_methods(typ, &mapper, &opaque_types, &core_import));
140            } else {
141                // gen_struct adds #[derive(Default)] when typ.has_default is true,
142                // so no separate Default impl is needed.
143                builder.add_item(&gen_php_struct(typ, &mapper, &cfg));
144                builder.add_item(&gen_struct_methods(
145                    typ,
146                    &mapper,
147                    has_serde,
148                    &core_import,
149                    &opaque_types,
150                ));
151            }
152        }
153
154        for enum_def in &api.enums {
155            builder.add_item(&gen_enum_constants(enum_def));
156        }
157
158        for func in &api.functions {
159            if func.is_async {
160                builder.add_item(&gen_async_function(func, &mapper, &opaque_types, &core_import));
161            } else {
162                builder.add_item(&gen_function(func, &mapper, &opaque_types, &core_import));
163            }
164        }
165
166        let convertible = alef_codegen::conversions::convertible_types(api);
167        let core_to_binding = alef_codegen::conversions::core_to_binding_convertible_types(api);
168        // From/Into conversions with PHP-specific i64 casts.
169        // Types with enum Named fields (or that reference such types transitively) can't
170        // have binding->core From impls because PHP maps enums to String and there's no
171        // From<String> for the core enum type. Core->binding is always safe.
172        let enum_names_ref = &mapper.enum_names;
173        let php_conv_config = ConversionConfig {
174            cast_large_ints_to_i64: true,
175            enum_string_names: Some(enum_names_ref),
176            json_to_string: true,
177            include_cfg_metadata: false,
178            option_duration_on_defaults: true,
179            ..Default::default()
180        };
181        // Build transitive set of types that can't have binding->core From
182        let mut enum_tainted: AHashSet<String> = AHashSet::new();
183        for typ in &api.types {
184            if has_enum_named_field(typ, enum_names_ref) {
185                enum_tainted.insert(typ.name.clone());
186            }
187        }
188        // Transitively mark types that reference enum-tainted types
189        let mut changed = true;
190        while changed {
191            changed = false;
192            for typ in &api.types {
193                if !enum_tainted.contains(&typ.name)
194                    && typ.fields.iter().any(|f| references_named_type(&f.ty, &enum_tainted))
195                {
196                    enum_tainted.insert(typ.name.clone());
197                    changed = true;
198                }
199            }
200        }
201        for typ in &api.types {
202            // binding->core: only when not enum-tainted
203            if !enum_tainted.contains(&typ.name)
204                && alef_codegen::conversions::can_generate_conversion(typ, &convertible)
205            {
206                builder.add_item(&alef_codegen::conversions::gen_from_binding_to_core_cfg(
207                    typ,
208                    &core_import,
209                    &php_conv_config,
210                ));
211            } else if enum_tainted.contains(&typ.name) && has_serde {
212                // Enum-tainted types can't use field-by-field From (no From<String> for core enum),
213                // but when serde is available we bridge via JSON serialization round-trip.
214                builder.add_item(&gen_serde_bridge_from(typ, &core_import));
215            } else if enum_tainted.contains(&typ.name) {
216                // Enum-tainted types: generate From with string->enum parsing for enum-Named
217                // fields, using first variant as fallback. Data-variant enum fields fill
218                // data fields with Default::default().
219                builder.add_item(&gen_enum_tainted_from_binding_to_core(
220                    typ,
221                    &core_import,
222                    enum_names_ref,
223                    &enum_tainted,
224                    &php_conv_config,
225                    &api.enums,
226                ));
227            }
228            // core->binding: always (enum->String via format, sanitized fields via format)
229            if alef_codegen::conversions::can_generate_conversion(typ, &core_to_binding) {
230                builder.add_item(&alef_codegen::conversions::gen_from_core_to_binding_cfg(
231                    typ,
232                    &core_import,
233                    &opaque_types,
234                    &php_conv_config,
235                ));
236            }
237        }
238
239        // Error converter functions
240        for error in &api.errors {
241            builder.add_item(&alef_codegen::error_gen::gen_php_error_converter(error, &core_import));
242        }
243
244        let _adapter_bodies = alef_adapters::build_adapter_bodies(config, Language::Php)?;
245
246        // Add feature gate as inner attribute — entire crate is gated
247        let php_config = config.php.as_ref();
248        if let Some(feature_name) = php_config.and_then(|c| c.feature_gate.as_deref()) {
249            builder.add_inner_attribute(&format!("cfg(feature = \"{feature_name}\")"));
250            builder.add_inner_attribute(&format!(
251                "cfg_attr(all(windows, target_env = \"msvc\", feature = \"{feature_name}\"), feature(abi_vectorcall))"
252            ));
253        }
254
255        // PHP module entry point — required for ext-php-rs to register the extension
256        builder.add_item("#[php_module]\npub fn get_module(module: ModuleBuilder) -> ModuleBuilder {\n    module\n}");
257
258        let content = builder.build();
259
260        Ok(vec![GeneratedFile {
261            path: PathBuf::from(&output_dir).join("lib.rs"),
262            content,
263            generated_header: false,
264        }])
265    }
266
267    fn generate_public_api(&self, api: &ApiSurface, config: &AlefConfig) -> anyhow::Result<Vec<GeneratedFile>> {
268        let extension_name = config.php_extension_name();
269        let class_name = extension_name.to_pascal_case();
270
271        // Generate PHP wrapper class
272        let mut content = String::from("<?php\n");
273        content.push_str("// This file is auto-generated by alef. DO NOT EDIT.\n");
274        content.push_str("declare(strict_types=1);\n\n");
275
276        // Determine namespace
277        let namespace = if extension_name.contains('_') {
278            let parts: Vec<&str> = extension_name.split('_').collect();
279            let ns_parts: Vec<String> = parts.iter().map(|p| p.to_pascal_case()).collect();
280            ns_parts.join("\\")
281        } else {
282            class_name.clone()
283        };
284
285        content.push_str(&format!("namespace {};\n\n", namespace));
286        content.push_str(&format!("final class {}\n", class_name));
287        content.push_str("{\n");
288
289        // Generate wrapper methods for functions
290        for func in &api.functions {
291            let method_name = func.name.to_lower_camel_case();
292            let return_php_type = php_type(&func.return_type);
293
294            // PHPDoc block
295            content.push_str("    /**\n");
296            for line in func.doc.lines() {
297                if line.is_empty() {
298                    content.push_str("     *\n");
299                } else {
300                    content.push_str(&format!("     * {}\n", line));
301                }
302            }
303            if func.doc.is_empty() {
304                content.push_str(&format!("     * {}.\n", method_name));
305            }
306            content.push_str("     *\n");
307            for p in &func.params {
308                let ptype = php_phpdoc_type(&p.ty);
309                let nullable_prefix = if p.optional { "?" } else { "" };
310                content.push_str(&format!("     * @param {}{} ${}\n", nullable_prefix, ptype, p.name));
311            }
312            let return_phpdoc = php_phpdoc_type(&func.return_type);
313            content.push_str(&format!("     * @return {}\n", return_phpdoc));
314            if func.error_type.is_some() {
315                content.push_str(&format!("     * @throws \\{}\\{}Exception\n", namespace, class_name));
316            }
317            content.push_str("     */\n");
318
319            // Method signature with type hints
320            content.push_str(&format!("    public static function {}(", method_name));
321
322            let params: Vec<String> = func
323                .params
324                .iter()
325                .map(|p| {
326                    let ptype = php_type(&p.ty);
327                    if p.optional {
328                        format!("?{} ${} = null", ptype, p.name)
329                    } else {
330                        format!("{} ${}", ptype, p.name)
331                    }
332                })
333                .collect();
334            content.push_str(&params.join(", "));
335            content.push_str(&format!("): {}\n", return_php_type));
336            content.push_str("    {\n");
337            content.push_str(&format!(
338                "        return \\{}({}); // delegate to extension function\n",
339                func.name,
340                func.params
341                    .iter()
342                    .map(|p| format!("${}", p.name))
343                    .collect::<Vec<_>>()
344                    .join(", ")
345            ));
346            content.push_str("    }\n\n");
347        }
348
349        content.push_str("}\n");
350
351        // Use PHP stubs output path if configured, otherwise fall back to packages/php/src/.
352        // This is intentionally separate from config.output.php, which controls the Rust binding
353        // crate output directory (e.g., crates/kreuzcrawl-php/src/).
354        let output_dir = config
355            .php
356            .as_ref()
357            .and_then(|p| p.stubs.as_ref())
358            .map(|s| s.output.to_string_lossy().to_string())
359            .unwrap_or_else(|| "packages/php/src/".to_string());
360
361        Ok(vec![GeneratedFile {
362            path: PathBuf::from(&output_dir).join(format!("{}.php", class_name)),
363            content,
364            generated_header: false,
365        }])
366    }
367
368    fn generate_type_stubs(&self, api: &ApiSurface, config: &AlefConfig) -> anyhow::Result<Vec<GeneratedFile>> {
369        let extension_name = config.php_extension_name();
370        let class_name = extension_name.to_pascal_case();
371
372        // Determine namespace (same logic as generate_public_api)
373        let namespace = if extension_name.contains('_') {
374            let parts: Vec<&str> = extension_name.split('_').collect();
375            let ns_parts: Vec<String> = parts.iter().map(|p| p.to_pascal_case()).collect();
376            ns_parts.join("\\")
377        } else {
378            class_name.clone()
379        };
380
381        let mut content = String::from("<?php\n");
382        content.push_str("// This file is auto-generated by alef. DO NOT EDIT.\n");
383        content.push_str("// Type stubs for the native PHP extension — declares classes\n");
384        content.push_str("// provided at runtime by the compiled Rust extension (.so/.dll).\n");
385        content.push_str("// Include this in phpstan.neon scanFiles for static analysis.\n\n");
386        content.push_str("declare(strict_types=1);\n\n");
387        // Use bracketed namespace syntax so we can add global-namespace function stubs later.
388        content.push_str(&format!("namespace {} {{\n\n", namespace));
389
390        // Exception class
391        content.push_str(&format!(
392            "class {}Exception extends \\RuntimeException\n{{\n",
393            class_name
394        ));
395        content.push_str("    public function getErrorCode(): int { }\n");
396        content.push_str("}\n\n");
397
398        // Opaque handle classes
399        for typ in &api.types {
400            if typ.is_opaque {
401                if !typ.doc.is_empty() {
402                    content.push_str("/**\n");
403                    for line in typ.doc.lines() {
404                        if line.is_empty() {
405                            content.push_str(" *\n");
406                        } else {
407                            content.push_str(&format!(" * {}\n", line));
408                        }
409                    }
410                    content.push_str(" */\n");
411                }
412                content.push_str(&format!("class {}\n{{\n", typ.name));
413                // Opaque handles have no public constructors in PHP
414                content.push_str("}\n\n");
415            }
416        }
417
418        // Record / struct types (non-opaque with fields)
419        for typ in &api.types {
420            if typ.is_opaque || typ.fields.is_empty() {
421                continue;
422            }
423            if !typ.doc.is_empty() {
424                content.push_str("/**\n");
425                for line in typ.doc.lines() {
426                    if line.is_empty() {
427                        content.push_str(" *\n");
428                    } else {
429                        content.push_str(&format!(" * {}\n", line));
430                    }
431                }
432                content.push_str(" */\n");
433            }
434            content.push_str(&format!("class {}\n{{\n", typ.name));
435
436            // Constructor with typed parameters.
437            // PHP requires required parameters to come before optional ones, so sort
438            // the fields: required first, then optional (preserving relative order within each group).
439            let mut sorted_fields: Vec<&alef_core::ir::FieldDef> = typ.fields.iter().collect();
440            sorted_fields.sort_by_key(|f| f.optional);
441
442            // Emit PHPDoc before the constructor for any array-typed fields so PHPStan
443            // understands the generic element type (e.g. `@param array<string> $items`).
444            let array_fields: Vec<&alef_core::ir::FieldDef> = sorted_fields
445                .iter()
446                .copied()
447                .filter(|f| matches!(&f.ty, TypeRef::Vec(_) | TypeRef::Map(_, _)))
448                .collect();
449            if !array_fields.is_empty() {
450                content.push_str("    /**\n");
451                for f in &array_fields {
452                    let phpdoc = php_phpdoc_type(&f.ty);
453                    let nullable_prefix = if f.optional { "?" } else { "" };
454                    content.push_str(&format!("     * @param {}{} ${}\n", nullable_prefix, phpdoc, f.name));
455                }
456                content.push_str("     */\n");
457            }
458
459            let params: Vec<String> = sorted_fields
460                .iter()
461                .map(|f| {
462                    let ptype = php_type(&f.ty);
463                    let nullable = if f.optional { format!("?{}", ptype) } else { ptype };
464                    let default = if f.optional { " = null" } else { "" };
465                    format!("        {} ${}{}", nullable, f.name, default)
466                })
467                .collect();
468            content.push_str("    public function __construct(\n");
469            content.push_str(&params.join(",\n"));
470            content.push_str("\n    ) { }\n\n");
471
472            // Getter methods for each field
473            for field in &typ.fields {
474                let is_array = matches!(&field.ty, TypeRef::Vec(_) | TypeRef::Map(_, _));
475                let return_type = if field.optional {
476                    format!("?{}", php_type(&field.ty))
477                } else {
478                    php_type(&field.ty)
479                };
480                let getter_name = field.name.to_lower_camel_case();
481                // Emit PHPDoc for array return types so PHPStan knows the element type.
482                if is_array {
483                    let phpdoc = php_phpdoc_type(&field.ty);
484                    let nullable_prefix = if field.optional { "?" } else { "" };
485                    content.push_str(&format!("    /** @return {}{} */\n", nullable_prefix, phpdoc));
486                }
487                content.push_str(&format!(
488                    "    public function get{}(): {} {{ }}\n",
489                    getter_name.to_pascal_case(),
490                    return_type
491                ));
492            }
493
494            content.push_str("}\n\n");
495        }
496
497        // Enum constants (PHP 8.1+ enums)
498        for enum_def in &api.enums {
499            content.push_str(&format!("enum {}: string\n{{\n", enum_def.name));
500            for variant in &enum_def.variants {
501                content.push_str(&format!("    case {} = '{}';\n", variant.name, variant.name));
502            }
503            content.push_str("}\n\n");
504        }
505
506        // Close the namespaced block
507        content.push_str("} // end namespace\n\n");
508
509        // Extension function stubs (global namespace).
510        // The facade class delegates to these via `\func_name(...)`.
511        content.push_str("namespace {\n\n");
512
513        for func in &api.functions {
514            let return_type = php_type_fq(&func.return_type, &namespace);
515            let return_phpdoc = php_phpdoc_type_fq(&func.return_type, &namespace);
516            content.push_str("/**\n");
517            // PHPDoc params with fully-qualified types
518            for p in &func.params {
519                let ptype = php_phpdoc_type_fq(&p.ty, &namespace);
520                let nullable_prefix = if p.optional { "?" } else { "" };
521                content.push_str(&format!(" * @param {}{} ${}\n", nullable_prefix, ptype, p.name));
522            }
523            content.push_str(&format!(" * @return {}\n */\n", return_phpdoc));
524
525            let params: Vec<String> = func
526                .params
527                .iter()
528                .map(|p| {
529                    let ptype = php_type_fq(&p.ty, &namespace);
530                    if p.optional {
531                        format!("?{} ${} = null", ptype, p.name)
532                    } else {
533                        format!("{} ${}", ptype, p.name)
534                    }
535                })
536                .collect();
537            content.push_str(&format!(
538                "function {}({}): {} {{ }}\n\n",
539                func.name,
540                params.join(", "),
541                return_type
542            ));
543        }
544
545        content.push_str("}\n");
546
547        // Use stubs output path if configured, otherwise packages/php/stubs/
548        let output_dir = config
549            .php
550            .as_ref()
551            .and_then(|p| p.stubs.as_ref())
552            .map(|s| s.output.to_string_lossy().to_string())
553            .unwrap_or_else(|| "packages/php/stubs/".to_string());
554
555        Ok(vec![GeneratedFile {
556            path: PathBuf::from(&output_dir).join(format!("{}_extension.php", extension_name)),
557            content,
558            generated_header: false,
559        }])
560    }
561
562    fn build_config(&self) -> Option<BuildConfig> {
563        Some(BuildConfig {
564            tool: "cargo",
565            crate_suffix: "-php",
566            depends_on_ffi: false,
567            post_build: vec![],
568        })
569    }
570}
571
572/// Map an IR [`TypeRef`] to a PHPDoc type string with generic parameters (e.g., `array<string>`).
573/// PHPStan at level `max` requires iterable value types in PHPDoc annotations.
574fn php_phpdoc_type(ty: &TypeRef) -> String {
575    match ty {
576        TypeRef::Vec(inner) => format!("array<{}>", php_phpdoc_type(inner)),
577        TypeRef::Map(k, v) => format!("array<{}, {}>", php_phpdoc_type(k), php_phpdoc_type(v)),
578        TypeRef::Optional(inner) => format!("?{}", php_phpdoc_type(inner)),
579        _ => php_type(ty),
580    }
581}
582
583/// Map an IR [`TypeRef`] to a fully-qualified PHPDoc type string with generics (e.g., `array<\Ns\T>`).
584fn php_phpdoc_type_fq(ty: &TypeRef, namespace: &str) -> String {
585    match ty {
586        TypeRef::Vec(inner) => format!("array<{}>", php_phpdoc_type_fq(inner, namespace)),
587        TypeRef::Map(k, v) => format!(
588            "array<{}, {}>",
589            php_phpdoc_type_fq(k, namespace),
590            php_phpdoc_type_fq(v, namespace)
591        ),
592        TypeRef::Named(name) => format!("\\{}\\{}", namespace, name),
593        TypeRef::Optional(inner) => format!("?{}", php_phpdoc_type_fq(inner, namespace)),
594        _ => php_type(ty),
595    }
596}
597
598/// Map an IR [`TypeRef`] to a fully-qualified PHP type-hint string for use outside the namespace.
599fn php_type_fq(ty: &TypeRef, namespace: &str) -> String {
600    match ty {
601        TypeRef::Named(name) => format!("\\{}\\{}", namespace, name),
602        TypeRef::Optional(inner) => {
603            let inner_type = php_type_fq(inner, namespace);
604            format!("?{}", inner_type)
605        }
606        _ => php_type(ty),
607    }
608}
609
610/// Map an IR [`TypeRef`] to a PHP type-hint string.
611fn php_type(ty: &TypeRef) -> String {
612    match ty {
613        TypeRef::String | TypeRef::Char | TypeRef::Json | TypeRef::Bytes | TypeRef::Path => "string".to_string(),
614        TypeRef::Primitive(p) => match p {
615            PrimitiveType::Bool => "bool".to_string(),
616            PrimitiveType::F32 | PrimitiveType::F64 => "float".to_string(),
617            PrimitiveType::U8
618            | PrimitiveType::U16
619            | PrimitiveType::U32
620            | PrimitiveType::U64
621            | PrimitiveType::I8
622            | PrimitiveType::I16
623            | PrimitiveType::I32
624            | PrimitiveType::I64
625            | PrimitiveType::Usize
626            | PrimitiveType::Isize => "int".to_string(),
627        },
628        TypeRef::Optional(inner) => {
629            let inner_type = php_type(inner);
630            format!("?{}", inner_type)
631        }
632        TypeRef::Vec(_) | TypeRef::Map(_, _) => "array".to_string(),
633        TypeRef::Named(name) => name.clone(),
634        TypeRef::Unit => "void".to_string(),
635        TypeRef::Duration => "float".to_string(),
636    }
637}