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    /// Documentation.
12    pub doc: Option<DocBlock>,
13    /// Visibility of the module.
14    pub visibility: Visibility,
15    /// Name of the module.
16    pub id: Identifier,
17    /// Module body. ('None' if external module
18    pub body: Option<Body>,
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.id.src_ref()
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            if let Some(doc) = &self.doc {
50                doc.tree_print(f, depth)?;
51            }
52            body.tree_print(f, depth)
53        } else {
54            writeln!(
55                f,
56                "{:depth$}ModuleDefinition {visibility}'{id}' (external)",
57                "",
58                id = self.id,
59                visibility = self.visibility,
60            )?;
61            if let Some(doc) = &self.doc {
62                doc.tree_print(f, depth)?;
63            }
64            Ok(())
65        }
66    }
67}
68
69impl std::fmt::Display for ModuleDefinition {
70    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
71        write!(
72            f,
73            "{visibility}mod {id}",
74            id = self.id,
75            visibility = self.visibility,
76        )
77    }
78}
79
80impl std::fmt::Debug for ModuleDefinition {
81    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
82        write!(
83            f,
84            "{visibility}mod {id:?}",
85            id = self.id,
86            visibility = self.visibility,
87        )
88    }
89}
90
91impl Doc for ModuleDefinition {
92    fn doc(&self) -> Option<DocBlock> {
93        self.doc.clone()
94    }
95}