Skip to content

Use a truncating remainder for XPath mod - #386

Merged
naitoh merged 2 commits into
ruby:masterfrom
sourya2704:xpath-mod-truncating-remainder
Nov 28, 2026
Merged

naitoh merged 2 commits into
ruby:masterfrom
sourya2704:xpath-mod-truncating-remainder

Conversation

@sourya2704

Copy link
Copy Markdown
Contributor

Fixes #385.

XPath 1.0 defines mod as the remainder from a truncating division, but the parser used Ruby's %, which floors, so the sign followed the right operand. This uses Numeric#remainder instead:

spec before after
5 mod -2 1 -1 1
-5 mod 2 -1 1 -1
-0.5 mod 3 -0.5 2.5 -0.5

x mod 0 raised ZeroDivisionError, because Float#% and Float#remainder both raise for a zero divisor. It now returns NaN, like div by zero already returns Infinity or NaN.

The new tests use the spec's examples and fail without the change.

XPath 1.0 defines mod as the remainder from a truncating division, so 5 mod -2 is 1 and -5 mod 2 is -1. Ruby's % floors instead. x mod 0 also raised ZeroDivisionError, while it should be NaN like div by zero.

@naitoh naitoh left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for fixing the XPath mod operator!
The implementation in lib/rexml/xpath_parser.rb matches the XPath 1.0 specification and looks good to me.

I left one minor inline suggestion on test/xpath/test_base.rb to use individual assert_equal calls for readability.

Comment thread test/xpath/test_base.rb Resolved

@naitoh naitoh left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1

@naitoh
naitoh merged commit cf4c2fe into ruby:master Nov 28, 2026
71 checks passed
@naitoh

naitoh commented Nov 28, 2026

Copy link
Copy Markdown
Contributor

Thanks!

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.

XPath: mod uses floored modulo instead of truncating remainder

2 participants