Sha256: b7d41d7758536d2aaa502cc27c7c360b56e009525e06a86b29b91a8193557b6f

Contents?: true

Size: 1.62 KB

Versions: 13

Compression:

Stored size: 1.62 KB

Contents

# frozen_string_literal: true

module RubyNext
  module Language
    module Rewriters
      class AnonymousBlock < Base
        NAME = "anonymous-block"
        SYNTAX_PROBE = "obj = Object.new; def obj.foo(&) bar(&); end"
        MIN_SUPPORTED_VERSION = Gem::Version.new("3.1.0")

        BLOCK = :__block__

        def on_args(node)
          block = node.children.last

          return super unless block&.type == :blockarg
          return super unless block.children.first.nil?

          context.track! self

          replace(block.loc.expression, "&#{BLOCK}")

          node.updated(
            :args,
            [
              *node.children.slice(0, node.children.index(block)),
              s(:blockarg, BLOCK)
            ]
          )
        end

        def on_send(node)
          block = extract_block_pass(node)
          return super unless block&.children == [nil]

          process_block(node, block)
        end

        def on_super(node)
          block = extract_block_pass(node)
          return super unless block&.children == [nil]

          process_block(node, block)
        end

        private

        def extract_block_pass(node)
          node.children.find { |child| child.is_a?(::Parser::AST::Node) && child.type == :block_pass }
        end

        def process_block(node, block)
          replace(block.loc.expression, "&#{BLOCK}")

          process(
            node.updated(
              nil,
              [
                *node.children.take(node.children.index(block)),
                s(:block_pass, s(:lvar, BLOCK))
              ]
            )
          )
        end
      end
    end
  end
end

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
ruby-next-core-1.1.1 lib/ruby-next/language/rewriters/3.1/anonymous_block.rb
ruby-next-core-1.1.0 lib/ruby-next/language/rewriters/3.1/anonymous_block.rb
ruby-next-core-1.0.3 lib/ruby-next/language/rewriters/3.1/anonymous_block.rb
ruby-next-core-1.0.2 lib/ruby-next/language/rewriters/3.1/anonymous_block.rb
ruby-next-core-1.0.1 lib/ruby-next/language/rewriters/3.1/anonymous_block.rb
ruby-next-core-1.0.0 lib/ruby-next/language/rewriters/3.1/anonymous_block.rb
ruby-next-core-1.0.0.rc.1 lib/ruby-next/language/rewriters/3.1/anonymous_block.rb
ruby-next-core-0.15.3 lib/ruby-next/language/rewriters/3.1/anonymous_block.rb
ruby-next-core-0.15.2 lib/ruby-next/language/rewriters/3.1/anonymous_block.rb
ruby-next-core-0.15.1 lib/ruby-next/language/rewriters/3.1/anonymous_block.rb
ruby-next-core-0.15.0 lib/ruby-next/language/rewriters/3.1/anonymous_block.rb
ruby-next-core-0.14.1 lib/ruby-next/language/rewriters/3.1/anonymous_block.rb
ruby-next-core-0.14.0 lib/ruby-next/language/rewriters/3.1/anonymous_block.rb