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_head(), 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(
95 &self.src_ref_head(),
96 result.expect_err("Error"),
97 )?;
98 }
99 result => {
100 context
101 .error(&self.src_ref_head(), result.expect_err("Error"))?;
102 }
103 }
104 }
105 _ => panic!("A workbench must produce a workpiece."),
106 }
107 }
108
109 Ok(model)
110 },
111 )
112 }
113}
114
115impl WorkbenchDefinition {
116 /// Evaluate the call of a workbench with given arguments.
117 ///
118 /// - `args`: Arguments which will be matched with the building plan and the initializers using parameter multiplicity.
119 /// - `context`: Current evaluation context.
120 ///
121 /// Return evaluated nodes (multiple nodes might be created by parameter multiplicity).
122 pub fn call(
123 &self,
124 call_src_ref: SrcRef,
125 symbol: Symbol,
126 arguments: &ArgumentValueList,
127 context: &mut EvalContext,
128 ) -> EvalResult<Model> {
129 log::debug!(
130 "Workbench {call} {kind} {id:?}({arguments:?})",
131 call = crate::mark!(CALL),
132 id = self.id,
133 kind = self.kind
134 );
135
136 // prepare models
137 let mut models = Models::default();
138 // prepare building plan
139 let plan = self.plan.eval(context)?;
140
141 // try to match arguments with the building plan
142 match ArgumentMatch::find_multi_match(arguments, &plan) {
143 Ok(matches) => {
144 log::debug!(
145 "Building plan matches: {}",
146 matches
147 .iter()
148 .map(|m| format!("{m:?}"))
149 .collect::<Vec<_>>()
150 .join("\n")
151 );
152 // evaluate models for all multiplicity matches
153 for arguments in matches {
154 models.push(self.eval_to_model(
155 call_src_ref.clone(),
156 Creator::new(symbol.clone(), arguments),
157 None,
158 context,
159 )?);
160 }
161 }
162 _ => {
163 log::trace!("Building plan did not match, finding initializer");
164
165 // at the end: check if initialization was successful
166 let mut initialized = false;
167
168 // find an initializer that matches the arguments
169 for init in self.inits() {
170 if let Ok(matches) =
171 ArgumentMatch::find_multi_match(arguments, &init.parameters.eval(context)?)
172 {
173 log::debug!(
174 "Initializer matches: {}",
175 matches
176 .iter()
177 .map(|m| format!("{m:?}"))
178 .collect::<Vec<_>>()
179 .join("\n")
180 );
181 // evaluate models for all multiplicity matches
182 for arguments in matches {
183 models.push(self.eval_to_model(
184 call_src_ref.clone(),
185 Creator::new(symbol.clone(), arguments),
186 Some(init),
187 context,
188 )?);
189 }
190 initialized = true;
191 break;
192 }
193 }
194 if !initialized {
195 context.error(arguments, EvalError::NoInitializationFound(self.id.clone()))?;
196 }
197 }
198 }
199
200 Ok(models.to_multiplicity(self.src_ref.clone()))
201 }
202}