Sha256: 449e19fb791992be14b9e3effce35ebddbef835e66bb17d64dd04852e21c7d36

Contents?: true

Size: 1.32 KB

Versions: 2

Compression:

Stored size: 1.32 KB

Contents

# typed: strict
# frozen_string_literal: true

module RBI
  module Rewriters
    # This rewriter moves top-level members into a top-level Object class
    #
    # Example:
    # ~~~rb
    # def foo; end
    # attr_reader :bar
    # ~~~
    #
    # will be rewritten to:
    #
    # ~~~rb
    # class Object
    #  def foo; end
    #  attr_reader :bar
    # end
    # ~~~
    class NestTopLevelMembers < Visitor
      extend T::Sig

      sig { void }
      def initialize
        super

        @top_level_object_class = T.let(nil, T.nilable(Class))
      end

      sig { override.params(node: T.nilable(Node)).void }
      def visit(node)
        return unless node

        case node
        when Tree
          visit_all(node.nodes.dup)
        else
          scope = node.parent_scope
          unless scope
            parent = node.parent_tree
            raise unless parent

            node.detach

            unless @top_level_object_class
              @top_level_object_class = Class.new("Object")
              parent.nodes << @top_level_object_class
            end

            @top_level_object_class << node
          end
        end
      end
    end
  end

  class Tree
    extend T::Sig

    sig { void }
    def nest_top_level_members!
      visitor = Rewriters::NestTopLevelMembers.new
      visitor.visit(self)
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
rbi-0.2.1 lib/rbi/rewriters/nest_top_level_members.rb
rbi-0.2.0 lib/rbi/rewriters/nest_top_level_members.rb