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 let mut builder = RustFileBuilder::new();
86 builder.add_import("ext_php_rs::prelude::*");
87
88 if has_serde {
90 builder.add_import("serde_json");
91 }
92
93 for trait_path in generators::collect_trait_imports(api) {
95 builder.add_import(&trait_path);
96 }
97
98 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 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 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 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 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 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 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 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 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 builder.add_item(&gen_serde_bridge_from(typ, &core_import));
215 } else if enum_tainted.contains(&typ.name) {
216 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 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 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 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 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 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 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 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 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 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(¶ms.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 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 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 content.push_str(&format!("namespace {} {{\n\n", namespace));
389
390 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 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 content.push_str("}\n\n");
415 }
416 }
417
418 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 let mut sorted_fields: Vec<&alef_core::ir::FieldDef> = typ.fields.iter().collect();
440 sorted_fields.sort_by_key(|f| f.optional);
441
442 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(¶ms.join(",\n"));
470 content.push_str("\n ) { }\n\n");
471
472 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 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 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 content.push_str("} // end namespace\n\n");
508
509 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 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 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
572fn 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
583fn 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
598fn 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
610fn 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}