Skip to main content

fic/xta_backend/xta/
types.rs

1//! Types (`Type`, parser.y:657): the prefix, the base type, array dimensions
2//! on the declarator, and struct fields.
3
4use std::fmt;
5
6use super::expr::Expr;
7use super::{joined, INDENT};
8
9keywords! {
10    /// A type prefix (`TypePrefix`, parser.y:759).
11    ///
12    /// UTAP gives a type **one** prefix slot, not a set: `urgent broadcast` is a
13    /// production of its own and is the only combination that parses. `const
14    /// urgent` is a syntax error, which is why this is an enum and not a set of
15    /// flags.
16    #[derive(Default)]
17    pub enum TypePrefix {
18        #[default]
19        None => "",
20        Urgent => "urgent",
21        Broadcast => "broadcast",
22        UrgentBroadcast => "urgent broadcast",
23        Const => "const",
24        Meta => "meta",
25    }
26}
27
28/// A base type (`Type`, parser.y:657), without its prefix.
29///
30/// Array dimensions are deliberately absent: UTAP attaches them to the
31/// *declarator*, not the type (`int a[4], b;` declares one array and one
32/// scalar), so they live on [`Declarator`] and [`DeclId`](super::decl::DeclId).
33#[derive(Debug, Clone, PartialEq)]
34pub enum Type {
35    /// A previously declared type name (`T_TYPENAME`).
36    Named(String),
37    /// `bool`.
38    Bool,
39    /// `int`.
40    Int,
41    /// `int[lo, hi]` — a bounded integer.
42    BoundedInt {
43        /// Inclusive lower bound.
44        lo: Expr,
45        /// Inclusive upper bound.
46        hi: Expr,
47    },
48    /// `double`.
49    Double,
50    /// `string`.
51    String,
52    /// `chan`.
53    Chan,
54    /// `clock`.
55    Clock,
56    /// `hybrid clock` — its own production, not a prefix plus `clock`.
57    HybridClock,
58    /// `void`.
59    Void,
60    /// `scalar[n]`.
61    Scalar(Expr),
62    /// `struct { … }`.
63    Struct(Vec<Field>),
64}
65
66impl fmt::Display for Type {
67    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68        match self {
69            Type::Named(name) => f.write_str(name),
70            Type::Bool => f.write_str("bool"),
71            Type::Int => f.write_str("int"),
72            Type::BoundedInt { lo, hi } => write!(f, "int[{lo}, {hi}]"),
73            Type::Double => f.write_str("double"),
74            Type::String => f.write_str("string"),
75            Type::Chan => f.write_str("chan"),
76            Type::Clock => f.write_str("clock"),
77            Type::HybridClock => f.write_str("hybrid clock"),
78            Type::Void => f.write_str("void"),
79            Type::Scalar(n) => write!(f, "scalar[{n}]"),
80            Type::Struct(fields) => {
81                f.write_str("struct {\n")?;
82                for field in fields {
83                    writeln!(f, "{INDENT}{field}")?;
84                }
85                f.write_str("}")
86            }
87        }
88    }
89}
90
91/// A prefixed type, as it appears in front of a declarator list.
92#[derive(Debug, Clone, PartialEq)]
93pub struct TypeExpr {
94    /// The single prefix slot.
95    pub prefix: TypePrefix,
96    /// The base type.
97    pub base: Type,
98}
99
100impl TypeExpr {
101    /// A type with no prefix.
102    pub fn plain(base: Type) -> Self {
103        TypeExpr {
104            prefix: TypePrefix::None,
105            base,
106        }
107    }
108
109    /// A `const`-prefixed type.
110    pub fn constant(base: Type) -> Self {
111        TypeExpr {
112            prefix: TypePrefix::Const,
113            base,
114        }
115    }
116}
117
118impl fmt::Display for TypeExpr {
119    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
120        if self.prefix == TypePrefix::None {
121            write!(f, "{}", self.base)
122        } else {
123            write!(f, "{} {}", self.prefix, self.base)
124        }
125    }
126}
127
128/// One array dimension (`ArrayDecl2`, parser.y:627).
129///
130/// UTAP has two distinct productions, and they mean different things: a
131/// dimension given by a size, and a dimension indexed by a type (a `scalar`
132/// set or a bounded-integer typedef).
133#[derive(Debug, Clone, PartialEq)]
134pub enum ArrayDim {
135    /// `[n]` — a dimension of the given size.
136    Size(Expr),
137    /// `[T]` — a dimension indexed by the given type.
138    IndexType(TypeExpr),
139}
140
141impl fmt::Display for ArrayDim {
142    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
143        match self {
144            ArrayDim::Size(e) => write!(f, "[{e}]"),
145            ArrayDim::IndexType(t) => write!(f, "[{t}]"),
146        }
147    }
148}
149
150/// A name with its array dimensions — UTAP's `Id ArrayDecl`, shared by
151/// typedef names (`TypeId`), struct fields (`FieldDeclId`) and parameters.
152#[derive(Debug, Clone, PartialEq)]
153pub struct Declarator {
154    /// The declared name.
155    pub name: String,
156    /// Array dimensions, outermost first; empty for a scalar.
157    pub array: Vec<ArrayDim>,
158}
159
160impl Declarator {
161    /// A scalar declarator.
162    pub fn scalar(name: impl Into<String>) -> Self {
163        Declarator {
164            name: name.into(),
165            array: Vec::new(),
166        }
167    }
168}
169
170impl fmt::Display for Declarator {
171    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
172        f.write_str(&self.name)?;
173        for dim in &self.array {
174            write!(f, "{dim}")?;
175        }
176        Ok(())
177    }
178}
179
180/// One field group of a `struct` (`FieldDecl`, parser.y:739). Fields take no
181/// initialiser.
182#[derive(Debug, Clone, PartialEq)]
183pub struct Field {
184    /// The field type.
185    pub ty: TypeExpr,
186    /// The names declared at that type.
187    pub ids: Vec<Declarator>,
188}
189
190impl fmt::Display for Field {
191    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
192        write!(f, "{} ", self.ty)?;
193        joined(f, &self.ids, ", ")?;
194        f.write_str(";")
195    }
196}
197
198#[cfg(test)]
199mod tests {
200    use crate::xta_backend::xta::*;
201
202    fn int() -> TypeExpr {
203        TypeExpr::plain(Type::Int)
204    }
205
206    #[test]
207    fn urgent_broadcast_is_one_prefix() {
208        let ty = TypeExpr {
209            prefix: TypePrefix::UrgentBroadcast,
210            base: Type::Chan,
211        };
212        assert_eq!(
213            VarDecl::single(ty, "go", None).to_string(),
214            "urgent broadcast chan go;"
215        );
216    }
217
218    #[test]
219    fn array_indexed_by_a_type() {
220        let d = VarDecl {
221            ty: int(),
222            ids: vec![DeclId {
223                decl: Declarator {
224                    name: "seat".into(),
225                    array: vec![ArrayDim::IndexType(TypeExpr::plain(Type::Named(
226                        "pid_t".into(),
227                    )))],
228                },
229                init: None,
230            }],
231        };
232        assert_eq!(d.to_string(), "int seat[pid_t];");
233    }
234
235    #[test]
236    fn bounded_int_and_scalar() {
237        assert_eq!(
238            VarDecl::single(
239                TypeExpr::plain(Type::BoundedInt {
240                    lo: Expr::Int(0),
241                    hi: Expr::ident("N")
242                }),
243                "i",
244                None
245            )
246            .to_string(),
247            "int[0, N] i;"
248        );
249        assert_eq!(
250            TypeDef {
251                ty: TypeExpr::plain(Type::Scalar(Expr::Int(3))),
252                ids: vec![Declarator::scalar("pid_t")],
253            }
254            .to_string(),
255            "typedef scalar[3] pid_t;"
256        );
257    }
258}