findNodesAtPosition method

List<AstNode> findNodesAtPosition(
  1. int offset, {
  2. int length = 0,
})

Attempts to find the most relevant (bottom-most in the AST) nodes that intersects with the source range from offset to offset + length.

Implementation

List<AstNode> findNodesAtPosition(int offset, {int length = 0}) {
  if (tokens.isEmpty) return const [];

  final candidates = <AstNode>{};
  final unchecked = Queue<AstNode>();
  unchecked.add(rootNode);

  while (unchecked.isNotEmpty) {
    final node = unchecked.removeFirst();

    final span = node.span!;
    final start = span.start.offset;
    final end = span.end.offset;

    final hasIntersection = !(end < offset || start > offset + length);
    if (hasIntersection) {
      // this node matches. As we want to find the bottom-most node in the AST
      // that matches, this means that the parent is no longer a candidate.
      candidates.add(node);
      candidates.remove(node.parent);

      // assume that the span of a node is a superset of the span of any
      // child, so each child could potentially be interesting.
      unchecked.addAll(node.childNodes);
    }
  }

  return candidates.toList();
}