Class: Fast::Find

Inherits:
Object
  • Object
show all
Defined in:
lib/fast.rb

Overview

Find is the top level class that respond to #match?(node) interface. It matches recurively and check deeply depends of the token type.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(token) ⇒ Find

Returns a new instance of Find.



551
552
553
# File 'lib/fast.rb', line 551

def initialize(token)
  self.token = token
end

Instance Attribute Details

#tokenObject

Returns the value of attribute token.



550
551
552
# File 'lib/fast.rb', line 550

def token
  @token
end

Instance Method Details

#==(other) ⇒ Object



609
610
611
612
613
# File 'lib/fast.rb', line 609

def ==(other)
  return false if other.nil? || !other.respond_to?(:token)

  token == other.token
end

#compare_symbol_or_head(expression, node) ⇒ Object



578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
# File 'lib/fast.rb', line 578

def compare_symbol_or_head(expression, node)
  return true if node.nil? && (expression.nil? || expression == :nil)

  case node
  when ->(candidate) { Fast.ast_node?(candidate) }
    node.type == expression&.to_sym
  when String
    node == expression.to_s
  when TrueClass
    expression == :true
  when FalseClass
    expression == :false
  else
    node == expression
  end
end

#debug(expression, node, match) ⇒ Object



601
602
603
# File 'lib/fast.rb', line 601

def debug(expression, node, match)
  puts "#{expression} == #{node} # => #{match}"
end

#debug_match_recursive(expression, node) ⇒ Object



595
596
597
598
599
# File 'lib/fast.rb', line 595

def debug_match_recursive(expression, node)
  match = original_match_recursive(expression, node)
  debug(expression, node, match)
  match
end

#match?(node) ⇒ Boolean

Returns:

  • (Boolean)


555
556
557
# File 'lib/fast.rb', line 555

def match?(node)
  match_recursive(valuate(token), node)
end

#match_recursive(expression, node) ⇒ Object



559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
# File 'lib/fast.rb', line 559

def match_recursive(expression, node)
  case expression
  when Proc then expression.call(node)
  when Find then expression.match?(node)
  when Enumerable
    if expression.last == :'...' || expression.last.is_a?(Find) && expression.last.token == '...'
      expression[0...-1].each_with_index.all? do |exp, i|
        match_recursive(exp, i.zero? ? node : node.children[i - 1])
      end
    else
      expression.each_with_index.all? do |exp, i|
        match_recursive(exp, i.zero? ? node : node.children[i - 1])
      end
    end
  else
    compare_symbol_or_head(expression, node)
  end
end

#to_sObject



605
606
607
# File 'lib/fast.rb', line 605

def to_s
  "f[#{[*token].map(&:to_s).join(', ')}]"
end