Skip to main content

microcad_lang/builtin/
builtin.rs

1// Copyright © 2025-2026 The µcad authors <info@ucad.xyz>
2// SPDX-License-Identifier: AGPL-3.0-or-later
3
4//! Builtin evaluation entity
5
6use crate::{builtin::*, eval::*, syntax::*, value::*};
7
8/// Builtin function type
9pub type BuiltinFn =
10    dyn Fn(&ParameterValueList, &ArgumentValueList, &mut EvalContext) -> EvalResult<Value>;
11
12/// Builtin function struct
13#[derive(Clone)]
14pub struct Builtin {
15    /// Name of the builtin function
16    pub id: Identifier,
17
18    /// Optional parameter value list to check the builtin signature.
19    pub parameters: ParameterValueList,
20
21    /// Built-in kind.
22    pub kind: BuiltinKind,
23
24    /// Functor to evaluate this function
25    pub f: &'static BuiltinFn,
26
27    /// Functor which returns documentation of this function
28    pub doc: Option<DocBlock>,
29}
30
31/// Kind of the built-in.
32#[derive(Clone)]
33pub enum BuiltinKind {
34    /// A built-in function: `fn ()`.
35    Function,
36    /// A built-in workpiece: operation, transform, sketch, part.
37    Workbench(BuiltinWorkbenchKind),
38}
39
40impl BuiltinKind {
41    /// return kind name
42    pub fn as_str(&self) -> &'static str {
43        match self {
44            Self::Function => "function",
45            Self::Workbench(kind) => kind.as_str(),
46        }
47    }
48}
49
50impl std::fmt::Display for BuiltinKind {
51    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
52        match self {
53            Self::Function => write!(f, "Function"),
54            Self::Workbench(kind) => write!(f, "{kind}"),
55        }
56    }
57}
58
59impl std::fmt::Debug for Builtin {
60    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
61        write!(f, "__builtin::{}", &self.id)
62    }
63}
64
65impl Builtin {
66    /// Return identifier.
67    pub fn id(&self) -> Identifier {
68        self.id.clone()
69    }
70}
71
72impl CallTrait for Builtin {
73    /// Call builtin function with given parameter.
74    ///
75    /// # Arguments
76    /// - `args`: Function arguments.
77    /// - `context`: Execution context.
78    fn call(&self, args: &ArgumentValueList, context: &mut EvalContext) -> EvalResult<Value> {
79        (self.f)(&self.parameters, args, context)
80    }
81}