Skip to content

Commit

Permalink
Change interface for in_sequence_head
Browse files Browse the repository at this point in the history
  • Loading branch information
marcandre committed Aug 31, 2020
1 parent f011935 commit fa4bcbb
Showing 1 changed file with 25 additions and 21 deletions.
46 changes: 25 additions & 21 deletions lib/rubocop/ast/node_pattern/node.rb
Expand Up @@ -26,9 +26,9 @@ def arity
1
end

# Return [Symbol] either :ok, :raise, or :insert_wildcard
# @return [Array<Nodes>, nil] replace node with result, or `nil` if no change requested.
def in_sequence_head
:ok
nil
end

###
Expand Down Expand Up @@ -64,14 +64,20 @@ def arity_range
INT_TO_RANGE = Hash.new { |h, k| h[k] = k..k }
private_constant :INT_TO_RANGE

module ForbidInSeqHead
def in_sequence_head
raise NodePattern::Invalid, "A sequence can not start with #{children.first}"
end
end

###
# Subclasses for specific node types
###

# Node class for `$something`
class Capture < Node
# Delegate most introspection methods to it's only child
def_delegators :child, :arity, :rest?, :in_sequence_head
def_delegators :child, :arity, :rest?

def capture?
true
Expand All @@ -80,24 +86,26 @@ def capture?
def nb_captures
1 + super
end

def in_sequence_head # ($...) => (_ $...)
wildcard, original_child = child.in_sequence_head
return unless original_child

[wildcard, self]
end
end

# Node class for `(type first second ...)`
class Sequence < Node
include ForbidInSeqHead

def initialize(type, children = [], properties = {})
case children.first.in_sequence_head
when :insert_wildcard
children = [Node.new(:wildcard), *children]
when :raise
raise NodePattern::Invalid, "A sequence can not start with #{children.first}"
if (replace = children.first.in_sequence_head)
children = [*replace, *children[1..-1]]
end

super
end

def in_sequence_head
:raise
end
end

# Node class for `predicate?(:arg, :list)`
Expand All @@ -114,6 +122,8 @@ def arg_list

# Node class for `int+`
class Repetition < Node
include ForbidInSeqHead

def operator
children[1]
end
Expand All @@ -127,10 +137,6 @@ def operator
def arity
ARITIES[operator]
end

def in_sequence_head
:raise
end
end

# Node class for `...`
Expand All @@ -147,12 +153,14 @@ def arity
end

def in_sequence_head
:insert_wildcard
[Node.new(:wildcard), self]
end
end

# Node class for `<int str ...>`
class AnyOrder < Node
include ForbidInSeqHead

ARITIES = Hash.new { |h, k| h[k] = k - 1..Float::INFINITY }
private_constant :ARITIES

Expand All @@ -173,10 +181,6 @@ def arity

ARITIES[children.size]
end

def in_sequence_head
:raise
end
end

# Registry
Expand Down

0 comments on commit fa4bcbb

Please sign in to comment.