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    /// Source code reference.
20    pub src_ref: SrcRef,
21}
22
23impl ModuleDefinition {
24    /// Create a new module definition.
25    pub fn new(visibility: Visibility, id: Identifier) -> Rc<Self> {
26        Rc::new(Self {
27            visibility,
28            id,
29            ..Default::default()
30        })
31    }
32}
33
34impl SrcReferrer for ModuleDefinition {
35    fn src_ref(&self) -> SrcRef {
36        self.src_ref.clone()
37    }
38}
39
40impl TreeDisplay for ModuleDefinition {
41    fn tree_print(&self, f: &mut std::fmt::Formatter, mut depth: TreeState) -> std::fmt::Result {
42        if let Some(body) = &self.body {
43            writeln!(
44                f,
45                "{:depth$}ModuleDefinition {visibility}'{id}':",
46                "",
47                id = self.id,
48                visibility = self.visibility,
49            )?;
50            depth.indent();
51            if let Some(doc) = &self.doc {
52                doc.tree_print(f, depth)?;
53            }
54            body.tree_print(f, depth)
55        } else {
56            writeln!(
57                f,
58                "{:depth$}ModuleDefinition {visibility}'{id}' (external)",
59                "",
60                id = self.id,
61                visibility = self.visibility,
62            )?;
63            if let Some(doc) = &self.doc {
64                doc.tree_print(f, depth)?;
65            }
66            Ok(())
67        }
68    }
69}
70
71impl std::fmt::Display for ModuleDefinition {
72    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
73        write!(
74            f,
75            "{visibility}mod {id}",
76            id = self.id,
77            visibility = self.visibility,
78        )
79    }
80}
81
82impl std::fmt::Debug for ModuleDefinition {
83    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
84        write!(
85            f,
86            "{visibility}mod {id:?}",
87            id = self.id,
88            visibility = self.visibility,
89        )
90    }
91}
92
93impl Doc for ModuleDefinition {
94    fn doc(&self) -> Option<DocBlock> {
95        self.doc.clone()
96    }
97}