- let preorder = &mut b.syntax().preorder();
- let ev_as_expr = |ev| match ev {
- WalkEvent::Enter(it) => Some(WalkEvent::Enter(ast::Expr::cast(it)?)),
- WalkEvent::Leave(it) => Some(WalkEvent::Leave(ast::Expr::cast(it)?)),
- };
- let eq_label = |lt: Option<ast::Lifetime>| {
- lt.zip(label.as_ref()).map_or(false, |(lt, lbl)| lt.text() == lbl.text())
- };
- while let Some(node) = preorder.find_map(ev_as_expr) {
- match node {
- WalkEvent::Enter(expr) => match expr {
- ast::Expr::LoopExpr(_) | ast::Expr::WhileExpr(_) | ast::Expr::ForExpr(_) => {
- depth += 1
- }
- ast::Expr::BlockExpr(e) if e.label().is_some() => depth += 1,
- ast::Expr::BreakExpr(b)
- if (depth == 0 && b.lifetime().is_none()) || eq_label(b.lifetime()) =>
- {
- cb(b);
- }
- _ => (),
- },
- WalkEvent::Leave(expr) => match expr {
- ast::Expr::LoopExpr(_) | ast::Expr::WhileExpr(_) | ast::Expr::ForExpr(_) => {
- depth -= 1
- }
- ast::Expr::BlockExpr(e) if e.label().is_some() => depth -= 1,
- _ => (),
- },
+ let tree_depth_iterator = TreeWithDepthIterator::new(b);
+ for (expr, depth) in tree_depth_iterator {
+ match expr {
+ ast::Expr::BreakExpr(b)
+ if (depth == 0 && b.lifetime().is_none())
+ || eq_label_lt(&label, &b.lifetime()) =>
+ {
+ cb(b);
+ }
+ _ => (),
+ }
+ }
+ }
+}
+
+fn eq_label_lt(lt1: &Option<ast::Lifetime>, lt2: &Option<ast::Lifetime>) -> bool {
+ lt1.as_ref().zip(lt2.as_ref()).map_or(false, |(lt, lbl)| lt.text() == lbl.text())
+}
+
+struct TreeWithDepthIterator {
+ preorder: Preorder<RustLanguage>,
+ depth: i32,
+}
+
+impl TreeWithDepthIterator {
+ fn new(body: ast::StmtList) -> Self {
+ let preorder = body.syntax().preorder();
+ Self { preorder, depth: 0 }
+ }
+}
+
+impl<'a> Iterator for TreeWithDepthIterator {
+ type Item = (ast::Expr, i32);
+
+ fn next(&mut self) -> Option<Self::Item> {
+ while let Some((event, expr)) = self.preorder.find_map(|ev| match ev {
+ WalkEvent::Enter(it) => Some(WalkEvent::Enter(())).zip(ast::Expr::cast(it)),
+ WalkEvent::Leave(it) => Some(WalkEvent::Leave(())).zip(ast::Expr::cast(it)),
+ }) {
+ match (event, expr) {
+ (
+ WalkEvent::Enter(_),
+ ast::Expr::LoopExpr(_) | ast::Expr::WhileExpr(_) | ast::Expr::ForExpr(_),
+ ) => {
+ self.depth += 1;
+ }
+ (
+ WalkEvent::Leave(_),
+ ast::Expr::LoopExpr(_) | ast::Expr::WhileExpr(_) | ast::Expr::ForExpr(_),
+ ) => {
+ self.depth -= 1;
+ }
+ (WalkEvent::Enter(_), ast::Expr::BlockExpr(e)) if e.label().is_some() => {
+ self.depth += 1;
+ }
+ (WalkEvent::Leave(_), ast::Expr::BlockExpr(e)) if e.label().is_some() => {
+ self.depth -= 1;
+ }
+ (WalkEvent::Enter(_), expr) => return Some((expr, self.depth)),
+ _ => (),