Sha256: 08b792e35618e09221d43bbbdc2fe94d5a9beeee189613fd180ea63b231f84b6

Contents?: true

Size: 1.81 KB

Versions: 15

Compression:

Stored size: 1.81 KB

Contents

# typed: strict
# frozen_string_literal: true

module RubyLsp
  module Requests
    # Show syntax tree is a custom [LSP
    # request](https://microsoft.github.io/language-server-protocol/specification#requestMessage) that displays the AST
    # for the current document or for the current selection in a new tab.
    class ShowSyntaxTree < Request
      extend T::Sig

      sig { params(document: RubyDocument, range: T.nilable(T::Hash[Symbol, T.untyped])).void }
      def initialize(document, range)
        super()
        @document = document
        @range = range
        @tree = T.let(document.parse_result.value, Prism::ProgramNode)
      end

      sig { override.returns(String) }
      def perform
        return ast_for_range if @range

        output_string = +""
        PP.pp(@tree, output_string)
        output_string
      end

      private

      sig { returns(String) }
      def ast_for_range
        range = T.must(@range)

        scanner = @document.create_scanner
        start_char = scanner.find_char_position(range[:start])
        end_char = scanner.find_char_position(range[:end])

        queue = @tree.statements.body.dup
        found_nodes = []

        until queue.empty?
          node = queue.shift
          next unless node

          loc = node.location

          # If the node is fully covered by the selection, then we found one of the nodes to be displayed and don't want
          # to continue descending into its children
          if (start_char..end_char).cover?(loc.start_offset..loc.end_offset)
            found_nodes << node
          else
            T.unsafe(queue).unshift(*node.child_nodes)
          end
        end

        found_nodes.map do |node|
          output_string = +""
          PP.pp(node, output_string)
          output_string
        end.join("\n")
      end
    end
  end
end

Version data entries

15 entries across 15 versions & 1 rubygems

Version Path
ruby-lsp-0.22.1 lib/ruby_lsp/requests/show_syntax_tree.rb
ruby-lsp-0.22.0 lib/ruby_lsp/requests/show_syntax_tree.rb
ruby-lsp-0.21.3 lib/ruby_lsp/requests/show_syntax_tree.rb
ruby-lsp-0.21.2 lib/ruby_lsp/requests/show_syntax_tree.rb
ruby-lsp-0.21.1 lib/ruby_lsp/requests/show_syntax_tree.rb
ruby-lsp-0.21.0 lib/ruby_lsp/requests/show_syntax_tree.rb
ruby-lsp-0.20.1 lib/ruby_lsp/requests/show_syntax_tree.rb
ruby-lsp-0.20.0 lib/ruby_lsp/requests/show_syntax_tree.rb
ruby-lsp-0.19.1 lib/ruby_lsp/requests/show_syntax_tree.rb
ruby-lsp-0.19.0 lib/ruby_lsp/requests/show_syntax_tree.rb
ruby-lsp-0.18.4 lib/ruby_lsp/requests/show_syntax_tree.rb
ruby-lsp-0.18.3 lib/ruby_lsp/requests/show_syntax_tree.rb
ruby-lsp-0.18.2 lib/ruby_lsp/requests/show_syntax_tree.rb
ruby-lsp-0.18.1 lib/ruby_lsp/requests/show_syntax_tree.rb
ruby-lsp-0.18.0 lib/ruby_lsp/requests/show_syntax_tree.rb