getRootOfSubtreeEnclosingRegion static method

ParserRuleContext? getRootOfSubtreeEnclosingRegion(
  1. ParseTree t,
  2. int startTokenIndex,
  3. int stopTokenIndex
)

Find smallest subtree of t enclosing range startTokenIndex..stopTokenIndex inclusively using postorder traversal. Recursive depth-first-search.

@since 4.5.1

Implementation

static ParserRuleContext? getRootOfSubtreeEnclosingRegion(
  ParseTree t,
  int startTokenIndex, // inclusive
  int stopTokenIndex, // inclusive
) {
  final n = t.childCount;
  for (var i = 0; i < n; i++) {
    final child = t.getChild(i)!;
    final r = getRootOfSubtreeEnclosingRegion(
      child,
      startTokenIndex,
      stopTokenIndex,
    );
    if (r != null) return r;
  }
  if (t is ParserRuleContext) {
    // is range fully contained in t?
    final start = t.start != null && startTokenIndex >= t.start!.tokenIndex;
    final end = t.stop == null || stopTokenIndex <= t.stop!.tokenIndex;
    if (start && end) {
      return t;
    }
  }
  return null;
}