1mod 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#[derive(Clone, Default, PartialEq)]
42pub enum Value {
43 #[default]
45 None,
46 Quantity(Quantity),
48 Bool(bool),
50 Integer(Integer),
52 String(String),
54 Array(Array),
56 Tuple(Box<Tuple>),
58 Matrix(Box<Matrix>),
60 Model(Model),
62 Return(Box<Value>),
64 ConstExpression(Rc<Expression>),
66 Target(Target),
68}
69
70impl Value {
71 pub fn is_invalid(&self) -> bool {
73 matches!(self, Value::None)
74 }
75
76 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 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 pub fn unary_op(self, op: &str) -> ValueResult {
109 match op {
110 "-" => -self,
111 _ => unimplemented!(),
112 }
113 }
114
115 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 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 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 (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
202impl std::ops::Add for Value {
204 type Output = ValueResult;
205
206 fn add(self, rhs: Self) -> Self::Output {
207 match (self, rhs) {
208 (Value::Integer(lhs), Value::Integer(rhs)) => Ok(Value::Integer(lhs + rhs)),
210 (Value::Integer(lhs), Value::Quantity(rhs)) => Ok(Value::Quantity((lhs + rhs)?)),
212 (Value::Quantity(lhs), Value::Integer(rhs)) => Ok(Value::Quantity((lhs + rhs)?)),
214 (Value::Quantity(lhs), Value::Quantity(rhs)) => Ok(Value::Quantity((lhs + rhs)?)),
216 (Value::String(lhs), Value::String(rhs)) => Ok(Value::String(lhs + &rhs)),
218 (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 (Value::Array(lhs), rhs) => Ok((lhs + rhs)?),
234 (Value::Tuple(lhs), Value::Tuple(rhs)) => Ok((*lhs + *rhs)?.into()),
236 (lhs, rhs) => Err(ValueError::InvalidOperator(format!("{lhs} + {rhs}"))),
237 }
238 }
239}
240
241impl std::ops::Sub for Value {
243 type Output = ValueResult;
244
245 fn sub(self, rhs: Self) -> Self::Output {
246 match (self, rhs) {
247 (Value::Integer(lhs), Value::Integer(rhs)) => Ok(Value::Integer(lhs - rhs)),
249 (Value::Quantity(lhs), Value::Integer(rhs)) => Ok(Value::Quantity((lhs - rhs)?)),
251 (Value::Integer(lhs), Value::Quantity(rhs)) => Ok(Value::Quantity((lhs - rhs)?)),
253 (Value::Quantity(lhs), Value::Quantity(rhs)) => Ok(Value::Quantity((lhs - rhs)?)),
255 (Value::Array(lhs), rhs) => Ok((lhs - rhs)?),
257 (Value::Tuple(lhs), Value::Tuple(rhs)) => Ok((*lhs - *rhs)?.into()),
259
260 (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
269impl std::ops::Mul for Value {
271 type Output = ValueResult;
272
273 fn mul(self, rhs: Self) -> Self::Output {
274 match (self, rhs) {
275 (Value::Integer(lhs), Value::Integer(rhs)) => Ok(Value::Integer(lhs * rhs)),
277 (Value::Integer(lhs), Value::Quantity(rhs)) => Ok(Value::Quantity((lhs * rhs)?)),
279 (Value::Quantity(lhs), Value::Integer(rhs)) => Ok(Value::Quantity((lhs * rhs)?)),
281 (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
292impl 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
315impl std::ops::Div for Value {
317 type Output = ValueResult;
318
319 fn div(self, rhs: Self) -> Self::Output {
320 match (self, rhs) {
321 (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
335impl 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
350impl 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
403macro_rules! impl_try_from {
404 ($($variant:ident),+ => $ty:ty ) => {
405 impl TryFrom<Value> for $ty {
406 type Error = ValueError;
407
408 fn try_from(value: Value) -> std::result::Result<Self, Self::Error> {
409 match value {
410 $(Value::$variant(v) => Ok(v),)*
411 value => Err(ValueError::CannotConvert(value.to_string(), stringify!($ty).into())),
412 }
413 }
414 }
415
416 impl TryFrom<&Value> for $ty {
417 type Error = ValueError;
418
419 fn try_from(value: &Value) -> std::result::Result<Self, Self::Error> {
420 match value {
421 $(Value::$variant(v) => Ok(v.clone().into()),)*
422 value => Err(ValueError::CannotConvert(value.to_string(), stringify!($ty).into())),
423 }
424 }
425 }
426 };
427}
428
429impl_try_from!(Integer => i64);
430impl_try_from!(Bool => bool);
431impl_try_from!(String => String);
432
433impl TryFrom<&Value> for Scalar {
434 type Error = ValueError;
435
436 fn try_from(value: &Value) -> Result<Self, Self::Error> {
437 match value {
438 Value::Integer(i) => Ok(*i as Scalar),
439 Value::Quantity(Quantity {
440 value,
441 quantity_type: QuantityType::Scalar,
442 }) => Ok(*value),
443 _ => Err(ValueError::CannotConvert(
444 value.to_string(),
445 "Scalar".into(),
446 )),
447 }
448 }
449}
450
451impl TryFrom<Value> for Scalar {
452 type Error = ValueError;
453
454 fn try_from(value: Value) -> Result<Self, Self::Error> {
455 match value {
456 Value::Integer(i) => Ok(i as Scalar),
457 Value::Quantity(Quantity {
458 value,
459 quantity_type: QuantityType::Scalar,
460 }) => Ok(value),
461 _ => Err(ValueError::CannotConvert(
462 value.to_string(),
463 "Scalar".into(),
464 )),
465 }
466 }
467}
468
469impl TryFrom<&Value> for Angle {
470 type Error = ValueError;
471
472 fn try_from(value: &Value) -> Result<Self, Self::Error> {
473 match value {
474 Value::Quantity(Quantity {
475 value,
476 quantity_type: QuantityType::Angle,
477 }) => Ok(cgmath::Rad(*value)),
478 _ => Err(ValueError::CannotConvert(value.to_string(), "Angle".into())),
479 }
480 }
481}
482
483impl TryFrom<&Value> for Size2 {
484 type Error = ValueError;
485
486 fn try_from(value: &Value) -> Result<Self, Self::Error> {
487 match value {
488 Value::Tuple(tuple) => Ok(tuple.as_ref().try_into()?),
489 _ => Err(ValueError::CannotConvert(value.to_string(), "Size2".into())),
490 }
491 }
492}
493
494impl TryFrom<&Value> for Mat3 {
495 type Error = ValueError;
496
497 fn try_from(value: &Value) -> Result<Self, Self::Error> {
498 if let Value::Matrix(m) = value {
499 if let Matrix::Matrix3(matrix3) = m.as_ref() {
500 return Ok(*matrix3);
501 }
502 }
503
504 Err(ValueError::CannotConvert(
505 value.to_string(),
506 "Matrix3".into(),
507 ))
508 }
509}
510
511impl From<f32> for Value {
512 fn from(f: f32) -> Self {
513 Value::Quantity((f as Scalar).into())
514 }
515}
516
517impl From<Scalar> for Value {
518 fn from(scalar: Scalar) -> Self {
519 Value::Quantity(scalar.into())
520 }
521}
522
523impl From<Size2> for Value {
524 fn from(value: Size2) -> Self {
525 Value::Tuple(Box::new(value.into()))
526 }
527}
528
529impl From<Quantity> for Value {
530 fn from(qty: Quantity) -> Self {
531 Value::Quantity(qty)
532 }
533}
534
535impl From<String> for Value {
536 fn from(value: String) -> Self {
537 Value::String(value)
538 }
539}
540
541impl FromIterator<Value> for Value {
542 fn from_iter<T: IntoIterator<Item = Value>>(iter: T) -> Self {
543 Self::Array(iter.into_iter().collect())
544 }
545}
546
547impl From<Model> for Value {
548 fn from(model: Model) -> Self {
549 Self::Model(model)
550 }
551}
552
553impl AttributesAccess for Value {
554 fn get_attributes_by_id(&self, id: &Identifier) -> Vec<crate::model::Attribute> {
555 match self {
556 Value::Model(model) => model.get_attributes_by_id(id),
557 _ => Vec::default(),
558 }
559 }
560}
561
562#[cfg(test)]
563fn integer(value: i64) -> Value {
564 Value::Integer(value)
565}
566
567#[cfg(test)]
568fn scalar(value: f64) -> Value {
569 Value::Quantity(Quantity::new(value, QuantityType::Scalar))
570}
571
572#[cfg(test)]
573fn check(result: ValueResult, value: Value) {
574 let result = result.expect("error result");
575 assert_eq!(result, value);
576}
577
578#[test]
579fn test_value_integer() {
580 let u = || integer(2);
581 let v = || integer(5);
582 let w = || scalar(5.0);
583
584 check(u() + v(), integer(2 + 5));
586 check(u() - v(), integer(2 - 5));
587 check(u() * v(), integer(2 * 5));
588 check(u() / v(), scalar(2.0 / 5.0));
589 check(-u(), integer(-2));
590
591 check(u() + w(), scalar(2 as Scalar + 5.0));
593 check(u() - w(), scalar(2 as Scalar - 5.0));
594 check(u() * w(), scalar(2 as Scalar * 5.0));
595 check(u() / w(), scalar(2.0 / 5.0));
596}
597
598#[test]
599fn test_value_scalar() {
600 let u = || scalar(2.0);
601 let v = || scalar(5.0);
602 let w = || integer(5);
603
604 check(u() + v(), scalar(2.0 + 5.0));
606 check(u() - v(), scalar(2.0 - 5.0));
607 check(u() * v(), scalar(2.0 * 5.0));
608 check(u() / v(), scalar(2.0 / 5.0));
609 check(-u(), scalar(-2.0));
610
611 check(u() + w(), scalar(2.0 + 5.0));
613 check(u() - w(), scalar(2.0 - 5.0));
614 check(u() * w(), scalar(2.0 * 5.0));
615 check(u() / w(), scalar(2.0 / 5.0));
616}