Skip to main content

find_node_at_offset

Function find_node_at_offset 

Source
pub fn find_node_at_offset(node: &Node, offset: usize) -> Option<&Node>
Expand description

Finds the most specific AST node containing the given byte offset.

Performs recursive descent through the AST to locate the deepest node that encompasses the specified position. Essential for cursor-based LSP operations like go-to-definition and hover.

§Arguments

  • node - AST node to search within (typically root)
  • offset - Byte offset in the source document

§Returns

  • Some(&Node) - Deepest node containing the offset
  • None - Offset is outside the node’s range

§Performance

  • Search time: O(log n) average, O(n) worst case
  • Memory: Zero allocations, returns borrowed reference
  • Spatial locality: Optimized for sequential offset queries

§LSP Integration

Core primitive for:

  • Hover information: Find node for symbol details
  • Go-to-definition: Identify symbol under cursor
  • Completion: Determine context for suggestions
  • Diagnostics: Map error positions to AST nodes

§Examples

use perl_parser::declaration::find_node_at_offset;
use perl_parser::ast::Node;

let ast = Node::new_root();
if let Some(node) = find_node_at_offset(&ast, 42) {
    println!("Found node: {:?}", node.kind);
}