Sha256: a0632ae6c9a9674746ef5435065faa40297345b580b813d8fce0ea67f952fa1a

Contents?: true

Size: 1.38 KB

Versions: 3

Compression:

Stored size: 1.38 KB

Contents

# frozen_string_literal: true

module Delorean
  module Ruby
    module Whitelists
      module Matchers
        class Arguments
          attr_reader :called_on, :method_name, :with

          def initialize(called_on:, method_name:, with: [])
            @called_on = called_on
            @method_name = method_name
            @with = with
          end

          def match!(args:)
            raise "too many args to #{method_name}" if args.size > with.size

            with.each_with_index do |s, i|
              arg_signature = Array(s)

              arg = args[i]

              # Sometimes signature contains extra elements that can be nil.
              # In that case we allow it to not be passed.
              # For example .first and .first(4)
              next if arg_signature.member?(nil) && i >= args.size

              next if valid_argument?(arg_signature: arg_signature, arg: arg)

              bad_arg_error(arg_signature: arg_signature, index: i, arg: arg)
            end
          end

          private

          def valid_argument?(arg_signature:, arg:)
            arg_signature.any? { |sc| sc && arg.class <= sc }
          end

          def bad_arg_error(arg_signature:, index:, arg:)
            arg_error = "#{arg}/#{arg.class} #{arg_signature}"
            raise "bad arg #{index}, method #{method_name}: #{arg_error}"
          end
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
delorean_lang-0.5.4 lib/delorean/ruby/whitelists/matchers/arguments.rb
delorean_lang-0.5.3 lib/delorean/ruby/whitelists/matchers/arguments.rb
delorean_lang-0.5.2 lib/delorean/ruby/whitelists/matchers/arguments.rb