rexml 3.4.4 → 3.4.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. checksums.yaml +4 -4
  2. data/NEWS.md +304 -0
  3. data/doc/rexml/tasks/rdoc/child.rdoc +1 -1
  4. data/doc/rexml/tasks/rdoc/document.rdoc +1 -1
  5. data/doc/rexml/tasks/rdoc/element.rdoc +1 -1
  6. data/doc/rexml/tasks/rdoc/node.rdoc +1 -1
  7. data/doc/rexml/tasks/rdoc/parent.rdoc +1 -1
  8. data/doc/rexml/tutorial.rdoc +4 -2
  9. data/lib/rexml/attribute.rb +11 -2
  10. data/lib/rexml/cdata.rb +1 -1
  11. data/lib/rexml/comment.rb +1 -1
  12. data/lib/rexml/doctype.rb +21 -18
  13. data/lib/rexml/document.rb +6 -21
  14. data/lib/rexml/element.rb +164 -158
  15. data/lib/rexml/entity.rb +19 -10
  16. data/lib/rexml/formatters/default.rb +35 -19
  17. data/lib/rexml/formatters/pretty.rb +2 -3
  18. data/lib/rexml/functions.rb +164 -147
  19. data/lib/rexml/instruction.rb +3 -3
  20. data/lib/rexml/namespace.rb +9 -1
  21. data/lib/rexml/output.rb +1 -1
  22. data/lib/rexml/parent.rb +1 -3
  23. data/lib/rexml/parsers/baseparser.rb +60 -73
  24. data/lib/rexml/parsers/sax2parser.rb +9 -20
  25. data/lib/rexml/parsers/xpathparser.rb +87 -58
  26. data/lib/rexml/rexml.rb +2 -2
  27. data/lib/rexml/security.rb +6 -6
  28. data/lib/rexml/source.rb +9 -8
  29. data/lib/rexml/text.rb +39 -35
  30. data/lib/rexml/validation/relaxng.rb +11 -0
  31. data/lib/rexml/xmldecl.rb +2 -2
  32. data/lib/rexml/xmltokens.rb +8 -8
  33. data/lib/rexml/xpath.rb +0 -1
  34. data/lib/rexml/xpath_parser.rb +745 -467
  35. metadata +16 -17
  36. data/lib/rexml/quickpath.rb +0 -267
  37. /data/doc/rexml/tasks/{tocs → includes}/child_toc.rdoc +0 -0
  38. /data/doc/rexml/tasks/{tocs → includes}/document_toc.rdoc +0 -0
  39. /data/doc/rexml/tasks/{tocs → includes}/element_toc.rdoc +0 -0
  40. /data/doc/rexml/tasks/{tocs → includes}/node_toc.rdoc +0 -0
  41. /data/doc/rexml/tasks/{tocs → includes}/parent_toc.rdoc +0 -0
  42. /data/doc/rexml/tasks/{tocs/master_toc.rdoc → rdoc/toc.rdoc} +0 -0
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: false
2
2
 
3
3
  require "pp"
4
+ require "set"
4
5
 
5
6
  require_relative 'namespace'
6
7
  require_relative 'xmltokens'
@@ -62,18 +63,21 @@ module REXML
62
63
  @parser = REXML::Parsers::XPathParser.new
63
64
  @namespaces = nil
64
65
  @variables = {}
66
+ @functions = FunctionsClass.new
67
+ @attlist_mappings = nil
68
+ @document = nil
69
+ @element_namespaces_cache = {}
70
+ @node_indexes = nil
65
71
  @nest = 0
66
72
  @strict = strict
67
73
  end
68
74
 
69
75
  def namespaces=( namespaces={} )
70
- Functions::namespace_context = namespaces
71
76
  @namespaces = namespaces
72
77
  end
73
78
 
74
- def variables=( vars={} )
75
- Functions::variables = vars
76
- @variables = vars
79
+ def variables=(vars)
80
+ @variables = vars.transform_values { |v| coerce_variable(v) }
77
81
  end
78
82
 
79
83
  def parse path, node
@@ -84,18 +88,12 @@ module REXML
84
88
  node = node.first
85
89
  end
86
90
 
87
- document = node.document
88
- if document
89
- document.__send__(:enable_cache) do
90
- match( path_stack, node )
91
- end
92
- else
93
- match( path_stack, node )
94
- end
91
+ match(path_stack, node)
95
92
  end
96
93
 
97
94
  def get_first path, node
98
95
  path_stack = @parser.parse( path )
96
+ @document = node.document
99
97
  first( path_stack, node )
100
98
  end
101
99
 
@@ -105,7 +103,7 @@ module REXML
105
103
  end
106
104
 
107
105
  def []=( variable_name, value )
108
- @variables[ variable_name ] = value
106
+ @variables[variable_name] = coerce_variable(value)
109
107
  end
110
108
 
111
109
 
@@ -151,14 +149,26 @@ module REXML
151
149
 
152
150
 
153
151
  def match(path_stack, node)
154
- nodeset = [XPathNode.new(node, position: 1)]
152
+ @document = node.document
153
+ # A fresh cache per evaluation, so that a document modified between two
154
+ # evaluations is not ordered by stale indexes.
155
+ @node_indexes = {}.compare_by_identity
156
+ @functions.node_indexes = @node_indexes
157
+ nodeset = [node]
155
158
  result = expr(path_stack, nodeset)
156
159
  case result
157
160
  when Array # nodeset
158
- unnode(result).uniq
161
+ XPathParser.sort(result, @node_indexes)
159
162
  else
160
163
  [result]
161
164
  end
165
+ ensure
166
+ # Let go of the indexes: they are no use to the next evaluation, and the
167
+ # cache holds one entry per node it had to look up. The document itself
168
+ # stays reachable through @document and @element_namespaces_cache, which
169
+ # outlive the evaluation.
170
+ @node_indexes = nil
171
+ @functions.node_indexes = nil
162
172
  end
163
173
 
164
174
  private
@@ -166,20 +176,45 @@ module REXML
166
176
  @strict
167
177
  end
168
178
 
169
- # Returns a String namespace for a node, given a prefix
179
+ # Returns a String namespace for a prefix used in xpath
170
180
  # The rules are:
171
181
  #
172
182
  # 1. Use the supplied namespace mapping first.
173
- # 2. If no mapping was supplied, use the context node to look up the namespace
174
- def get_namespace( node, prefix )
183
+ # 2. If no mapping was supplied, use the context node to look up the namespace as a fallback.
184
+ def get_xpath_namespace(node, prefix)
175
185
  if @namespaces
176
- @namespaces[prefix] || ''
186
+ Namespace.resolve_prefix(prefix, @namespaces) || ''
187
+ elsif node.node_type == :element
188
+ element_namespace_lookup(node, prefix)
177
189
  else
178
- return node.namespace( prefix ) if node.node_type == :element
179
190
  ''
180
191
  end
181
192
  end
182
193
 
194
+ # Returns attribute's namespace URI while caching the
195
+ # intermediate result to speed up retrieval of namespaces
196
+ def attribute_namespace(attribute)
197
+ attribute.prefix == '' ? '' : element_namespace_lookup(attribute.element, attribute.prefix)
198
+ end
199
+
200
+ # Return element's namespace URI while caching the
201
+ # intermediate result to speed up retrieval of namespaces
202
+ def element_namespace(element)
203
+ element._namespace_internal(element_namespaces(element))
204
+ end
205
+
206
+ # Returns a hash of namespaces for the given element while caching the
207
+ # intermediate result to speed up retrieval of namespaces
208
+ def element_namespaces(element)
209
+ @attlist_mappings ||= @document&.doctype&._attlist_mappings || {}
210
+ element._calculate_namespaces(@element_namespaces_cache, @attlist_mappings)
211
+ end
212
+
213
+ # Returns namespace of the prefix in the context of the element,
214
+ # while caching the intermediate result to speed up retrieval of namespaces
215
+ def element_namespace_lookup(element, prefix)
216
+ element._namespace_lookup_internal(prefix, element_namespaces(element))
217
+ end
183
218
 
