Skip to content

Fix parsing xpath that has string literal containing parentheses and brackets - #318

Merged
naitoh merged 1 commit into
ruby:masterfrom
tompng:xpath_paren_bracket_in_string
Jun 4, 2026
Merged

naitoh merged 1 commit into
ruby:masterfrom
tompng:xpath_paren_bracket_in_string

Conversation

@tompng

@tompng tompng commented May 24, 2026 •

Copy link
Copy Markdown
Member

String literal in XPath 1.0 doesn't have escapes.
begin end while cond is not a normal modifier while, but a do-while loop. (I didn't know it). REXML uses this syntax in several files.

Removes preprocessing that removes spaces with gsub which may wrongly modifies string literal.
Also fixes error parsing //a[1] [2].
All test except exact-error-message test and the one I added in this PR passed with:

def parse path
  path = path.gsub('(', '( ').gsub(/[\)\[\]]/, ' \0 ') # Insert space around paren/bracket

REF: https://www.w3.org/TR/xpath-10/#exprlex

For readability, whitespace may be used in expressions even though not explicitly allowed by the grammar: ExprWhitespace may be freely added within patterns before or after any ExprToken.

Copilot AI review requested due to automatic review settings May 24, 2026 17:38

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

Note

Copilot was unable to run its full agentic suite in this review.

This PR improves XPath parsing robustness around whitespace handling, especially when spaces appear inside string literals, and adds regression tests to cover these cases.

Changes:

  • Add tests validating that extra whitespace in XPath expressions is treated as ignorable where appropriate.
  • Update XPathParser#parse to strip ignorable spaces without altering whitespace inside quoted string literals.
  • Update group parsing to ignore parentheses/brackets that appear inside quoted string literals.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 3 comments.

File Description
test/xpath/test_base.rb Adds test coverage for whitespace normalization and for bracket/paren characters inside XPath string literals.
lib/rexml/parsers/xpathparser.rb Refactors space-stripping into a helper that respects string literals; improves grouping logic to ignore delimiters inside quotes.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread lib/rexml/parsers/xpathparser.rb Resolved
Comment thread lib/rexml/parsers/xpathparser.rb Resolved
Comment thread lib/rexml/parsers/xpathparser.rb Resolved
@tompng
tompng force-pushed the xpath_paren_bracket_in_string branch from f342f18 to 1578eb2 Compare May 27, 2026 04:42
…brackets

Also fixes xpath that has space around closing paren and opening/closing brackets that removing spaces with gsub wrongly removes spaces within string literal.
Copilot AI review requested due to automatic review settings June 3, 2026 17:27
@tompng
tompng force-pushed the xpath_paren_bracket_in_string branch from 1578eb2 to 8aa671b Compare June 3, 2026 17:27
@tompng tompng changed the title Fix xpath parsing xpath that has string literal containing parentheses and brackets Fix parsing xpath that has string literal containing parentheses and brackets Jun 3, 2026

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 3 out of 3 changed files in this pull request and generated 3 comments.

Comment thread test/xpath/test_base.rb
match.call('/ a / child:: c [( @id )] /'))
end

def test_space_paren_brace_inside_xpath_string
Comment on lines +359 to 368
path = $'.lstrip
literal = nil
if path =~ /^\s*\)/
path = $'
else
unless path.start_with?(')')
path =~ LITERAL
literal = $1
path = $'
path = $'.lstrip
raise ParseException.new("Missing ')' after processing instruction") if path[0] != ?)
path = path[1..-1]
end
path = path[1..-1]
parsed << :processing_instruction
Comment on lines 21 to 24
def parse path
path = path.dup
path.gsub!(/([\(\[])\s+/, '\1') # Strip ignorable spaces
path.gsub!( /\s+([\]\)])/, '\1')
parsed = []
rest = OrExpr(path, parsed)
if rest

@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.

Thanks!

@naitoh
naitoh merged commit a98066c into ruby:master Jun 4, 2026
71 of 73 checks passed
@tompng
tompng deleted the xpath_paren_bracket_in_string branch June 4, 2026 03:05
naitoh added a commit to naitoh/rexml that referenced this pull request Nov 30, 2026
`UnaryExpr` did not strip leading spaces before matching `-` or allow
spaces between multiple `-` operators, and `PathExpr` / `LocationPath`
stripped leading spaces even when they did not match anything. As a
result, unary minus expressions with spaces such as `" -6"` or `"- - 6"`
were misinterpreted by `AdditiveExpr` as a binary subtraction
(`[:minus, [], [:literal, 6]]` or `[:minus, [:neg], [:literal, 6]]`).
After ruby#318 removed the `gsub!(/([\(\[])\s+/, '\1')` preprocessing in
`parse`, this also affected expressions after `(` or `[` such as
`"( -6 )"` and `"//v[ -1 ]"`.

