microcad_lang/syntax/
assignment.rs

1// Copyright © 2024-2025 The µcad authors <info@ucad.xyz>
2// SPDX-License-Identifier: AGPL-3.0-or-later
3
4//! µcad assignment syntax element
5
6use crate::{src_ref::*, syntax::*, ty::*};
7
8/// Assignment specifying an identifier, type and value
9#[derive(Clone, Debug)]
10pub struct Assignment {
11    /// Value's visibility
12    pub visibility: Visibility,
13    /// Assignee qualifier
14    pub qualifier: Qualifier,
15    /// Assignee
16    pub id: Identifier,
17    /// Type of the assignee
18    pub specified_type: Option<TypeAnnotation>,
19    /// Value to assign
20    pub expression: Expression,
21    /// Source code reference
22    pub src_ref: SrcRef,
23}
24
25impl SrcReferrer for Assignment {
26    fn src_ref(&self) -> SrcRef {
27        self.src_ref.clone()
28    }
29}
30
31impl std::fmt::Display for Assignment {
32    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
33        match &self.specified_type {
34            Some(t) => write!(
35                f,
36                "{vis}{qual}{id}: {ty} = {expr}",
37                vis = match self.visibility {
38                    Visibility::Private => "",
39                    Visibility::Public => "pub ",
40                },
41                qual = match self.qualifier {
42                    Qualifier::Value => "",
43                    Qualifier::Const => "const ",
44                    Qualifier::Prop => "prop ",
45                },
46                id = self.id,
47                ty = t.ty(),
48                expr = self.expression
49            ),
50            None => write!(f, "{} = {}", self.id, self.expression),
51        }
52    }
53}
54
55impl TreeDisplay for Assignment {
56    fn tree_print(&self, f: &mut std::fmt::Formatter, mut depth: TreeState) -> std::fmt::Result {
57        writeln!(f, "{:depth$}Assignment {}:", "", self.id)?;
58        depth.indent();
59        if let Some(specified_type) = &self.specified_type {
60            specified_type.tree_print(f, depth)?;
61        }
62        self.expression.tree_print(f, depth)
63    }
64}