184
219
  # Expr takes a stack of path elements and a set of nodes (either a Parent
185
220
  # or an Array and returns an Array of matching nodes
@@ -195,168 +230,58 @@ module REXML
195
230
  op = path_stack.shift
196
231
  case op
197
232
  when :document
198
- first_raw_node = nodeset.first.raw_node
199
- nodeset = [XPathNode.new(first_raw_node.root_node, position: 1)]
233
+ nodeset = [nodeset.first.root_node]
200
234
  when :self
201
235
  nodeset = step(path_stack) do
202
- [nodeset]
236
+ [:iterate_nodesets, nodeset.map {|node| [node] }]
203
237
  end
204
238
  when :child
205
239
  nodeset = step(path_stack) do
206
- child(nodeset)
240
+ [:iterate_nodesets, child(nodeset)]
207
241
  end
208
242
  when :literal
209
243
  trace(:literal, path_stack, nodeset) if @debug
210
244
  return path_stack.shift
211
245
  when :attribute
212
246
  nodeset = step(path_stack, any_type: :attribute) do
213
- nodesets = []
214
- nodeset.each do |node|
215
- raw_node = node.raw_node
216
- next unless raw_node.node_type == :element
217
- attributes = raw_node.attributes
247
+ nodesets = nodeset.map do |node|
248
+ next unless node.node_type == :element
249
+ attributes = node.attributes
218
250
  next if attributes.empty?
219
- nodesets << attributes.each_attribute.collect.with_index do |attribute, i|
220
- XPathNode.new(attribute, position: i + 1)
221
- end
222
- end
223
- nodesets
251
+ attributes.each_attribute.to_a
252
+ end.compact
253
+ [:iterate_nodesets, nodesets]
224
254
  end
225
255
  when :namespace
226
- pre_defined_namespaces = {
227
- "xml" => "http://www.w3.org/XML/1998/namespace",
228
- }
229
- nodeset = step(path_stack, any_type: :namespace) do
230
- nodesets = []
231
- nodeset.each do |node|
232
- raw_node = node.raw_node
233
- case raw_node.node_type
234
- when :element
235
- if @namespaces
236
- nodesets << pre_defined_namespaces.merge(@namespaces)
237
- else
238
- nodesets << pre_defined_namespaces.merge(raw_node.namespaces)
239
- end
240
- when :attribute
241
- if @namespaces
242
- nodesets << pre_defined_namespaces.merge(@namespaces)
243
- else
244
- nodesets << pre_defined_namespaces.merge(raw_node.element.namespaces)
245
- end
246
- end
247
- end
248
- nodesets
249
- end
256
+ warn 'Namespace axis is not supported in REXML::XPathParser', uplevel: 1
257
+ # TODO: We need to create NamespaceNode class to support this feature
258
+ nodeset = step(path_stack) { [:iterate_nodesets, []] }
250
259
  when :parent
251
260
  nodeset = step(path_stack) do
252
- nodesets = []
261
+ parents = Set.new.compare_by_identity
253
262
  nodeset.each do |node|
254
- raw_node = node.raw_node
255
- if raw_node.node_type == :attribute
256
- parent = raw_node.element
263
+ if node.node_type == :attribute
264
+ parent = node.element
257
265
  else
258
- parent = raw_node.parent
259
- end
260
- nodesets << [XPathNode.new(parent, position: 1)] if parent
261
- end
262
- nodesets
263
- end
264
- when :ancestor
265
- nodeset = step(path_stack) do
266
- nodesets = []
267
- # new_nodes = {}
268
- nodeset.each do |node|
269
- raw_node = node.raw_node
270
- new_nodeset = []
271
- while raw_node.parent
272
- raw_node = raw_node.parent
273
- # next if new_nodes.key?(node)
274
- new_nodeset << XPathNode.new(raw_node,
275
- position: new_nodeset.size + 1)
276
- # new_nodes[node] = true
266
+ parent = node.parent
277
267
  end
278
- nodesets << new_nodeset unless new_nodeset.empty?
268
+ parents << parent if parent
279
269
  end
280
- nodesets
281
- end
282
- when :ancestor_or_self
283
- nodeset = step(path_stack) do
284
- nodesets = []
285
- # new_nodes = {}
286
- nodeset.each do |node|
287
- raw_node = node.raw_node
288
- next unless raw_node.node_type == :element
289
- new_nodeset = [XPathNode.new(raw_node, position: 1)]
290
- # new_nodes[node] = true
291
- while raw_node.parent
292
- raw_node = raw_node.parent
293
- # next if new_nodes.key?(node)
294
- new_nodeset << XPathNode.new(raw_node,
295
- position: new_nodeset.size + 1)
296
- # new_nodes[node] = true
297
- end
298
- nodesets << new_nodeset unless new_nodeset.empty?
299
- end
300
- nodesets
301
- end
302
- when :descendant_or_self
303
- nodeset = step(path_stack) do
304
- descendant(nodeset, true)
270
+ [:iterate_nodesets, parents.map {|parent| [parent] }]
305
271
  end
306
- when :descendant
272
+ when :ancestor, :ancestor_or_self,
273
+ :descendant, :descendant_or_self,
274
+ :preceding, :preceding_sibling,
275
+ :following, :following_sibling
307
276
  nodeset = step(path_stack) do
308
- descendant(nodeset, false)
309
- end
310
- when :following_sibling
311
- nodeset = step(path_stack) do
312
- nodesets = []
313
- nodeset.each do |node|
314
- raw_node = node.raw_node
315
- next unless raw_node.respond_to?(:parent)
316
- next if raw_node.parent.nil?
317
- all_siblings = raw_node.parent.children
318
- current_index = all_siblings.index(raw_node)
319
- following_siblings = all_siblings[(current_index + 1)..-1]
320
- next if following_siblings.empty?
321
- nodesets << following_siblings.collect.with_index do |sibling, i|
322
- XPathNode.new(sibling, position: i + 1)
323
- end
324
- end
325
- nodesets
326
- end
327
- when :preceding_sibling
328
- nodeset = step(path_stack, order: :reverse) do
329
- nodesets = []
330
- nodeset.each do |node|
331
- raw_node = node.raw_node
332
- next unless raw_node.respond_to?(:parent)
333
- next if raw_node.parent.nil?
334
- all_siblings = raw_node.parent.children
335
- current_index = all_siblings.index(raw_node)
336
- preceding_siblings = all_siblings[0, current_index].reverse
337
- next if preceding_siblings.empty?
338
- nodesets << preceding_siblings.collect.with_index do |sibling, i|
339
- XPathNode.new(sibling, position: i + 1)
340
- end
341
- end
342
- nodesets
343
- end
344
- when :preceding
345
- nodeset = step(path_stack, order: :reverse) do
346
- unnode(nodeset) do |node|
347
- preceding(node)
348
- end
349
- end
350
- when :following
351
- nodeset = step(path_stack) do
352
- unnode(nodeset) do |node|
353
- following(node)
354
- end
277
+ [op, nodeset]
355
278
  end
356
279
  when :variable
357
280
  var_name = path_stack.shift
358
- return [@variables[var_name]]
281
+ value = @variables.key?(var_name) ? @variables[var_name] : ""
282
+ return value if path_stack.empty?
359
283
 
284
+ nodeset = apply_remaining_predicates(path_stack, value)
360
285
  when :eq, :neq, :lt, :lteq, :gt, :gteq
361
286
  left = expr( path_stack.shift, nodeset.dup, context )
362
287
  right = expr( path_stack.shift, nodeset.dup, context )
@@ -366,28 +291,27 @@ module REXML
366
291
 
367
292
  when :or
368
293
  left = expr(path_stack.shift, nodeset.dup, context)
369
- return true if Functions.boolean(left)
294
+ return true if @functions.boolean(left)
370
295
  right = expr(path_stack.shift, nodeset.dup, context)
