ext_php_rs/describe/
stub.rs

1//! Traits and implementations to convert describe units into PHP stub code.
2
3use std::{
4    cmp::Ordering,
5    collections::HashMap,
6    fmt::{Error as FmtError, Result as FmtResult, Write},
7    option::Option as StdOption,
8    vec::Vec as StdVec,
9};
10
11use super::{
12    Class, Constant, DocBlock, Function, Method, MethodType, Module, Parameter, Property,
13    Visibility,
14    abi::{Option, RString},
15};
16
17#[cfg(feature = "enum")]
18use crate::describe::{Enum, EnumCase};
19use crate::flags::{ClassFlags, DataType};
20
21/// Implemented on types which can be converted into PHP stubs.
22pub trait ToStub {
23    /// Converts the implementor into PHP code, represented as a PHP stub.
24    /// Returned as a string.
25    ///
26    /// # Returns
27    ///
28    /// Returns a string on success.
29    ///
30    /// # Errors
31    ///
32    /// Returns an error if there was an error writing into the string.
33    fn to_stub(&self) -> Result<String, FmtError> {
34        let mut buf = String::new();
35        self.fmt_stub(&mut buf)?;
36        Ok(buf)
37    }
38
39    /// Converts the implementor into PHP code, represented as a PHP stub.
40    ///
41    /// # Parameters
42    ///
43    /// * `buf` - The buffer to write the PHP code into.
44    ///
45    /// # Returns
46    ///
47    /// Returns nothing on success.
48    ///
49    /// # Errors
50    ///
51    /// Returns an error if there was an error writing into the buffer.
52    fn fmt_stub(&self, buf: &mut String) -> FmtResult;
53}
54
55impl ToStub for Module {
56    fn fmt_stub(&self, buf: &mut String) -> FmtResult {
57        writeln!(buf, "<?php")?;
58        writeln!(buf)?;
59        writeln!(buf, "// Stubs for {}", self.name.as_ref())?;
60        writeln!(buf)?;
61
62        // To account for namespaces we need to group by them. [`None`] as the key
63        // represents no namespace, while [`Some`] represents a namespace.
64        let mut entries: HashMap<StdOption<&str>, StdVec<String>> = HashMap::new();
65
66        // Inserts a value into the entries hashmap. Takes a key and an entry, creating
67        // the internal vector if it doesn't already exist.
68        let mut insert = |ns, entry| {
69            let bucket = entries.entry(ns).or_default();
70            bucket.push(entry);
71        };
72
73        for c in &*self.constants {
74            let (ns, _) = split_namespace(c.name.as_ref());
75            insert(ns, c.to_stub()?);
76        }
77
78        for func in &*self.functions {
79            let (ns, _) = split_namespace(func.name.as_ref());
80            insert(ns, func.to_stub()?);
81        }
82
83        for class in &*self.classes {
84            let (ns, _) = split_namespace(class.name.as_ref());
85            insert(ns, class.to_stub()?);
86        }
87
88        #[cfg(feature = "enum")]
89        for r#enum in &*self.enums {
90            let (ns, _) = split_namespace(r#enum.name.as_ref());
91            insert(ns, r#enum.to_stub()?);
92        }
93
94        let mut entries: StdVec<_> = entries.iter().collect();
95        entries.sort_by(|(l, _), (r, _)| match (l, r) {
96            (None, _) => Ordering::Greater,
97            (_, None) => Ordering::Less,
98            (Some(l), Some(r)) => l.cmp(r),
99        });
100
101        buf.push_str(
102            &entries
103                .into_iter()
104                .map(|(ns, entries)| {
105                    let mut buf = String::new();
106                    if let Some(ns) = ns {
107                        writeln!(buf, "namespace {ns} {{")?;
108                    } else {
109                        writeln!(buf, "namespace {{")?;
110                    }
111
112                    buf.push_str(
113                        &entries
114                            .iter()
115                            .map(|entry| indent(entry, 4))
116                            .collect::<StdVec<_>>()
117                            .join(NEW_LINE_SEPARATOR),
118                    );
119
120                    writeln!(buf, "}}")?;
121                    Ok(buf)
122                })
123                .collect::<Result<StdVec<_>, FmtError>>()?
124                .join(NEW_LINE_SEPARATOR),
125        );
126
127        Ok(())
128    }
129}
130
131impl ToStub for Function {
132    fn fmt_stub(&self, buf: &mut String) -> FmtResult {
133        self.docs.fmt_stub(buf)?;
134
135        let (_, name) = split_namespace(self.name.as_ref());
136        write!(
137            buf,
138            "function {}({})",
139            name,
140            self.params
141                .iter()
142                .map(ToStub::to_stub)
143                .collect::<Result<StdVec<_>, FmtError>>()?
144                .join(", ")
145        )?;
146
147        if let Option::Some(retval) = &self.ret {
148            write!(buf, ": ")?;
149            if retval.nullable {
150                write!(buf, "?")?;
151            }
152            retval.ty.fmt_stub(buf)?;
153        }
154
155        writeln!(buf, " {{}}")
156    }
157}
158
159impl ToStub for Parameter {
160    fn fmt_stub(&self, buf: &mut String) -> FmtResult {
161        if let Option::Some(ty) = &self.ty {
162            if self.nullable {
163                write!(buf, "?")?;
164            }
165
166            ty.fmt_stub(buf)?;
167            write!(buf, " ")?;
168        }
169
170        if self.variadic {
171            write!(buf, "...")?;
172        }
173
174        write!(buf, "${}", self.name)?;
175
176        // Add default value to stub
177        if let Option::Some(default) = &self.default {
178            write!(buf, " = {default}")?;
179        } else if self.nullable {
180            // For nullable parameters without explicit default, add = null
181            // This makes Option<T> parameters truly optional in PHP
182            write!(buf, " = null")?;
183        }
184
185        Ok(())
186    }
187}
188
189impl ToStub for DataType {
190    fn fmt_stub(&self, buf: &mut String) -> FmtResult {
191        let mut fqdn = "\\".to_owned();
192        write!(
193            buf,
194            "{}",
195            match self {
196                DataType::Bool | DataType::True | DataType::False => "bool",
197                DataType::Long => "int",
198                DataType::Double => "float",
199                DataType::String => "string",
200                DataType::Array => "array",
201                DataType::Object(Some(ty)) => {
202                    fqdn.push_str(ty);
203                    fqdn.as_str()
204                }
205                DataType::Object(None) => "object",
206                DataType::Resource => "resource",
207                DataType::Reference => "reference",
208                DataType::Callable => "callable",
209                DataType::Iterable => "iterable",
210                _ => "mixed",
211            }
212        )
213    }
214}
215
216impl ToStub for DocBlock {
217    fn fmt_stub(&self, buf: &mut String) -> FmtResult {
218        if !self.0.is_empty() {
219            writeln!(buf, "/**")?;
220            for comment in self.0.iter() {
221                writeln!(buf, " *{comment}")?;
222            }
223            writeln!(buf, " */")?;
224        }
225        Ok(())
226    }
227}
228
229impl ToStub for Class {
230    fn fmt_stub(&self, buf: &mut String) -> FmtResult {
231        fn stub<T: ToStub>(items: &[T]) -> impl Iterator<Item = Result<String, FmtError>> + '_ {
232            items
233                .iter()
234                .map(|item| item.to_stub().map(|stub| indent(&stub, 4)))
235        }
236
237        self.docs.fmt_stub(buf)?;
238
239        let (_, name) = split_namespace(self.name.as_ref());
240        let flags = ClassFlags::from_bits(self.flags).unwrap_or(ClassFlags::empty());
241        let is_interface = flags.contains(ClassFlags::Interface);
242
243        if is_interface {
244            write!(buf, "interface {name} ")?;
245        } else {
246            write!(buf, "class {name} ")?;
247        }
248
249        if let Option::Some(extends) = &self.extends {
250            write!(buf, "extends {extends} ")?;
251        }
252
253        if !self.implements.is_empty() && !is_interface {
254            write!(
255                buf,
256                "implements {} ",
257                self.implements
258                    .iter()
259                    .map(RString::as_str)
260                    .collect::<StdVec<_>>()
261                    .join(", ")
262            )?;
263        }
264
265        if !self.implements.is_empty() && is_interface {
266            write!(
267                buf,
268                "extends {} ",
269                self.implements
270                    .iter()
271                    .map(RString::as_str)
272                    .collect::<StdVec<_>>()
273                    .join(", ")
274            )?;
275        }
276
277        writeln!(buf, "{{")?;
278
279        buf.push_str(
280            &stub(&self.constants)
281                .chain(stub(&self.properties))
282                .chain(stub(&self.methods))
283                .collect::<Result<StdVec<_>, FmtError>>()?
284                .join(NEW_LINE_SEPARATOR),
285        );
286
287        writeln!(buf, "}}")
288    }
289}
290
291#[cfg(feature = "enum")]
292impl ToStub for Enum {
293    fn fmt_stub(&self, buf: &mut String) -> FmtResult {
294        self.docs.fmt_stub(buf)?;
295
296        let (_, name) = split_namespace(self.name.as_ref());
297        write!(buf, "enum {name}")?;
298
299        if let Option::Some(backing_type) = &self.backing_type {
300            write!(buf, ": {backing_type}")?;
301        }
302
303        writeln!(buf, " {{")?;
304
305        for case in self.cases.iter() {
306            case.fmt_stub(buf)?;
307        }
308
309        writeln!(buf, "}}")
310    }
311}
312
313#[cfg(feature = "enum")]
314impl ToStub for EnumCase {
315    fn fmt_stub(&self, buf: &mut String) -> FmtResult {
316        self.docs.fmt_stub(buf)?;
317
318        write!(buf, "  case {}", self.name)?;
319        if let Option::Some(value) = &self.value {
320            write!(buf, " = {value}")?;
321        }
322        writeln!(buf, ";")
323    }
324}
325
326impl ToStub for Property {
327    fn fmt_stub(&self, buf: &mut String) -> FmtResult {
328        self.docs.fmt_stub(buf)?;
329        self.vis.fmt_stub(buf)?;
330
331        write!(buf, " ")?;
332
333        if self.static_ {
334            write!(buf, "static ")?;
335        }
336        if let Option::Some(ty) = &self.ty {
337            ty.fmt_stub(buf)?;
338        }
339        write!(buf, "${}", self.name)?;
340        if let Option::Some(default) = &self.default {
341            write!(buf, " = {default}")?;
342        }
343        writeln!(buf, ";")
344    }
345}
346
347impl ToStub for Visibility {
348    fn fmt_stub(&self, buf: &mut String) -> FmtResult {
349        write!(
350            buf,
351            "{}",
352            match self {
353                Visibility::Private => "private",
354                Visibility::Protected => "protected",
355                Visibility::Public => "public",
356            }
357        )
358    }
359}
360
361impl ToStub for Method {
362    fn fmt_stub(&self, buf: &mut String) -> FmtResult {
363        self.docs.fmt_stub(buf)?;
364        self.visibility.fmt_stub(buf)?;
365
366        write!(buf, " ")?;
367
368        if matches!(self.ty, MethodType::Static) {
369            write!(buf, "static ")?;
370        }
371
372        write!(
373            buf,
374            "function {}({})",
375            self.name,
376            self.params
377                .iter()
378                .map(ToStub::to_stub)
379                .collect::<Result<StdVec<_>, FmtError>>()?
380                .join(", ")
381        )?;
382
383        if !matches!(self.ty, MethodType::Constructor)
384            && let Option::Some(retval) = &self.retval
385        {
386            write!(buf, ": ")?;
387            if retval.nullable {
388                write!(buf, "?")?;
389            }
390            retval.ty.fmt_stub(buf)?;
391        }
392
393        if self.r#abstract {
394            writeln!(buf, ";")
395        } else {
396            writeln!(buf, " {{}}")
397        }
398    }
399}
400
401impl ToStub for Constant {
402    fn fmt_stub(&self, buf: &mut String) -> FmtResult {
403        self.docs.fmt_stub(buf)?;
404
405        write!(buf, "const {} = ", self.name)?;
406        if let Option::Some(value) = &self.value {
407            write!(buf, "{value}")?;
408        } else {
409            write!(buf, "null")?;
410        }
411        writeln!(buf, ";")
412    }
413}
414
415#[cfg(windows)]
416const NEW_LINE_SEPARATOR: &str = "\r\n";
417#[cfg(not(windows))]
418const NEW_LINE_SEPARATOR: &str = "\n";
419
420/// Takes a class name and splits the namespace off from the actual class name.
421///
422/// # Returns
423///
424/// A tuple, where the first item is the namespace (or [`None`] if not
425/// namespaced), and the second item is the class name.
426fn split_namespace(class: &str) -> (StdOption<&str>, &str) {
427    let idx = class.rfind('\\');
428
429    if let Some(idx) = idx {
430        (Some(&class[0..idx]), &class[idx + 1..])
431    } else {
432        (None, class)
433    }
434}
435
436/// Indents a given string to a given depth. Depth is given in number of spaces
437/// to be appended. Returns a new string with the new indentation. Will not
438/// indent whitespace lines.
439///
440/// # Parameters
441///
442/// * `s` - The string to indent.
443/// * `depth` - The depth to indent the lines to, in spaces.
444///
445/// # Returns
446///
447/// The indented string.
448fn indent(s: &str, depth: usize) -> String {
449    let indent = format!("{:depth$}", "", depth = depth);
450
451    s.split('\n')
452        .map(|line| {
453            let mut result = String::new();
454            if line.chars().any(|c| !c.is_whitespace()) {
455                result.push_str(&indent);
456                result.push_str(line);
457            }
458            result
459        })
460        .collect::<StdVec<_>>()
461        .join(NEW_LINE_SEPARATOR)
462}
463
464#[cfg(test)]
465mod test {
466    use super::split_namespace;
467
468    #[test]
469    pub fn test_split_ns() {
470        assert_eq!(split_namespace("ext\\php\\rs"), (Some("ext\\php"), "rs"));
471        assert_eq!(split_namespace("test_solo_ns"), (None, "test_solo_ns"));
472        assert_eq!(split_namespace("simple\\ns"), (Some("simple"), "ns"));
473    }
474
475    #[test]
476    #[cfg(not(windows))]
477    #[allow(clippy::uninlined_format_args)]
478    pub fn test_indent() {
479        use super::indent;
480        use crate::describe::stub::NEW_LINE_SEPARATOR;
481
482        assert_eq!(indent("hello", 4), "    hello");
483        assert_eq!(
484            indent(&format!("hello{nl}world{nl}", nl = NEW_LINE_SEPARATOR), 4),
485            format!("    hello{nl}    world{nl}", nl = NEW_LINE_SEPARATOR)
486        );
487    }
488}