forked from rubocop/rubocop-ast
/
def_node.rb
91 lines (82 loc) · 2.89 KB
/
def_node.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# frozen_string_literal: true
module RuboCop
module AST
# A node extension for `def` nodes. This will be used in place of a plain
# node when the builder constructs the AST, making its methods available
# to all `def` nodes within RuboCop.
class DefNode < Node
include ParameterizedNode
include MethodIdentifierPredicates
# Checks whether this node body is a void context.
#
# @return [Boolean] whether the `def` node body is a void context
def void_context?
method?(:initialize) || assignment_method?
end
# Checks whether this method definition node forwards its arguments
# as per the feature added in Ruby 2.7.
#
# @note This is written in a way that may support lead arguments
# which are rumored to be added in a later version of Ruby.
#
# @return [Boolean] whether the `def` node uses argument forwarding
def argument_forwarding?
arguments.any?(&:forward_args_type?) || arguments.any?(&:forward_arg_type?)
end
# Checks whether this is an endless method definition node
# as per the feature added in Ruby 2.8.
#
# @note This is written in a way that may support method definition
# which are rumored to be added in a later version of Ruby.
#
# @return [Boolean] whether the `def_s` node
alias endless? def_e_type?
# The name of the defined method as a symbol.
#
# @return [Symbol] the name of the defined method
def method_name
node_parts[2]
end
# An array containing the arguments of the method definition.
#
# @return [Array<Node>] the arguments of the method definition
def arguments
node_parts[1]
end
# The body of the method definition.
#
# @note this can be either a `begin` node, if the method body contains
# multiple expressions, or any other node, if it contains a single
# expression.
#
# @return [Node] the body of the method definition
def body
node_parts[0]
end
# The receiver of the method definition, if any.
#
# @return [Node, nil] the receiver of the method definition, or `nil`.
def receiver
node_parts[3]
end
# Custom destructuring method. This can be used to normalize
# destructuring for different variations of the node.
#
# In this case, the `def` node destructures into:
#
# `method_name, arguments, body`
#
# while the `defs` node destructures into:
#
# `receiver, method_name, arguments, body`
#
# so we reverse the destructured array to get the optional receiver
# at the end, where it can be discarded.
#
# @return [Array] the different parts of the `def` or `defs` node
def node_parts
to_a.reverse
end
end
end
end