Sha256: 46ede7ec2a32b31c1f00023c850150aca14526544f3d17c24871e970a32579b4

Contents?: true

Size: 1.58 KB

Versions: 6

Compression:

Stored size: 1.58 KB

Contents

# frozen_string_literal: true

require 'rubocop'

module RuboCop
  module Cop
    module Sorbet
      # This cop checks for the ordering of keyword arguments required by
      # sorbet-runtime. The ordering requires that all keyword arguments
      # are at the end of the parameters list, and all keyword arguments
      # with a default value must be after those without default values.
      #
      # @example
      #
      #   # bad
      #   sig { params(a: Integer, b: String).void }
      #   def foo(a: 1, b:); end
      #
      #   # good
      #   sig { params(b: String, a: Integer).void }
      #   def foo(b:, a: 1); end
      class KeywordArgumentOrdering < RuboCop::Cop::Cop
        def_node_matcher(:signature?, <<-PATTERN)
          (block (send nil? :sig) (args) ...)
        PATTERN

        def on_block(node)
          return unless signature?(node)

          method_node = node.parent.children[node.sibling_index + 1]
          return if method_node.nil?
          method_parameters = method_node.arguments

          check_order_for_kwoptargs(method_parameters)
        end

        private

        def check_order_for_kwoptargs(parameters)
          out_of_kwoptarg = false

          parameters.reverse.each do |param|
            out_of_kwoptarg = true unless param.type == :kwoptarg || param.type == :blockarg

            next unless param.type == :kwoptarg && out_of_kwoptarg

            add_offense(
              param,
              message: 'Optional keyword arguments must be at the end of the parameter list.'
            )
          end
        end
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
rubocop-sorbet-0.3.3 lib/rubocop/cop/sorbet/keyword_argument_ordering.rb
rubocop-sorbet-0.3.2 lib/rubocop/cop/sorbet/keyword_argument_ordering.rb
rubocop-sorbet-0.3.1 lib/rubocop/cop/sorbet/keyword_argument_ordering.rb
rubocop-sorbet-0.3.0 lib/rubocop/cop/sorbet/keyword_argument_ordering.rb
rubocop-sorbet-0.2.0 lib/rubocop/cop/sorbet/keyword_argument_ordering.rb
rubocop-sorbet-0.0.2 lib/rubocop/cop/sorbet/keyword_argument_ordering.rb