Class: Synvert::Core::NodeQuery::Compiler::Expression

Inherits:
Object
  • Object
show all
Defined in:
lib/synvert/core/node_query/compiler/expression.rb

Overview

Expression represents a node query expression.

Instance Method Summary collapse

Constructor Details

#initialize(selector: nil, goto_scope: nil, rest: nil, relationship: nil) ⇒ Expression

Initialize a Expression.

Parameters:



11
12
13
14
15
16
# File 'lib/synvert/core/node_query/compiler/expression.rb', line 11

def initialize(selector: nil, goto_scope: nil, rest: nil, relationship: nil)
  @selector = selector
  @goto_scope = goto_scope
  @rest = rest
  @relationship = relationship
end

Instance Method Details

#match?(node) ⇒ Boolean

Check if the node matches the expression.

Parameters:

Returns:



21
22
23
# File 'lib/synvert/core/node_query/compiler/expression.rb', line 21

def match?(node)
  !query_nodes(node).empty?
end

#query_nodes(node, descendant_match = true) ⇒ Array<Parser::AST::Node>

Query nodes by the expression.

  • If relationship is nil, it will match in all recursive child nodes and return matching nodes.

  • If relationship is :decendant, it will match in all recursive child nodes.

  • If relationship is :child, it will match in direct child nodes.

  • If relationship is :next_sibling, it try to match next sibling node.

  • If relationship is :subsequent_sibling, it will match in all sibling nodes.

Parameters:

  • node (Parser::AST::Node)

    node to match

  • descendant_match (Boolean) (defaults to: true)

    whether to match in descendant node

Returns:



35
36
37
38
39
40
41
42
43
44
45
# File 'lib/synvert/core/node_query/compiler/expression.rb', line 35

def query_nodes(node, descendant_match = true)
  return find_nodes_by_goto_scope(node) if @goto_scope

  return find_nodes_by_relationship(node) if @relationship

  matching_nodes = find_nodes_without_relationship(node, descendant_match)
  return matching_nodes if @rest.nil?

  matching_nodes.map { |matching_node| find_nodes_by_rest(matching_node, descendant_match) }
                .flatten
end

#to_sObject



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/synvert/core/node_query/compiler/expression.rb', line 47

def to_s
  return @selector.to_s unless @rest

  result = []
  result << @selector.to_s if @selector
  result << "<#{@goto_scope}>" if @goto_scope
  case @relationship
  when :child then result << "> #{@rest}"
  when :subsequent_sibling then result << "~ #{@rest}"
  when :next_sibling then result << "+ #{@rest}"
  when :has then result << ":has(#{@rest})"
  when :not_has then result << ":not_has(#{@rest})"
  else result << @rest.to_s
  end
  result.join(' ')
end