Skip to content

Commit fe9e775

Browse files
committed
Implement try-catch without label $x | ....
1 parent df70529 commit fe9e775

File tree

2 files changed

+13
-12
lines changed

2 files changed

+13
-12
lines changed

jaq-core/src/compile.rs

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -671,15 +671,9 @@ impl<'s, F> Compiler<&'s str, F> {
671671
t
672672
}
673673
Num(n) => n.parse().map_or_else(|_| Term::Num(n.into()), Term::Int),
674-
// map `try f catch g` to `label $x | try f catch (g, break $x)`
675-
// and `try f` or `f?` to `label $x | try f catch ( break $x)`
676674
TryCatch(try_, catch) => {
677-
let catch = match catch {
678-
None => Break(""),
679-
Some(c) => BinOp(c, parse::BinaryOp::Comma, Break("").into()),
680-
};
681-
let tc = self.with_label("", |c| Term::TryCatch(c.iterm(*try_), c.iterm(catch)));
682-
Term::Label(self.lut.insert_term(tc))
675+
let catch = catch.map_or_else(|| Call("!empty", Vec::new()), |t| *t);
676+
Term::TryCatch(self.iterm(*try_), self.iterm(catch))
683677
}
684678
Fold(name, xs, pat, args) => {
685679
use self::Fold::{Foreach, Reduce};

jaq-core/src/filter.rs

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -321,11 +321,18 @@ impl<F: FilterT<F>> FilterT<F> for Id {
321321
Ast::ObjSingle(k, v) => Box::new(
322322
Self::cartesian(k, v, lut, cv).map(|(k, v)| Ok(Self::V::from_map([(k?, v?)])?)),
323323
),
324-
// TODO: write test for `try (break $x)`
325324
Ast::TryCatch(f, c) => {
326-
Box::new(f.run(lut, (cv.0.clone(), cv.1)).flat_map(move |y| match y {
327-
Err(Exn(exn::Inner::Err(e))) => c.run(lut, (cv.0.clone(), e.into_val())),
328-
y => box_once(y),
325+
let mut ys = f.run(lut, (cv.0.clone(), cv.1));
326+
let mut end: Option<ValXs<_>> = None;
327+
Box::new(core::iter::from_fn(move || match &mut end {
328+
Some(end) => end.next(),
329+
None => match ys.next()? {
330+
Err(Exn(exn::Inner::Err(e))) => {
331+
end = Some(c.run(lut, (cv.0.clone(), e.into_val())));
332+
end.as_mut().and_then(|end| end.next())
333+
}
334+
y => Some(y),
335+
},
329336
}))
330337
}
331338
Ast::Neg(f) => Box::new(f.run(lut, cv).map(|v| Ok((-v?)?))),

0 commit comments

Comments
 (0)