Skip to content

Commit a7e2b9c

Browse files
committed
pkgcheck/bash: sort captures by line and column
It has been observed that the order of nodes returned by tree-sitter's QueryCursor is not necessarily in order wrt line and column in the source, but it appears that some of pkgcheck's usage of tree-sitter assumes that captured nodes are returned in order. There doesn't appear to any features in QueryCursor (or other places) that allows one to specify that returned nodes should be ordered in a specific way, so instead we introduce a decorator on QueryCursor that takes dict of captured nodes and sorts each list of nodes by line and column. Signed-off-by: Thomas Bracht Laumann Jespersen <t@laumann.xyz>
1 parent 5e3d093 commit a7e2b9c

1 file changed

Lines changed: 25 additions & 1 deletion

File tree

src/pkgcheck/bash/__init__.py

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,32 @@ def query(query_str: str) -> "QueryCursor":
1919

2020
parser = Parser(language=lang)
2121

22+
23+
class SortedQuery:
24+
"""
25+
Sort query results by line and column. It's been observed that
26+
query results are not consistently returned in the same order
27+
"""
28+
29+
def __init__(self, query_cursor: QueryCursor):
30+
self._query_cursor = query_cursor
31+
32+
def captures(self, node):
33+
# QueryCursor.captures() returns a dict of lists, we decorate
34+
# it and return the sorted lists
35+
caps = self._query_cursor.captures(node)
36+
return {
37+
key: sorted(nodes, key=lambda n: (n.start_point.row, n.start_point.column))
38+
for key, nodes in caps.items()
39+
}
40+
41+
42+
def sorted_query(query_str: str):
43+
return SortedQuery(query(query_str))
44+
45+
2246
# various parse tree queries
23-
cmd_query = query("(command) @call")
47+
cmd_query = sorted_query("(command) @call")
2448
func_query = query("(function_definition) @func")
2549
var_assign_query = query("(variable_assignment) @assign")
2650
var_expansion_query = query("(expansion) @exp")

0 commit comments

Comments
 (0)