Skip to content

Count last() over the attribute axis - #194

Open
shounakjoshi88-a11y wants to merge 1 commit into
antchfx:masterfrom
shounakjoshi88-a11y:fix/last-on-attribute-axis
Open

shounakjoshi88-a11y wants to merge 1 commit into
antchfx:masterfrom
shounakjoshi88-a11y:fix/last-on-attribute-axis

Conversation

@shounakjoshi88-a11y

Copy link
Copy Markdown

The bug

last() in a predicate on the attribute axis always reports 1, so @*[last()]
selects the first attribute instead of the last one. For
<r k="1" n="2">:

Expression Before libxml2 / XPath 1.0
@*[last()] @k @n
@*[position()=last()] @k @n

lastFunc uses a fast path when it can count the input query, otherwise it
falls back to walking siblings with MoveToFirst/MoveToNext. Attribute
nodes are not siblings - those calls walk the parent element's children - so
the fallback sees a single node and returns 1. The numeric predicates ([1],
[2], position()=2) already work because they use the axis query's
position().

The fix

When the context node is an attribute, count the parent element's attribute
axis instead of the sibling axis:

if node.NodeType() == AttributeNode {
    if !node.MoveToParent() {
        return float64(0)
    }
    for node.MoveToNextAttribute() {
        if test(node) {
            count++
        }
    }
    return float64(count)
}

This follows the same shape as the existing fix for last() on the following
axes (#188).

Verification

  • Extended Test_attribute_position with @*[last()], @*[position()=last()]
    on one element and across several elements. The new cases fail on the
    unmodified tree ('1' and '0' are not equal) and pass with the change.
  • A Hegel corpus property pin (TestHegelPinAttributePositions) compares the
    expression against lxml 6.1; it fails on upstream HEAD and passes with this
    change.
  • go test ./... green (full package suite); gofmt clean.

No AI policy or CONTRIBUTING file in this repository, so no agent trailer on
the commit.

last() on @* used the fallback that walks sibling nodes with
MoveToFirst/MoveToNext. Attributes are not siblings, so it always counted
one node and @*[last()] selected the first attribute instead of the last.
When the context node is an attribute, walk the parent's attribute axis
instead. Extends Test_attribute_position with last() and position()=last()
cases, which fail without the change.
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.

1 participant