371
- return Functions.boolean(right)
296
+ return @functions.boolean(right)
372
297
 
373
298
  when :and
374
299
  left = expr(path_stack.shift, nodeset.dup, context)
375
- return false unless Functions.boolean(left)
300
+ return false unless @functions.boolean(left)
376
301
  right = expr(path_stack.shift, nodeset.dup, context)
377
- return Functions.boolean(right)
302
+ return @functions.boolean(right)
378
303
 
379
304
  when :div, :mod, :mult, :plus, :minus
380
305
  left = expr(path_stack.shift, nodeset, context)
381
306
  right = expr(path_stack.shift, nodeset, context)
382
- left = unnode(left) if left.is_a?(Array)
383
- right = unnode(right) if right.is_a?(Array)
384
- left = Functions::number(left)
385
- right = Functions::number(right)
307
+ left = @functions.number(left)
308
+ right = @functions.number(right)
386
309
  case op
387
310
  when :div
388
311
  return left / right
389
312
  when :mod
390
- return left % right
313
+ return Float::NAN if right.zero?
314
+ return left.remainder(right)
391
315
  when :mult
392
316
  return left * right
393
317
  when :plus
@@ -400,16 +324,13 @@ module REXML
400
324
  when :union
401
325
  left = expr( path_stack.shift, nodeset, context )
402
326
  right = expr( path_stack.shift, nodeset, context )
403
- left = unnode(left) if left.is_a?(Array)
404
- right = unnode(right) if right.is_a?(Array)
405
327
  return (left | right)
406
328
  when :neg
407
329
  res = expr( path_stack, nodeset, context )
408
- res = unnode(res) if res.is_a?(Array)
409
- return -Functions.number(res)
330
+ return -@functions.number(res)
410
331
  when :not
411
332
  when :function
412
- func_name = path_stack.shift.tr('-','_')
333
+ func_name = path_stack.shift
413
334
  arguments = path_stack.shift
414
335
 
415
336
  if nodeset.size != 1
@@ -424,22 +345,28 @@ module REXML
424
345
  target_context = context
425
346
  else
426
347
  target_context = {:size => nodeset.size}
427
- if node.is_a?(XPathNode)
428
- target_context[:node] = node.raw_node
429
- target_context[:index] = node.position
430
- else
431
- target_context[:node] = node
432
- target_context[:index] = 1
433
- end
348
+ target_context[:node] = node
349
+ target_context[:position] = 1
434
350
  end
435
351
  args = arguments.dclone.collect do |arg|
436
- result = expr(arg, nodeset, target_context)
437
- result = unnode(result) if result.is_a?(Array)
438
- result
352
+ expr(arg, nodeset, target_context)
439
353
  end
440
- Functions.context = target_context
441
- return Functions.send(func_name, *args)
354
+ @functions.context = target_context
355
+
356
+ # TODO: Maybe, this is not XPath spec behavior.
357
+ # This behavior must be reconsidered.
358
+ func_name = func_name.tr('_', '-') unless strict?
359
+ result = @functions.call(func_name, args: args, fallback: [])
360
+
361
+ return result if path_stack.empty?
362
+
363
+ nodeset = apply_remaining_predicates(path_stack, result)
364
+ when :group
365
+ sub_expression = path_stack.shift
366
+ result = expr(sub_expression, nodeset, context)
367
+ return result if path_stack.empty?
442
368
 
369
+ nodeset = apply_remaining_predicates(path_stack, result)
443
370
  else
444
371
  raise "[BUG] Unexpected path: <#{op.inspect}>: <#{path_stack.inspect}>"
445
372
  end
@@ -449,184 +376,418 @@ module REXML
449
376
  leave(:expr, path_stack, nodeset) if @debug
450
377
  end
451
378
 
