Returns the node with a minimal range that fully contains `range`. If `range` is empty and falls within a parser *synthesized* node generated during error recovery, then the first node with the given range is returned. ## Panics Panics if `range` is not contained within `root`.
(root: AnyNodeRef, range: TextRange)
| 12 | /// ## Panics |
| 13 | /// Panics if `range` is not contained within `root`. |
| 14 | pub fn covering_node(root: AnyNodeRef, range: TextRange) -> CoveringNode { |
| 15 | struct Visitor<'a> { |
| 16 | range: TextRange, |
| 17 | found: bool, |
| 18 | ancestors: Vec<AnyNodeRef<'a>>, |
| 19 | } |
| 20 | |
| 21 | impl<'a> SourceOrderVisitor<'a> for Visitor<'a> { |
| 22 | fn enter_node(&mut self, node: AnyNodeRef<'a>) -> TraversalSignal { |
| 23 | // If the node fully contains the range, than it is a possible match but traverse into its children |
| 24 | // to see if there's a node with a narrower range. |
| 25 | if !self.found && node.range().contains_range(self.range) { |
| 26 | self.ancestors.push(node); |
| 27 | TraversalSignal::Traverse |
| 28 | } else { |
| 29 | TraversalSignal::Skip |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | fn leave_node(&mut self, node: AnyNodeRef<'a>) { |
| 34 | if !self.found && self.ancestors.last() == Some(&node) { |
| 35 | self.found = true; |
| 36 | } |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | assert!( |
| 41 | root.range().contains_range(range), |
| 42 | "Range is not contained within root" |
| 43 | ); |
| 44 | |
| 45 | let mut visitor = Visitor { |
| 46 | range, |
| 47 | found: false, |
| 48 | ancestors: Vec::new(), |
| 49 | }; |
| 50 | |
| 51 | walk_node(&mut visitor, root); |
| 52 | CoveringNode::from_ancestors(visitor.ancestors) |
| 53 | } |
| 54 | |
| 55 | /// The node with a minimal range that fully contains the search range. |
| 56 | pub struct CoveringNode<'a> { |
no test coverage detected