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    abi::{Option, RString},
13    Class, Constant, DocBlock, Function, Method, MethodType, Module, Parameter, Property,
14    Visibility,
15};
16
17#[cfg(feature = "enum")]
18use crate::describe::{Enum, EnumCase};
19use crate::flags::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}
177
178impl ToStub for DataType {
179    fn fmt_stub(&self, buf: &mut String) -> FmtResult {
180        let mut fqdn = "\\".to_owned();
181        write!(
182            buf,
183            "{}",
184            match self {
185                DataType::Bool | DataType::True | DataType::False => "bool",
186                DataType::Long => "int",
187                DataType::Double => "float",
188                DataType::String => "string",
189                DataType::Array => "array",
190                DataType::Object(Some(ty)) => {
191                    fqdn.push_str(ty);
192                    fqdn.as_str()
193                }
194                DataType::Object(None) => "object",
195                DataType::Resource => "resource",
196                DataType::Reference => "reference",
197                DataType::Callable => "callable",
198                DataType::Iterable => "iterable",
199                _ => "mixed",
200            }
201        )
202    }
203}
204
205impl ToStub for DocBlock {
206    fn fmt_stub(&self, buf: &mut String) -> FmtResult {
207        if !self.0.is_empty() {
208            writeln!(buf, "/**")?;
209            for comment in self.0.iter() {
210                writeln!(buf, " *{comment}")?;
211            }
212            writeln!(buf, " */")?;
213        }
214        Ok(())
215    }
216}
217
218impl ToStub for Class {
219    fn fmt_stub(&self, buf: &mut String) -> FmtResult {
220        fn stub<T: ToStub>(items: &[T]) -> impl Iterator<Item = Result<String, FmtError>> + '_ {
221            items
222                .iter()
223                .map(|item| item.to_stub().map(|stub| indent(&stub, 4)))
224        }
225
226        self.docs.fmt_stub(buf)?;
227
228        let (_, name) = split_namespace(self.name.as_ref());
229        write!(buf, "class {name} ")?;
230
231        if let Option::Some(extends) = &self.extends {
232            write!(buf, "extends {extends} ")?;
233        }
234
235        if !self.implements.is_empty() {
236            write!(
237                buf,
238                "implements {} ",
239                self.implements
240                    .iter()
241                    .map(RString::as_str)
242                    .collect::<StdVec<_>>()
243                    .join(", ")
244            )?;
245        }
246
247        writeln!(buf, "{{")?;
248
249        buf.push_str(
250            &stub(&self.constants)
251                .chain(stub(&self.properties))
252                .chain(stub(&self.methods))
253                .collect::<Result<StdVec<_>, FmtError>>()?
254                .join(NEW_LINE_SEPARATOR),
255        );
256
257        writeln!(buf, "}}")
258    }
259}
260
261#[cfg(feature = "enum")]
262impl ToStub for Enum {
263    fn fmt_stub(&self, buf: &mut String) -> FmtResult {
264        self.docs.fmt_stub(buf)?;
265
266        let (_, name) = split_namespace(self.name.as_ref());
267        write!(buf, "enum {name}")?;
268
269        if let Option::Some(backing_type) = &self.backing_type {
270            write!(buf, ": {backing_type}")?;
271        }
272
273        writeln!(buf, " {{")?;
274
275        for case in self.cases.iter() {
276            case.fmt_stub(buf)?;
277        }
278
279        writeln!(buf, "}}")
280    }
281}
282
283#[cfg(feature = "enum")]
284impl ToStub for EnumCase {
285    fn fmt_stub(&self, buf: &mut String) -> FmtResult {
286        self.docs.fmt_stub(buf)?;
287
288        write!(buf, "  case {}", self.name)?;
289        if let Option::Some(value) = &self.value {
290            write!(buf, " = {value}")?;
291        }
292        writeln!(buf, ";")
293    }
294}
295
296impl ToStub for Property {
297    fn fmt_stub(&self, buf: &mut String) -> FmtResult {
298        self.docs.fmt_stub(buf)?;
299        self.vis.fmt_stub(buf)?;
300
301        write!(buf, " ")?;
302
303        if self.static_ {
304            write!(buf, "static ")?;
305        }
306        if let Option::Some(ty) = &self.ty {
307            ty.fmt_stub(buf)?;
308        }
309        write!(buf, "${}", self.name)?;
310        if let Option::Some(default) = &self.default {
311            write!(buf, " = {default}")?;
312        }
313        writeln!(buf, ";")
314    }
315}
316
317impl ToStub for Visibility {
318    fn fmt_stub(&self, buf: &mut String) -> FmtResult {
319        write!(
320            buf,
321            "{}",
322            match self {
323                Visibility::Private => "private",
324                Visibility::Protected => "protected",
325                Visibility::Public => "public",
326            }
327        )
328    }
329}
330
331impl ToStub for Method {
332    fn fmt_stub(&self, buf: &mut String) -> FmtResult {
333        self.docs.fmt_stub(buf)?;
334        self.visibility.fmt_stub(buf)?;
335
336        write!(buf, " ")?;
337
338        if matches!(self.ty, MethodType::Static) {
339            write!(buf, "static ")?;
340        }
341
342        write!(
343            buf,
344            "function {}({})",
345            self.name,
346            self.params
347                .iter()
348                .map(ToStub::to_stub)
349                .collect::<Result<StdVec<_>, FmtError>>()?
350                .join(", ")
351        )?;
352
353        if !matches!(self.ty, MethodType::Constructor) {
354            if let Option::Some(retval) = &self.retval {
355                write!(buf, ": ")?;
356                if retval.nullable {
357                    write!(buf, "?")?;
358                }
359                retval.ty.fmt_stub(buf)?;
360            }
361        }
362
363        writeln!(buf, " {{}}")
364    }
365}
366
367impl ToStub for Constant {
368    fn fmt_stub(&self, buf: &mut String) -> FmtResult {
369        self.docs.fmt_stub(buf)?;
370
371        write!(buf, "const {} = ", self.name)?;
372        if let Option::Some(value) = &self.value {
373            write!(buf, "{value}")?;
374        } else {
375            write!(buf, "null")?;
376        }
377        writeln!(buf, ";")
378    }
379}
380
381#[cfg(windows)]
382const NEW_LINE_SEPARATOR: &str = "\r\n";
383#[cfg(not(windows))]
384const NEW_LINE_SEPARATOR: &str = "\n";
385
386/// Takes a class name and splits the namespace off from the actual class name.
387///
388/// # Returns
389///
390/// A tuple, where the first item is the namespace (or [`None`] if not
391/// namespaced), and the second item is the class name.
392fn split_namespace(class: &str) -> (StdOption<&str>, &str) {
393    let idx = class.rfind('\\');
394
395    if let Some(idx) = idx {
396        (Some(&class[0..idx]), &class[idx + 1..])
397    } else {
398        (None, class)
399    }
400}
401
402/// Indents a given string to a given depth. Depth is given in number of spaces
403/// to be appended. Returns a new string with the new indentation. Will not
404/// indent whitespace lines.
405///
406/// # Parameters
407///
408/// * `s` - The string to indent.
409/// * `depth` - The depth to indent the lines to, in spaces.
410///
411/// # Returns
412///
413/// The indented string.
414fn indent(s: &str, depth: usize) -> String {
415    let indent = format!("{:depth$}", "", depth = depth);
416
417    s.split('\n')
418        .map(|line| {
419            let mut result = String::new();
420            if line.chars().any(|c| !c.is_whitespace()) {
421                result.push_str(&indent);
422                result.push_str(line);
423            }
424            result
425        })
426        .collect::<StdVec<_>>()
427        .join(NEW_LINE_SEPARATOR)
428}
429
430#[cfg(test)]
431mod test {
432    use super::split_namespace;
433
434    #[test]
435    pub fn test_split_ns() {
436        assert_eq!(split_namespace("ext\\php\\rs"), (Some("ext\\php"), "rs"));
437        assert_eq!(split_namespace("test_solo_ns"), (None, "test_solo_ns"));
438        assert_eq!(split_namespace("simple\\ns"), (Some("simple"), "ns"));
439    }
440
441    #[test]
442    #[cfg(not(windows))]
443    #[allow(clippy::uninlined_format_args)]
444    pub fn test_indent() {
445        use super::indent;
446        use crate::describe::stub::NEW_LINE_SEPARATOR;
447
448        assert_eq!(indent("hello", 4), "    hello");
449        assert_eq!(
450            indent(&format!("hello{nl}world{nl}", nl = NEW_LINE_SEPARATOR), 4),
451            format!("    hello{nl}    world{nl}", nl = NEW_LINE_SEPARATOR)
452        );
453    }
454}