Class: Fast::Matcher
- Inherits:
-
Object
- Object
- Fast::Matcher
- Defined in:
- lib/fast.rb
Overview
Joins the AST and the search expression to create a complete matcher that recusively check if the node pattern expression matches with the given AST.
Using captures
One of the most important features of the matcher is find captures and also bind them on demand in case the expression is using previous captures.
Instance Method Summary collapse
-
#captures?(expression = @expression) ⇒ true
Look recursively into @param expression to check if the expression is have captures.
-
#find_captures(expression = @expression) ⇒ Array<Object>, true
Find search captures recursively.
-
#initialize(pattern, ast, *args) ⇒ Matcher
constructor
A new instance of Matcher.
- #match?(expression = @expression, ast = @ast) ⇒ true
-
#match_tail?(tail, child) ⇒ true
If all children matches with tail.
Constructor Details
#initialize(pattern, ast, *args) ⇒ Matcher
Returns a new instance of Matcher.
721 722 723 724 725 726 727 728 729 730 |
# File 'lib/fast.rb', line 721 def initialize(pattern, ast, *args) @ast = ast @expression = if pattern.is_a?(String) Fast.expression(pattern) else [*pattern].map(&Find.method(:new)) end @captures = [] prepare_arguments(@expression, args) if args.any? end |
Instance Method Details
#captures?(expression = @expression) ⇒ true
Look recursively into @param expression to check if the expression is have captures.
753 754 755 756 757 758 759 |
# File 'lib/fast.rb', line 753 def captures?(expression = @expression) case expression when Capture then true when Array then expression.any?(&method(:captures?)) when Find then captures?(expression.token) end end |
#find_captures(expression = @expression) ⇒ Array<Object>, true
Find search captures recursively.
767 768 769 770 771 772 773 774 775 |
# File 'lib/fast.rb', line 767 def find_captures(expression = @expression) return true if expression == @expression && !captures?(expression) case expression when Capture then expression.captures when Array then expression.flat_map(&method(:find_captures)).compact when Find then find_captures(expression.token) end end |
#match?(expression = @expression, ast = @ast) ⇒ true
734 735 736 737 738 739 740 |
# File 'lib/fast.rb', line 734 def match?(expression = @expression, ast = @ast) head, *tail_expression = expression return false unless head.match?(ast) return find_captures if tail_expression.empty? match_tail?(tail_expression, ast.children) end |
#match_tail?(tail, child) ⇒ true
Returns if all children matches with tail.
743 744 745 746 747 748 |
# File 'lib/fast.rb', line 743 def match_tail?(tail, child) tail.each_with_index.all? do |token, i| prepare_token(token) token.is_a?(Array) ? match?(token, child[i]) : token.match?(child[i]) end && find_captures end |