Skip to main content

microcad_lang/syntax/function/
function_signature.rs

1// Copyright © 2024-2026 The µcad authors <info@microcad.xyz>
2// SPDX-License-Identifier: AGPL-3.0-or-later
3
4//! Function signature syntax element
5
6use microcad_lang_base::{SrcRef, SrcReferrer, TreeDisplay, TreeState};
7
8use crate::syntax::*;
9
10/// Parameters and return type of a function
11#[derive(Clone)]
12pub struct FunctionSignature {
13    /// Function's parameters
14    pub parameters: ParameterList,
15    /// Function's return type
16    pub return_type: Option<TypeAnnotation>,
17    /// Source code reference
18    pub src_ref: SrcRef,
19}
20
21impl SrcReferrer for FunctionSignature {
22    fn src_ref(&self) -> SrcRef {
23        self.src_ref.clone()
24    }
25}
26
27impl FunctionSignature {
28    /// Get parameter by name
29    pub fn parameter_by_name(&self, name: &Identifier) -> Option<&Parameter> {
30        self.parameters.iter().find(|arg| arg.id_ref() == name)
31    }
32}
33
34impl TreeDisplay for FunctionSignature {
35    fn tree_print(&self, f: &mut std::fmt::Formatter, mut depth: TreeState) -> std::fmt::Result {
36        writeln!(f, "{:depth$}Parameters:", "")?;
37        depth.indent();
38        self.parameters.tree_print(f, depth)?;
39        if let Some(return_type) = &self.return_type {
40            writeln!(f, "{:depth$}Return:", "")?;
41            return_type.tree_print(f, depth)?;
42        };
43        Ok(())
44    }
45}
46
47impl std::fmt::Display for FunctionSignature {
48    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
49        write!(
50            f,
51            "({}){}",
52            self.parameters,
53            if let Some(ret) = &self.return_type {
54                format!("-> {ret}")
55            } else {
56                String::default()
57            }
58        )
59    }
60}
61
62impl std::fmt::Debug for FunctionSignature {
63    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
64        write!(
65            f,
66            "({:?}){:?}",
67            self.parameters,
68            if let Some(ret) = &self.return_type {
69                format!("-> {ret}")
70            } else {
71                String::default()
72            }
73        )
74    }
75}