- Strip leading spaces in `UnaryExpr` and allow spaces between multiple
  `-` operators.
- Restore `original_path` in `UnaryExpr`, `PathExpr`, and `LocationPath`
  when no expression matches.
naitoh added a commit to naitoh/rexml that referenced this pull request Nov 30, 2026
`UnaryExpr` did not strip leading spaces before matching `-` or allow
spaces between multiple `-` operators, and `PathExpr` / `LocationPath`
stripped leading spaces even when they did not match anything. As a
result, unary minus expressions with spaces such as `" -6"` or `"- - 6"`
were misinterpreted by `AdditiveExpr` as a binary subtraction
(`[:minus, [], [:literal, 6]]` or `[:minus, [:neg], [:literal, 6]]`).
After ruby#318 removed the `gsub!(/([\(\[])\s+/, '\1')` preprocessing in
`parse`, this also affected expressions after `(` or `[` such as
`"( -6 )"` and `"//v[ -1 ]"`.

- Strip leading spaces in `UnaryExpr` and allow spaces between multiple
  `-` operators.
- Restore `original_path` in `UnaryExpr`, `PathExpr`, and `LocationPath`
  when no expression matches.
naitoh added a commit to naitoh/rexml that referenced this pull request Nov 30, 2026
`UnaryExpr` did not strip leading spaces before matching `-` or allow
spaces between multiple `-` operators. In addition, `LocationPath`
returned `nil` instead of the (empty) rest when the path was empty, and
`PathExpr` returned the `lstrip`-ed string even when nothing matched.
As a result, unary minus expressions with spaces such as `" -6"` or
`"- - 6"` were misinterpreted by `AdditiveExpr` as a binary subtraction
(`[:minus, [], [:literal, 6]]` or `[:minus, [:neg], [:literal, 6]]`).
After ruby#318 removed the `gsub!(/([\(\[])\s+/, '\1')` preprocessing in
`parse`, this also affected expressions after `(` or `[` such as
`"( -6 )"` and `"//v[ -1 ]"`.

- Strip leading spaces in `UnaryExpr` and allow spaces between multiple
  `-` operators.
- Return `original_path` in `UnaryExpr` and `PathExpr` when no
  expression matches.
- Make `LocationPath` return the rest (an empty string) instead of `nil`
  when the path is empty.
- Unary minus without an operand (e.g. `"-"`, `" - - "`) now raises
  `REXML::ParseException` instead of being evaluated to a meaningless
  value.
kou pushed a commit that referenced this pull request Dec 2, 2026
## Why?

`REXML::Parsers::XPathParser#UnaryExpr` did not strip leading spaces
before matching `-` or allow spaces between multiple `-` operators. In
addition, `LocationPath` returned `nil` instead of the (empty) rest when
the path was empty, and `PathExpr` returned the `lstrip`-ed string even
when nothing matched.

As a result, `AdditiveExpr` treated `rest != path` as a match and
misinterpreted unary minus expressions with spaces (such as `" -6"` or
`"- - 6"`) as binary subtractions (`[:minus, [], [:literal, 6]]` or
`[:minus, [:neg], [:literal, 6]]`).

Furthermore, after #318 removed the `gsub!(/([\(\[])\s+/, '\1')`
preprocessing in `REXML::Parsers::XPathParser#parse`, this issue also
affected unary minus expressions after `(` or `[` such as `"( -6 )"`
and `"//v[ -1 ]"`:

```ruby
doc = REXML::Document.new("<r><v>6</v><v>2</v></r>")

# Before
REXML::XPath.match(doc, "-6")     # => [-6.0]
REXML::XPath.match(doc, " -6")    # => [56.0] (evaluated as 62 - 6)
REXML::XPath.match(doc, "--6")    # => [6]
REXML::XPath.match(doc, "- - 6")  # => [-68.0] (evaluated as -62 - 6)
REXML::XPath.match(doc, "(-6)")   # => [-6.0]
REXML::XPath.match(doc, "( -6 )") # => [56.0] (evaluated as 62 - 6)

# After
REXML::XPath.match(doc, " -6")    # => [-6.0]
REXML::XPath.match(doc, "- - 6")  # => [6]
REXML::XPath.match(doc, "( -6 )") # => [-6.0]
REXML::XPath.match(doc, "-")      # => REXML::ParseException (was [-62.0])
```

## Changes

- Strip leading spaces in `UnaryExpr` and allow spaces after `-`
(`/\A((?:-\s*)*)/`).
- Return `original_path` in `UnaryExpr` and `PathExpr` when no
expression matches.
- Make `LocationPath` return the rest (an empty string) instead of `nil`
when the path is empty.
- Unary minus without an operand (e.g. `"-"`, `" - - "`) now raises
`REXML::ParseException` instead of being evaluated to a meaningless
value.
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.

3 participants