ombre: Support `dict` with lists

1c2549c99601f3484b985b5f0373d68fc445e883
Alexis Sellier committed ago 1 parent 4dee80ef
ombre/src/lisp/evaluator.rs +33 -20
1599 1599
            return Err(Error::WrongArgumentCount {
1600 1600
                expected: 1,
1601 1601
                actual: arity,
1602 1602
            });
1603 1603
        };
1604 -
        if let Expr::Vector(v) = expr {
1605 -
            let mut iter = v.into_iter();
1606 -
            let mut dict = HashMap::new();
1607 1604
1608 -
            loop {
1609 -
                let Some(k) = iter.next() else {
1610 -
                    break;
1611 -
                };
1612 -
                let Some(v) = iter.next() else {
1613 -
                    return Err(Error::ExpectedValue("any"));
1614 -
                };
1615 -
                let k = match Key::try_from(k) {
1616 -
                    Ok(key) => key,
1617 -
                    Err(e) => return Err(Error::UnexpectedValue(e)),
1618 -
                };
1619 -
                dict.insert(k, v);
1620 -
            }
1621 -
            Ok(Expr::Dict(dict))
1622 -
        } else {
1623 -
            Err(Error::ExpectedValue("vector"))
1605 +
        let mut iter: Box<dyn Iterator<Item = Expr>> = match expr {
1606 +
            Expr::Vector(v) => Box::new(v.into_iter()),
1607 +
            Expr::List(l) => Box::new(l.into_iter()),
1608 +
            _ => return Err(Error::ExpectedValue("list")),
1609 +
        };
1610 +
        let mut dict = HashMap::new();
1611 +
1612 +
        while let Some(k) = iter.next() {
1613 +
            let Some(v) = iter.next() else {
1614 +
                return Err(Error::ExpectedValue("any"));
1615 +
            };
1616 +
            let k = match Key::try_from(k) {
1617 +
                Ok(key) => key,
1618 +
                Err(e) => return Err(Error::UnexpectedValue(e)),
1619 +
            };
1620 +
            dict.insert(k, v);
1624 1621
        }
1622 +
        Ok(Expr::Dict(dict))
1625 1623
    }
1626 1624
1627 1625
    /// Lookup a value in a dictionary.
1628 1626
    pub fn lookup(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> {
1629 1627
        if args.len() != 2 {
2368 2366
                (Key::Atom("x".into()), Expr::Integer(1)),
2369 2367
                (Key::Atom("y".into()), Expr::Integer(2)),
2370 2368
                (Key::Atom("z".into()), Expr::Integer(3)),
2371 2369
            ])),
2372 2370
        );
2371 +
        expect(
2372 +
            &["(dict {:x 1 :y 2 :z 3})"],
2373 +
            Expr::Dict(HashMap::from_iter([
2374 +
                (Key::Atom("x".into()), Expr::Integer(1)),
2375 +
                (Key::Atom("y".into()), Expr::Integer(2)),
2376 +
                (Key::Atom("z".into()), Expr::Integer(3)),
2377 +
            ])),
2378 +
        );
2373 2379
        expect(
2374 2380
            &["(let [d (dict [1 :x 2 :y 3 :z])] (lookup 2 d))"],
2375 2381
            Expr::Atom("y".into()),
2376 2382
        );
2377 2383
        expect(
2383 2389
            ])),
2384 2390
        );
2385 2391
        expect(&["(dict)"], Expr::Dict(HashMap::new()));
2386 2392
        expect(&["(dict [])"], Expr::Dict(HashMap::new()));
2387 2393
        expect_err(&["(dict [:x])"], Error::ExpectedValue("any"));
2388 -
        expect_err(&["(dict {:x 1})"], Error::ExpectedValue("vector"));
2394 +
        expect_err(&["(dict :who)"], Error::ExpectedValue("list"));
2389 2395
    }
2390 2396
2391 2397
    #[test]
2392 2398
    fn test_map() {
2393 2399
        expect(
2428 2434
        );
2429 2435
        expect(
2430 2436
            &["{+ 1 2}"],
2431 2437
            Expr::list([Expr::Symbol("+".into()), Expr::Integer(1), Expr::Integer(2)]),
2432 2438
        );
2439 +
        expect(
2440 +
            &["{1 (2 3)}"],
2441 +
            Expr::list([
2442 +
                Expr::Integer(1),
2443 +
                Expr::list([Expr::Integer(2), Expr::Integer(3)]),
2444 +
            ]),
2445 +
        );
2433 2446
        expect(&["(eq? {} ())"], Expr::Bool(true));
2434 2447
        expect_err(&["(list (4 2))"], Error::ExpectedValue("function or atom"));
2435 2448
    }
2436 2449
2437 2450
    #[test]
ombre/src/lisp/list.rs +44 -0
121 121
        }
122 122
        list
123 123
    }
124 124
}
125 125
126 +
impl<T: Clone> List<T> {
127 +
    /// Split the list into its head element and tail.
128 +
    pub fn uncons(&mut self) -> Option<(T, List<T>)> {
129 +
        self.head.take().map(|node| match Rc::try_unwrap(node) {
130 +
            Ok(mut node) => {
131 +
                let tail = List {
132 +
                    head: node.next.take(),
133 +
                };
134 +
                (node.elem, tail)
135 +
            }
136 +
            Err(rc) => {
137 +
                let tail = List {
138 +
                    head: rc.next.clone(),
139 +
                };
140 +
                (rc.elem.clone(), tail)
141 +
            }
142 +
        })
143 +
    }
144 +
}
145 +
126 146
impl<T: PartialEq> List<T> {
127 147
    /// Check if the list contains an item.
128 148
    pub fn contains(&self, item: &T) -> bool {
129 149
        self.iter().any(|i| i == item)
130 150
    }
144 164
            &node.elem
145 165
        })
146 166
    }
147 167
}
148 168
169 +
/// Owned list iterator.
170 +
pub struct IntoIter<T> {
171 +
    list: List<T>,
172 +
}
173 +
174 +
impl<T: Clone> Iterator for IntoIter<T> {
175 +
    type Item = T;
176 +
177 +
    fn next(&mut self) -> Option<Self::Item> {
178 +
        let (head, tail) = self.list.uncons()?;
179 +
        self.list = tail;
180 +
        Some(head)
181 +
    }
182 +
}
183 +
184 +
impl<T: Clone + std::fmt::Debug> IntoIterator for List<T> {
185 +
    type Item = T;
186 +
    type IntoIter = IntoIter<T>;
187 +
188 +
    fn into_iter(self) -> Self::IntoIter {
189 +
        IntoIter { list: self }
190 +
    }
191 +
}
192 +
149 193
/// Nb. This function creates a list in reverse order.
150 194
impl<T> FromIterator<T> for List<T> {
151 195
    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
152 196
        let mut list = List::default();
153 197
        for item in iter {