simploxide_bindgen/
commands.rs

1//! Turns COMMANDS.md file into na Iterator of [`crate::commands::CommandResponse`].
2
3use convert_case::{Case, Casing as _};
4
5use crate::{
6    parse_utils,
7    types::{
8        DiscriminatedUnionType, Field, RecordType, TopLevelDocs,
9        discriminated_union_type::DiscriminatedUnionVariant,
10    },
11};
12
13pub fn parse(commands_md: &str) -> impl Iterator<Item = Result<CommandResponse, String>> {
14    let mut parser = Parser::default();
15
16    commands_md
17        .split("---")
18        .skip(1)
19        .filter_map(|s| {
20            let trimmed = s.trim();
21            (!trimmed.is_empty()).then_some(trimmed)
22        })
23        .map(move |blk| parser.parse_block(blk))
24}
25
26pub struct CommandResponse {
27    pub command: RecordType,
28    pub response: DiscriminatedUnionType,
29}
30
31/// Generates the provided trait method for the ClientApi trait.
32///
33/// The ClientApi trait definition itself must be generated by the client and should look like this
34///
35/// ```ignore
36/// pub trait ClientApi {
37///     type Error;
38///
39///     fn send_raw(&self, command: String) -> impl Future<Output = Result<Arc<{}>, Self::Error>> + Send;
40///
41///     //..
42/// }
43/// ```
44///
45/// Then the provided methods could be inserted.
46///
47/// For methods that return multiple kinds a valid responses the additional wrapper type should be
48/// generated. You can get this type definition using the
49/// [`CommandResponseTraitMethod::response_wrapper`] method.
50pub struct CommandResponseTraitMethod<'a> {
51    pub command: &'a RecordType,
52    pub response: &'a DiscriminatedUnionType,
53    pub shapes: &'a [RecordType],
54}
55
56impl<'a> CommandResponseTraitMethod<'a> {
57    pub fn new(
58        command: &'a RecordType,
59        response: &'a DiscriminatedUnionType,
60        shapes: &'a [RecordType],
61    ) -> Self {
62        Self {
63            command,
64            response,
65            shapes,
66        }
67    }
68}
69
70impl<'a> CommandResponseTraitMethod<'a> {
71    /// If some method has multiple valid responses a helper type representing valid response
72    /// variants must be generated.
73    ///
74    /// If only one possible valid response is possible it can get inlined without extra helper
75    /// types and for this case this method returns `None`.
76    pub fn response_wrapper(&self) -> Option<ResponseWrapperFmt> {
77        if self.can_inline_response().is_some() {
78            return None;
79        }
80
81        Some(ResponseWrapperFmt(DiscriminatedUnionType::new(
82            self.response_wrapper_name(),
83            self.valid_responses()
84                .cloned()
85                .zip(self.valid_response_shapes())
86                .map(|(mut resp, shape)| {
87                    if shape.fields.len() == 1 {
88                        resp.fields[0] = Field {
89                            api_name: String::new(),
90                            rust_name: String::new(),
91                            typ: shape.fields[0].typ.clone(),
92                        }
93                    }
94
95                    resp
96                })
97                .collect(),
98        )))
99    }
100
101    /// Instead of accepting a command type directly we can accept its arguments and construct it
102    /// internally.
103    ///
104    /// ```ignore
105    ///     fn api_show_my_address(cmd: ApiShowMyAddressCommand) -> ...
106    /// ```
107    ///
108    /// turns into
109    ///
110    /// ```ignore
111    ///     fn api_show_my_address(user_id: i64) -> ... {
112    ///         let cmd = ApiShowMyAddressCommand { user_id };
113    ///     }
114    /// ```
115    ///
116    /// This condition determines when such transformation takes place
117    fn can_inline_args(&self) -> bool {
118        !self
119            .command
120            .fields
121            .iter()
122            .any(|f| f.is_optional() || f.is_bool())
123    }
124
125    /// If response consists only of a single valid variant this variant's inner struct can be
126    /// used directly as a return value of the API method.
127    fn can_inline_response(&self) -> Option<&DiscriminatedUnionVariant> {
128        if self.valid_responses().count() == 1 {
129            self.valid_responses().next()
130        } else {
131            None
132        }
133    }
134
135    /// If underlying struct of the response contains only a single documented field this field can be directly
136    /// returned instead of returning the whole response struct.
137    fn can_inline_response_shape(&self) -> Option<&Field> {
138        if self.valid_response_shapes().count() != 1 {
139            return None;
140        }
141
142        let shape = self.valid_response_shapes().next().unwrap();
143
144        if shape.fields.len() == 1 {
145            Some(&shape.fields[0])
146        } else {
147            None
148        }
149    }
150
151    fn valid_responses(&self) -> impl Iterator<Item = &'_ DiscriminatedUnionVariant> {
152        self.response
153            .variants
154            .iter()
155            .filter(|x| x.rust_name != "ChatCmdError")
156    }
157
158    fn valid_response_shapes(&self) -> impl Iterator<Item = &'_ RecordType> {
159        self.shapes.iter().filter(|x| x.name != "ChatCmdError")
160    }
161
162    fn response_wrapper_name(&self) -> String {
163        format!("{}s", self.response.name)
164    }
165}
166
167impl<'a> std::fmt::Display for CommandResponseTraitMethod<'a> {
168    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
169        self.command.write_docs_fmt(f)?;
170        write!(f, "    fn {}(&self", self.command.name.to_case(Case::Snake))?;
171
172        let (ret_type, unwrapped_response_typename) =
173            if let Some(inlined_variant) = self.can_inline_response() {
174                let typename = if let Some(field) = self.can_inline_response_shape() {
175                    field.typ.clone()
176                } else {
177                    inlined_variant.fields[0].typ.clone()
178                };
179
180                (format!("Arc<{typename}>"), typename)
181            } else {
182                let typename = self.response_wrapper_name();
183                (typename.clone(), typename)
184            };
185
186        if self.can_inline_args() {
187            for field in self.command.fields.iter() {
188                write!(f, ", {}: {}", field.rust_name, field.typ)?;
189            }
190
191            writeln!(
192                f,
193                ") -> impl Future<Output = Result<{ret_type}, Self::Error>> + Send {{ async move {{",
194            )?;
195            write!(f, "        let command = {} {{", self.command.name)?;
196
197            for (ix, field) in self.command.fields.iter().enumerate() {
198                if ix > 0 {
199                    write!(f, ", ")?;
200                }
201
202                write!(f, "{}", field.rust_name)?;
203            }
204            writeln!(f, "}};")?;
205        } else {
206            writeln!(
207                f,
208                ", command: {}) -> impl Future<Output = Result<{ret_type}, Self::Error>> + Send {{ async move {{",
209                self.command.name,
210            )?;
211        }
212
213        writeln!(
214            f,
215            "        let json = self.send_raw(command.interpret()).await?;"
216        )?;
217        writeln!(
218            f,
219            "        // Safe to unwrap because unrecognized JSON goes to undocumented variant"
220        )?;
221        writeln!(
222            f,
223            "        let response = serde_json::from_value(json).unwrap();"
224        )?;
225        writeln!(f, "        match response {{")?;
226
227        if let Some(variant) = self.can_inline_response() {
228            if let Some(field) = self.can_inline_response_shape() {
229                writeln!(
230                    f,
231                    "            {}::{}(resp) => Ok(Arc::new(resp.{})),",
232                    self.response.name, variant.rust_name, field.rust_name,
233                )?;
234            } else {
235                writeln!(
236                    f,
237                    "            {}::{}(resp) => Ok(Arc::new(resp)),",
238                    self.response.name, variant.rust_name
239                )?;
240            }
241        } else {
242            for (variant, shape) in self.valid_responses().zip(self.valid_response_shapes()) {
243                if shape.fields.len() == 1 {
244                    writeln!(
245                        f,
246                        "            {resp_name}::{var_name}(resp) => Ok({typename}::{var_name}(Arc::new(resp.{field}))),",
247                        resp_name = self.response.name,
248                        typename = unwrapped_response_typename,
249                        var_name = variant.rust_name,
250                        field = shape.fields[0].rust_name,
251                    )?;
252                } else {
253                    writeln!(
254                        f,
255                        "            {}::{var_name}(resp) => Ok({}::{var_name}(Arc::new(resp))),",
256                        self.response.name,
257                        unwrapped_response_typename,
258                        var_name = variant.rust_name,
259                    )?;
260                }
261            }
262        }
263
264        writeln!(
265            f,
266            "            {}::ChatCmdError(resp) => Err(BadResponseError::ChatCmdError(Arc::new(resp.chat_error)).into()),",
267            self.response.name,
268        )?;
269        writeln!(
270            f,
271            "            {}::Undocumented(resp) => Err(BadResponseError::Undocumented(resp).into()),",
272            self.response.name,
273        )?;
274        writeln!(f, "        }}")?;
275
276        writeln!(f, "    }}")?;
277        writeln!(f, "    }}")
278    }
279}
280
281/// Use this formatter for command types instead of the standard std::fmt::Display impl of the
282/// [`RecordType`]. This impl strips down all serialization attributes and undocumented fields.
283pub struct CommandFmt<'a>(pub &'a RecordType);
284
285impl std::fmt::Display for CommandFmt<'_> {
286    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
287        self.0.write_docs_fmt(f)?;
288
289        writeln!(f, "#[derive(Debug, Clone, PartialEq)]")?;
290        writeln!(f, "#[cfg_attr(feature = \"bon\", derive(::bon::Builder))]")?;
291
292        writeln!(f, "pub struct {} {{", self.0.name)?;
293
294        for field in self.0.fields.iter() {
295            writeln!(f, "    pub {}: {},", field.rust_name, field.typ)?;
296        }
297
298        writeln!(f, "}}")
299    }
300}
301
302pub struct ResponseWrapperFmt(pub DiscriminatedUnionType);
303
304impl std::fmt::Display for ResponseWrapperFmt {
305    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
306        writeln!(
307            f,
308            "#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]"
309        )?;
310        writeln!(f, "#[serde(tag = \"type\")]")?;
311        writeln!(f, "pub enum {} {{", self.0.name)?;
312
313        for variant in &self.0.variants {
314            for comment_line in &variant.doc_comments {
315                writeln!(f, "    /// {}", comment_line)?;
316            }
317            writeln!(f, "    #[serde(rename = \"{}\")]", variant.api_name)?;
318            writeln!(
319                f,
320                "    {}(Arc<{}>),",
321                variant.rust_name, variant.fields[0].typ
322            )?;
323        }
324        writeln!(f, "}}\n")?;
325
326        // Gen helper getters
327        writeln!(f, "impl {} {{", self.0.name)?;
328
329        for var in self.0.variants.iter() {
330            assert_eq!(var.fields.len(), 1, "Discriminated union is not disjointed");
331            assert!(
332                var.fields[0].rust_name.is_empty(),
333                "Discriminated union is not disjointed"
334            );
335
336            writeln!(
337                f,
338                "    pub fn {}(&self) -> Option<&{}> {{",
339                var.rust_name.to_case(Case::Snake),
340                var.fields[0].typ
341            )?;
342
343            writeln!(f, "        if let Self::{}(ret) = self {{", var.rust_name)?;
344            writeln!(f, "            Some(ret)",)?;
345            writeln!(f, "        }} else {{ None }}",)?;
346            writeln!(f, "    }}\n")?;
347        }
348
349        writeln!(f, "}}")
350    }
351}
352
353#[derive(Default)]
354struct Parser {
355    current_doc_section: Option<DocSection>,
356}
357
358impl Parser {
359    pub fn parse_block(&mut self, block: &str) -> Result<CommandResponse, String> {
360        self.parser(block.lines().map(str::trim))
361            .map_err(|e| format!("{e} in block\n```\n{block}\n```"))
362    }
363
364    fn parser<'a>(
365        &mut self,
366        mut lines: impl Iterator<Item = &'a str>,
367    ) -> Result<CommandResponse, String> {
368        const DOC_SECTION_PAT: &str = parse_utils::H2;
369        const TYPENAME_PAT: &str = parse_utils::H3;
370        const TYPEKINDS_PAT: &str = parse_utils::BOLD;
371
372        let mut next =
373            parse_utils::skip_empty(&mut lines).ok_or_else(|| "Got an empty block".to_owned())?;
374
375        let mut command_docs: Vec<String> = Vec::new();
376
377        let (typename, mut typekind) = loop {
378            if let Some(section_name) = next.strip_prefix(DOC_SECTION_PAT) {
379                let mut doc_section = DocSection::new(section_name.to_owned());
380
381                next = parse_utils::parse_doc_lines(&mut lines, &mut doc_section.contents, |s| {
382                    s.starts_with(TYPENAME_PAT)
383                })
384                .ok_or_else(|| format!("Failed to find a typename by pattern {TYPENAME_PAT:?} after the doc section"))?;
385
386                self.current_doc_section.replace(doc_section);
387            } else if let Some(name) = next.strip_prefix(TYPENAME_PAT) {
388                next = parse_utils::parse_doc_lines(&mut lines, &mut command_docs, |s| {
389                    s.starts_with(TYPEKINDS_PAT)
390                })
391                .map(|s| s.strip_prefix(TYPEKINDS_PAT).unwrap())
392                .ok_or_else(|| format!("Failed to find a typekind by pattern {TYPEKINDS_PAT:?} after the inner docs "))?;
393
394                break (name, next);
395            }
396        };
397
398        let command_name = typename.to_case(Case::Pascal);
399        let mut command = RecordType::new(command_name.clone(), vec![]);
400
401        loop {
402            if typekind.starts_with("Parameters") {
403                typekind = parse_utils::parse_record_fields(
404                    &mut lines,
405                    &mut command.fields,
406                    |s| s.starts_with(TYPEKINDS_PAT),
407                )?
408                .map(|s| s.strip_prefix(TYPEKINDS_PAT).unwrap())
409                .ok_or_else(|| format!(
410                    "Failed to find a command syntax after parameters by pattern {TYPENAME_PAT:?}"
411                ))?;
412            } else if typekind.starts_with("Syntax") {
413                parse_utils::parse_syntax(&mut lines, &mut command.syntax)?;
414                break;
415            }
416        }
417
418        let mut response_variants: Vec<DiscriminatedUnionVariant> = Vec::with_capacity(4);
419
420        parse_utils::skip_while(&mut lines, |s| !s.starts_with("**Response")).ok_or_else(|| {
421            "Failed to find responses section by pattern \"**Response\"".to_owned()
422        })?;
423
424        let mut variant_docline = Vec::new();
425
426        while let Some(docline) = parse_utils::skip_empty(&mut lines) {
427            if docline.starts_with(TYPEKINDS_PAT) {
428                break;
429            } else {
430                variant_docline.push(docline.to_owned());
431            }
432
433            let (mut variant, next) = parse_utils::parse_discriminated_union_variant(&mut lines)?;
434            assert!(next.map(|s| s.is_empty()).unwrap_or(true));
435            variant.doc_comments = std::mem::take(&mut variant_docline);
436            response_variants.push(variant);
437        }
438
439        let response =
440            DiscriminatedUnionType::new(format!("{command_name}Response"), response_variants);
441
442        if let Some(ref outer_docs) = self.current_doc_section {
443            command
444                .doc_comments
445                .push(format!("### {}", outer_docs.header.clone()));
446
447            command.doc_comments.push(String::new());
448
449            command
450                .doc_comments
451                .extend(outer_docs.contents.iter().cloned());
452
453            command.doc_comments.push(String::new());
454            command.doc_comments.push("----".to_owned());
455            command.doc_comments.push(String::new());
456        }
457
458        command.doc_comments.extend(command_docs);
459        Ok(CommandResponse { command, response })
460    }
461}
462
463#[derive(Default, Clone)]
464struct DocSection {
465    header: String,
466    contents: Vec<String>,
467}
468
469impl DocSection {
470    fn new(header: String) -> Self {
471        Self {
472            header,
473            contents: Vec::new(),
474        }
475    }
476}