452
- def step(path_stack, any_type: :element, order: :forward)
453
- nodesets = yield
379
+ def apply_remaining_predicates(path_stack, value)
380
+ value = [] unless value.is_a?(Array)
381
+ path_stack.unshift(:node)
382
+ step(path_stack) do
383
+ [:iterate_nodesets, [XPathParser.sort(value, @node_indexes)]]
384
+ end
385
+ end
386
+
387
+ # Validates and coerces a variable value to a type that can be used in XPath expressions.
388
+ def coerce_variable(value)
389
+ case value
390
+ when REXML::Node
391
+ [value]
392
+ when Array
393
+ unless value.all?(REXML::Node)
394
+ raise TypeError, 'Array variable must contain only REXML::Node objects'
395
+ end
396
+ value.uniq
397
+ when Numeric, String, true, false
398
+ value
399
+ when nil
400
+ # Convert to an empty string for backward compatibility
401
+ ""
402
+ else
403
+ raise TypeError, "Unsupported variable type: #{value.class}"
404
+ end
405
+ end
406
+
407
+ # Determines if a predicate expression is dependent on the position of nodes.
408
+ # Returns false if the expression is guaranteed to be position-independent.
409
+ # Returns true if the expression might be position-dependent.
410
+ def position_dependent?(predicate_expr)
411
+ # expressions that contain position-dependent functions are position-dependent.
412
+ return true if calls_position_dependent_function?(predicate_expr)
413
+
414
+ # Even if expression is followed by path steps, the analysis of
415
+ # position dependency is the same as the expression itself.
416
+ case predicate_expr[0]
417
+ when :union, :or, :and, :eq, :neq, :lt, :lteq, :gt, :gteq, :not
418
+ # Expressions that don't evaluate to a number are position independent
419
+ # if it doesn't contain position-dependent functions.
420
+ false
421
+ when :div, :mod, :mult, :plus, :minus, :neg
422
+ # expressions that return number. eg. `[@attr + 1]`
423
+ true
424
+ when :literal
425
+ # Numeric literal is position dependent. String and boolean literal is useless
426
+ # and not worth optimizing
427
+ true
428
+ when :variable
429
+ # A variable could resolve to a number at runtime.
430
+ # It's possible to optimize this by checking the actual value of the variable.
431
+ true
432
+ when :function
433
+ # functions that return number is position dependent. eg. `[position() = string-length(@attr)]`
434
+ %w[number ceiling round floor string-length sum count].include?(predicate_expr[1])
435
+ when :group
436
+ position_dependent?(predicate_expr[1])
437
+ when :descendant, :descendant_or_self, :ancestor, :ancestor_or_self,
438
+ :following, :following_sibling, :preceding, :preceding_sibling,
439
+ :document, :child, :self, :parent, :attribute, :namespace
440
+ # paths are position independent. `foo[path[1]]` doesn't depend on the position of `foo`
441
+ false
442
+ else
443
+ # Every other unhandled expressions are treated position dependent for safety
444
+ true
445
+ end
446
+ end
447
+
448
+ # Recursively checks if the expression contains position-dependent functions such as position() or last()
449
+ def calls_position_dependent_function?(expr)
450
+ return false unless Array === expr
451
+ return true if expr[0] == :function && (expr[1] == 'position' || expr[1] == 'last')
452
+ expr.any? {|part| calls_position_dependent_function?(part) }
453
+ end
454
+
455
+ # Detects simple position-based predicates that can be optimized in axis scanning, such as [1], [position()=1], [position() < 2], [last()-3], etc.
456
+ # Returns operators and values such as [:index_eq, 0], [:index_lt, 1], [:index_gt, 2], [:reverse_index_eq, 0], [:reverse_index_lt, 1], [:reverse_index_gt, 2]
457
+ # Returns nil if the predicate is not a simple position-based predicate
458
+ def position_operation(predicate_expr)
459
+ return [:index_eq, predicate_expr[1] - 1] if predicate_expr[0] == :literal && predicate_expr[1].is_a?(Integer)
460
+
461
+ reverse_index = last_minus_integer(predicate_expr)
462
+ return [:reverse_index_eq, reverse_index] if reverse_index
463
+
464
+ op, left, right = predicate_expr
465
+ return unless op == :eq || op == :lt || op == :lteq || op == :gt || op == :gteq
466
+ return unless [left, right].include?([:function, 'position', []])
467
+
468
+ if right == [:function, 'position', []]
469
+ op = { eq: :eq, lt: :gt, lteq: :gteq, gt: :lt, gteq: :lteq }[op]
470
+ left, right = right, left
471
+ end
472
+
473
+ index = right[1] - 1 if right[0] == :literal && right[1].is_a?(Integer)
474
+ reverse_index = last_minus_integer(right)
475
+
476
+ if index
477
+ case op
478
+ when :eq
479
+ [:index_eq, index]
480
+ when :lt
481
+ [:index_lt, index]
482
+ when :lteq
483
+ [:index_lt, index + 1]
484
+ when :gt
485
+ [:index_gt, index]
486
+ when :gteq
487
+ [:index_gt, index - 1]
488
+ end
489
+ elsif reverse_index
490
+ case op
491
+ when :eq
492
+ [:reverse_index_eq, reverse_index]
493
+ when :lt
494
+ [:reverse_index_gt, reverse_index]
495
+ when :lteq
496
+ [:reverse_index_gt, reverse_index - 1]
497
+ when :gt
498
+ [:reverse_index_lt, reverse_index]
499
+ when :gteq
500
+ [:reverse_index_lt, reverse_index + 1]
501
+ end
502
+ end
503
+ end
504
+
505
+ # If the expression is `last()-INTEGER` or `last()` (equivalent to `last()-0`), returns the integer part.
506
+ # Otherwise, returns nil.
507
+ def last_minus_integer(expr)
508
+ if expr == [:function, 'last', []]
509
+ 0
510
+ elsif expr[0] == :minus && expr[1] == [:function, 'last', []] && expr[2][0] == :literal && expr[2][1].is_a?(Integer)
511
+ expr[2][1]
512
+ end
513
+ end
514
+
515
+ # Pseudo scanner for axis scanning step that nodesets are already collected
516
+ def iterate_nodesets(nodesets, tester, selector)
517
+ non_optimized_nodesets_select(nodesets, tester, selector)
518
+ end
519
+
520
+ # Scanner for ancestor-or-self axis
521
+ def ancestor_or_self(nodeset, tester, selector)
522
+ ancestor(nodeset, tester, selector, include_self: true)
523
+ end
524
+
525
+ # Scanner for preceding-sibling axis
526
+ def preceding_sibling(nodeset, tester, selector)
527
+ preceding_following_sibling(nodeset, tester, selector, reverse: true)
528
+ end
529
+
530
+ # Scanner for following-sibling axis
531
+ def following_sibling(nodeset, tester, selector)
532
+ preceding_following_sibling(nodeset, tester, selector, reverse: false)
533
+ end
534
+
535
+ def preceding_following_sibling(nodeset, tester, selector, reverse:)
536
+ nodeset = nodeset.select {|node| node.respond_to?(:parent) && node.parent }
537
+ nodeset.group_by(&:parent).flat_map do |parent, sibling_nodes|
538
+ anchors = Set.new.compare_by_identity.replace(sibling_nodes)
539
+ children = parent.children
540
+ children = children.reverse if reverse
541
+ followings = children.drop_while {|child| !anchors.include?(child) }.drop(1)
542
+ events = [:push]
543
+ followings.each do |node|
544
+ events << node if tester.call(node)
545
+ events << :push if anchors.include?(node)
546
+ end
547
+ anchors.size.times { events << :pop }
548
+ sequence_positional_scan(events, selector)
549
+ end
550
+ end
551
+
552
+ # Scanner for ancestor axis
553
+ def ancestor(nodeset, tester, selector, include_self: false)
554
+ nodeset = nodeset.select {|node| node.respond_to?(:parent) && node.parent }
555
+ case selector
556
+ when :uniq
557
+ ancestors = Set.new.compare_by_identity
558
+ nodeset.each do |node|
559
+ ancestors << node if include_self
560
+ parent = node.parent
561
+ while parent
562
+ break if ancestors.include?(parent)
563
+ ancestors << parent
564
+ parent = parent.parent
565
+ end
566
+ end
567
+ ancestors.select(&tester)
568
+ else
569
+ # Slow path
570
+ nodesets = nodeset.map do |node|
571
+ ancestors = []
572
+ ancestors << node if include_self
573
+ parent = node.parent
574
+ while parent
575
+ ancestors << parent
576
+ parent = parent.parent
577
+ end
578
+ ancestors
579
+ end
580
+ non_optimized_nodesets_select(nodesets, tester, selector)
581
+ end
582
+ end
583
+
584
+ # Scanner fallback step for axis that is not optimized for position-based predicates.
585
+ def non_optimized_nodesets_select(nodesets, tester, selector)
586
+ nodesets = nodesets.map do |nodeset|
587
+ nodeset.select(&tester)
588
+ end.reject(&:empty?)
589
+ case selector
590
+ when :nodesets
591
+ nodesets
592
+ when :uniq
593
+ seen = Set.new.compare_by_identity
594
+ nodesets.flatten.each {|node| seen << node }
595
+ seen.to_a
596
+ else
597
+ operator, value = selector
598
+ nodes =
599
+ case operator
600
+ when :index_eq
601
+ nodesets.map {|nodeset| nodeset[value] if value >= 0 }.compact
602
+ when :index_lt
603
+ nodesets.flat_map {|nodeset| nodeset[0...value] if value >= 0 }.compact
604
+ when :index_gt
605
+ nodesets.flat_map {|nodeset| value < 0 ? nodeset : nodeset.drop(value + 1) }
606
+ when :reverse_index_eq
607
+ nodesets.map {|nodeset| nodeset[-(value + 1)] if value >= 0 }.compact
608
+ when :reverse_index_lt
609
+ nodesets.flat_map {|nodeset| nodeset.last(value) if value > 0 }.compact
610
+ when :reverse_index_gt
611
+ nodesets.flat_map {|nodeset| value < 0 ? nodeset : nodeset[0...-(value + 1)] }
612
+ end
613
+ seen = Set.new.compare_by_identity
614
+ nodes.each {|node| seen << node }
615
+ seen.to_a
616
+ end
617
+ end
618
+
619
+ # Split predicates into several groups based on their dependency on the position of nodes
620
+ # If there are no position-based predicates,
621
+ # return [position_independent_predicates, nil, [], nil]
622
+ # If there are only one simple position-based predicate,
623
+ # return [position_independent_predicates, position_operator, post_position_independent_predicates, nil]
624
+ # If there are multiple position-based predicates or complex position-based predicates,
625
+ # return [position_independent_predicates, nil, nil, complex_predicates]
626
+ def split_positional_predicates(predicates)
627
+ pre_independent = predicates.take_while {|predicate| !position_dependent?(predicate) }
628
+ predicates = predicates.drop(pre_independent.size)
629
+ return [pre_independent, nil, [], nil] if predicates.empty?
630
+
631
+ op = position_operation(predicates.first)
632
+ if op && predicates[1..-1].all? {|predicate| !position_dependent?(predicate) }
633
+ [pre_independent, op, predicates[1..-1], nil]
634
+ else
635
+ [pre_independent, nil, nil, predicates]
636
+ end
637
+ end
638
+
639
+ # Performs an axis scanning step.
640
+ # Returns an unordered non-duplicated nodeset of matching nodes.
641
+ # The caller provides a scanner method and its argument, which determines the axis to scan and the nodes to scan from:
642
+ # step(path_stack) { [scanner_method, scanner_argument] }
643
+ # Scanner methods are called with `(scanner_argument, tester_block, selector)`
644
+ # selector is a flag for the scanner to determine how to return the scan result.
645
+ # It can be: `:uniq`, `:nodesets` or `[position_comparator, value]`.
646
+ # `:uniq` means the scanner should return unique nodes. Predicates are position-independent.
647
+ # `:nodesets` means the scanner should return nodesets. Predicates are complex position queries that can't be optimized in axis scanning.
648
+ # `[position_comparator, value]` means the scanner should return nodes matching the position comparator and value.
649
+ # Each scanner method can implement optimized scanning strategy for each selector.
650
+
651
+ def step(path_stack, any_type: :element)
652
+ scanner, scanner_argument = yield
454
653
  begin
