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::Derive;
7
8use super::Scalar;
9
10/// Bodies selected by an id the enclosing message has already read, as `#[derive(Dispatch)]`
11/// declares.
12#[derive(Debug, Clone, PartialEq, Eq)]
13#[non_exhaustive]
14pub struct DispatchDef {
15    /// The type name.
16    pub name: String,
17    /// The id's type: `#[dispatch(id = ..)]`.
18    pub id: Scalar,
19    /// The arms, in declaration order.
20    pub arms: Vec<DispatchArm>,
21    /// The fallback variant for an unlisted id.
22    pub other: String,
23    /// Documentation.
24    pub doc: Option<String>,
25    /// Derives for this catalogue, written after the module's.
26    pub derives: Vec<Derive>,
27}
28
29impl DispatchDef {
30    /// A dispatch with its fallback variant named `Unknown`.
31    #[must_use]
32    pub fn new(name: &str, id: Scalar, arms: Vec<DispatchArm>) -> Self {
33        Self {
34            name: String::from(name),
35            id,
36            arms,
37            other: String::from("Unknown"),
38            doc: None,
39            derives: Vec::new(),
40        }
41    }
42
43    /// Sets the derives written on this catalogue, after the module's.
44    #[must_use]
45    pub fn with_derives(self, derives: Vec<Derive>) -> Self {
46        Self { derives, ..self }
47    }
48
49    /// Renames the fallback variant.
50    #[must_use]
51    pub fn with_other(self, other: &str) -> Self {
52        Self { other: String::from(other), ..self }
53    }
54
55    /// Sets the documentation.
56    #[must_use]
57    pub fn with_doc(self, doc: &str) -> Self {
58        Self { doc: Some(String::from(doc)), ..self }
59    }
60}
61
62/// One arm of a [`DispatchDef`].
63#[derive(Debug, Clone, PartialEq, Eq)]
64#[non_exhaustive]
65pub struct DispatchArm {
66    /// The id that selects this arm.
67    pub id: i64,
68    /// The variant name.
69    pub name: String,
70    /// The body type, which implements `Layout`.
71    pub ty: String,
72    /// Documentation.
73    pub doc: Option<String>,
74}
75
76impl DispatchArm {
77    /// `#[value(id)] name(ty)`, undocumented.
78    #[must_use]
79    pub fn new(id: i64, name: &str, ty: &str) -> Self {
80        Self { id, name: String::from(name), ty: String::from(ty), doc: None }
81    }
82
83    /// Sets the documentation.
84    #[must_use]
85    pub fn with_doc(self, doc: &str) -> Self {
86        Self { doc: Some(String::from(doc)), ..self }
87    }
88}