Skip to main content

microcad_lang/model/
builder.rs

1// Copyright © 2025-2026 The µcad authors <info@microcad.xyz>
2// SPDX-License-Identifier: AGPL-3.0-or-later
3
4//! Model builder.
5
6use crate::model::*;
7
8use microcad_lang_base::SrcRef;
9
10/// A builder pattern to build models.
11#[derive(Default)]
12pub struct ModelBuilder {
13    root: ModelInner,
14    /// Properties of the model.
15    pub properties: Properties,
16    /// Children models of this model.
17    pub children: Models,
18}
19
20/// `ModelBuilder` creation.
21///
22/// All methods in this `impl` block are used to create a new model builder with a specific [`Element`] type.
23impl ModelBuilder {
24    /// Create a new model with an element.
25    pub fn new(element: Element, src_ref: SrcRef) -> Self {
26        Self {
27            root: ModelInner::new(element, src_ref),
28            ..Default::default()
29        }
30    }
31
32    /// Add multiple children to the model if it matches.
33    pub fn add_children(mut self, mut children: Models) -> Self {
34        self.children.append(&mut children);
35        self
36    }
37
38    /// Set model attributes.
39    pub fn attributes(mut self, attributes: Attributes) -> Self {
40        self.root.attributes = attributes;
41        self
42    }
43
44    /// Set model properties.
45    pub fn properties(mut self, properties: Properties) -> Self {
46        self.properties = properties;
47        self
48    }
49
50    /// Build a [`Model`].
51    pub fn build(mut self) -> Model {
52        if let Element::Workpiece(workpiece) = &mut self.root.element.value {
53            workpiece.add_properties(self.properties);
54        }
55
56        let model = Model::new(self.root.into());
57        model.append_children(self.children);
58        model.deduce_output_type();
59        model
60    }
61}
62
63impl std::fmt::Display for ModelBuilder {
64    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
65        write!(f, "{}", self.properties)
66    }
67}