microcad_lang/syntax/module/
module_definition.rs

1// Copyright © 2024-2025 The µcad authors <info@ucad.xyz>
2// SPDX-License-Identifier: AGPL-3.0-or-later
3
4//! Module definition syntax element.
5
6use crate::{rc::*, src_ref::*, syntax::*};
7
8/// Module definition.
9#[derive(Clone, Default)]
10pub struct ModuleDefinition {
11    /// Visibility of the module.
12    pub visibility: Visibility,
13    /// Name of the module.
14    pub id: Identifier,
15    /// Module body. ('None' if external module
16    pub body: Option<Body>,
17    /// Source code reference.
18    pub src_ref: SrcRef,
19}
20
21impl ModuleDefinition {
22    /// Create a new module definition.
23    pub fn new(visibility: Visibility, id: Identifier) -> Rc<Self> {
24        Rc::new(Self {
25            visibility,
26            id,
27            ..Default::default()
28        })
29    }
30}
31
32impl SrcReferrer for ModuleDefinition {
33    fn src_ref(&self) -> SrcRef {
34        self.src_ref.clone()
35    }
36}
37
38impl TreeDisplay for ModuleDefinition {
39    fn tree_print(&self, f: &mut std::fmt::Formatter, mut depth: TreeState) -> std::fmt::Result {
40        if let Some(body) = &self.body {
41            writeln!(
42                f,
43                "{:depth$}ModuleDefinition {visibility}'{id}':",
44                "",
45                id = self.id,
46                visibility = self.visibility,
47            )?;
48            depth.indent();
49            body.tree_print(f, depth)
50        } else {
51            writeln!(
52                f,
53                "{:depth$}ModuleDefinition {visibility}'{id}' (external)",
54                "",
55                id = self.id,
56                visibility = self.visibility,
57            )
58        }
59    }
60}
61
62impl std::fmt::Display for ModuleDefinition {
63    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
64        write!(
65            f,
66            "{visibility}mod {id}",
67            id = self.id,
68            visibility = self.visibility,
69        )
70    }
71}
72
73impl std::fmt::Debug for ModuleDefinition {
74    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
75        write!(
76            f,
77            "{visibility}mod {id:?}",
78            id = self.id,
79            visibility = self.visibility,
80        )
81    }
82}