File: masgn_node.rb

package info (click to toggle)
ruby-rubocop-ast 1.49.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,768 kB
  • sloc: ruby: 17,017; yacc: 90; makefile: 9
file content (63 lines) | stat: -rw-r--r-- 1,996 bytes parent folder | download
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
# frozen_string_literal: true

module RuboCop
  module AST
    # A node extension for `masgn` nodes.
    # This will be used in place of a plain node when the builder constructs
    # the AST, making its methods available to all assignment nodes within RuboCop.
    class MasgnNode < Node
      # @return [MlhsNode] the `mlhs` node
      def lhs
        # The first child is a `mlhs` node
        node_parts[0]
      end

      # @return [Array<Node>] the assignment nodes of the multiple assignment
      def assignments
        lhs.assignments
      end

      # @return [Array<Symbol>] names of all the variables being assigned
      def names
        assignments.map do |assignment|
          if assignment.type?(:send, :indexasgn)
            assignment.method_name
          else
            assignment.name
          end
        end
      end

      # The RHS (right hand side) of the multiple assignment. This returns
      # the nodes as parsed: either a single node if the RHS has a single value,
      # or an `array` node containing multiple nodes.
      #
      # NOTE: Due to how parsing works, `expression` will return the same for
      # `a, b = x, y` and `a, b = [x, y]`.
      #
      # @return [Node] the right hand side of a multiple assignment.
      def expression
        node_parts[1]
      end
      alias rhs expression

      # In contrast to `expression`, `values` always returns a Ruby array
      # containing all the nodes being assigned on the RHS.
      #
      # Literal arrays are considered a singular value; but unlike `expression`,
      # implied `array` nodes from assigning multiple values on the RHS are treated
      # as separate.
      #
      # @return [Array<Node>] individual values being assigned on the RHS of the multiple assignment
      def values
        multiple_rhs? ? expression.children : [expression]
      end

      private

      def multiple_rhs?
        expression.array_type? && !expression.bracketed?
      end
    end
  end
end