Skip to content

Commit 4495e40

Browse files
Marcono1234ObserverOfTime
authored andcommitted
fix(query): fix overflow for capture count
1 parent 5266b48 commit 4495e40

File tree

2 files changed

+14
-2
lines changed

2 files changed

+14
-2
lines changed

src/main/java/io/github/treesitter/jtreesitter/Query.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -544,10 +544,10 @@ public MatchesIterator(Tree tree, @Nullable BiPredicate<QueryPredicate, QueryMat
544544
public boolean tryAdvance(Consumer<? super QueryMatch> action) {
545545
MemorySegment match = arena.allocate(TSQueryMatch.layout());
546546
if (!ts_query_cursor_next_match(cursor, match)) return false;
547-
var count = TSQueryMatch.capture_count(match);
547+
var count = Short.toUnsignedInt(TSQueryMatch.capture_count(match));
548548
var matchCaptures = TSQueryMatch.captures(match);
549549
var captureList = new ArrayList<QueryCapture>(count);
550-
for (short i = 0; i < count; ++i) {
550+
for (int i = 0; i < count; ++i) {
551551
var capture = TSQueryCapture.asSlice(matchCaptures, i);
552552
var name = captureNames.get(TSQueryCapture.index(capture));
553553
var node = TSNode.allocate(arena).copyFrom(TSQueryCapture.node(capture));

src/test/java/io/github/treesitter/jtreesitter/QueryTest.java

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -288,5 +288,17 @@ void findMatches() {
288288
"Foo", matches.getFirst().captures().getFirst().node().getText());
289289
});
290290
}
291+
292+
// Verify that capture count is treated as `uint16_t` and not as signed Java `short`
293+
try (var tree = parser.parse(";".repeat(Short.MAX_VALUE + 1)).orElseThrow()) {
294+
var source = """
295+
";"+ @capture
296+
""";
297+
assertQuery(source, query -> {
298+
var matches = query.findMatches(tree.getRootNode()).toList();
299+
assertEquals(1, matches.size());
300+
assertEquals(Short.MAX_VALUE + 1, matches.getFirst().captures().size());
301+
});
302+
}
291303
}
292304
}

0 commit comments

Comments
 (0)