Skip to main content

layline_codegen/model/
dispatch.rs

1//! Dispatches: bodies selected by an id the enclosing message has already read.
2
3use alloc::string::String;
4use alloc::vec::Vec;
5
6use super::Scalar;
7
8/// Bodies selected by an id the enclosing message has already read, as `#[derive(Dispatch)]`
9/// declares.
10#[derive(Debug, Clone, PartialEq, Eq)]
11#[non_exhaustive]
12pub struct DispatchDef {
13    /// The type name.
14    pub name: String,
15    /// The id's type: `#[dispatch(id = ..)]`.
16    pub id: Scalar,
17    /// The arms, in declaration order.
18    pub arms: Vec<DispatchArm>,
19    /// The fallback variant for an unlisted id.
20    pub other: String,
21    /// Documentation.
22    pub doc: Option<String>,
23}
24
25impl DispatchDef {
26    /// A dispatch with its fallback variant named `Unknown`.
27    #[must_use]
28    pub fn new(name: &str, id: Scalar, arms: Vec<DispatchArm>) -> Self {
29        Self { name: String::from(name), id, arms, other: String::from("Unknown"), doc: None }
30    }
31
32    /// Renames the fallback variant.
33    #[must_use]
34    pub fn with_other(self, other: &str) -> Self {
35        Self { other: String::from(other), ..self }
36    }
37
38    /// Sets the documentation.
39    #[must_use]
40    pub fn with_doc(self, doc: &str) -> Self {
41        Self { doc: Some(String::from(doc)), ..self }
42    }
43}
44
45/// One arm of a [`DispatchDef`].
46#[derive(Debug, Clone, PartialEq, Eq)]
47#[non_exhaustive]
48pub struct DispatchArm {
49    /// The id that selects this arm.
50    pub id: i64,
51    /// The variant name.
52    pub name: String,
53    /// The body type, which implements `Layout`.
54    pub ty: String,
55    /// Documentation.
56    pub doc: Option<String>,
57}
58
59impl DispatchArm {
60    /// `#[value(id)] name(ty)`, undocumented.
61    #[must_use]
62    pub fn new(id: i64, name: &str, ty: &str) -> Self {
63        Self { id, name: String::from(name), ty: String::from(ty), doc: None }
64    }
65
66    /// Sets the documentation.
67    #[must_use]
68    pub fn with_doc(self, doc: &str) -> Self {
69        Self { doc: Some(String::from(doc)), ..self }
70    }
71}