Class: RubyLsp::Document

Inherits:
Object
  • Object
show all
Extended by:
T::Sig
Defined in:
lib/ruby_lsp/document.rb

Defined Under Namespace

Classes: Scanner

Constant Summary collapse

PositionShape =
T.type_alias { { line: Integer, character: Integer } }
RangeShape =
T.type_alias { { start: PositionShape, end: PositionShape } }
EditShape =
T.type_alias { { range: RangeShape, text: String } }

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(source, encoding = "utf-8") ⇒ Document

Returns a new instance of Document.



19
20
21
22
23
24
25
26
27
# File 'lib/ruby_lsp/document.rb', line 19

def initialize(source, encoding = "utf-8")
  @cache = T.let({}, T::Hash[Symbol, T.untyped])
  @encoding = T.let(encoding, String)
  @source = T.let(source, String)
  @unparsed_edits = T.let([], T::Array[EditShape])
  @tree = T.let(SyntaxTree.parse(@source), T.nilable(SyntaxTree::Node))
rescue SyntaxTree::Parser::ParseError
  # Do not raise if we failed to parse
end

Instance Attribute Details

#sourceObject (readonly)

Returns the value of attribute source.



16
17
18
# File 'lib/ruby_lsp/document.rb', line 16

def source
  @source
end

#treeObject (readonly)

Returns the value of attribute tree.



13
14
15
# File 'lib/ruby_lsp/document.rb', line 13

def tree
  @tree
end

Instance Method Details

#==(other) ⇒ Object



30
31
32
# File 'lib/ruby_lsp/document.rb', line 30

def ==(other)
  @source == other.source
end

#cache_fetch(request_name, &block) ⇒ Object



41
42
43
44
45
46
47
48
# File 'lib/ruby_lsp/document.rb', line 41

def cache_fetch(request_name, &block)
  cached = @cache[request_name]
  return cached if cached

  result = block.call(self)
  @cache[request_name] = result
  result
end

#create_scannerObject



87
88
89
# File 'lib/ruby_lsp/document.rb', line 87

def create_scanner
  Scanner.new(@source, @encoding)
end

#parseObject



67
68
69
70
71
72
73
74
# File 'lib/ruby_lsp/document.rb', line 67

def parse
  return if @unparsed_edits.empty?

  @tree = SyntaxTree.parse(@source)
  @unparsed_edits.clear
rescue SyntaxTree::Parser::ParseError
  # Do nothing if we fail parse
end

#parsed?Boolean

Returns:

  • (Boolean)


82
83
84
# File 'lib/ruby_lsp/document.rb', line 82

def parsed?
  !@tree.nil?
end

#push_edits(edits) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/ruby_lsp/document.rb', line 51

def push_edits(edits)
  edits.each do |edit|
    range = edit[:range]
    scanner = create_scanner

    start_position = scanner.find_char_position(range[:start])
    end_position = scanner.find_char_position(range[:end])

    @source[start_position...end_position] = edit[:text]
  end

  @unparsed_edits.concat(edits)
  @cache.clear
end

#syntax_error?Boolean

Returns:

  • (Boolean)


77
78
79
# File 'lib/ruby_lsp/document.rb', line 77

def syntax_error?
  @unparsed_edits.any?
end