Skip to content

Commit 0ca8dba

Browse files
author
Trinketer22
committed
Extended parent and sibling search utils
1 parent 3b9aef5 commit 0ca8dba

File tree

1 file changed

+24
-1
lines changed

1 file changed

+24
-1
lines changed

server/src/psi/utils.ts

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
// SPDX-License-Identifier: MIT
22
// Copyright © 2025 TON Core
3-
import type {Node as SyntaxNode} from "web-tree-sitter"
3+
import type { Node as SyntaxNode } from "web-tree-sitter"
44

55
export function parentOfType(node: SyntaxNode, ...types: readonly string[]): SyntaxNode | null {
66
let parent = node.parent
@@ -13,6 +13,29 @@ export function parentOfType(node: SyntaxNode, ...types: readonly string[]): Syn
1313

1414
return null
1515
}
16+
export function parentOfTypeWithCb<T>(node: SyntaxNode, cb: (parent: SyntaxNode, branch: SyntaxNode) => T, ...types: readonly string[]): T | null {
17+
let parent = node.parent;
18+
let prevNode = node;
19+
20+
for (let i = 0; i < 100; i++) {
21+
if (parent === null) return null
22+
if (types.includes(parent.type)) return cb(parent, prevNode)
23+
prevNode = parent;
24+
parent = parent.parent
25+
}
26+
27+
return null
28+
}
29+
export function closestNamedSibling(node: SyntaxNode, direction: 'prev' | 'next', cb: (sibling: SyntaxNode) => boolean): SyntaxNode | null {
30+
let curSibling = direction == 'prev' ? node.previousNamedSibling : node.nextNamedSibling;
31+
while (curSibling) {
32+
if (cb(curSibling)) {
33+
return curSibling;
34+
}
35+
curSibling = direction == 'prev' ? curSibling.previousNamedSibling : curSibling.nextNamedSibling;
36+
}
37+
return null;
38+
}
1639

1740
export function measureTime<T>(label: string, fn: () => T): T {
1841
const startTime = performance.now()

0 commit comments

Comments
 (0)