Skip to content

Count last() over the remaining axes - #192

Open
lprnmns wants to merge 1 commit into
antchfx:masterfrom
lprnmns:fix/last-on-remaining-axes
Open

lprnmns wants to merge 1 commit into
antchfx:masterfrom
lprnmns:fix/last-on-remaining-axes

Conversation

@lprnmns

@lprnmns lprnmns commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

#188 made last() count the nodes that a following or following-sibling step selects for its context node. The other axes still use the fallback in lastFunc, which counts the siblings of the candidate node. That count is only the context size on the child axis, so last() is wrong on the remaining axes.

Using employee_example from the tests (line numbers):

Expression Before Expected
/empinfo/descendant-or-self::*[last()] 2, 4 16
//employee[@id=2]/descendant-or-self::*[last()-3] (none) 8
//name/ancestor::*[last()] (none) 2
//name/ancestor-or-self::*[last()] (none) 2
//name/parent::*[last()] (none) 3, 8, 13
//name/self::*[last()] (none) 4, 9, 14
//employee[@id=3]/preceding::*[last()] 9 3
//employee[@id=3]/preceding-sibling::*[last()] (none) 3
//employee[@id=3]/preceding-sibling::*[last()-1] 3 8
/root/item/@*[last()] (the document in Test_attribute_position) 1, 4, 6 3, 5, 6

Fix

Following the same pattern as #188, ancestorQuery, attributeQuery, descendantQuery and precedingQuery record the context node when they start on a new input node, and their contextSize() counts the nodes their axis selects from it, caching the result per context node. parentQuery and selfQuery select at most one node per context node, and the predicate is only evaluated for a node that was selected, so their context size is 1.

Tests

Test_descendant_last, Test_ancestor_last, Test_parent_last, Test_self_last and Test_preceding_last are new, and Test_attribute_position has two more cases. Each of them fails on master, and go test ./... and go vet ./... pass.

I also compared //x/AXIS::*[last()], [last()-1] and [position()=last()] on all twelve axes with lxml over 400 random documents. With this change the only differences left are the order of the results, which #187 covers.

Two related cases are not changed here and fail on master too:

  • A predicate after another predicate still uses the fallback, for example //b/ancestor::*[@id][last()].
  • A predicate on a parenthesized expression still uses the fallback, for example (//c)[last()-1] and (//c)[position()=last()]. [last()] alone on a group already works through lastFuncQuery.

@coveralls

Copy link
Copy Markdown

Coverage Status

coverage: 85.942% (+0.2%) from 85.736% — lprnmns:fix/last-on-remaining-axes into antchfx:master

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants