Skip to main content

microcad_lang/syntax/function/
function_definition.rs

1// Copyright © 2024-2026 The µcad authors <info@microcad.xyz>
2// SPDX-License-Identifier: AGPL-3.0-or-later
3
4//! Function definition syntax element
5
6use microcad_lang_base::{SrcRef, SrcReferrer, TreeDisplay, TreeState};
7
8use crate::syntax::*;
9
10/// Function definition
11#[derive(Clone)]
12pub struct FunctionDefinition {
13    /// SrcRef of the `fn` keyword
14    pub keyword_ref: SrcRef,
15    /// Documentation.
16    pub doc: Option<DocBlock>,
17    /// Visibility
18    pub visibility: Visibility,
19    /// Name of the function
20    pub(crate) id: Identifier,
21    /// Function signature
22    pub signature: FunctionSignature,
23    /// Function body
24    pub body: Body,
25}
26
27impl Identifiable for FunctionDefinition {
28    fn id_ref(&self) -> &Identifier {
29        &self.id
30    }
31}
32
33impl SrcReferrer for FunctionDefinition {
34    fn src_ref(&self) -> SrcRef {
35        self.id.src_ref()
36    }
37}
38
39impl TreeDisplay for FunctionDefinition {
40    fn tree_print(&self, f: &mut std::fmt::Formatter, mut depth: TreeState) -> std::fmt::Result {
41        writeln!(f, "{:depth$}FunctionDefinition '{}':", "", self.id)?;
42        depth.indent();
43        if let Some(doc) = &self.doc {
44            doc.tree_print(f, depth)?;
45        }
46        writeln!(f, "{:depth$}Signature:", "")?;
47        self.signature.tree_print(f, depth)?;
48        writeln!(f, "{:depth$}Body:", "")?;
49        self.body.tree_print(f, depth)
50    }
51}
52
53impl std::fmt::Display for FunctionDefinition {
54    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
55        write!(f, "fn {}{}", self.id, self.signature)
56    }
57}
58
59impl std::fmt::Debug for FunctionDefinition {
60    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
61        write!(f, "fn {:?}{:?}", self.id, self.signature)
62    }
63}