455
- enter(:step, path_stack, nodesets) if @debug
456
- nodesets = node_test(path_stack, nodesets, any_type: any_type)
457
- while path_stack[0] == :predicate
458
- path_stack.shift # :predicate
459
- predicate_expression = path_stack.shift.dclone
460
- nodesets = evaluate_predicate(predicate_expression, nodesets)
461
- end
462
- if nodesets.size == 1
463
- ordered_nodeset = nodesets[0]
464
- else
465
- raw_nodes = []
466
- nodesets.each do |nodeset|
467
- nodeset.each do |node|
468
- if node.respond_to?(:raw_node)
469
- raw_nodes << node.raw_node
470
- else
471
- raw_nodes << node
472
- end
654
+ enter(:step, path_stack, scanner, scanner_argument) if @debug
655
+ tester = node_test(path_stack, any_type: any_type)
656
+ predicates = []
657
+ while path_stack.first == :predicate
658
+ path_stack.shift
659
+ predicates << path_stack.shift
660
+ end
661
+ pre_predicates, position_operator, post_predicates, complex_predicates = split_positional_predicates(predicates)
662
+
663
+ if pre_predicates.any?
664
+ original_tester = tester
665
+ tester = -> (node) do
666
+ original_tester.call(node) &&
667
+ pre_predicates.all? do |predicate_expr|
668
+ evaluate_predicate(predicate_expr.dclone, [[node]]).flatten.size == 1
473
669
  end
474
670
  end
475
- ordered_nodeset = sort(raw_nodes, order)
476
671
  end
477
- new_nodeset = []
478
- ordered_nodeset.each do |node|
479
- # TODO: Remove duplicated
480
- new_nodeset << XPathNode.new(node, position: new_nodeset.size + 1)
672
+ if complex_predicates
673
+ nodesets = send(scanner, scanner_argument, tester, :nodesets)
674
+ elsif position_operator
675
+ nodeset = send(scanner, scanner_argument, tester, position_operator)
676
+ nodesets = [nodeset]
677
+ else
678
+ nodeset = send(scanner, scanner_argument, tester, :uniq)
679
+ nodesets = [nodeset]
481
680
  end
482
- new_nodeset
681
+
682
+ (complex_predicates || post_predicates).each do |predicate_expr|
683
+ nodesets = evaluate_predicate(predicate_expr.dclone, nodesets)
684
+ end
685
+ nodes = Set.new.compare_by_identity
686
+ nodesets.each do |nodeset|
687
+ nodeset.each do |node|
688
+ nodes << node
689
+ end
690
+ end
691
+ new_nodeset = nodes.to_a
483
692
  ensure
484
693
  leave(:step, path_stack, new_nodeset) if @debug
485
694
  end
486
695
  end
487
696
 
488
- def node_test(path_stack, nodesets, any_type: :element)
489
- enter(:node_test, path_stack, nodesets) if @debug
697
+ def node_test(path_stack, any_type: :element)
698
+ enter(:node_test, path_stack) if @debug
490
699
  operator = path_stack.shift
491
700
  case operator
492
701
  when :qname
493
702
  prefix = path_stack.shift
494
703
  name = path_stack.shift
495
- new_nodesets = nodesets.collect do |nodeset|
496
- filter_nodeset(nodeset) do |node|
497
- raw_node = node.raw_node
498
- case raw_node.node_type
499
- when :element
500
- if prefix.nil?
501
- raw_node.name == name
502
- elsif prefix.empty?
503
- if strict?
504
- raw_node.name == name and raw_node.namespace == ""
505
- else
506
- raw_node.name == name and raw_node.namespace == get_namespace(raw_node, prefix)
507
- end
704
+ ->(node) do
705
+ case node.node_type
706
+ when :element
707
+ if prefix.nil?
708
+ node.name == name
709
+ elsif prefix.empty?
710
+ if strict?
711
+ node.name == name and element_namespace(node) == ""
508
712
  else
509
- raw_node.name == name and raw_node.namespace == get_namespace(raw_node, prefix)
510
- end
511
- when :attribute
512
- if prefix.nil?
513
- raw_node.name == name
514
- elsif prefix.empty?
515
- raw_node.name == name and raw_node.namespace == ""
516
- else
517
- raw_node.name == name and raw_node.namespace == get_namespace(raw_node.element, prefix)
713
+ node.name == name and element_namespace(node) == get_xpath_namespace(node, prefix)
518
714
  end
519
715
  else
520
- false
716
+ node.name == name and element_namespace(node) == get_xpath_namespace(node, prefix)
717
+ end
718
+ when :attribute
719
+ if prefix.nil?
720
+ node.name == name
721
+ elsif prefix.empty?
722
+ node.name == name and attribute_namespace(node) == ""
723
+ else
724
+ node.name == name and attribute_namespace(node) == get_xpath_namespace(node.element, prefix)
521
725
  end
726
+ else
727
+ false
522
728
  end
523
729
  end
524
730
  when :namespace
525
731
  prefix = path_stack.shift
526
- new_nodesets = nodesets.collect do |nodeset|
527
- filter_nodeset(nodeset) do |node|
528
- raw_node = node.raw_node
529
- case raw_node.node_type
530
- when :element
531
- namespaces = @namespaces || raw_node.namespaces
532
- raw_node.namespace == namespaces[prefix]
533
- when :attribute
534
- namespaces = @namespaces || raw_node.element.namespaces
535
- raw_node.namespace == namespaces[prefix]
536
- else
537
- false
538
- end
732
+ ->(node) do
733
+ case node.node_type
734
+ when :element
735
+ namespaces = @namespaces || element_namespaces(node)
736
+ element_namespace(node) == Namespace.resolve_prefix(prefix, namespaces)
737
+ when :attribute
738
+ namespaces = @namespaces || element_namespaces(node.element)
739
+ attribute_namespace(node) == Namespace.resolve_prefix(prefix, namespaces)
740
+ else
741
+ false
539
742
  end
540
743
  end
541
744
  when :any
542
- new_nodesets = nodesets.collect do |nodeset|
543
- filter_nodeset(nodeset) do |node|
544
- raw_node = node.raw_node
545
- raw_node.node_type == any_type
546
- end
745
+ ->(node) do
746
+ node.node_type == any_type
547
747
  end
548
748
  when :comment
549
- new_nodesets = nodesets.collect do |nodeset|
550
- filter_nodeset(nodeset) do |node|
551
- raw_node = node.raw_node
552
- raw_node.node_type == :comment
553
- end
749
+ ->(node) do
750
+ node.node_type == :comment
554
751
  end
555
752
  when :text
556
- new_nodesets = nodesets.collect do |nodeset|
557
- filter_nodeset(nodeset) do |node|
558
- raw_node = node.raw_node
559
- raw_node.node_type == :text
560
- end
753
+ ->(node) do
754
+ node.node_type == :text
561
755
  end
562
756
  when :processing_instruction
563
757
  target = path_stack.shift
564
- new_nodesets = nodesets.collect do |nodeset|
565
- filter_nodeset(nodeset) do |node|
566
- raw_node = node.raw_node
567
- (raw_node.node_type == :processing_instruction) and
568
- (target.empty? or (raw_node.target == target))
569
- end
758
+ ->(node) do
759
+ (node.node_type == :processing_instruction) and
760
+ (target.empty? or (node.target == target))
570
761
  end
571
762
  when :node
572
- new_nodesets = nodesets.collect do |nodeset|
573
- filter_nodeset(nodeset) do |node|
574
- true
575
- end
763
+ ->(_node) do
764
+ true
576
765
  end
577
766
  else
578
767
  message = "[BUG] Unexpected node test: " +
