microcad_lang/value/
mod.rs

1// Copyright © 2024-2025 The µcad authors <info@ucad.xyz>
2// SPDX-License-Identifier: AGPL-3.0-or-later
3
4//! Evaluation entities.
5//!
6//! Every evaluation of any *symbol* leads to a [`Value`] which then might continued
7//! to process or ends up as the overall evaluation result.
8
9mod argument_value;
10mod argument_value_list;
11mod array;
12mod matrix;
13mod parameter_value;
14mod parameter_value_list;
15mod quantity;
16mod target;
17mod tuple;
18mod value_access;
19mod value_error;
20mod value_list;
21
22pub use argument_value::*;
23pub use argument_value_list::*;
24pub use array::*;
25pub use matrix::*;
26pub use parameter_value::*;
27pub use parameter_value_list::*;
28pub use quantity::*;
29pub use target::*;
30pub use tuple::*;
31pub use value_access::*;
32pub use value_error::*;
33pub use value_list::*;
34
35use crate::{model::*, rc::*, syntax::*, ty::*};
36use microcad_core::*;
37
38pub(crate) type ValueResult<Type = Value> = std::result::Result<Type, ValueError>;
39
40/// A variant value with attached source code reference.
41#[derive(Clone, Default, PartialEq)]
42pub enum Value {
43    /// Invalid value (used for error handling).
44    #[default]
45    None,
46    /// A quantity value.
47    Quantity(Quantity),
48    /// A boolean value.
49    Bool(bool),
50    /// An integer value.
51    Integer(Integer),
52    /// A string value.
53    String(String),
54    /// A list of values with a common type.
55    Array(Array),
56    /// A tuple of named items.
57    Tuple(Box<Tuple>),
58    /// A matrix.
59    Matrix(Box<Matrix>),
60    /// A model in the model tree.
61    Model(Model),
62    /// Return value
63    Return(Box<Value>),
64    /// Unevaluated const expression.
65    ConstExpression(Rc<Expression>),
66    /// for assert_valid() and assert_invalid()
67    Target(Target),
68}
69
70impl Value {
71    /// Check if the value is invalid.
72    pub fn is_invalid(&self) -> bool {
73        matches!(self, Value::None)
74    }
75
76    /// Calculate the power of two values, if possible.
77    pub fn pow(&self, rhs: &Value) -> ValueResult {
78        match (&self, rhs) {
79            (Value::Quantity(lhs), Value::Quantity(rhs)) => Ok(Value::Quantity(lhs.pow(rhs))),
80            (Value::Quantity(lhs), Value::Integer(rhs)) => Ok(Value::Quantity(lhs.pow_int(rhs))),
81            (Value::Integer(lhs), Value::Integer(rhs)) => Ok(Value::Integer(lhs.pow(*rhs as u32))),
82            _ => Err(ValueError::InvalidOperator("^".to_string())),
83        }
84    }
85
86    /// Binary operation
87    pub fn binary_op(lhs: Value, rhs: Value, op: &str) -> ValueResult {
88        match op {
89            "+" => lhs + rhs,
90            "-" => lhs - rhs,
91            "*" => lhs * rhs,
92            "/" => lhs / rhs,
93            "^" => lhs.pow(&rhs),
94            "&" => lhs & rhs,
95            "|" => lhs | rhs,
96            ">" => Ok(Value::Bool(lhs > rhs)),
97            "<" => Ok(Value::Bool(lhs < rhs)),
98            "≤" => Ok(Value::Bool(lhs <= rhs)),
99            "≥" => Ok(Value::Bool(lhs >= rhs)),
100            "~" => todo!("implement near ~="),
101            "==" => Ok(Value::Bool(lhs == rhs)),
102            "!=" => Ok(Value::Bool(lhs != rhs)),
103            _ => unimplemented!("{op:?}"),
104        }
105    }
106
107    /// Unary operation.
108    pub fn unary_op(self, op: &str) -> ValueResult {
109        match op {
110            "-" => -self,
111            _ => unimplemented!(),
112        }
113    }
114
115    /// Try to get boolean value.
116    ///
117    /// A `Value::None` will return false.
118    pub fn try_bool(&self) -> Result<bool, ValueError> {
119        match self {
120            Value::Bool(b) => Ok(*b),
121            Value::None => Ok(false),
122            value => Err(ValueError::CannotConvertToBool(value.to_string())),
123        }
124    }
125
126    /// Try to convert to [`String`].
127    pub fn try_string(&self) -> Result<String, ValueError> {
128        match self {
129            Value::String(s) => return Ok(s.clone()),
130            Value::Integer(i) => return Ok(i.to_string()),
131            _ => {}
132        }
133
134        Err(ValueError::CannotConvert(self.to_string(), "String".into()))
135    }
136
137    /// Try to convert to [`Scalar`].
138    pub fn try_scalar(&self) -> Result<Scalar, ValueError> {
139        match self {
140            Value::Quantity(q) => return Ok(q.value),
141            Value::Integer(i) => return Ok((*i) as f64),
142            _ => {}
143        }
144
145        Err(ValueError::CannotConvert(self.to_string(), "Scalar".into()))
146    }
147}
148
149impl PartialOrd for Value {
150    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
151        match (self, other) {
152            // integer type
153            (Value::Integer(lhs), Value::Integer(rhs)) => lhs.partial_cmp(rhs),
154            (Value::Quantity(lhs), Value::Quantity(rhs)) => lhs.partial_cmp(rhs),
155            (
156                Value::Quantity(Quantity {
157                    value,
158                    quantity_type: QuantityType::Scalar,
159                }),
160                Value::Integer(rhs),
161            ) => value.partial_cmp(&(*rhs as Scalar)),
162            _ => {
163                log::warn!("unhandled type mismatch between {self} and {other}");
164                None
165            }
166        }
167    }
168}
169
170impl crate::ty::Ty for Value {
171    fn ty(&self) -> Type {
172        match self {
173            Value::None | Value::ConstExpression(_) => Type::Invalid,
174            Value::Integer(_) => Type::Integer,
175            Value::Quantity(q) => q.ty(),
176            Value::Bool(_) => Type::Bool,
177            Value::String(_) => Type::String,
178            Value::Array(list) => list.ty(),
179            Value::Tuple(tuple) => tuple.ty(),
180            Value::Matrix(matrix) => matrix.ty(),
181            Value::Model(_) => Type::Models,
182            Value::Return(r) => r.ty(),
183            Value::Target(..) => Type::Target,
184        }
185    }
186}
187
188impl std::ops::Neg for Value {
189    type Output = ValueResult;
190
191    fn neg(self) -> Self::Output {
192        match self {
193            Value::Integer(n) => Ok(Value::Integer(-n)),
194            Value::Quantity(q) => Ok(Value::Quantity(q.neg())),
195            Value::Array(a) => -a,
196            Value::Tuple(t) => -t.as_ref().clone(),
197            _ => Err(ValueError::InvalidOperator("-".into())),
198        }
199    }
200}
201
202/// Rules for operator `+`.
203impl std::ops::Add for Value {
204    type Output = ValueResult;
205
206    fn add(self, rhs: Self) -> Self::Output {
207        match (self, rhs) {
208            // Add two integers
209            (Value::Integer(lhs), Value::Integer(rhs)) => Ok(Value::Integer(lhs + rhs)),
210            // Add a quantity to an integer
211            (Value::Integer(lhs), Value::Quantity(rhs)) => Ok(Value::Quantity((lhs + rhs)?)),
212            // Add an integer to a quantity
213            (Value::Quantity(lhs), Value::Integer(rhs)) => Ok(Value::Quantity((lhs + rhs)?)),
214            // Add two scalars
215            (Value::Quantity(lhs), Value::Quantity(rhs)) => Ok(Value::Quantity((lhs + rhs)?)),
216            // Concatenate two strings
217            (Value::String(lhs), Value::String(rhs)) => Ok(Value::String(lhs + &rhs)),
218            // Concatenate two lists
219            (Value::Array(lhs), Value::Array(rhs)) => {
220                if lhs.ty() != rhs.ty() {
221                    return Err(ValueError::CannotCombineVecOfDifferentType(
222                        lhs.ty(),
223                        rhs.ty(),
224                    ));
225                }
226
227                Ok(Value::Array(Array::from_values(
228                    lhs.iter().chain(rhs.iter()).cloned().collect(),
229                    lhs.ty(),
230                )))
231            }
232            // Add a value to an array.
233            (Value::Array(lhs), rhs) => Ok((lhs + rhs)?),
234            // Add two tuples of the same type: (x = 1., y = 2.) + (x = 3., y = 4.)
235            (Value::Tuple(lhs), Value::Tuple(rhs)) => Ok((*lhs + *rhs)?.into()),
236            (lhs, rhs) => Err(ValueError::InvalidOperator(format!("{lhs} + {rhs}"))),
237        }
238    }
239}
240
241/// Rules for operator `-`.
242impl std::ops::Sub for Value {
243    type Output = ValueResult;
244
245    fn sub(self, rhs: Self) -> Self::Output {
246        match (self, rhs) {
247            // Subtract two integers
248            (Value::Integer(lhs), Value::Integer(rhs)) => Ok(Value::Integer(lhs - rhs)),
249            // Subtract an scalar and an integer
250            (Value::Quantity(lhs), Value::Integer(rhs)) => Ok(Value::Quantity((lhs - rhs)?)),
251            // Subtract an integer and a scalar
252            (Value::Integer(lhs), Value::Quantity(rhs)) => Ok(Value::Quantity((lhs - rhs)?)),
253            // Subtract two numbers
254            (Value::Quantity(lhs), Value::Quantity(rhs)) => Ok(Value::Quantity((lhs - rhs)?)),
255            // Subtract value to an array: `[1,2,3] - 1 = [0,1,2]`.
256            (Value::Array(lhs), rhs) => Ok((lhs - rhs)?),
257            // Subtract two tuples of the same type: (x = 1., y = 2.) - (x = 3., y = 4.)
258            (Value::Tuple(lhs), Value::Tuple(rhs)) => Ok((*lhs - *rhs)?.into()),
259
260            // Boolean difference operator for models
261            (Value::Model(lhs), Value::Model(rhs)) => Ok(Value::Model(
262                lhs.boolean_op(microcad_core::BooleanOp::Subtract, rhs),
263            )),
264            (lhs, rhs) => Err(ValueError::InvalidOperator(format!("{lhs} - {rhs}"))),
265        }
266    }
267}
268
269/// Rules for operator `*`.
270impl std::ops::Mul for Value {
271    type Output = ValueResult;
272
273    fn mul(self, rhs: Self) -> Self::Output {
274        match (self, rhs) {
275            // Multiply two integers
276            (Value::Integer(lhs), Value::Integer(rhs)) => Ok(Value::Integer(lhs * rhs)),
277            // Multiply an integer and a scalar, result is scalar
278            (Value::Integer(lhs), Value::Quantity(rhs)) => Ok(Value::Quantity((lhs * rhs)?)),
279            // Multiply a scalar and an integer, result is scalar
280            (Value::Quantity(lhs), Value::Integer(rhs)) => Ok(Value::Quantity((lhs * rhs)?)),
281            // Multiply two scalars
282            (Value::Quantity(lhs), Value::Quantity(rhs)) => Ok(Value::Quantity((lhs * rhs)?)),
283            (Value::Array(array), value) | (value, Value::Array(array)) => Ok((array * value)?),
284            (Value::Tuple(tuple), value) | (value, Value::Tuple(tuple)) => {
285                Ok((tuple.as_ref().clone() * value)?.into())
286            }
287            (lhs, rhs) => Err(ValueError::InvalidOperator(format!("{lhs} * {rhs}"))),
288        }
289    }
290}
291
292/// Multiply a Unit with a value. Used for unit bundling: `[1,2,3]mm`.
293///
294/// `[1,2,3]mm` is a shortcut for `[1,2,3] * 1mm`.
295impl std::ops::Mul<Unit> for Value {
296    type Output = ValueResult;
297
298    fn mul(self, unit: Unit) -> Self::Output {
299        match (self, unit.ty()) {
300            (value, Type::Quantity(QuantityType::Scalar)) | (value, Type::Integer) => Ok(value),
301            (Value::Integer(i), Type::Quantity(quantity_type)) => Ok(Value::Quantity(
302                Quantity::new(unit.normalize(i as Scalar), quantity_type),
303            )),
304            (Value::Quantity(quantity), Type::Quantity(quantity_type)) => Ok(Value::Quantity(
305                (quantity * Quantity::new(unit.normalize(1.0), quantity_type))?,
306            )),
307            (Value::Array(array), Type::Quantity(quantity_type)) => {
308                Ok((array * Value::Quantity(Quantity::new(unit.normalize(1.0), quantity_type)))?)
309            }
310            (value, _) => Err(ValueError::CannotAddUnitToValueWithUnit(value.to_string())),
311        }
312    }
313}
314
315/// Rules for operator `/`.
316impl std::ops::Div for Value {
317    type Output = ValueResult;
318
319    fn div(self, rhs: Self) -> Self::Output {
320        match (self, rhs) {
321            // Division with scalar result
322            (Value::Integer(lhs), Value::Integer(rhs)) => {
323                Ok(Value::Quantity((lhs as Scalar / rhs as Scalar).into()))
324            }
325            (Value::Quantity(lhs), Value::Integer(rhs)) => Ok(Value::Quantity((lhs / rhs)?)),
326            (Value::Integer(lhs), Value::Quantity(rhs)) => Ok(Value::Quantity((lhs / rhs)?)),
327            (Value::Quantity(lhs), Value::Quantity(rhs)) => Ok(Value::Quantity((lhs / rhs)?)),
328            (Value::Array(array), value) => Ok((array / value)?),
329            (Value::Tuple(tuple), value) => Ok((tuple.as_ref().clone() / value)?.into()),
330            (lhs, rhs) => Err(ValueError::InvalidOperator(format!("{lhs} / {rhs}"))),
331        }
332    }
333}
334
335/// Rules for operator `|`` (union).
336impl std::ops::BitOr for Value {
337    type Output = ValueResult;
338
339    fn bitor(self, rhs: Self) -> Self::Output {
340        match (self, rhs) {
341            (Value::Model(lhs), Value::Model(rhs)) => Ok(Value::Model(
342                lhs.boolean_op(microcad_core::BooleanOp::Union, rhs),
343            )),
344            (Value::Bool(lhs), Value::Bool(rhs)) => Ok(Value::Bool(lhs | rhs)),
345            (lhs, rhs) => Err(ValueError::InvalidOperator(format!("{lhs} | {rhs}"))),
346        }
347    }
348}
349
350/// Rules for operator `&` (intersection).
351impl std::ops::BitAnd for Value {
352    type Output = ValueResult;
353
354    fn bitand(self, rhs: Self) -> Self::Output {
355        match (self, rhs) {
356            (Value::Model(lhs), Value::Model(rhs)) => {
357                Ok(Value::Model(lhs.boolean_op(BooleanOp::Intersect, rhs)))
358            }
359            (Value::Bool(lhs), Value::Bool(rhs)) => Ok(Value::Bool(lhs & rhs)),
360            (lhs, rhs) => Err(ValueError::InvalidOperator(format!("{lhs} & {rhs}"))),
361        }
362    }
363}
364
365impl std::fmt::Display for Value {
366    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
367        match self {
368            Value::None => write!(f, crate::invalid_no_ansi!(VALUE)),
369            Value::Integer(n) => write!(f, "{n}"),
370            Value::Quantity(q) => write!(f, "{q}"),
371            Value::Bool(b) => write!(f, "{b}"),
372            Value::String(s) => write!(f, "{s}"),
373            Value::Array(l) => write!(f, "{l}"),
374            Value::Tuple(t) => write!(f, "{t}"),
375            Value::Matrix(m) => write!(f, "{m}"),
376            Value::Model(n) => write!(f, "{n}"),
377            Value::Return(r) => write!(f, "{r}"),
378            Value::ConstExpression(e) => write!(f, "{e}"),
379            Value::Target(target) => write!(f, "{target}"),
380        }
381    }
382}
383
384impl std::fmt::Debug for Value {
385    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
386        match self {
387            Value::None => write!(f, crate::invalid!(VALUE)),
388            Value::Integer(n) => write!(f, "{n}"),
389            Value::Quantity(q) => write!(f, "{q:?}"),
390            Value::Bool(b) => write!(f, "{b}"),
391            Value::String(s) => write!(f, "{s:?}"),
392            Value::Array(l) => write!(f, "{l:?}"),
393            Value::Tuple(t) => write!(f, "{t:?}"),
394            Value::Matrix(m) => write!(f, "{m:?}"),
395            Value::Model(n) => write!(f, "\n {n:?}"),
396            Value::Return(r) => write!(f, "->{r:?}"),
397            Value::ConstExpression(e) => write!(f, "{e:?}"),
398            Value::Target(target) => write!(f, "{target:?}"),
399        }
400    }
401}
402
403impl std::hash::Hash for Value {
404    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
405        match self {
406            Value::None => std::mem::discriminant(&Value::None).hash(state),
407            Value::Quantity(quantity) => quantity.hash(state),
408            Value::Bool(b) => b.hash(state),
409            Value::Integer(i) => i.hash(state),
410            Value::String(s) => s.hash(state),
411            Value::Array(array) => array.hash(state),
412            Value::Tuple(tuple) => tuple.hash(state),
413            Value::Matrix(matrix) => matrix.hash(state),
414            Value::Model(model) => model.hash(state),
415            Value::Return(value) => value.hash(state),
416            Value::ConstExpression(expression) => expression.to_string().hash(state), // TODO: Is this correct?
417            Value::Target(target) => target.hash(state),
418        }
419    }
420}
421
422macro_rules! impl_try_from {
423    ($($variant:ident),+ => $ty:ty ) => {
424        impl TryFrom<Value> for $ty {
425            type Error = ValueError;
426
427            fn try_from(value: Value) -> std::result::Result<Self, Self::Error> {
428                match value {
429                    $(Value::$variant(v) => Ok(v),)*
430                    value => Err(ValueError::CannotConvert(value.to_string(), stringify!($ty).into())),
431                }
432            }
433        }
434
435        impl TryFrom<&Value> for $ty {
436            type Error = ValueError;
437
438            fn try_from(value: &Value) -> std::result::Result<Self, Self::Error> {
439                match value {
440                    $(Value::$variant(v) => Ok(v.clone().into()),)*
441                    value => Err(ValueError::CannotConvert(value.to_string(), stringify!($ty).into())),
442                }
443            }
444        }
445    };
446}
447
448impl_try_from!(Integer => i64);
449impl_try_from!(Bool => bool);
450impl_try_from!(String => String);
451
452impl TryFrom<&Value> for Scalar {
453    type Error = ValueError;
454
455    fn try_from(value: &Value) -> Result<Self, Self::Error> {
456        match value {
457            Value::Integer(i) => Ok(*i as Scalar),
458            Value::Quantity(Quantity {
459                value,
460                quantity_type: QuantityType::Scalar,
461            }) => Ok(*value),
462            _ => Err(ValueError::CannotConvert(
463                value.to_string(),
464                "Scalar".into(),
465            )),
466        }
467    }
468}
469
470impl TryFrom<Value> for Scalar {
471    type Error = ValueError;
472
473    fn try_from(value: Value) -> Result<Self, Self::Error> {
474        match value {
475            Value::Integer(i) => Ok(i as Scalar),
476            Value::Quantity(Quantity {
477                value,
478                quantity_type: QuantityType::Scalar,
479            }) => Ok(value),
480            _ => Err(ValueError::CannotConvert(
481                value.to_string(),
482                "Scalar".into(),
483            )),
484        }
485    }
486}
487
488impl TryFrom<&Value> for Angle {
489    type Error = ValueError;
490
491    fn try_from(value: &Value) -> Result<Self, Self::Error> {
492        match value {
493            Value::Quantity(Quantity {
494                value,
495                quantity_type: QuantityType::Angle,
496            }) => Ok(cgmath::Rad(*value)),
497            _ => Err(ValueError::CannotConvert(value.to_string(), "Angle".into())),
498        }
499    }
500}
501
502impl TryFrom<&Value> for Size2 {
503    type Error = ValueError;
504
505    fn try_from(value: &Value) -> Result<Self, Self::Error> {
506        match value {
507            Value::Tuple(tuple) => Ok(tuple.as_ref().try_into()?),
508            _ => Err(ValueError::CannotConvert(value.to_string(), "Size2".into())),
509        }
510    }
511}
512
513impl TryFrom<&Value> for Mat3 {
514    type Error = ValueError;
515
516    fn try_from(value: &Value) -> Result<Self, Self::Error> {
517        if let Value::Matrix(m) = value {
518            if let Matrix::Matrix3(matrix3) = m.as_ref() {
519                return Ok(*matrix3);
520            }
521        }
522
523        Err(ValueError::CannotConvert(
524            value.to_string(),
525            "Matrix3".into(),
526        ))
527    }
528}
529
530impl From<f32> for Value {
531    fn from(f: f32) -> Self {
532        Value::Quantity((f as Scalar).into())
533    }
534}
535
536impl From<Scalar> for Value {
537    fn from(scalar: Scalar) -> Self {
538        Value::Quantity(scalar.into())
539    }
540}
541
542impl From<Size2> for Value {
543    fn from(value: Size2) -> Self {
544        Value::Tuple(Box::new(value.into()))
545    }
546}
547
548impl From<Quantity> for Value {
549    fn from(qty: Quantity) -> Self {
550        Value::Quantity(qty)
551    }
552}
553
554impl From<String> for Value {
555    fn from(value: String) -> Self {
556        Value::String(value)
557    }
558}
559
560impl FromIterator<Value> for Value {
561    fn from_iter<T: IntoIterator<Item = Value>>(iter: T) -> Self {
562        Self::Array(iter.into_iter().collect())
563    }
564}
565
566impl From<Model> for Value {
567    fn from(model: Model) -> Self {
568        Self::Model(model)
569    }
570}
571
572impl AttributesAccess for Value {
573    fn get_attributes_by_id(&self, id: &Identifier) -> Vec<crate::model::Attribute> {
574        match self {
575            Value::Model(model) => model.get_attributes_by_id(id),
576            _ => Vec::default(),
577        }
578    }
579}
580
581#[cfg(test)]
582fn integer(value: i64) -> Value {
583    Value::Integer(value)
584}
585
586#[cfg(test)]
587fn scalar(value: f64) -> Value {
588    Value::Quantity(Quantity::new(value, QuantityType::Scalar))
589}
590
591#[cfg(test)]
592fn check(result: ValueResult, value: Value) {
593    let result = result.expect("error result");
594    assert_eq!(result, value);
595}
596
597#[test]
598fn test_value_integer() {
599    let u = || integer(2);
600    let v = || integer(5);
601    let w = || scalar(5.0);
602
603    // symmetric operations
604    check(u() + v(), integer(2 + 5));
605    check(u() - v(), integer(2 - 5));
606    check(u() * v(), integer(2 * 5));
607    check(u() / v(), scalar(2.0 / 5.0));
608    check(-u(), integer(-2));
609
610    // asymmetric operations
611    check(u() + w(), scalar(2 as Scalar + 5.0));
612    check(u() - w(), scalar(2 as Scalar - 5.0));
613    check(u() * w(), scalar(2 as Scalar * 5.0));
614    check(u() / w(), scalar(2.0 / 5.0));
615}
616
617#[test]
618fn test_value_scalar() {
619    let u = || scalar(2.0);
620    let v = || scalar(5.0);
621    let w = || integer(5);
622
623    // symmetric operations
624    check(u() + v(), scalar(2.0 + 5.0));
625    check(u() - v(), scalar(2.0 - 5.0));
626    check(u() * v(), scalar(2.0 * 5.0));
627    check(u() / v(), scalar(2.0 / 5.0));
628    check(-u(), scalar(-2.0));
629
630    // asymmetric operations
631    check(u() + w(), scalar(2.0 + 5.0));
632    check(u() - w(), scalar(2.0 - 5.0));
633    check(u() * w(), scalar(2.0 * 5.0));
634    check(u() / w(), scalar(2.0 / 5.0));
635}