Skip to content

Commit 2af9e60

Browse files
fix(cbm): replace O(N²) indexed loop with O(N) cursor in parse_generic_imports
ts_node_child(root, i) and ts_node_next_sibling() both call ts_node_child_with_descendant() internally, making sibling iteration O(N²) total on roots with many children (e.g. generated TypeScript .d.ts files or large Perl files with 5,000–50,000 top-level nodes). Replace with TSTreeCursor: ts_tree_cursor_goto_next_sibling() maintains traversal state across calls and is O(1) per step, reducing total complexity from O(N²) to O(N). Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
1 parent 75b5dcb commit 2af9e60

1 file changed

Lines changed: 14 additions & 4 deletions

File tree

internal/cbm/extract_imports.c

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -575,9 +575,18 @@ static void parse_lua_imports(CBMExtractCtx *ctx) {
575575
static void parse_generic_imports(CBMExtractCtx *ctx, const char *node_type) {
576576
CBMArena *a = ctx->arena;
577577

578-
uint32_t count = ts_node_child_count(ctx->root);
579-
for (uint32_t i = 0; i < count; i++) {
580-
TSNode node = ts_node_child(ctx->root, i);
578+
/* Use TSTreeCursor for O(1)-per-step sibling traversal.
579+
* ts_node_child(root, i) and ts_node_next_sibling() both call
580+
* ts_node_child_with_descendant() internally, making naive iteration
581+
* O(N²) on roots with thousands of children (e.g. generated .d.ts files).
582+
* ts_tree_cursor_goto_next_sibling() maintains cursor state and is O(1). */
583+
TSTreeCursor cursor = ts_tree_cursor_new(ctx->root);
584+
if (!ts_tree_cursor_goto_first_child(&cursor)) {
585+
ts_tree_cursor_delete(&cursor);
586+
return;
587+
}
588+
do {
589+
TSNode node = ts_tree_cursor_current_node(&cursor);
581590
if (strcmp(ts_node_type(node), node_type) != 0) {
582591
continue;
583592
}
@@ -616,7 +625,8 @@ static void parse_generic_imports(CBMExtractCtx *ctx, const char *node_type) {
616625
}
617626
}
618627
}
619-
}
628+
} while (ts_tree_cursor_goto_next_sibling(&cursor));
629+
ts_tree_cursor_delete(&cursor);
620630
}
621631

622632
// --- Wolfram imports ---

0 commit comments

Comments
 (0)