579
768
  "<#{operator.inspect}>: <#{path_stack.inspect}>"
580
769
  raise message
581
770
  end
582
- new_nodesets
583
771
  ensure
584
- leave(:node_test, path_stack, new_nodesets) if @debug
585
- end
586
-
587
- def filter_nodeset(nodeset)
588
- new_nodeset = []
589
- nodeset.each do |node|
590
- next unless yield(node)
591
- new_nodeset << XPathNode.new(node, position: new_nodeset.size + 1)
592
- end
593
- new_nodeset
772
+ leave(:node_test, path_stack) if @debug
594
773
  end
595
774
 
596
775
  def evaluate_predicate(expression, nodesets)
597
776
  enter(:predicate, expression, nodesets) if @debug
598
- new_nodeset_count = 0
599
777
  new_nodesets = nodesets.collect do |nodeset|
600
778
  new_nodeset = []
601
779
  subcontext = { :size => nodeset.size }
602
- nodeset.each_with_index do |node, index|
603
- if node.is_a?(XPathNode)
604
- subcontext[:node] = node.raw_node
605
- subcontext[:index] = node.position
606
- else
607
- subcontext[:node] = node
608
- subcontext[:index] = index + 1
609
- end
780
+ nodeset.each.with_index(1) do |node, position|
781
+ subcontext[:node] = node
782
+ subcontext[:position] = position
610
783
  result = expr(expression.dclone, [node], subcontext)
611
784
  trace(:predicate_evaluate, expression, node, subcontext, result) if @debug
612
- result = result[0] if result.kind_of? Array and result.length == 1
613
785
  if result.kind_of? Numeric
614
- if result == node.position
615
- new_nodeset_count += 1
616
- new_nodeset << XPathNode.new(node, position: new_nodeset_count)
617
- end
618
- elsif result.instance_of? Array
619
- if result.size > 0 and result.inject(false) {|k,s| s or k}
620
- if result.size > 0
621
- new_nodeset_count += 1
622
- new_nodeset << XPathNode.new(node, position: new_nodeset_count)
623
- end
624
- end
625
- else
626
- if result
627
- new_nodeset_count += 1
628
- new_nodeset << XPathNode.new(node, position: new_nodeset_count)
786
+ if result == position
787
+ new_nodeset << node
629
788
  end
789
+ elsif @functions.boolean(result)
790
+ new_nodeset << node
630
791
  end
631
792
  end
632
793
  new_nodeset
@@ -653,68 +814,248 @@ module REXML
653
814
  trace(:leave, tag, *args)
654
815
  end
655
816
 
656
- # Reorders an array of nodes so that they are in document order
657
- # It tries to do this efficiently.
817
+ # Sorts before any real child index, so that the attributes of an element
818
+ # come after the element itself but before its children.
819
+ ATTRIBUTE_POSITION = -1
820
+ private_constant :ATTRIBUTE_POSITION
821
+
822
+ # Reorders an array of nodes so that they are in document order.
658
823
  #
659
- # FIXME: I need to get rid of this, but the issue is that most of the XPath
660
- # interpreter functions as a filter, which means that we lose context going
661
- # in and out of function calls. If I knew what the index of the nodes was,
662
- # I wouldn't have to do this. Maybe add a document IDX for each node?
663
- # Problems with mutable documents. Or, rewrite everything.
664
- def sort(array_of_nodes, order)
665
- new_arry = []
666
- array_of_nodes.each { |node|
667
- node_idx = []
668
- np = node.node_type == :attribute ? node.element : node
669
- while np.parent and np.parent.node_type == :element
670
- node_idx << np.parent.index( np )
671
- np = np.parent
672
- end
673
- new_arry << [ node_idx.reverse, node ]
674
- }
675
- ordered = new_arry.sort_by do |index, node|
676
- if order == :forward
677
- index
824
+ # Node sets are built up as unordered sets by the axis scanners, so they
825
+ # have to be put back into order here. A node is keyed on the index it
826
+ # holds under each of its ancestors, outermost first, so that comparing
827
+ # two keys compares them at their first differing ancestor.
828
+ #
829
+ # +node_indexes+ caches the index of every child and attribute that had to
830
+ # be looked up. Pass the same one to every sort of an evaluation: a sort
831
+ # can happen many times per evaluation (Functions#string sorts once per
832
+ # candidate node), and those sorts usually revisit the same parents.
833
+ # Passing nothing just means the caching lasts for this one call.
834
+ def self.sort(array_of_nodes, node_indexes = nil)
835
+ return array_of_nodes if array_of_nodes.size <= 1
836
+ node_indexes ||= {}.compare_by_identity
837
+ array_of_nodes.sort_by do |node|
838
+ if node.node_type == :attribute
839
+ # An attribute has no place of its own in the child tree, so its key
840
+ # extends that of the element carrying it.
841
+ ancestor_indexes(node.element, node_indexes) <<
842
+ ATTRIBUTE_POSITION << attribute_position(node, node_indexes)
678
843
  else
679
- index.map(&:-@)
844
+ ancestor_indexes(node, node_indexes)
680
845
  end
681
846
  end
682
- ordered.collect do |_index, node|
683
- node
847
+ end
848
+
849
+ # The index the node holds under each of its ancestors, outermost first.
850
+ def self.ancestor_indexes(node, node_indexes)
851
+ indexes = []
852
+ # Walk all the way up to the document. Stopping at the root element
853
+ # would leave every node outside it, and the root itself, with the same
854
+ # empty key, and ties are then broken arbitrarily.
855
+ while (parent = node.parent)
856
+ indexes << child_index_of(node, parent, node_indexes)
857
+ node = parent
684
858
  end
859
+ indexes.reverse!
685
860
  end
861
+ private_class_method :ancestor_indexes
686
862
 
687
- def descendant(nodeset, include_self)
688
- nodesets = []
689
- nodeset.each do |node|
690
- new_nodeset = []
691
- new_nodes = {}
692
- descendant_recursive(node.raw_node, new_nodeset, new_nodes, include_self)
693
- nodesets << new_nodeset unless new_nodeset.empty?
863
+ # Where the attribute sits among the attributes of its element. XPath 1.0
864
+ # leaves the relative order of those implementation dependent, but document
865
+ # order is a total ordering, so they do need one; this keeps them in the
866
+ # order they were written in.
867
+ def self.attribute_position(attribute, node_indexes)
868
+ position = node_indexes[attribute]
869
+ return position if position
870
+
871
+ # Index the whole attribute list at once, for the same reason the child
872
+ # list is indexed at once: a node set often holds every attribute of an
873
+ # element, and looking each one up on its own is quadratic.
874
+ i = 0
875
+ attribute.element.attributes.each_attribute do |other|
876
+ node_indexes[other] ||= i
877
+ i += 1
694
878
  end
695
- nodesets
879
+ node_indexes[attribute]
880
+ end
881
+ private_class_method :attribute_position
882
+
883
+ # Index the whole child list at once. A node set normally has many nodes
884
+ # under the same few parents, and walking that list once per node is what
885
+ # made sorting quadratic in the number of children.
886
+ def self.child_index_of(node, parent, node_indexes)
887
+ index = node_indexes[node]
888
+ return index if index
889
+
890
+ # Iterate the parent rather than its #children, which hands out a copy.
891
+ # Keep the first index of a node, as Parent#index does: a child list is
892
+ # not supposed to hold the same node twice, but Parent lets it happen,
893
+ # and the rest of REXML reads such a node as being at the first of its
894
+ # positions.
895
+ parent.each_with_index {|child, i| node_indexes[child] ||= i }
896
+ node_indexes[node]
696
897
  end
898
+ private_class_method :child_index_of
697
899
 
