Class: RubyLsp::ResponseBuilders::SemanticHighlighting::SemanticTokenEncoder

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby_lsp/response_builders/semantic_highlighting.rb

Instance Method Summary collapse

Constructor Details

#initializeSemanticTokenEncoder

: -> void



138
139
140
141
# File 'lib/ruby_lsp/response_builders/semantic_highlighting.rb', line 138

def initialize
  @current_row = 0 #: Integer
  @current_column = 0 #: Integer
end

Instance Method Details

#compute_delta(token) ⇒ Object

For more information on how each number is calculated, read: microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_semanticTokens : (SemanticToken token) -> Array



169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
# File 'lib/ruby_lsp/response_builders/semantic_highlighting.rb', line 169

def compute_delta(token)
  row = token.start_line - 1
  column = token.start_code_unit_column

  begin
    delta_line = row - @current_row

    delta_column = column
    delta_column -= @current_column if delta_line == 0

    [delta_line, delta_column, token.length, token.type, encode_modifiers(token.modifier)]
  ensure
    @current_row = row
    @current_column = column
  end
end

#encode(tokens) ⇒ Object

: (Array tokens) -> Array



144
145
146
147
148
149
150
151
152
153
154
155
156
157
# File 'lib/ruby_lsp/response_builders/semantic_highlighting.rb', line 144

def encode(tokens)
  sorted_tokens = tokens.sort_by.with_index do |token, index|
    # Enumerable#sort_by is not deterministic when the compared values are equal.
    # When that happens, we need to use the index as a tie breaker to ensure
    # that the order of the tokens is always the same.
    [token.start_line, token.start_code_unit_column, index]
  end

  delta = sorted_tokens.flat_map do |token|
    compute_delta(token)
  end

  delta
end

#encode_modifiers(modifiers) ⇒ Object

Encode an array of modifiers to positions onto a bit flag For example, [:default_library] will be encoded as 0b1000000000, as :default_library is the 10th bit according to the token modifiers index map. : (Array modifiers) -> Integer



191
192
193
194
195
# File 'lib/ruby_lsp/response_builders/semantic_highlighting.rb', line 191

def encode_modifiers(modifiers)
  modifiers.inject(0) do |encoded_modifiers, modifier|
    encoded_modifiers | (1 << modifier)
  end
end