Skip to content

Fix XPath parsing of expressions and literals that contain line breaks - #397

Open
mokshupadhyay wants to merge 1 commit into
ruby:masterfrom
mokshupadhyay:fix/xpath-multiline-token-anchors
Open

mokshupadhyay wants to merge 1 commit into
ruby:masterfrom
mokshupadhyay:fix/xpath-multiline-token-anchors

Conversation

@mokshupadhyay

Copy link
Copy Markdown
Contributor

The XPath parser anchors its token patterns with ^. In Ruby ^ matches at the start of every line, not only at the start of the string, so when the rest of the expression does not start with the token being tried, the pattern can match at the start of a later line and everything before it is dropped. An XPath expression written over several lines then raises ParseException or parses to something else, and a string literal that contains a line break is cut.

doc = REXML::Document.new("<r><a><b/><b/></a><a><b/></a></r>")

REXML::XPath.first(doc, "string(\"a\n1\")")
# before: "1"          after: "a\n1"

REXML::XPath.first(doc, "string-length(\"x\n2\")")
# before: 1            after: 3

REXML::XPath.match(doc, "//a[\ncount(b) > 1\n]").size
# before: REXML::ParseException (Garbage component exists at the end)
# after:  1  (same as the one-line form "//a[count(b) > 1]")

XPath 1.0 allows whitespace, including line breaks, between tokens (section 3.7, ExprWhitespace), and a Literal is '"' [^"]* '"', so it may contain a line break.

This changes ^ to \A in the token patterns of lib/rexml/parsers/xpathparser.rb (LITERAL, AXIS, PREFIX_WILDCARD, LOCAL_NAME_WILDCARD, NODE_TYPE, PI, VARIABLE_REFERENCE, NUMBER, the operator loops, the function-call pattern and the two single-character patterns). I left the ^ in UnaryExpr alone because #393 rewrites that line.

Tests: test_line_breaks_between_tokens and test_line_breaks_in_literal in test/parser/test_xpath.rb. Both error on master and pass now. bundle exec rake test passes (874 tests, 2774 assertions, 0 failures, 0 errors, 5 omissions) on Ruby 3.4.5.

Not changed here: operator names still need literal spaces around them (" and ", " or ", " div ", " mod "), so @x=1 and\n@x=2 with a line break right after and is a separate problem.

The XPath parser matched its tokens with `^`, which in Ruby matches at
the start of every line, not only at the start of the string. When the
remaining expression did not start with the token being tried, the
pattern could match at the start of a later line and everything before
it was dropped.

As a result an expression such as "//a[\ncount(b) > 1\n]" raised
ParseException, and a string literal with a line break was cut, e.g.
string("a\n1") returned "1".

Use `\A` so that the patterns only match at the current position.

This branch has not been deployed

No deployments
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