698
- def descendant_recursive(raw_node, new_nodeset, new_nodes, include_self)
699
- if include_self
700
- return if new_nodes.key?(raw_node)
701
- new_nodeset << XPathNode.new(raw_node, position: new_nodeset.size + 1)
702
- new_nodes[raw_node] = true
900
+ # Scanner for descendant-or-self axis
901
+ def descendant_or_self(nodeset, tester, selector)
902
+ descendant(nodeset, tester, selector, include_self: true)
903
+ end
904
+
905
+ # Scanner for descendant axis
906
+ def descendant(nodeset, tester, selector, include_self: false)
907
+ nodeset = nodeset.select {|node| node.respond_to?(:children) }
908
+ targets = Set.new.compare_by_identity.replace(nodeset)
909
+ descendant_anchor_roots(nodeset).flat_map do |root|
910
+ descendant_positional_scan(root, targets, tester, selector, include_self)
911
+ end
912
+ end
913
+
914
+ def descendant_anchor_roots(nodes)
915
+ seen = Set.new.compare_by_identity
916
+ nodes.each do |node|
917
+ descendant_traverse(node, include_self: false) do |n|
918
+ if !seen.include?(n)
919
+ seen << n
920
+ true
921
+ end
922
+ end
703
923
  end
924
+ nodes.reject {|node| seen.include?(node) }
925
+ end
704
926
 
705
- node_type = raw_node.node_type
706
- if node_type == :element or node_type == :document
707
- raw_node.children.each do |child|
708
- descendant_recursive(child, new_nodeset, new_nodes, true)
927
+ def descendant_positional_scan(root, targets, tester, selector, include_self)
928
+ events = []
929
+ descendant_traverse_event(root) do |type, node|
930
+ if type == :enter
931
+ if include_self
932
+ events << :push if targets.include?(node)
933
+ events << node if tester.call(node)
934
+ else
935
+ events << node if !node.equal?(root) && tester.call(node)
936
+ events << :push if targets.include?(node)
937
+ end
938
+ elsif type == :leave
939
+ events << :pop if targets.include?(node)
709
940
  end
710
941
  end
942
+ sequence_positional_scan(events, selector)
943
+ end
944
+
945
+ # Select nodes matching the positional predicate from a sequence of events.
946
+ # Events are: :push, :pop, and node
947
+ # push/pop is an event that pushes/pops an anchor of position-based predicate
948
+ def sequence_positional_scan(events, selector)
949
+ case selector
950
+ when :uniq
951
+ return events.grep_v(Symbol)
952
+ when :nodesets
953
+ nodes = []
954
+ indexes = []
955
+ nodesets = []
956
+ last_range = nil
957
+ events.each do |e|
958
+ case e
959
+ when :push
960
+ indexes << nodes.size
961
+ when :pop
962
+ start_idx = indexes.pop
963
+ range = start_idx...nodes.size
964
+ nodesets << nodes[range] if last_range != range
965
+ last_range = range
966
+ else
967
+ nodes << e
968
+ end
969
+ end
970
+ return nodesets
971
+ end
972
+
973
+ operator, value = selector
974
+ reverse = operator == :reverse_index_eq || operator == :reverse_index_lt || operator == :reverse_index_gt
975
+ events = events.reverse_each if reverse
976
+ start_event = reverse ? :pop : :push
977
+ end_event = reverse ? :push : :pop
978
+ anchor_indexes = []
979
+ anchor_set = Set.new
980
+ node_index = 0
981
+ result = []
982
+ events.each do |event|
983
+ if event == start_event
984
+ anchor_indexes << node_index
985
+ anchor_set << node_index
986
+ elsif event == end_event
987
+ idx = anchor_indexes.pop
988
+ anchor_set.delete(idx) if anchor_indexes.last != idx
989
+ else # event is a node that passed the tester
990
+ case operator
991
+ when :index_eq, :reverse_index_eq
992
+ result << event if anchor_set.include?(node_index - value)
993
+ when :index_lt, :reverse_index_lt
994
+ result << event if node_index - anchor_indexes.last < value
995
+ when :index_gt, :reverse_index_gt
996
+ result << event if node_index > value
997
+ end
998
+ node_index += 1
999
+ end
1000
+ end
1001
+ result
1002
+ end
1003
+
1004
+ # Scans the node and its descendants in document order
1005
+ # and dispatches two types of events: :enter and :leave for each node.
1006
+ def descendant_traverse_event(node)
1007
+ stack = [node]
1008
+ until stack.empty?
1009
+ if stack.last
1010
+ node = stack.last
1011
+ # Push nil as a mark that we are entering this node.
1012
+ # If we see this mark again, we know to pop the node and yield :leave
1013
+ stack << nil
1014
+ yield :enter, node
1015
+ node_type = node.node_type
1016
+ if node_type == :element or node_type == :document
1017
+ node.children.reverse_each do |child|
1018
+ stack << child if child.node_type != :xmldecl
1019
+ end
1020
+ end
1021
+ else
1022
+ stack.pop
1023
+ node = stack.pop
1024
+ yield :leave, node
1025
+ end
1026
+ end
1027
+ end
1028
+
1029
+ # Scans the descendants of a node in document order and yields each node to the block.
1030
+ # If a block returns falsy value, the node's descendants are not traversed.
1031
+ def descendant_traverse(anchor_node, include_self:)
1032
+ stack = [anchor_node]
1033
+ until stack.empty?
1034
+ node = stack.pop
1035
+ if include_self || !node.equal?(anchor_node)
1036
+ next unless yield node
1037
+ end
1038
+
1039
+ node_type = node.node_type
1040
+ if node_type == :element or node_type == :document
1041
+ node.children.reverse_each do |child|
1042
+ stack << child if child.node_type != :xmldecl
1043
+ end
1044
+ end
1045
+ end
1046
+ end
1047
+
1048
+ # Scanner for preceding axis
1049
+ def preceding(nodeset, tester, selector)
1050
+ nodesets = nodeset.select {|node| node.respond_to?(:parent) }.map {|node| preceding_nodes(node) }
1051
+ non_optimized_nodesets_select(nodesets, tester, selector)
711
1052
  end
712
1053
 
713
1054
  # Builds a nodeset of all of the preceding nodes of the supplied node,
714
1055
  # in reverse document order
715
1056
  # preceding:: includes every element in the document that precedes this node,
716
1057
  # except for ancestors
717
- def preceding(node)
1058
+ def preceding_nodes(node)
718
1059
  ancestors = []
719
1060
  parent = node.parent
720
1061
  while parent
@@ -728,8 +1069,7 @@ module REXML
728
1069
  if ancestors.include?(preceding_node)
729
1070
  ancestors.delete(preceding_node)
730
1071
  else
731
- precedings << XPathNode.new(preceding_node,
732
- position: precedings.size + 1)
1072
+ precedings << preceding_node
733
1073
  end
734
1074
  preceding_node = preceding_node_of(preceding_node)
735
1075
  end
@@ -751,52 +1091,31 @@ module REXML
751
1091
  psn
752
1092
  end
753
1093
 
754
- def following(node)
755
- followings = []
756
- following_node = next_sibling_node(node)
757
- while following_node
758
- followings << XPathNode.new(following_node,
759
- position: followings.size + 1)
760
- following_node = following_node_of(following_node)
761
- end
762
- followings
763
- end
764
-
765
- def following_node_of( node )
766
- return node.children[0] if node.kind_of?(Element) and node.children.size > 0
767
-
768
- next_sibling_node(node)
769
- end
770
-
771
- def next_sibling_node(node)
772
- psn = node.next_sibling_node
773
- while psn.nil?
774
- return nil if node.parent.nil? or node.parent.class == Document
775
- node = node.parent
776
- psn = node.next_sibling_node
1094
+ # Scanner for following axis
1095
+ def following(nodeset, tester, selector)
1096
+ anchors = Set.new.compare_by_identity.replace(nodeset)
1097
+ events = []
1098
+ descendant_traverse_event(nodeset.first.document || nodeset.first.root) do |type, node|
1099
+ events << :push if type == :leave && anchors.include?(node)
1100
+ events << node if !events.empty? && type == :enter && tester.call(node)
777
1101
  end
