microcad_lang/syntax/function/
function_definition.rs

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