ombre: Mutable dictionary support
5e59307a4dd59a318a24824825ec4b7f42fe98af
1 parent
67621d99
ombre/src/lang/evaluator.rs
+61 -39
| 213 | 213 | /// Eg. (vec3 x y z) |
|
| 214 | 214 | Vector3D(Vector3D<f64>), |
|
| 215 | 215 | /// Eg. (vec4 x y z w) |
|
| 216 | 216 | Vector4D(Vector4D<f64>), |
|
| 217 | 217 | /// Eg. (dict {:a 1 :b 2 :c 3}) |
|
| 218 | - | Dict(HashMap<Key, Expr>), |
|
| 218 | + | Dict(Mut<HashMap<Key, Expr>>), |
|
| 219 | 219 | /// Eg. fnord |
|
| 220 | 220 | Symbol(Symbol), |
|
| 221 | 221 | /// Eg. :yikes |
|
| 222 | 222 | Atom(Rc<str>), |
|
| 223 | 223 | /// Eg. "fnord" |
| 252 | 252 | /// Construct a vector. |
|
| 253 | 253 | pub fn vector(items: impl Into<Vec<Expr>>) -> Self { |
|
| 254 | 254 | Expr::Vector(Rc::from(RefCell::new(items.into()))) |
|
| 255 | 255 | } |
|
| 256 | 256 | ||
| 257 | + | /// Construct a dictionary. |
|
| 258 | + | pub fn dict(items: HashMap<Key, Expr>) -> Self { |
|
| 259 | + | Expr::Dict(Rc::from(RefCell::new(items))) |
|
| 260 | + | } |
|
| 261 | + | ||
| 257 | 262 | /// Construct a symbol. |
|
| 258 | 263 | pub fn symbol(name: impl Into<Symbol>) -> Self { |
|
| 259 | 264 | Expr::Symbol(name.into()) |
|
| 260 | 265 | } |
|
| 261 | 266 |
| 348 | 353 | _ => Err(expr), |
|
| 349 | 354 | } |
|
| 350 | 355 | } |
|
| 351 | 356 | } |
|
| 352 | 357 | ||
| 353 | - | impl TryFrom<Expr> for Rc<RefCell<Vec<Expr>>> { |
|
| 358 | + | impl TryFrom<Expr> for Mut<Vec<Expr>> { |
|
| 354 | 359 | type Error = Expr; |
|
| 355 | 360 | ||
| 356 | 361 | fn try_from(expr: Expr) -> std::result::Result<Self, Self::Error> { |
|
| 357 | 362 | match expr { |
|
| 358 | 363 | Expr::Vector(v) => Ok(v), |
|
| 359 | 364 | _ => Err(expr), |
|
| 360 | 365 | } |
|
| 361 | 366 | } |
|
| 362 | 367 | } |
|
| 363 | 368 | ||
| 369 | + | impl TryFrom<Expr> for Mut<HashMap<Key, Expr>> { |
|
| 370 | + | type Error = Expr; |
|
| 371 | + | ||
| 372 | + | fn try_from(expr: Expr) -> std::result::Result<Self, Self::Error> { |
|
| 373 | + | match expr { |
|
| 374 | + | Expr::Dict(d) => Ok(d), |
|
| 375 | + | _ => Err(expr), |
|
| 376 | + | } |
|
| 377 | + | } |
|
| 378 | + | } |
|
| 379 | + | ||
| 364 | 380 | impl TryFrom<Expr> for f32 { |
|
| 365 | 381 | type Error = Expr; |
|
| 366 | 382 | ||
| 367 | 383 | fn try_from(expr: Expr) -> std::result::Result<Self, Self::Error> { |
|
| 368 | 384 | match expr { |
| 622 | 638 | Expr::Vector2D(v) => write!(f, "[{} {}]", v.x, v.y), |
|
| 623 | 639 | Expr::Vector3D(v) => write!(f, "[{} {} {}]", v.x, v.y, v.z), |
|
| 624 | 640 | Expr::Vector4D(v) => write!(f, "[{} {} {} {}]", v.x, v.y, v.z, v.w), |
|
| 625 | 641 | Expr::Dict(d) => { |
|
| 626 | 642 | write!(f, "{{")?; |
|
| 643 | + | let d = d.borrow(); |
|
| 627 | 644 | let mut iter = d.iter(); |
|
| 628 | 645 | if let Some((k, v)) = iter.next() { |
|
| 629 | 646 | write!(f, "{k} {v}")?; |
|
| 630 | 647 | for (k, v) in iter { |
|
| 631 | 648 | write!(f, ", {k} {v}")?; |
| 1066 | 1083 | "dict", |
|
| 1067 | 1084 | "Create a new dictionary from the given list", |
|
| 1068 | 1085 | intrinsic::dict, |
|
| 1069 | 1086 | ); |
|
| 1070 | 1087 | env.intrinsic( |
|
| 1071 | - | "lookup", |
|
| 1072 | - | "Lookup a value in a dictionary, under the given key", |
|
| 1073 | - | intrinsic::lookup, |
|
| 1088 | + | "get", |
|
| 1089 | + | "Get a value in a dictionary, under the given key", |
|
| 1090 | + | intrinsic::get, |
|
| 1091 | + | ); |
|
| 1092 | + | env.intrinsic( |
|
| 1093 | + | "put", |
|
| 1094 | + | "Put a value in a dictionary, under the given key", |
|
| 1095 | + | intrinsic::put, |
|
| 1074 | 1096 | ); |
|
| 1075 | 1097 | env.intrinsic( |
|
| 1076 | 1098 | "map", |
|
| 1077 | 1099 | "Apply a function to each element of a tuple or vector", |
|
| 1078 | 1100 | intrinsic::map, |
| 1439 | 1461 | .map(Expr::vector), |
|
| 1440 | 1462 | Expr::Vector2D(v) => Ok(Expr::Vector2D(v)), |
|
| 1441 | 1463 | Expr::Vector3D(v) => Ok(Expr::Vector3D(v)), |
|
| 1442 | 1464 | Expr::Vector4D(v) => Ok(Expr::Vector4D(v)), |
|
| 1443 | 1465 | Expr::Dict(d) => d |
|
| 1466 | + | .borrow() |
|
| 1467 | + | .clone() |
|
| 1444 | 1468 | .into_iter() |
|
| 1445 | 1469 | .map(|(k, v)| eval(v, env).map(|v| (k, v))) |
|
| 1446 | 1470 | .collect::<Result<HashMap<_, _>>>() |
|
| 1447 | - | .map(Expr::Dict), |
|
| 1471 | + | .map(Expr::dict), |
|
| 1448 | 1472 | Expr::Ref(r) => Ok(Expr::Ref(r)), |
|
| 1449 | 1473 | Expr::Dynamic(d) => Ok(Expr::Dynamic(d)), |
|
| 1450 | 1474 | } |
|
| 1451 | 1475 | } |
|
| 1452 | 1476 |
| 1472 | 1496 | ("x", Expr::Vector4D(v)) => Ok(Expr::Float(v.x)), |
|
| 1473 | 1497 | ("y", Expr::Vector4D(v)) => Ok(Expr::Float(v.y)), |
|
| 1474 | 1498 | ("z", Expr::Vector4D(v)) => Ok(Expr::Float(v.z)), |
|
| 1475 | 1499 | ("w", Expr::Vector4D(v)) => Ok(Expr::Float(v.w)), |
|
| 1476 | 1500 | (_, Expr::Dict(dict)) => { |
|
| 1477 | - | if let Some(value) = dict.get(&Key::Atom(s)) { |
|
| 1501 | + | if let Some(value) = dict.borrow().get(&Key::Atom(s)) { |
|
| 1478 | 1502 | Ok(value.clone()) |
|
| 1479 | 1503 | } else { |
|
| 1480 | 1504 | Ok(Expr::Nil) |
|
| 1481 | 1505 | } |
|
| 1482 | 1506 | } |
| 1537 | 1561 | .flatten() |
|
| 1538 | 1562 | .into_iter() |
|
| 1539 | 1563 | .map(|(k, v)| (Key::Atom(k.0.clone()), v)) |
|
| 1540 | 1564 | .collect(); |
|
| 1541 | 1565 | ||
| 1542 | - | Ok(Expr::Dict(dict)) |
|
| 1566 | + | Ok(Expr::dict(dict)) |
|
| 1543 | 1567 | } |
|
| 1544 | 1568 | ||
| 1545 | 1569 | /// Get the first item of a tuple or vector. |
|
| 1546 | 1570 | pub fn first(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> { |
|
| 1547 | 1571 | let (list,) = <(Either<Vec<Expr>, Mut<Vec<Expr>>>,)>::try_from_args(args)?; |
| 1603 | 1627 | pub fn length(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> { |
|
| 1604 | 1628 | let (value,) = <(Expr,)>::try_from_args(args)?; |
|
| 1605 | 1629 | let length = match value { |
|
| 1606 | 1630 | Expr::Vector(l) => l.borrow().len(), |
|
| 1607 | 1631 | Expr::Tuple(l) => l.len(), |
|
| 1608 | - | Expr::Dict(d) => d.len(), |
|
| 1632 | + | Expr::Dict(d) => d.borrow().len(), |
|
| 1609 | 1633 | Expr::Str(s) => s.chars().count(), |
|
| 1610 | 1634 | _ => return Err(Error::UnexpectedValue(value)), |
|
| 1611 | 1635 | }; |
|
| 1612 | 1636 | Ok(Expr::Integer(length.try_into().expect( |
|
| 1613 | 1637 | "intrinsic::length: integer overflow on length calculation", |
| 1619 | 1643 | let (expr,) = <(Expr,)>::try_from_args(args)?; |
|
| 1620 | 1644 | let is_empty = match expr { |
|
| 1621 | 1645 | Expr::Vector(l) => l.borrow().is_empty(), |
|
| 1622 | 1646 | Expr::Tuple(l) => l.is_empty(), |
|
| 1623 | 1647 | Expr::Str(s) => s.is_empty(), |
|
| 1624 | - | Expr::Dict(d) => d.is_empty(), |
|
| 1648 | + | Expr::Dict(d) => d.borrow().is_empty(), |
|
| 1625 | 1649 | _ => return Err(Error::UnexpectedValue(expr)), |
|
| 1626 | 1650 | }; |
|
| 1627 | 1651 | Ok(Expr::Bool(is_empty)) |
|
| 1628 | 1652 | } |
|
| 1629 | 1653 | ||
| 1630 | 1654 | /// Create a dictionary. |
|
| 1631 | 1655 | pub fn dict(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> { |
|
| 1632 | 1656 | if args.is_empty() { |
|
| 1633 | - | return Ok(Expr::Dict(HashMap::new())); |
|
| 1657 | + | return Ok(Expr::dict(HashMap::new())); |
|
| 1634 | 1658 | } |
|
| 1635 | 1659 | let (list,) = <(Vec<Expr>,)>::try_from_args(args)?; |
|
| 1636 | 1660 | let mut dict = HashMap::new(); |
|
| 1637 | 1661 | let mut iter = list.into_iter(); |
|
| 1638 | 1662 |
| 1644 | 1668 | Ok(key) => key, |
|
| 1645 | 1669 | Err(e) => return Err(Error::UnexpectedValue(e)), |
|
| 1646 | 1670 | }; |
|
| 1647 | 1671 | dict.insert(k, v); |
|
| 1648 | 1672 | } |
|
| 1649 | - | Ok(Expr::Dict(dict)) |
|
| 1673 | + | Ok(Expr::dict(dict)) |
|
| 1650 | 1674 | } |
|
| 1651 | 1675 | ||
| 1652 | 1676 | /// Lookup a value in a dictionary. |
|
| 1653 | - | pub fn lookup(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> { |
|
| 1654 | - | if args.len() != 2 { |
|
| 1655 | - | return Err(Error::WrongArgumentCount { |
|
| 1656 | - | expected: 2, |
|
| 1657 | - | actual: args.len(), |
|
| 1658 | - | }); |
|
| 1659 | - | } |
|
| 1660 | - | let mut args = args.into_iter(); |
|
| 1661 | - | let Some(e) = args.next() else { |
|
| 1662 | - | return Err(Error::ExpectedValue("key")); |
|
| 1663 | - | }; |
|
| 1664 | - | let Some(Expr::Dict(d)) = args.next() else { |
|
| 1665 | - | return Err(Error::ExpectedValue("dictionary")); |
|
| 1666 | - | }; |
|
| 1667 | - | let k = match Key::try_from(e) { |
|
| 1668 | - | Ok(key) => key, |
|
| 1669 | - | Err(e) => return Err(Error::UnexpectedValue(e)), |
|
| 1670 | - | }; |
|
| 1671 | - | if let Some(v) = d.get(&k) { |
|
| 1677 | + | pub fn get(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> { |
|
| 1678 | + | let (dict, key) = <(Mut<HashMap<Key, Expr>>, Key)>::try_from_args(args)?; |
|
| 1679 | + | let d = dict.borrow(); |
|
| 1680 | + | ||
| 1681 | + | if let Some(v) = d.get(&key) { |
|
| 1672 | 1682 | Ok(v.clone()) |
|
| 1673 | 1683 | } else { |
|
| 1674 | 1684 | Ok(Expr::Nil) |
|
| 1675 | 1685 | } |
|
| 1676 | 1686 | } |
|
| 1677 | 1687 | ||
| 1688 | + | /// Set a value under a key in a dictionary. |
|
| 1689 | + | pub fn put(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> { |
|
| 1690 | + | let (dict, key, val) = <(Mut<HashMap<Key, Expr>>, Key, Expr)>::try_from_args(args)?; |
|
| 1691 | + | let mut d = dict.borrow_mut(); |
|
| 1692 | + | ||
| 1693 | + | if let Some(old) = d.insert(key, val) { |
|
| 1694 | + | Ok(old) |
|
| 1695 | + | } else { |
|
| 1696 | + | Ok(Expr::Nil) |
|
| 1697 | + | } |
|
| 1698 | + | } |
|
| 1699 | + | ||
| 1678 | 1700 | /// Check if a collection contains a key. |
|
| 1679 | 1701 | pub fn contains(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> { |
|
| 1680 | 1702 | if args.len() != 2 { |
|
| 1681 | 1703 | return Err(Error::WrongArgumentCount { |
|
| 1682 | 1704 | expected: 2, |
| 1698 | 1720 | Some(Expr::Dict(d)) => { |
|
| 1699 | 1721 | let k = match Key::try_from(key) { |
|
| 1700 | 1722 | Ok(key) => key, |
|
| 1701 | 1723 | Err(e) => return Err(Error::UnexpectedValue(e)), |
|
| 1702 | 1724 | }; |
|
| 1703 | - | d.contains_key(&k) |
|
| 1725 | + | d.borrow().contains_key(&k) |
|
| 1704 | 1726 | } |
|
| 1705 | 1727 | _ => return Err(Error::ExpectedValue("collection")), |
|
| 1706 | 1728 | }; |
|
| 1707 | 1729 | Ok(Expr::Bool(is_contained)) |
|
| 1708 | 1730 | } |
| 2485 | 2507 | ||
| 2486 | 2508 | #[test] |
|
| 2487 | 2509 | fn test_dict() { |
|
| 2488 | 2510 | expect( |
|
| 2489 | 2511 | &["{:x 1 :y 2 :z 3}"], |
|
| 2490 | - | Expr::Dict(HashMap::from_iter([ |
|
| 2512 | + | Expr::dict(HashMap::from_iter([ |
|
| 2491 | 2513 | (Key::Atom("x".into()), Expr::Integer(1)), |
|
| 2492 | 2514 | (Key::Atom("y".into()), Expr::Integer(2)), |
|
| 2493 | 2515 | (Key::Atom("z".into()), Expr::Integer(3)), |
|
| 2494 | 2516 | ])), |
|
| 2495 | 2517 | ); |
|
| 2496 | 2518 | expect( |
|
| 2497 | 2519 | &["(dict [:x 1 :y 2 :z (+ 2 1)])"], |
|
| 2498 | - | Expr::Dict(HashMap::from_iter([ |
|
| 2520 | + | Expr::dict(HashMap::from_iter([ |
|
| 2499 | 2521 | (Key::Atom("x".into()), Expr::Integer(1)), |
|
| 2500 | 2522 | (Key::Atom("y".into()), Expr::Integer(2)), |
|
| 2501 | 2523 | (Key::Atom("z".into()), Expr::Integer(3)), |
|
| 2502 | 2524 | ])), |
|
| 2503 | 2525 | ); |
|
| 2504 | 2526 | expect( |
|
| 2505 | 2527 | &["{:x 1 :y 2 :z (+ 2 1)}"], |
|
| 2506 | - | Expr::Dict(HashMap::from_iter([ |
|
| 2528 | + | Expr::dict(HashMap::from_iter([ |
|
| 2507 | 2529 | (Key::Atom("x".into()), Expr::Integer(1)), |
|
| 2508 | 2530 | (Key::Atom("y".into()), Expr::Integer(2)), |
|
| 2509 | 2531 | (Key::Atom("z".into()), Expr::Integer(3)), |
|
| 2510 | 2532 | ])), |
|
| 2511 | 2533 | ); |
|
| 2512 | 2534 | expect( |
|
| 2513 | - | &["(let [d {1 :x 2 :y 3 :z}] (lookup 2 d))"], |
|
| 2535 | + | &["(let [d {1 :x 2 :y 3 :z}] (get d 2))"], |
|
| 2514 | 2536 | Expr::Atom("y".into()), |
|
| 2515 | 2537 | ); |
|
| 2516 | 2538 | expect( |
|
| 2517 | 2539 | &["(dict [`x` 1 \"fnord\" 2 41 :a])"], |
|
| 2518 | - | Expr::Dict(HashMap::from_iter([ |
|
| 2540 | + | Expr::dict(HashMap::from_iter([ |
|
| 2519 | 2541 | (Key::Char('x'), Expr::Integer(1)), |
|
| 2520 | 2542 | (Key::Str("fnord".to_owned()), Expr::Integer(2)), |
|
| 2521 | 2543 | (Key::Integer(41), Expr::Atom("a".into())), |
|
| 2522 | 2544 | ])), |
|
| 2523 | 2545 | ); |
|
| 2524 | - | expect(&["(dict)"], Expr::Dict(HashMap::new())); |
|
| 2525 | - | expect(&["(dict [])"], Expr::Dict(HashMap::new())); |
|
| 2546 | + | expect(&["(dict)"], Expr::dict(HashMap::new())); |
|
| 2547 | + | expect(&["(dict [])"], Expr::dict(HashMap::new())); |
|
| 2526 | 2548 | expect_err(&["(dict [:x])"], Error::ExpectedValue("any")); |
|
| 2527 | 2549 | expect_err( |
|
| 2528 | 2550 | &["(dict :who)"], |
|
| 2529 | 2551 | Error::UnexpectedValue(Expr::Atom("who".into())), |
|
| 2530 | 2552 | ); |
ombre/src/lang/parser.rs
+4 -4
| 173 | 173 | let Some(v) = exprs.next() else { |
|
| 174 | 174 | return Err(Error::IncompleteDictPair(k)); |
|
| 175 | 175 | }; |
|
| 176 | 176 | dict.insert(k, v); |
|
| 177 | 177 | } |
|
| 178 | - | Ok(Expr::Dict(dict)) |
|
| 178 | + | Ok(Expr::dict(dict)) |
|
| 179 | 179 | } |
|
| 180 | 180 | ||
| 181 | 181 | fn parse_tuple_lit(&mut self) -> Result<Vec<Expr>> { |
|
| 182 | 182 | self.next_if(|t| t == &Token::LBracket)?; |
|
| 183 | 183 | let exprs = self.parse_until(|t| t == &Token::RBracket)?; |
| 334 | 334 | ); |
|
| 335 | 335 | } |
|
| 336 | 336 | ||
| 337 | 337 | #[test] |
|
| 338 | 338 | fn test_parse_dict() { |
|
| 339 | - | ok("{}", &[Expr::Dict(HashMap::default())]); |
|
| 339 | + | ok("{}", &[Expr::dict(HashMap::default())]); |
|
| 340 | 340 | ok( |
|
| 341 | 341 | "{:x 32 :y 64 :z 128}", |
|
| 342 | - | &[Expr::Dict(HashMap::from_iter([ |
|
| 342 | + | &[Expr::dict(HashMap::from_iter([ |
|
| 343 | 343 | (Key::Atom("x".into()), Expr::Integer(32)), |
|
| 344 | 344 | (Key::Atom("y".into()), Expr::Integer(64)), |
|
| 345 | 345 | (Key::Atom("z".into()), Expr::Integer(128)), |
|
| 346 | 346 | ]))], |
|
| 347 | 347 | ); |
|
| 348 | 348 | ok( |
|
| 349 | 349 | "{1 2}", |
|
| 350 | - | &[Expr::Dict(HashMap::from_iter([( |
|
| 350 | + | &[Expr::dict(HashMap::from_iter([( |
|
| 351 | 351 | Key::Integer(1), |
|
| 352 | 352 | Expr::Integer(2), |
|
| 353 | 353 | )]))], |
|
| 354 | 354 | ); |
|
| 355 | 355 | err("{:x}"); |
ombre/tests/basic.om
+17 -0
| 36 | 36 | (assert (eq? (pop v) 7)) |
|
| 37 | 37 | (assert (eq? v @[1 2 3 4 5 6])) |
|
| 38 | 38 | (assert (eq? (pop v) 6)) |
|
| 39 | 39 | (assert (eq? (pop @[]) nil))) |
|
| 40 | 40 | ||
| 41 | + | ;; Test dictionary operations |
|
| 42 | + | (assert (eq? (dict) {})) |
|
| 43 | + | (assert (eq? (dict []) {})) |
|
| 44 | + | (assert (eq? (dict [:x 1 :y 2 :z (+ 2 1)]) {:x 1 :y 2 :z 3})) |
|
| 45 | + | (assert (eq? (let [d {1 :x 2 :y 3 :z}] (get d 2)) :y)) |
|
| 46 | + | ||
| 47 | + | (do |
|
| 48 | + | (def d {:x 1 :y 2 :z 3}) |
|
| 49 | + | (assert (eq? (get d :x) 1)) |
|
| 50 | + | (assert (eq? (get d :y) 2)) |
|
| 51 | + | (assert (eq? (get d :z) 3)) |
|
| 52 | + | (assert (eq? (get d :w) nil)) |
|
| 53 | + | (assert (eq? (put d :w 4) nil)) |
|
| 54 | + | (assert (eq? (get d :w) 4)) |
|
| 55 | + | (assert (eq? (put d :w 5) 4)) |
|
| 56 | + | (assert (eq? (get d :w) 5))) |
|
| 57 | + | ||
| 41 | 58 | ;; Test boolean operations |
|
| 42 | 59 | (assert true) |
|
| 43 | 60 | (assert (not false)) |
|
| 44 | 61 | (assert (and true true)) |
|
| 45 | 62 | (assert (not (and true false))) |