778
- psn
1102
+ anchors.size.times { events << :pop }
1103
+ sequence_positional_scan(events, selector)
779
1104
  end
780
1105
 
781
1106
  def child(nodeset)
782
1107
  nodesets = []
783
1108
  nodeset.each do |node|
784
- raw_node = node.raw_node
785
- node_type = raw_node.node_type
1109
+ node_type = node.node_type
786
1110
  # trace(:child, node_type, node)
787
1111
  case node_type
788
1112
  when :element
789
- nodesets << raw_node.children.collect.with_index do |child_node, i|
790
- XPathNode.new(child_node, position: i + 1)
791
- end
1113
+ nodesets << node.children
792
1114
  when :document
793
- new_nodeset = []
794
- raw_node.children.each do |child|
1115
+ new_nodeset = node.children.reject do |child|
795
1116
  case child
796
1117
  when XMLDecl, Text
797
- # Ignore
798
- else
799
- new_nodeset << XPathNode.new(child, position: new_nodeset.size + 1)
1118
+ true # Ignore
800
1119
  end
801
1120
  end
802
1121
  nodesets << new_nodeset unless new_nodeset.empty?
@@ -810,18 +1129,15 @@ module REXML
810
1129
  when true, false
811
1130
  b
812
1131
  when 'true', 'false'
813
- Functions::boolean( b )
1132
+ @functions.boolean( b )
814
1133
  when /^\d+(\.\d+)?$/, Numeric
815
- Functions::number( b )
1134
+ @functions.number( b )
816
1135
  else
817
- Functions::string( b )
1136
+ @functions.string( b )
818
1137
  end
819
1138
  end
820
1139
 
821
1140
  def equality_relational_compare(set1, op, set2)
822
- set1 = unnode(set1) if set1.is_a?(Array)
823
- set2 = unnode(set2) if set2.is_a?(Array)
824
-
825
1141
  if set1.kind_of? Array and set2.kind_of? Array
826
1142
  # If both objects to be compared are node-sets, then the
827
1143
  # comparison will be true if and only if there is a node in the
@@ -829,43 +1145,33 @@ module REXML
829
1145
  # result of performing the comparison on the string-values of
830
1146
  # the two nodes is true.
831
1147
  set1.product(set2).any? do |node1, node2|
832
- node_string1 = Functions.string(node1)
833
- node_string2 = Functions.string(node2)
1148
+ node_string1 = @functions.string(node1)
1149
+ node_string2 = @functions.string(node2)
834
1150
  compare(node_string1, op, node_string2)
835
1151
  end
836
1152
  elsif set1.kind_of? Array or set2.kind_of? Array
837
- # If one is nodeset and other is number, compare number to each item
838
- # in nodeset s.t. number op number(string(item))
839
- # If one is nodeset and other is string, compare string to each item
840
- # in nodeset s.t. string op string(item)
841
- # If one is nodeset and other is boolean, compare boolean to each item
842
- # in nodeset s.t. boolean op boolean(item)
843
- if set1.kind_of? Array
844
- a = set1
845
- b = set2
846
- else
847
- a = set2
848
- b = set1
849
- end
850
-
851
- case b
852
- when true, false
853
- each_unnode(a).any? do |unnoded|
854
- compare(Functions.boolean(unnoded), op, b)
855
- end
856
- when Numeric
857
- each_unnode(a).any? do |unnoded|
858
- compare(Functions.number(unnoded), op, b)
859
- end
860
- when /\A\d+(\.\d+)?\z/
861
- b = Functions.number(b)
862
- each_unnode(a).any? do |unnoded|
863
- compare(Functions.number(unnoded), op, b)
1153
+ if set1 == true or set1 == false or set2 == true or set2 == false
1154
+ # If one object to be compared is a node-set and the other is
1155
+ # a boolean, then the comparison will be true if and only if
1156
+ # the result of performing the comparison on the boolean and
1157
+ # on the result of converting the node-set to a boolean using
1158
+ # the boolean function is true.
1159
+ compare(@functions.boolean(set1), op, @functions.boolean(set2))
1160
+ elsif set1.kind_of? Array
1161
+ # If one object to be compared is a node-set and the other is
1162
+ # a number (string), then the comparison will be true if and
1163
+ # only if there is a node in the node-set such that the result
1164
+ # of performing the comparison on the number to be compared
1165
+ # and on the result of converting the string-value of that
1166
+ # node to a number using the number function (on the
1167
+ # string-value of the node and the other string) is true.
1168
+ set1.any? do |node|
1169
+ compare(node_set_item_value(node, set2), op, set2)
864
1170
  end
865
1171
  else
866
- b = Functions::string(b)
867
- each_unnode(a).any? do |unnoded|
868
- compare(Functions::string(unnoded), op, b)
1172
+ # Keep the operand order: "1 < @n" is not "@n < 1".
1173
+ set2.any? do |node|
1174
+ compare(set1, op, node_set_item_value(node, set1))
869
1175
  end
870
1176
  end
871
1177
  else
@@ -880,6 +1186,14 @@ module REXML
880
1186
  end
881
1187
  end
882
1188
 
1189
+ def node_set_item_value(node, other)
1190
+ if other.kind_of? Numeric
1191
+ @functions.number(node)
1192
+ else
1193
+ @functions.string(node)
1194
+ end
1195
+ end
1196
+
883
1197
  def value_type(value)
884
1198
  case value
885
1199
  when true, false
@@ -899,18 +1213,18 @@ module REXML
899
1213
  case operator
900
1214
  when :eq, :neq
901
1215
  if a_type == :boolean or b_type == :boolean
902
- a = Functions.boolean(a) unless a_type == :boolean
903
- b = Functions.boolean(b) unless b_type == :boolean
1216
+ a = @functions.boolean(a) unless a_type == :boolean
1217
+ b = @functions.boolean(b) unless b_type == :boolean
904
1218
  elsif a_type == :number or b_type == :number
905
- a = Functions.number(a) unless a_type == :number
906
- b = Functions.number(b) unless b_type == :number
1219
+ a = @functions.number(a) unless a_type == :number
1220
+ b = @functions.number(b) unless b_type == :number
907
1221
  else
908
- a = Functions.string(a) unless a_type == :string
909
- b = Functions.string(b) unless b_type == :string
1222
+ a = @functions.string(a) unless a_type == :string
1223
+ b = @functions.string(b) unless b_type == :string
910
1224
  end
911
1225
  when :lt, :lteq, :gt, :gteq
912
- a = Functions.number(a) unless a_type == :number
913
- b = Functions.number(b) unless b_type == :number
1226
+ a = @functions.number(a) unless a_type == :number
1227
+ b = @functions.number(b) unless b_type == :number
914
1228
  else
915
1229
  message = "[BUG] Unexpected compare operator: " +
916
1230
  "<#{operator.inspect}>: <#{a.inspect}>: <#{b.inspect}>"
@@ -940,41 +1254,5 @@ module REXML
940
1254
  raise message
941
1255
  end
942
1256
  end
943
-
944
- def each_unnode(nodeset)
945
- return to_enum(__method__, nodeset) unless block_given?
946
- nodeset.each do |node|
947
- if node.is_a?(XPathNode)
948
- unnoded = node.raw_node
949
- else
950
- unnoded = node
951
- end
952
- yield(unnoded)
953
- end
954
- end
955
-
956
- def unnode(nodeset)
957
- each_unnode(nodeset).collect do |unnoded|
958
- unnoded = yield(unnoded) if block_given?
959
- unnoded
960
- end
961
- end
962
- end
963
-
964
- # @private
965
- class XPathNode
966
- attr_reader :raw_node, :context
967
- def initialize(node, context=nil)
968
- if node.is_a?(XPathNode)
969
- @raw_node = node.raw_node
970
- else
971
- @raw_node = node
972
- end
973
- @context = context || {}
974
- end
975
-
976
- def position
977
- @context[:position]
978
- end
979
1257
  end
980
1258
  end