Skip to main content

fic/xta_backend/xta/
decl.rs

1//! Declarations (`Declaration`, parser.y:494 onwards): variables, typedefs,
2//! functions, externs, instantiations, channel priorities, dynamic templates,
3//! and the three scopes that admit them.
4
5use std::fmt;
6
7use super::expr::Expr;
8use super::stmt::{write_body, Stmt};
9use super::types::{Declarator, TypeExpr};
10use super::{joined, write_comment, INDENT};
11
12/// One declared name of a [`VarDecl`] (`DeclId`, parser.y:593).
13#[derive(Debug, Clone, PartialEq)]
14pub struct DeclId {
15    /// The name and its array dimensions.
16    pub decl: Declarator,
17    /// The initialiser, when the declaration gives one.
18    pub init: Option<Initializer>,
19}
20
21impl DeclId {
22    /// A scalar name with no initialiser.
23    pub fn scalar(name: impl Into<String>) -> Self {
24        DeclId {
25            decl: Declarator::scalar(name),
26            init: None,
27        }
28    }
29
30    /// A scalar name initialised to `value`.
31    pub fn initialised(name: impl Into<String>, value: Expr) -> Self {
32        DeclId {
33            decl: Declarator::scalar(name),
34            init: Some(Initializer::Expr(value)),
35        }
36    }
37}
38
39impl fmt::Display for DeclId {
40    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
41        write!(f, "{}", self.decl)?;
42        match &self.init {
43            Some(init) => write!(f, " = {init}"),
44            None => Ok(()),
45        }
46    }
47}
48
49/// A variable initialiser (`Initializer`, parser.y:606).
50#[derive(Debug, Clone, PartialEq)]
51pub enum Initializer {
52    /// A scalar initialiser.
53    Expr(Expr),
54    /// A brace-enclosed list, for arrays and structs.
55    List(Vec<FieldInit>),
56}
57
58impl fmt::Display for Initializer {
59    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
60        match self {
61            Initializer::Expr(e) => write!(f, "{e}"),
62            Initializer::List(items) => {
63                f.write_str("{ ")?;
64                joined(f, items, ", ")?;
65                f.write_str(" }")
66            }
67        }
68    }
69}
70
71/// One element of a brace initialiser (`FieldInit`, parser.y:618), optionally
72/// labelled with the field it initialises.
73#[derive(Debug, Clone, PartialEq)]
74pub struct FieldInit {
75    /// The field name, when the initialiser is labelled.
76    pub name: Option<String>,
77    /// The value.
78    pub value: Initializer,
79}
80
81impl fmt::Display for FieldInit {
82    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83        match &self.name {
84            Some(name) => write!(f, "{name}: {}", self.value),
85            None => write!(f, "{}", self.value),
86        }
87    }
88}
89
90/// A variable declaration (`VariableDecl`, parser.y:581): one type, one or
91/// more declared names.
92#[derive(Debug, Clone, PartialEq)]
93pub struct VarDecl {
94    /// The declared type.
95    pub ty: TypeExpr,
96    /// The names declared at that type.
97    pub ids: Vec<DeclId>,
98}
99
100impl VarDecl {
101    /// A single scalar variable, with an optional initialiser.
102    pub fn single(ty: TypeExpr, name: impl Into<String>, init: Option<Expr>) -> Self {
103        let decl = Declarator::scalar(name);
104        VarDecl {
105            ty,
106            ids: vec![DeclId {
107                decl,
108                init: init.map(Initializer::Expr),
109            }],
110        }
111    }
112}
113
114impl fmt::Display for VarDecl {
115    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
116        write!(f, "{} ", self.ty)?;
117        joined(f, &self.ids, ", ")?;
118        f.write_str(";")
119    }
120}
121
122/// A type declaration (`TypeDecl`, parser.y:637): `typedef T a, b[4];`.
123#[derive(Debug, Clone, PartialEq)]
124pub struct TypeDef {
125    /// The type being named.
126    pub ty: TypeExpr,
127    /// The names introduced for it.
128    pub ids: Vec<Declarator>,
129}
130
131impl fmt::Display for TypeDef {
132    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
133        write!(f, "typedef {} ", self.ty)?;
134        joined(f, &self.ids, ", ")?;
135        f.write_str(";")
136    }
137}
138
139/// A function parameter (`Parameter`, parser.y:572).
140#[derive(Debug, Clone, PartialEq)]
141pub struct Param {
142    /// The parameter type.
143    pub ty: TypeExpr,
144    /// Passed by reference (`&`).
145    pub by_ref: bool,
146    /// The name and its array dimensions.
147    pub decl: Declarator,
148}
149
150impl Param {
151    /// A by-value scalar parameter.
152    pub fn value(ty: TypeExpr, name: impl Into<String>) -> Self {
153        Param {
154            ty,
155            by_ref: false,
156            decl: Declarator::scalar(name),
157        }
158    }
159}
160
161impl fmt::Display for Param {
162    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
163        if self.by_ref {
164            write!(f, "{} &{}", self.ty, self.decl)
165        } else {
166            write!(f, "{} {}", self.ty, self.decl)
167        }
168    }
169}
170
171/// A function declaration (`FunctionDecl`, parser.y:516).
172#[derive(Debug, Clone, PartialEq)]
173pub struct FnDecl {
174    /// Return type; [`Type::Void`](super::types::Type::Void) for a procedure.
175    pub ret: TypeExpr,
176    /// The function name.
177    pub name: String,
178    /// Parameters, in order.
179    pub params: Vec<Param>,
180    /// Block-local declarations, which UTAP requires before the first
181    /// statement.
182    pub body_vars: Vec<BlockLocalDecl>,
183    /// The body.
184    pub body: Vec<Stmt>,
185}
186
187impl fmt::Display for FnDecl {
188    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
189        write!(f, "{} {}(", self.ret, self.name)?;
190        joined(f, &self.params, ", ")?;
191        f.write_str(") {\n")?;
192        write_body(f, &self.body_vars, &self.body, 1)?;
193        f.write_str("}")
194    }
195}
196
197/// An external-library declaration (`ExternDecl`, parser.y:537):
198/// `import "lib" { … };`.
199#[derive(Debug, Clone, PartialEq)]
200pub struct ExternDecl {
201    /// The library path, printed quoted.
202    pub library: String,
203    /// The forward declarations it provides.
204    pub decls: Vec<FwdDecl>,
205}
206
207impl fmt::Display for ExternDecl {
208    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
209        writeln!(f, "import \"{}\" {{", self.library)?;
210        for decl in &self.decls {
211            writeln!(f, "{INDENT}{decl};")?;
212        }
213        f.write_str("};")
214    }
215}
216
217/// One forward declaration of an [`ExternDecl`] (`FwdDecl`, parser.y:551).
218#[derive(Debug, Clone, PartialEq)]
219pub struct FwdDecl {
220    /// The UPPAAL-side name, when it differs from the library symbol.
221    pub alias: Option<String>,
222    /// Return type.
223    pub ret: TypeExpr,
224    /// The library symbol.
225    pub name: String,
226    /// Parameters, in order.
227    pub params: Vec<Param>,
228}
229
230impl fmt::Display for FwdDecl {
231    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
232        if let Some(alias) = &self.alias {
233            write!(f, "{alias} = ")?;
234        }
235        write!(f, "{} {}(", self.ret, self.name)?;
236        joined(f, &self.params, ", ")?;
237        f.write_str(")")
238    }
239}
240
241/// A template instantiation (`Instantiation`, parser.y:368):
242/// `p = P(args);`, or a parameterised `p(int i) = P(i);`.
243#[derive(Debug, Clone, PartialEq)]
244pub struct Instantiation {
245    /// The instance name.
246    pub name: String,
247    /// Parameters of the instance itself; usually empty.
248    pub params: Vec<Param>,
249    /// The template being instantiated.
250    pub template: String,
251    /// Arguments passed to it.
252    pub args: Vec<Expr>,
253}
254
255impl fmt::Display for Instantiation {
256    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
257        write!(f, "{}", self.name)?;
258        if !self.params.is_empty() {
259            f.write_str("(")?;
260            joined(f, &self.params, ", ")?;
261            f.write_str(")")?;
262        }
263        write!(f, " = {}(", self.template)?;
264        joined(f, &self.args, ", ")?;
265        f.write_str(");")
266    }
267}
268
269/// A channel-priority declaration (`PriorityDecl`, parser.y:396):
270/// `chan priority a, b < c < default;`.
271///
272/// Each element of `levels` is one comma-separated group of equal priority;
273/// the groups themselves are separated by `<`, in increasing order.
274#[derive(Debug, Clone, PartialEq)]
275pub struct ChanPriority {
276    /// Priority levels, lowest first.
277    pub levels: Vec<Vec<ChanElement>>,
278}
279
280impl fmt::Display for ChanPriority {
281    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
282        f.write_str("chan priority ")?;
283        for (i, level) in self.levels.iter().enumerate() {
284            if i > 0 {
285                f.write_str(" < ")?;
286            }
287            joined(f, level, ", ")?;
288        }
289        f.write_str(";")
290    }
291}
292
293/// One element of a [`ChanPriority`] list (`ChanElement`, parser.y:407).
294///
295/// Not an [`Expr`]: UTAP uses `<` as the list separator, so an element is an
296/// identifier with array indices and nothing more.
297#[derive(Debug, Clone, PartialEq)]
298pub enum ChanElement {
299    /// The `default` placeholder — where unlisted channels sit.
300    Default,
301    /// A channel, possibly indexed.
302    Chan {
303        /// The channel name.
304        name: String,
305        /// Array indices applied to it.
306        index: Vec<Expr>,
307    },
308}
309
310impl fmt::Display for ChanElement {
311    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
312        match self {
313            ChanElement::Default => f.write_str("default"),
314            ChanElement::Chan { name, index } => {
315                f.write_str(name)?;
316                for i in index {
317                    write!(f, "[{i}]")?;
318                }
319                Ok(())
320            }
321        }
322    }
323}
324
325/// A dynamic-template declaration (`DynamicDeclaration`, parser.y:509).
326#[derive(Debug, Clone, PartialEq)]
327pub struct DynamicDecl {
328    /// The template name.
329    pub name: String,
330    /// Its parameters.
331    pub params: Vec<Param>,
332}
333
334impl fmt::Display for DynamicDecl {
335    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
336        write!(f, "dynamic {}(", self.name)?;
337        joined(f, &self.params, ", ")?;
338        f.write_str(");")
339    }
340}
341
342// ── The three scopes ─────────────────────────────────────────────────────────
343/// A global declaration — one element of UTAP's `Declarations` list
344/// (parser.y:494), which is order-free and interleavable.
345#[derive(Debug, Clone, PartialEq)]
346pub enum GlobalDecl {
347    /// A variable declaration.
348    Var(VarDecl),
349    /// A typedef.
350    Type(TypeDef),
351    /// A function.
352    Fn(FnDecl),
353    /// An `import "lib" { … };` block.
354    Extern(ExternDecl),
355    /// `before_update { … }`.
356    BeforeUpdate(Vec<Expr>),
357    /// `after_update { … }`.
358    AfterUpdate(Vec<Expr>),
359    /// A template instantiation.
360    Instantiation(Instantiation),
361    /// A channel-priority declaration.
362    ChanPriority(ChanPriority),
363    /// A dynamic-template declaration.
364    Dynamic(DynamicDecl),
365    /// A comment line, printed as `// text`.
366    Comment(String),
367}
368
369impl fmt::Display for GlobalDecl {
370    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
371        match self {
372            GlobalDecl::Var(d) => write!(f, "{d}"),
373            GlobalDecl::Type(d) => write!(f, "{d}"),
374            GlobalDecl::Fn(d) => write!(f, "{d}"),
375            GlobalDecl::Extern(d) => write!(f, "{d}"),
376            GlobalDecl::BeforeUpdate(es) => update_block(f, "before_update", es),
377            GlobalDecl::AfterUpdate(es) => update_block(f, "after_update", es),
378            GlobalDecl::Instantiation(d) => write!(f, "{d}"),
379            GlobalDecl::ChanPriority(d) => write!(f, "{d}"),
380            GlobalDecl::Dynamic(d) => write!(f, "{d}"),
381            GlobalDecl::Comment(text) => write_comment(f, text),
382        }
383    }
384}
385
386/// `before_update { … }` / `after_update { … }`.
387fn update_block(f: &mut fmt::Formatter<'_>, keyword: &str, exprs: &[Expr]) -> fmt::Result {
388    write!(f, "{keyword} {{ ")?;
389    joined(f, exprs, ", ")?;
390    f.write_str(" }")
391}
392
393/// A template-local declaration — one element of `ProcLocalDeclList`
394/// (parser.y:786).
395///
396/// UTAP admits only these three forms inside a template, and they must all
397/// precede the template's locations. No instantiation, no `import`, no
398/// `chan priority`, no nested template.
399#[derive(Debug, Clone, PartialEq)]
400pub enum ProcLocalDecl {
401    /// A variable declaration.
402    Var(VarDecl),
403    /// A typedef.
404    Type(TypeDef),
405    /// A function.
406    Fn(FnDecl),
407    /// A comment line, printed as `// text`.
408    Comment(String),
409}
410
411impl fmt::Display for ProcLocalDecl {
412    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
413        match self {
414            ProcLocalDecl::Var(d) => write!(f, "{d}"),
415            ProcLocalDecl::Type(d) => write!(f, "{d}"),
416            ProcLocalDecl::Fn(d) => write!(f, "{d}"),
417            ProcLocalDecl::Comment(text) => write_comment(f, text),
418        }
419    }
420}
421
422/// A block-local declaration — one element of `BlockLocalDeclList`
423/// (parser.y:1008), at the head of a function body or nested block.
424///
425/// Functions cannot nest, which is why there is no `Fn` variant here.
426#[derive(Debug, Clone, PartialEq)]
427pub enum BlockLocalDecl {
428    /// A variable declaration.
429    Var(VarDecl),
430    /// A typedef.
431    Type(TypeDef),
432}
433
434impl fmt::Display for BlockLocalDecl {
435    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
436        match self {
437            BlockLocalDecl::Var(d) => write!(f, "{d}"),
438            BlockLocalDecl::Type(d) => write!(f, "{d}"),
439        }
440    }
441}
442
443#[cfg(test)]
444mod tests {
445    use crate::xta_backend::xta::*;
446
447    fn int() -> TypeExpr {
448        TypeExpr::plain(Type::Int)
449    }
450
451    #[test]
452    fn const_int_variable() {
453        let d = GlobalDecl::Var(VarDecl::single(
454            TypeExpr::constant(Type::Int),
455            "ROUNDS",
456            Some(Expr::Int(5)),
457        ));
458        assert_eq!(d.to_string(), "const int ROUNDS = 5;");
459    }
460
461    #[test]
462    fn channel_declaration() {
463        let d = GlobalDecl::Var(VarDecl::single(TypeExpr::plain(Type::Chan), "ball", None));
464        assert_eq!(d.to_string(), "chan ball;");
465    }
466
467    #[test]
468    fn several_names_share_one_type() {
469        let d = VarDecl {
470            ty: int(),
471            ids: vec![
472                DeclId {
473                    decl: Declarator {
474                        name: "a".into(),
475                        array: vec![ArrayDim::Size(Expr::Int(4))],
476                    },
477                    init: None,
478                },
479                DeclId::initialised("b", Expr::Int(0)),
480            ],
481        };
482        // The array dimension belongs to the declarator, not the type: `a` is
483        // an array and `b` is not.
484        assert_eq!(d.to_string(), "int a[4], b = 0;");
485    }
486
487    #[test]
488    fn struct_typedef_prints_its_fields() {
489        let d = TypeDef {
490            ty: TypeExpr::plain(Type::Struct(vec![Field {
491                ty: int(),
492                ids: vec![Declarator::scalar("x"), Declarator::scalar("y")],
493            }])),
494            ids: vec![Declarator::scalar("point")],
495        };
496        assert_eq!(d.to_string(), "typedef struct {\n    int x, y;\n} point;");
497    }
498
499    #[test]
500    fn brace_initialiser_labels_its_fields() {
501        let init = Initializer::List(vec![
502            FieldInit {
503                name: Some("x".into()),
504                value: Initializer::Expr(Expr::Int(1)),
505            },
506            FieldInit {
507                name: None,
508                value: Initializer::Expr(Expr::Int(2)),
509            },
510        ]);
511        let d = VarDecl {
512            ty: TypeExpr::plain(Type::Named("point".into())),
513            ids: vec![DeclId {
514                decl: Declarator::scalar("p"),
515                init: Some(init),
516            }],
517        };
518        assert_eq!(d.to_string(), "point p = { x: 1, 2 };");
519    }
520
521    #[test]
522    fn function_with_assert_and_return() {
523        let d = ProcLocalDecl::Fn(FnDecl {
524            ret: int(),
525            name: "io_tally".into(),
526            params: vec![Param::value(int(), "r")],
527            body_vars: Vec::new(),
528            body: vec![
529                Stmt::Assert(Expr::binary(BinOp::Le, Expr::Int(0), Expr::ident("r"))),
530                Stmt::Return(Some(Expr::binary(
531                    BinOp::Add,
532                    Expr::ident("r"),
533                    Expr::Int(1),
534                ))),
535            ],
536        });
537        assert_eq!(
538            d.to_string(),
539            "int io_tally(int r) {\n    assert((0) <= (r));\n    return (r) + (1);\n}"
540        );
541    }
542
543    #[test]
544    fn void_function_with_no_parameters() {
545        let d = FnDecl {
546            ret: TypeExpr::plain(Type::Void),
547            name: "tally".into(),
548            params: Vec::new(),
549            body_vars: Vec::new(),
550            body: vec![Stmt::Expr(Expr::assign(
551                Expr::ident("rounds"),
552                AssignOp::Assign,
553                Expr::binary(BinOp::Add, Expr::ident("rounds"), Expr::Int(1)),
554            ))],
555        };
556        assert_eq!(
557            d.to_string(),
558            "void tally() {\n    rounds = (rounds) + (1);\n}"
559        );
560    }
561
562    #[test]
563    fn by_reference_parameter_and_block_locals() {
564        let d = FnDecl {
565            ret: TypeExpr::plain(Type::Void),
566            name: "swap".into(),
567            params: vec![Param {
568                ty: int(),
569                by_ref: true,
570                decl: Declarator::scalar("a"),
571            }],
572            body_vars: vec![BlockLocalDecl::Var(VarDecl::single(
573                int(),
574                "t",
575                Some(Expr::Int(0)),
576            ))],
577            body: vec![Stmt::Expr(Expr::assign(
578                Expr::ident("a"),
579                AssignOp::Assign,
580                Expr::ident("t"),
581            ))],
582        };
583        assert_eq!(
584            d.to_string(),
585            "void swap(int &a) {\n    int t = 0;\n    a = t;\n}"
586        );
587    }
588
589    #[test]
590    fn comments_print_as_lines() {
591        assert_eq!(
592            GlobalDecl::Comment("TODO: buffered chan `ball` not yet translated".into()).to_string(),
593            "// TODO: buffered chan `ball` not yet translated"
594        );
595        // The continuation lines of a traceability block keep their own
596        // leading spaces inside the comment text.
597        assert_eq!(
598            Stmt::Comment("  requires 0 <= r".into()).to_string(),
599            "//   requires 0 <= r"
600        );
601    }
602
603    #[test]
604    fn instantiation_and_system_forms() {
605        let d = GlobalDecl::Instantiation(Instantiation {
606            name: "ping".into(),
607            params: Vec::new(),
608            template: "Ping".into(),
609            args: Vec::new(),
610        });
611        assert_eq!(d.to_string(), "ping = Ping();");
612    }
613
614    #[test]
615    fn chan_priority_levels_and_default() {
616        let d = ChanPriority {
617            levels: vec![
618                vec![
619                    ChanElement::Chan {
620                        name: "a".into(),
621                        index: Vec::new(),
622                    },
623                    ChanElement::Chan {
624                        name: "b".into(),
625                        index: vec![Expr::Int(0)],
626                    },
627                ],
628                vec![ChanElement::Default],
629            ],
630        };
631        assert_eq!(d.to_string(), "chan priority a, b[0] < default;");
632    }
633
634    #[test]
635    fn extern_block_and_dynamic() {
636        let d = ExternDecl {
637            library: "libm".into(),
638            decls: vec![FwdDecl {
639                alias: Some("root".into()),
640                ret: TypeExpr::plain(Type::Double),
641                name: "sqrt".into(),
642                params: vec![Param::value(TypeExpr::plain(Type::Double), "x")],
643            }],
644        };
645        assert_eq!(
646            d.to_string(),
647            "import \"libm\" {\n    root = double sqrt(double x);\n};"
648        );
649        assert_eq!(
650            DynamicDecl {
651                name: "Train".into(),
652                params: vec![Param::value(int(), "id")],
653            }
654            .to_string(),
655            "dynamic Train(int id);"
656        );
657    }
658}