microcad_lang/eval/
workbench.rs

1// Copyright © 2024-2025 The µcad authors <info@ucad.xyz>
2// SPDX-License-Identifier: AGPL-3.0-or-later
3
4//! Workbench definition syntax element evaluation
5
6use crate::{eval::*, model::*, render::Hashed, syntax::*};
7
8impl WorkbenchDefinition {
9    /// Try to evaluate a single call into a [`Model`].
10    ///
11    /// - `arguments`: Single argument tuple (will not be multiplied).
12    /// - `init`: Initializer to call with given `arguments`.
13    /// - `context`: Current evaluation context.
14    fn eval_to_model<'a>(
15        &'a self,
16        call_src_ref: SrcRef,
17        creator: Creator,
18        init: Option<&'a InitDefinition>,
19        context: &mut EvalContext,
20    ) -> EvalResult<Model> {
21        log::debug!(
22            "Evaluating model of `{id:?}` {kind}",
23            id = self.id,
24            kind = self.kind
25        );
26
27        let arguments = creator.arguments.clone();
28
29        // copy all arguments which are part of the building plan into properties
30        let (mut properties, non_properties): (Vec<_>, Vec<_>) = arguments
31            .named_iter()
32            .map(|(id, value)| (id.clone(), value.clone()))
33            .partition(|(id, _)| self.plan.contains_key(id));
34
35        // create uninitialized values for all missing building plan properties
36        let missing: Vec<_> = self
37            .plan
38            .iter()
39            .filter(|param| !properties.iter().any(|(id, _)| param.id == *id))
40            .map(|param| param.id.clone())
41            .collect();
42        missing
43            .into_iter()
44            .for_each(|id| properties.push((id, Value::None)));
45
46        log::trace!("Properties: {properties:?}");
47        log::trace!("Non-Properties: {non_properties:?}");
48
49        // Create model
50        let model = ModelBuilder::new(
51            Element::Workpiece(Workpiece {
52                kind: *self.kind,
53                // copy all arguments which are part of the building plan to properties
54                properties: properties.into_iter().collect(),
55                creator: Hashed::new(creator),
56            }),
57            call_src_ref,
58        )
59        .attributes(self.attribute_list.eval(context)?)
60        .build();
61
62        context.scope(
63            StackFrame::Workbench(model, self.id.clone(), Default::default()),
64            |context| {
65                let model = context.get_model()?;
66
67                // run init code
68                if let Some(init) = init {
69                    log::trace!(
70                        "Initializing`{id:?}` {kind}",
71                        id = self.id,
72                        kind = self.kind
73                    );
74                    if let Err(err) = init.eval(non_properties.into_iter().collect(), context) {
75                        context.error(&self.src_ref(), err)?;
76                    }
77                }
78
79                // At this point, all properties must have a value
80                log::trace!("Run body`{id:?}` {kind}", id = self.id, kind = self.kind);
81                model.append_children(self.body.statements.eval(context)?);
82
83                // We have to deduce the output type of this model, otherwise the model is incomplete.
84                {
85                    let model_ = model.borrow();
86                    match &*model_.element {
87                        Element::Workpiece(workpiece) => {
88                            let output_type = model.deduce_output_type();
89
90                            let result = workpiece.check_output_type(output_type);
91                            match result {
92                                Ok(()) => {}
93                                Err(EvalError::WorkbenchNoOutput(..)) => {
94                                    context.warning(&self.src_ref(), result.expect_err("Error"))?;
95                                }
96                                result => {
97                                    context.error(&self.src_ref(), result.expect_err("Error"))?;
98                                }
99                            }
100                        }
101                        _ => panic!("A workbench must produce a workpiece."),
102                    }
103                }
104
105                Ok(model)
106            },
107        )
108    }
109}
110
111impl WorkbenchDefinition {
112    /// Evaluate the call of a workbench with given arguments.
113    ///
114    /// - `args`: Arguments which will be matched with the building plan and the initializers using parameter multiplicity.
115    /// - `context`: Current evaluation context.
116    ///
117    /// Return evaluated nodes (multiple nodes might be created by parameter multiplicity).
118    pub fn call(
119        &self,
120        call_src_ref: SrcRef,
121        symbol: Symbol,
122        arguments: &ArgumentValueList,
123        context: &mut EvalContext,
124    ) -> EvalResult<Model> {
125        log::debug!(
126            "Workbench {call} {kind} {id:?}({arguments:?})",
127            call = crate::mark!(CALL),
128            id = self.id,
129            kind = self.kind
130        );
131
132        // prepare models
133        let mut models = Models::default();
134        // prepare building plan
135        let plan = self.plan.eval(context)?;
136
137        // try to match arguments with the building plan
138        match ArgumentMatch::find_multi_match(arguments, &plan) {
139            Ok(matches) => {
140                log::debug!(
141                    "Building plan matches: {}",
142                    matches
143                        .iter()
144                        .map(|m| format!("{m:?}"))
145                        .collect::<Vec<_>>()
146                        .join("\n")
147                );
148                // evaluate models for all multiplicity matches
149                for arguments in matches {
150                    models.push(self.eval_to_model(
151                        call_src_ref.clone(),
152                        Creator::new(symbol.clone(), arguments),
153                        None,
154                        context,
155                    )?);
156                }
157            }
158            _ => {
159                log::trace!("Building plan did not match, finding initializer");
160
161                // at the end: check if initialization was successful
162                let mut initialized = false;
163
164                // find an initializer that matches the arguments
165                for init in self.inits() {
166                    if let Ok(matches) =
167                        ArgumentMatch::find_multi_match(arguments, &init.parameters.eval(context)?)
168                    {
169                        log::debug!(
170                            "Initializer matches: {}",
171                            matches
172                                .iter()
173                                .map(|m| format!("{m:?}"))
174                                .collect::<Vec<_>>()
175                                .join("\n")
176                        );
177                        // evaluate models for all multiplicity matches
178                        for arguments in matches {
179                            models.push(self.eval_to_model(
180                                call_src_ref.clone(),
181                                Creator::new(symbol.clone(), arguments),
182                                Some(init),
183                                context,
184                            )?);
185                        }
186                        initialized = true;
187                        break;
188                    }
189                }
190                if !initialized {
191                    context.error(arguments, EvalError::NoInitializationFound(self.id.clone()))?;
192                }
193            }
194        }
195
196        Ok(models.to_multiplicity(self.src_ref()))
197    }
198}