Module: MilkTea::LSP::Server::ServerSemanticTokens

Included in:
MilkTea::LSP::Server
Defined in:
lib/milk_tea/lsp/server/semantic_tokens.rb

Constant Summary collapse

STANDS_ALONE_WITH_COLON =

Keywords whose standalone syntax is "keyword:" — they form blocks or expressions directly with a colon and no intervening token, so they are not field declarations when followed by ":".

%i[unsafe else defer parallel].to_set.freeze

Instance Method Summary collapse

Instance Method Details

#bare_builtin_specialization?(name, tokens, index) ⇒ Boolean

Returns:

  • (Boolean)


1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 1126

def bare_builtin_specialization?(name, tokens, index)
  return false unless name == 'zero' || name == 'default'

  next_index = next_non_trivia_token_index(tokens, index + 1)
  return false unless next_index && tokens[next_index].type == :lbracket

  rbracket_index = matching_closer_index(tokens, next_index, :lbracket, :rbracket)
  return false unless rbracket_index

  after_bracket_index = next_non_trivia_token_index(tokens, rbracket_index + 1)
  after_bracket_index.nil? || tokens[after_bracket_index].type != :lparen
end

#bare_function_value_identifier_site?(facts, token) ⇒ Boolean

Returns:

  • (Boolean)


1139
1140
1141
1142
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 1139

def bare_function_value_identifier_site?(facts, token)
  facts.functions.key?(token.lexeme) &&
    facts.callable_value_identifier_sites.fetch([token.line, token.column], false)
end

#build_attribute_name_semantic_overrides(tokens, facts) ⇒ Object



1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 1570

def build_attribute_name_semantic_overrides(tokens, facts)
  return {} unless facts&.respond_to?(:ast) && facts.ast

  token_indices_by_position = tokens.each_with_index.each_with_object({}) do |(token, index), positions|
    positions[[token.line, token.column]] = index
  end
  overrides = {}

  walk_ast_nodes(facts.ast) do |node|
    case node
    when AST::AttributeDecl
      mark_attribute_name_override(
        overrides,
        token_indices_by_position,
        tokens,
        [node.name],
        line: node.line,
        column: node.column,
        declaration: true,
      )
    when AST::AttributeApplication
      mark_attribute_name_override(
        overrides,
        token_indices_by_position,
        tokens,
        node.name.parts,
        line: node.line,
        column: node.column,
      )
    when AST::Call
      mark_attribute_reflection_name_overrides(overrides, token_indices_by_position, tokens, node)
    end
  end

  overrides
end

#build_semantic_token_entries(tokens, facts = nil) ⇒ Object



127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 127

def build_semantic_token_entries(tokens, facts = nil)
  # Precompute line → non-trivia tokens index so non_trivia_tokens_on_line
  # is O(1) per call instead of O(n), turning the overall build from O(n²) to O(n).
  trivia_types = Set[:newline, :indent, :dedent, :eof]
  @tokens_by_line_cache = Hash.new { |h, k| h[k] = [] }
  @semantic_token_build_cache = {}
  tokens.each { |t| @tokens_by_line_cache[t.line] << t unless trivia_types.include?(t.type) }
  @attribute_name_semantic_overrides = build_attribute_name_semantic_overrides(tokens, facts)

  entries = []

  tokens.each_with_index do |tok, index|
    next if [:newline, :indent, :dedent, :eof].include?(tok.type)

    if tok.type == :fstring
      next if embedded_heredoc_token?(tok)
      fstring_interpolation_entries(tok, facts).each { |e| entries << e }
      next
    end

    semantic_type, modifiers = classify_semantic_token(tokens, index, facts)
    next unless semantic_type

    token_semantic_entries(tok, semantic_type, modifiers).each { |entry| entries << entry }
  end

  entries.sort_by { |entry| [entry[:line], entry[:start_char]] }
ensure
  @tokens_by_line_cache = nil
  @attribute_name_semantic_overrides = nil
  @semantic_token_build_cache = nil
end

#callable_field_member_access?(name, tokens, index, facts) ⇒ Boolean

Returns:

  • (Boolean)


1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 1035

def callable_field_member_access?(name, tokens, index, facts)
  next_tok = next_non_trivia_token(tokens, index + 1)
  return false unless next_tok&.type == :lparen

  dot_index = previous_non_trivia_token_index(tokens, index)
  return false unless dot_index && tokens[dot_index].type == :dot

  receiver_index = previous_non_trivia_token_index(tokens, dot_index)
  return false unless receiver_index

  receiver_tok = tokens[receiver_index]
  return false unless receiver_tok.type == :identifier

  resolve_receiver_value_type(facts, receiver_tok).then do |receiver_type|
    next false unless receiver_type

    field_receiver_type = project_field_receiver_type_for_completion(receiver_type, facts)
    next false unless field_receiver_type.respond_to?(:field)

    callable_semantic_type?(field_receiver_type.field(name))
  end
end

#callable_parameter_declaration_token?(tokens, index) ⇒ Boolean

Returns:

  • (Boolean)


719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 719

def callable_parameter_declaration_token?(tokens, index)
  return false unless parameter_declaration_token?(tokens, index)

  opener_index = parameter_list_opener_index(tokens, index)
  return false unless opener_index

  head_index = previous_non_trivia_token_index(tokens, opener_index)
  return false unless head_index

  head = tokens[head_index]
  return true if [:fn, :proc].include?(head.type)

  if head.type == :rbracket
    lbracket_index = matching_opener_index(tokens, head_index)
    return false unless lbracket_index

    head_index = previous_non_trivia_token_index(tokens, lbracket_index)
    return false unless head_index

    head = tokens[head_index]
  end

  return false unless head.type == :identifier

  previous_non_trivia_token(tokens, head_index)&.type == :function
end

#callable_semantic_type?(type) ⇒ Boolean

Returns:

  • (Boolean)


1069
1070
1071
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 1069

def callable_semantic_type?(type)
  type.is_a?(Types::Function) || type.is_a?(Types::Proc)
end

#classify_name_semantic(name, tokens, index, facts = nil) ⇒ Object



336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 336

def classify_name_semantic(name, tokens, index, facts = nil)
  tok = tokens[index]
  prev_tok = previous_non_trivia_token(tokens, index)
  next_tok = next_non_trivia_token(tokens, index + 1)
  parameter_declaration = parameter_declaration_token?(tokens, index)
  user_defined_function = facts ? facts.functions.key?(name) : lexically_declared_free_function_name?(tokens, name)

  if @attribute_name_semantic_overrides && (override = @attribute_name_semantic_overrides[[tok.line, tok.column]])
    return override
  end

  if (import_info = import_path_info_at(tokens, index, allow_keywords: true))
    modifiers = []
    modifiers << 'declaration' if import_info[:role] == :alias
    return [:namespace, modifiers]
  end

  return [:namespace, []] if module_declaration_path_token?(tokens, index, allow_keywords: true)

  if prev_tok && [:function, :fn, :proc].include?(prev_tok.type)
    return [:function, ['declaration']]
  end

  if prev_tok && [:struct, :union, :enum, :flags, :variant, :type, :opaque, :interface].include?(prev_tok.type)
    return [:type, ['declaration']]
  end

  return [:variable, []] if name == "_"

  if prev_tok&.type == :event
    return struct_event_declaration_token?(tokens, index) ? [:property, ['declaration']] : [:variable, ['declaration']]
  end

  if prev_tok&.type == :const
    return [:variable, ['declaration', 'readonly']]
  end

  if prev_tok&.type == :let
    return [:variable, ['declaration', 'readonly']] unless next_tok&.type == :lparen
  end

  if prev_tok&.type == :var
    return [:variable, ['declaration']] unless next_tok&.type == :lparen
  end

  if prev_tok&.type == :for
    return [:variable, ['declaration', 'readonly']]
  end

  return [:variable, ['declaration', 'readonly']] if match_arm_binding_token?(tokens, index)
  return [:parameter, ['declaration']] if callable_parameter_declaration_token?(tokens, index)
  return [:property, ['declaration']] if variant_payload_field_declaration_token?(tokens, index)
  return [:property, ['declaration']] if field_declaration_token?(tokens, index)

  if destructure_let_binding?(tokens, index)
    return [:variable, ['declaration', 'readonly']]
  end

  if facts
    return [:typeParameter, ['declaration']] if type_parameter_declaration_token?(facts, tokens, index)
    return [:typeParameter, []] if type_parameter_reference_token?(facts, tokens, index)
  end

  return [:property, []] if named_argument_label_token?(tokens, index) && named_argument_label_in_type_constructor?(tokens, index, facts)
  return [:parameter, []] if named_argument_label_token?(tokens, index)

  if facts && prev_tok&.type != :dot && (generic_binding = generic_function_lexical_binding_semantic(facts, tok))
    return generic_binding
  end

  if next_tok&.type == :dot && facts
    return [:type, []] if known_type_name?(facts, name)
    return [:type, []] if facts.interfaces.key?(name)
    return [:namespace, []] if facts.imports.key?(name)

    if (binding = local_semantic_value_binding(facts, tok, allow_same_line_future: parameter_declaration))
      return semantic_value_binding_entry(binding, declaration: binding.kind == :param && parameter_declaration)
    end

    if (binding = facts.values[name])
      return semantic_value_binding_entry(binding)
    end
  end

  if facts && (known_type_name?(facts, name) || facts.interfaces.key?(name)) && identifier_in_type_argument_position?(tokens, index)
    return [:type, []]
  end

  return [:enumMember, ['declaration']] if variant_enum_member_declaration?(tokens, index)

  if prev_tok&.type == :dot
    if facts
      module_binding = imported_module_binding_for_member(tokens, index, facts)
      if module_binding
        if module_binding.functions.key?(name)
          return [:function, []] if next_tok&.type == :lparen || specialized_call_with_type_args?(tokens, index)
          return [:function, []] if next_tok&.type == :lbracket
          return [:function, []] if imported_module_function_value_member_access_site?(facts, tokens, index)
          return [:property, []]
        end
        return [:type, []] if module_binding.types.key?(name)
        return [:type, []] if module_binding.interfaces.key?(name)
        if (value_binding = module_binding.values[name])
          modifiers = []
          modifiers << 'readonly' if value_binding.respond_to?(:mutable) && value_binding.mutable == false
          return [:variable, modifiers]
        end
        return [:namespace, []] if facts.imports.key?(name)
      end

      return [:type, []] if dot_nested_type_member?(tokens, index, facts)
      return [:property, []] if callable_field_member_access?(name, tokens, index, facts)
      return [:method, []] if static_type_member_access?(tokens, index, facts)
    end

    return [:enumMember, []] if type_name_member_access?(tokens, index, facts)
    return [:method, []] if next_tok&.type == :lparen || specialized_call_with_type_args?(tokens, index)
    return [:property, []]
  end

  if next_tok&.type == :lparen || specialized_call_with_type_args?(tokens, index)
    if facts && (resolved = resolved_call_callee_semantic(name, tok, parameter_declaration, facts))
      return resolved
    end

    return [:function, []] if user_defined_function

    modifiers = []
    modifiers << 'defaultLibrary' if BUILTIN_FUNCTION_NAMES.include?(name)
    if BUILTIN_ASSOCIATED_HOOK_NAMES.include?(name) && specialized_call_with_type_args?(tokens, index) && !user_defined_function
      modifiers << 'defaultLibrary'
    end
    return [:function, modifiers]
  end

  return [:function, []] if next_tok&.type == :lbracket && user_defined_function

  if facts && identifier_in_type_reference_position?(tokens, index)
    if known_type_name?(facts, name)
      modifiers = []
      modifiers << 'defaultLibrary' if DEFAULT_LIBRARY_TYPE_NAMES.include?(name)
      return [:type, modifiers]
    end
    return [:type, []] if facts.interfaces.key?(name)

    if DEFAULT_LIBRARY_TYPE_NAMES.include?(name)
      return [:type, ['defaultLibrary']]
    end
  end

  if facts

    if (binding = local_semantic_value_binding(facts, tok, allow_same_line_future: parameter_declaration))
      return semantic_value_binding_entry(binding, declaration: binding.kind == :param && parameter_declaration)
    end

    if known_type_name?(facts, name)
      modifiers = []
      modifiers << 'defaultLibrary' if DEFAULT_LIBRARY_TYPE_NAMES.include?(name)
      return [:type, modifiers]
    end
    return [:type, []] if facts.interfaces.key?(name)

    return [:namespace, []] if facts.imports.key?(name)

    if (binding = facts.values[name])
      return semantic_value_binding_entry(binding)
    end

    return [:function, []] if bare_function_value_identifier_site?(facts, tok)
  end

  if DEFAULT_LIBRARY_TYPE_NAMES.include?(name)
    return [:type, ['defaultLibrary']]
  end

  return [:function, ['defaultLibrary']] if bare_builtin_specialization?(name, tokens, index)

  [:variable, []]
end

#classify_semantic_token(tokens, index, facts = nil) ⇒ Object



275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 275

def classify_semantic_token(tokens, index, facts = nil)
  tok = tokens[index]

  if tok.type == :identifier || namespace_keyword_token?(tokens, index)
    return classify_name_semantic(tok.lexeme, tokens, index, facts)
  end

  if [:string, :cstring].include?(tok.type)
    return [nil, []] if embedded_heredoc_token?(tok)

    return [:string, []]
  end

  if tok.type == :comment
    return [:comment, []]
  end

  if [:integer, :float].include?(tok.type)
    return [:number, []]
  end

  if KEYWORD_TOKEN_TYPES.include?(tok.type)
    return [:typeParameter, []] if keyword_lifetime_or_type_param?(tokens, index)
    return [:type, []] if keyword_type_annotation?(tokens, index)
    return [:enumMember, [:declaration]] if variant_enum_member_declaration?(tokens, index)
    return [:property, [:declaration]] if keyword_field_declaration_token?(tokens, index)
    return [:property, []] if keyword_member_access?(tokens, index)
    return [:parameter, []] if keyword_named_argument_token?(tokens, index)
    return [:keyword, []]
  end

  if OPERATOR_TOKEN_TYPES.include?(tok.type)
    return [:operator, []]
  end

  [nil, []]
end

#collect_generic_function_local_scopes(statements, current_bindings, block_end_line, scopes) ⇒ Object



889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 889

def collect_generic_function_local_scopes(statements, current_bindings, block_end_line, scopes)
  active_bindings = current_bindings.dup
  Array(statements).each do |statement|
    case statement
    when AST::LocalDecl
      active_bindings[statement.name] = statement.kind == :var ? :var : :let
      scopes << generic_binding_scope(statement, active_bindings, block_end_line)
    when AST::IfStmt
      Array(statement.branches).each do |branch|
        branch_body = Array(branch.body)
        branch_end_line = generic_statement_list_end_line(branch_body, statement.line)
        collect_generic_function_local_scopes(branch_body, active_bindings, branch_end_line, scopes)
      end

      else_body = Array(statement.else_body)
      unless else_body.empty?
        else_end_line = generic_statement_list_end_line(else_body, statement.line)
        collect_generic_function_local_scopes(else_body, active_bindings, else_end_line, scopes)
      end
    when AST::MatchStmt
      Array(statement.arms).each do |arm|
        arm_bindings = active_bindings.dup
        arm_body = Array(arm.body)
        arm_end_line = generic_statement_list_end_line(arm_body, statement.line)
        if arm.respond_to?(:binding_name) && arm.binding_name
          arm_bindings[arm.binding_name] = :let
          scopes << generic_binding_scope(arm, arm_bindings, arm_end_line)
        end
        collect_generic_function_local_scopes(arm_body, arm_bindings, arm_end_line, scopes)
      end
    when AST::UnsafeStmt, AST::WhileStmt, AST::DeferStmt
      body = Array(statement.body)
      body_end_line = generic_statement_list_end_line(body, statement.line)
      collect_generic_function_local_scopes(body, active_bindings, body_end_line, scopes)
    when AST::ForStmt
      next unless statement.respond_to?(:name) && statement.name

      body = Array(statement.body)
      body_end_line = generic_statement_list_end_line(body, statement.line)
      for_bindings = active_bindings.dup
      for_bindings[statement.name] = :let
      scopes << generic_binding_scope(statement, for_bindings, body_end_line)
      collect_generic_function_local_scopes(body, for_bindings, body_end_line, scopes)
    end
  end
end

#compute_semantic_tokens_edits(old_entries, new_entries) ⇒ Object



1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 1771

def compute_semantic_tokens_edits(old_entries, new_entries)
  return [] if old_entries == new_entries

  prefix = find_semantic_token_common_prefix(old_entries, new_entries)
  suffix = find_semantic_token_common_suffix(old_entries, new_entries, prefix)

  old_mid = old_entries.length - prefix - suffix
  new_mid = new_entries.length - prefix - suffix

  if old_mid.zero? && new_mid.zero?
    return []
  end

  start_offset = prefix * 5
  delete_count = old_mid * 5

  # The inserted segment must keep the relative encoding against the
  # last unchanged token preceding the edit, so encode the full token
  # stream from the document origin and slice out the middle segment.
  full_encoded = encode_semantic_tokens(new_entries)
  insert_tokens = full_encoded[start_offset...(new_entries.length - suffix) * 5]

  [{ start: start_offset, deleteCount: delete_count, data: insert_tokens }]
end

#constructible_semantic_type?(type) ⇒ Boolean

Returns:

  • (Boolean)


1122
1123
1124
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 1122

def constructible_semantic_type?(type)
  type.is_a?(Types::Struct) || type.is_a?(Types::GenericStructDefinition) || type.is_a?(Types::StringView) || type.is_a?(Types::Task) || type.is_a?(Types::Vector) || type.is_a?(Types::Matrix) || type.is_a?(Types::Quaternion)
end

#declaration_scope_end_line(decls, index) ⇒ Object



1430
1431
1432
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 1430

def declaration_scope_end_line(decls, index)
  nested_declaration_scope_end_line(decls, index, fallback_end_line: Float::INFINITY)
end

#destructure_let_binding?(tokens, index) ⇒ Boolean

Returns:

  • (Boolean)


642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 642

def destructure_let_binding?(tokens, index)
  tok = tokens[index]
  return false unless tok&.type == :identifier

  line_tokens = non_trivia_tokens_on_line(tokens, tok.line)
  return false unless line_tokens.length >= 3

  first = line_tokens[0]
  return false unless [:let, :var].include?(first.type)

  eq_idx = line_tokens.index { |t| t.type == :equal }
  lparen_idx = line_tokens.index { |t| t.type == :lparen }
  return false unless lparen_idx

  return false if eq_idx && lparen_idx >= eq_idx

  # let (a, b) = ...
  if line_tokens[1]&.type == :lparen
    return first.type == :let
  end

  # let Vec2(x, y) = ... — identifier then lparen adjacency
  return false unless line_tokens[1]&.type == :identifier && lparen_idx == 2

  first.type == :let
end

#dot_nested_type_member?(tokens, index, facts) ⇒ Boolean

Returns:

  • (Boolean)


1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 1094

def dot_nested_type_member?(tokens, index, facts)
  return false unless facts

  dot_index = index - 1
  return false unless dot_index >= 0 && tokens[dot_index].type == :dot

  receiver_index = previous_non_trivia_token_index(tokens, dot_index)
  return false unless receiver_index && tokens[receiver_index].type == :identifier

  receiver_name = tokens[receiver_index].lexeme
  type = resolve_struct_type_name(facts, receiver_name)
  return false unless type.is_a?(Types::Struct)

  member_name = tokens[index].lexeme
  type.nested_types.key?(member_name)
end

#dot_type_receiver_info(tokens, index, facts) ⇒ Object



1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 1180

def dot_type_receiver_info(tokens, index, facts)
  dot_index = previous_non_trivia_token_index(tokens, index)
  return nil unless dot_index && tokens[dot_index].type == :dot

  receiver_index = previous_non_trivia_token_index(tokens, dot_index)
  return nil unless receiver_index

  if tokens[receiver_index].type == :rbracket
    lbracket_index = matching_opener_index(tokens, receiver_index)
    return nil unless lbracket_index

    receiver_index = previous_non_trivia_token_index(tokens, lbracket_index)
    return nil unless receiver_index
  end

  receiver = tokens[receiver_index]
  return nil unless receiver.type == :identifier

  receiver_name = receiver.lexeme
  receiver_path = receiver_name

  module_dot_index = previous_non_trivia_token_index(tokens, receiver_index)
  if module_dot_index && tokens[module_dot_index].type == :dot
    module_index = previous_non_trivia_token_index(tokens, module_dot_index)
    return nil unless module_index && tokens[module_index].type == :identifier

    receiver_path = "#{tokens[module_index].lexeme}.#{receiver_name}"
  end

  resolve_type_receiver_info(facts, receiver_name, receiver_path)
end

#embedded_heredoc_token?(token) ⇒ Boolean

Returns:

  • (Boolean)


313
314
315
316
317
318
319
320
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 313

def embedded_heredoc_token?(token)
  return false unless [:string, :cstring, :fstring].include?(token.type)

  tag = token.lexeme[/\A(?:f|c)?<<-([A-Za-z_][A-Za-z0-9_]*)[ \t]*\n/, 1]
  return false if tag.nil?

  %w[GLSL VERT FRAG COMP JSON JSONC SQL HTML MT].include?(tag)
end

#encode_semantic_tokens(entries) ⇒ Object



1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 1741

def encode_semantic_tokens(entries)
  data = []
  prev_line = 0
  prev_char = 0

  entries.each do |entry|
    delta_line = entry[:line] - prev_line
    delta_start = delta_line.zero? ? entry[:start_char] - prev_char : entry[:start_char]
    type_index = SEMANTIC_TOKEN_TYPES.index(entry[:type].to_s) || 0
    modifiers_bitset = semantic_modifiers_bitset(entry[:modifiers])

    data << delta_line
    data << delta_start
    data << entry[:length]
    data << type_index
    data << modifiers_bitset

    prev_line = entry[:line]
    prev_char = entry[:start_char]
  end

  data
end

#field_declaration_token?(tokens, index) ⇒ Boolean

Returns:

  • (Boolean)


567
568
569
570
571
572
573
574
575
576
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 567

def field_declaration_token?(tokens, index)
  tok = tokens[index]
  return false unless tok&.type == :identifier
  return false unless first_non_trivia_token_on_line?(tokens, index)
  return false if parameter_declaration_token?(tokens, index)
  return false if match_arm_binding_token?(tokens, index)

  next_tok = next_non_trivia_token(tokens, index + 1)
  next_tok&.type == :colon
end

#find_semantic_token_common_prefix(old_entries, new_entries) ⇒ Object



1796
1797
1798
1799
1800
1801
1802
1803
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 1796

def find_semantic_token_common_prefix(old_entries, new_entries)
  limit = [old_entries.length, new_entries.length].min
  prefix = 0
  while prefix < limit && semantic_token_entry_equal?(old_entries[prefix], new_entries[prefix])
    prefix += 1
  end
  prefix
end

#find_semantic_token_common_suffix(old_entries, new_entries, prefix) ⇒ Object



1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 1805

def find_semantic_token_common_suffix(old_entries, new_entries, prefix)
  old_limit = old_entries.length - prefix
  new_limit = new_entries.length - prefix
  limit = [old_limit, new_limit].min
  suffix = 0
  while suffix < limit &&
        semantic_token_entry_equal?(old_entries[old_entries.length - 1 - suffix],
                                    new_entries[new_entries.length - 1 - suffix])
    suffix += 1
  end
  suffix
end

#first_non_trivia_token_on_line?(tokens, index) ⇒ Boolean

Returns:

  • (Boolean)


1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 1705

def first_non_trivia_token_on_line?(tokens, index)
  token = tokens[index]
  return false unless token

  i = index - 1
  while i >= 0
    previous = tokens[i]
    return true if previous.type == :newline
    return false if previous.line == token.line && ![:indent, :dedent].include?(previous.type)

    i -= 1
  end

  true
end

#fstring_interpolation_entries(fstring_tok, facts) ⇒ Object



177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 177

def fstring_interpolation_entries(fstring_tok, facts)
  parts = fstring_tok.literal
  return [{ line: fstring_tok.line - 1, start_char: fstring_tok.column - 1, length: fstring_tok.lexeme.length, type: :string, modifiers: [] }] unless parts.is_a?(Array)

  result = []
  fstr_line = fstring_tok.line - 1   # 0-indexed
  fstr_col0 = fstring_tok.column - 1 # 0-indexed start of `f`
  cursor = fstr_col0

  parts.each do |part|
    next unless part[:kind] == :expr

    # part[:column] is 1-indexed column of the first char of the expression source
    # (i.e. the char right after `#{`).
    expr_col0  = part[:column] - 1          # 0-indexed
    hash_col0  = expr_col0 - 2              # 0-indexed position of `#`

    raw_len       = part[:source].length + (part[:format_spec] ? 1 + part[:format_spec].length : 0)
    rbrace_col0   = expr_col0 + raw_len     # 0-indexed position of `}`

    # :string for everything from cursor up to (but not including) `#`
    text_len = hash_col0 - cursor
    result << { line: fstr_line, start_char: cursor, length: text_len, type: :string, modifiers: [] } if text_len > 0

    # classified entries for the expression source only (not format spec).
    source = part[:source]
    unless source.nil? || source.strip.empty?
      begin
        sub_tokens = interpolation_expression_tokens(part)
        sub_tokens.each_with_index do |sub_tok, i|
          sem_type, modifiers = classify_semantic_token(sub_tokens, i, facts)
          next unless sem_type
          result << {
            line: sub_tok.line - 1,
            start_char: sub_tok.column - 1,
            length: sub_tok.lexeme.length,
            type: sem_type,
            modifiers: modifiers
          }
        end
      rescue MilkTea::LexError
        # Fall back to string coloring for malformed expression.
        result << {
          line: fstr_line,
          start_char: expr_col0,
          length: source.length,
          type: :string,
          modifiers: [],
        }
      end
    end

    # classified entries for format spec (if present), excluding the
    # delimiter token so TextMate interpolation punctuation can style it.
    if part[:format_spec]
      spec_col0 = expr_col0 + source.length
      # Format spec content (e.g., ".0", "3", ".5f") as individual token-like entries.
      # Treat it as lexable content or just string for simplicity.
      spec = part[:format_spec]
      unless spec.empty?
        begin
          spec_tokens = MilkTea::Lexer.new(spec).lex
                                    .reject { |t| [:newline, :indent, :dedent, :eof].include?(t.type) }
          spec_tokens.each_with_index do |spec_tok, i|
            spec_sem_type, spec_modifiers = classify_semantic_token(spec_tokens, i, facts)
            next unless spec_sem_type
            result << {
              line: fstr_line,
              start_char: spec_col0 + 1 + (spec_tok.column - 1),
              length: spec_tok.lexeme.length,
              type: spec_sem_type,
              modifiers: spec_modifiers
            }
          end
        rescue MilkTea::LexError
          # Fall back: treat spec as a number/string token.
          result << {
            line: fstr_line,
            start_char: spec_col0 + 1,
            length: spec.length,
            type: :number,
            modifiers: []
          }
        end
      end
    end

    cursor = rbrace_col0 + 1
  end

  # :string for tail text + closing `"`
  fstr_end_col0 = fstr_col0 + fstring_tok.lexeme.length - 1
  tail_len = fstr_end_col0 - cursor + 1
  result << { line: fstr_line, start_char: cursor, length: tail_len, type: :string, modifiers: [] } if tail_len > 0

  result
end

#generic_binding_scope(node, bindings, end_line) ⇒ Object



936
937
938
939
940
941
942
943
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 936

def generic_binding_scope(node, bindings, end_line)
  {
    start_line: node.line ? node.line : 0,
    start_column: node.column ? node.column : 0,
    end_line: end_line,
    bindings: bindings.dup,
  }
end

#generic_callable_lexical_scopes(decl, end_line:, include_receiver: false) ⇒ Object



857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 857

def generic_callable_lexical_scopes(decl, end_line:, include_receiver: false)
  scopes = []
  current_bindings = {}
  current_bindings['this'] = :param if include_receiver
  Array(decl.params).each do |param|
    next unless param.respond_to?(:name)

    current_bindings[param.name] = :param
  end

  unless current_bindings.empty?
    scopes << {
      start_line: decl.line,
      start_column: 0,
      end_line: end_line,
      bindings: current_bindings.dup,
    }
  end

  collect_generic_function_local_scopes(Array(decl.body), current_bindings, end_line, scopes)

  scopes
end

#generic_function_binding_for_line(facts, line) ⇒ Object



1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 1837

def generic_function_binding_for_line(facts, line)
  generic_function_bindings(facts).filter_map do |binding|
    next unless binding.ast.respond_to?(:body) && binding.ast.line

    start_line = binding.ast.line
    end_line = generic_statement_list_end_line(Array(binding.ast.body), start_line)
    next unless start_line <= line && line <= end_line

    [end_line - start_line, -start_line, binding]
  end.min_by { |span, start_line, _binding| [span, start_line] }&.last
end

#generic_function_bindings(facts) ⇒ Object



1849
1850
1851
1852
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 1849

def generic_function_bindings(facts)
  facts.functions.each_value.select { |binding| binding.type_params.any? } +
    facts.methods.each_value.flat_map(&:values).select { |binding| binding.type_params.any? }
end

#generic_function_declaration?(decl) ⇒ Boolean

Returns:

  • (Boolean)


881
882
883
884
885
886
887
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 881

def generic_function_declaration?(decl)
  decl.respond_to?(:type_params) &&
    Array(decl.type_params).any? &&
    decl.respond_to?(:params) &&
    decl.respond_to?(:body) &&
    !decl.body.nil?
end

#generic_function_lexical_binding_kind_at(facts, line, column, name) ⇒ Object



799
800
801
802
803
804
805
806
807
808
809
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 799

def generic_function_lexical_binding_kind_at(facts, line, column, name)
  generic_function_lexical_binding_scopes(facts).reverse_each do |scope|
    next if line < scope[:start_line] || line > scope[:end_line]
    next if line == scope[:start_line] && column < scope[:start_column]

    kind = scope[:bindings][name]
    return kind if kind
  end

  nil
end

#generic_function_lexical_binding_scopes(facts) ⇒ Object



811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 811

def generic_function_lexical_binding_scopes(facts)
  scopes = @generic_function_lexical_binding_scope_cache ||= {}
  cached = scopes[facts.object_id]
  unless cached
    decls = Array(facts.ast&.declarations)
    cached = decls.each_with_index.flat_map do |decl, index|
      generic_function_lexical_scopes_for_declaration(
        decl,
        end_line: declaration_scope_end_line(decls, index),
      )
    end
    scopes[facts.object_id] = cached
  end

  cached
end

#generic_function_lexical_binding_semantic(facts, token) ⇒ Object



787
788
789
790
791
792
793
794
795
796
797
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 787

def generic_function_lexical_binding_semantic(facts, token)
  kind = generic_function_lexical_binding_kind_at(facts, token.line, token.column, token.lexeme)
  case kind
  when :param
    [:parameter, []]
  when :variable
    [:variable, []]
  else
    nil
  end
end

#generic_function_lexical_scopes_for_declaration(decl, end_line: Float::INFINITY) ⇒ Object



828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 828

def generic_function_lexical_scopes_for_declaration(decl, end_line: Float::INFINITY)
  if decl.is_a?(AST::ExtendingBlock)
    receiver_type_params = generic_type_parameter_names_for_extending_block(decl)
    methods = Array(decl.methods)
    return methods.each_with_index.flat_map do |method, index|
      generic_method_lexical_scopes(
        method,
        receiver_type_params: receiver_type_params,
        end_line: nested_declaration_scope_end_line(methods, index, fallback_end_line: end_line),
      )
    end
  end

  return [] unless generic_function_declaration?(decl)

  generic_callable_lexical_scopes(decl, end_line: generic_statement_list_end_line(decl.body, decl.line))
end

#generic_method_lexical_scopes(method, receiver_type_params:, end_line:) ⇒ Object



846
847
848
849
850
851
852
853
854
855
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 846

def generic_method_lexical_scopes(method, receiver_type_params:, end_line:)
  return [] unless method.respond_to?(:body) && !method.body.nil?
  return [] if receiver_type_params.empty? && Array(method.type_params).empty?

  generic_callable_lexical_scopes(
    method,
    end_line:,
    include_receiver: method.respond_to?(:kind) && method.kind != :static,
  )
end

#generic_statement_end_line(statement) ⇒ Object



951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 951

def generic_statement_end_line(statement)
  return 0 unless statement

  case statement
  when AST::IfStmt
    branch_lines = Array(statement.branches).map do |branch|
      generic_statement_list_end_line(Array(branch.body), branch.line || statement.line)
    end
    else_line = generic_statement_list_end_line(Array(statement.else_body), statement.line)
    ([statement.line, else_line] + branch_lines).compact.max
  when AST::MatchStmt
    arm_lines = Array(statement.arms).map do |arm|
      generic_statement_list_end_line(Array(arm.body), arm.line || statement.line)
    end
    ([statement.line] + arm_lines).compact.max
  when AST::UnsafeStmt, AST::WhileStmt, AST::ForStmt, AST::DeferStmt
    [statement.line, generic_statement_list_end_line(Array(statement.body), statement.line)].compact.max
  else
    statement.line || 0
  end
end

#generic_statement_list_end_line(statements, fallback_line) ⇒ Object



945
946
947
948
949
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 945

def generic_statement_list_end_line(statements, fallback_line)
  Array(statements).reduce(fallback_line || 0) do |max_line, statement|
    [max_line, generic_statement_end_line(statement)].compact.max
  end
end

#generic_type_parameter_header_token?(type) ⇒ Boolean

Returns:

  • (Boolean)


1347
1348
1349
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 1347

def generic_type_parameter_header_token?(type)
  [:function, :struct, :union, :enum, :flags, :variant, :type, :extending].include?(type)
end

#generic_type_parameter_names_for_declaration(decl) ⇒ Object



1405
1406
1407
1408
1409
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 1405

def generic_type_parameter_names_for_declaration(decl)
  return [] unless decl.respond_to?(:type_params)

  Array(decl.type_params).filter_map { |type_param| type_param.respond_to?(:name) ? type_param.name : nil }
end

#generic_type_parameter_names_for_extending_block(decl) ⇒ Object



1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 1411

def generic_type_parameter_names_for_extending_block(decl)
  return [] unless decl.respond_to?(:type_name)

  type_ref = decl.type_name
  return [] unless type_ref.is_a?(AST::TypeRef)

  Array(type_ref.arguments).filter_map do |argument|
    simple_type_parameter_name_from_type_argument(argument)
  end
end

#handle_semantic_tokens_delta(params) ⇒ Object



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 58

def handle_semantic_tokens_delta(params)
  uri = params.dig('textDocument', 'uri')
  previous_result_id = params['previousResultId']
  return handle_semantic_tokens_full(params) unless uri && previous_result_id

  cached = @semantic_tokens_delta_cache[uri]
  unless cached && cached[:result_id] == previous_result_id
    return handle_semantic_tokens_full(params)
  end

  content = @workspace.get_content(uri)
  cache_key = content.hash
  facts = @workspace.peek_facts(uri)
  facts_id = facts&.object_id
  if cached[:content_hash] == cache_key && cached[:facts_id] == facts_id
    return { resultId: cached[:result_id], edits: [] }
  end

  tokens = @workspace.get_tokens(uri) || []
  new_entries = build_semantic_token_entries(tokens, facts)

  new_result_id = next_semantic_token_result_id(uri)
  @semantic_tokens_delta_cache[uri] = {
    result_id: new_result_id,
    content_hash: cache_key,
    facts_id: facts_id,
    entries: new_entries,
  }

  edits = compute_semantic_tokens_edits(cached[:entries], new_entries)
  { resultId: new_result_id, edits: edits }
rescue StandardError => e
  warn "Error in semanticTokens/full/delta handler: #{e.message}"
  handle_semantic_tokens_full(params)
end

#handle_semantic_tokens_full(params) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 7

def handle_semantic_tokens_full(params)
  uri = params.dig('textDocument', 'uri')
  return { data: [] } unless uri

  total_start = monotonic_time

  content = @workspace.get_content(uri)
  cache_key = content.hash
  facts = @workspace.peek_facts(uri)
  facts_id = facts&.object_id
  cached = @semantic_tokens_cache[uri]
  if cached && cached[:content_hash] == cache_key && cached[:facts_id] == facts_id
    elapsed = elapsed_ms(total_start)
    short_uri = shorten_uri(uri) || uri
    log_perf_breakdown('textDocument/semanticTokens/full', elapsed,
                      "uri=#{short_uri} bytes=#{content.bytesize} lines=#{content.count("\n") + 1} cache=hit data_len=#{cached[:data].length}")
    return { resultId: cached[:result_id], data: cached[:data] }
  end

  tokens_start = monotonic_time
  tokens = @workspace.get_tokens(uri) || []
  tokens_ms = elapsed_ms(tokens_start)

  build_start = monotonic_time
  semantic_entries = build_semantic_token_entries(tokens, facts)
  build_ms = elapsed_ms(build_start)

  encode_start = monotonic_time
  data = encode_semantic_tokens(semantic_entries)
  encode_ms = elapsed_ms(encode_start)

  result_id = next_semantic_token_result_id(uri)
  @semantic_tokens_cache[uri] = { content_hash: cache_key, data: data, result_id: result_id, facts_id: facts_id }
  @semantic_tokens_delta_cache[uri] = {
    result_id: result_id,
    content_hash: cache_key,
    facts_id: facts_id,
    entries: semantic_entries,
  }

  elapsed = elapsed_ms(total_start)
  short_uri = shorten_uri(uri) || uri
  log_perf_breakdown('textDocument/semanticTokens/full', elapsed,
                    "uri=#{short_uri} bytes=#{content.bytesize} lines=#{content.count("\n") + 1} cache=miss tokens=#{tokens.length} entries=#{semantic_entries.length} data_len=#{data.length} facts=#{facts_id ? 'on' : 'off'} stages_ms=tokens:#{tokens_ms},build:#{build_ms},encode:#{encode_ms}")

  { resultId: result_id, data: data }
rescue StandardError => e
  warn "Error in semanticTokens/full handler: #{e.message}"
  { data: [] }
end

#handle_semantic_tokens_range(params) ⇒ Object



94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 94

def handle_semantic_tokens_range(params)
  uri = params.dig("textDocument", "uri")
  range = params["range"]
  return { data: [] } unless uri && range

  content = @workspace.get_content(uri)
  return { data: [] } unless content

  tokens = @workspace.get_tokens(uri) || []
  return { data: [] } if tokens.empty?

  start_line = range.dig("start", "line") + 1
  end_line = range.dig("end", "line") + 1

  range_tokens = tokens.select do |t|
    t.line >= start_line && t.line <= end_line &&
      ![:newline, :indent, :dedent, :eof].include?(t.type)
  end

  facts = @workspace.peek_facts(uri)
  semantic_entries = build_semantic_token_entries(range_tokens, facts)

  entries_in_range = semantic_entries.select do |entry|
    entry[:line] >= start_line && entry[:line] <= end_line
  end

  data = encode_semantic_tokens(entries_in_range)
  { data: data }
rescue StandardError => e
  warn "Error in semanticTokens/range handler: #{e.message}"
  { data: [] }
end

#identifier_in_type_argument_position?(tokens, index) ⇒ Boolean

Returns:

  • (Boolean)


1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 1223

def identifier_in_type_argument_position?(tokens, index)
  lbracket_index = previous_non_trivia_token_index(tokens, index)
  return false unless lbracket_index

  if tokens[lbracket_index].type == :comma
    depth = 0
    i = lbracket_index - 1
    lbracket_index = nil
    while i >= 0
      tok = tokens[i]
      if tok.type == :rbracket
        depth += 1
      elsif tok.type == :lbracket
        if depth.zero?
          lbracket_index = i
          break
        end

        depth -= 1
      end
      i -= 1
    end
  end

  return false unless lbracket_index && tokens[lbracket_index].type == :lbracket

  rbracket_index = matching_closer_index(tokens, lbracket_index, :lbracket, :rbracket)
  return false unless rbracket_index

  next_index = next_non_trivia_token_index(tokens, index + 1)
  return false unless next_index

  # Type argument entries should stay inside the current [] pair.
  next_index <= rbracket_index
end

#identifier_in_type_parameter_reference_position?(tokens, index) ⇒ Boolean

Returns:

  • (Boolean)


1272
1273
1274
1275
1276
1277
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 1272

def identifier_in_type_parameter_reference_position?(tokens, index)
  return true if identifier_in_type_argument_position?(tokens, index)

  prev_tok = previous_non_trivia_token(tokens, index)
  [:colon, :arrow].include?(prev_tok&.type)
end

#identifier_in_type_reference_position?(tokens, index) ⇒ Boolean

Returns:

  • (Boolean)


1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 1279

def identifier_in_type_reference_position?(tokens, index)
  return true if identifier_in_type_argument_position?(tokens, index)

  prev_tok = previous_non_trivia_token(tokens, index)
  return true if [:colon, :arrow, :as].include?(prev_tok&.type)

  line_tokens = non_trivia_tokens_on_line(tokens, tokens[index].line)
  return true if prev_tok&.type == :equal && line_tokens.first&.type == :type

  next_index = next_non_trivia_token_index(tokens, index + 1)
  return false unless next_index && tokens[next_index].type == :less

  minus_index = next_non_trivia_token_index(tokens, next_index + 1)
  return false unless minus_index && tokens[minus_index].type == :minus

  tokens[next_index].line == tokens[index].line &&
    tokens[next_index].column == (tokens[index].column + tokens[index].lexeme.length) &&
    tokens[minus_index].line == tokens[next_index].line &&
    tokens[minus_index].column == (tokens[next_index].column + tokens[next_index].lexeme.length)
end

#import_path_info_at(tokens, index, allow_keywords: false) ⇒ Object



1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 1455

def import_path_info_at(tokens, index, allow_keywords: false)
  tok = tokens[index]
  return nil unless tok
  return nil unless tok.type == :identifier || (allow_keywords && Token::KEYWORDS.value?(tok.type))

  line_tokens = non_trivia_tokens_on_line(tokens, tok.line)
  return nil if line_tokens.empty? || line_tokens.first.type != :import

  as_index = line_tokens.index { |line_tok| line_tok.type == :as }
  module_tokens = line_tokens[1...(as_index || line_tokens.length)] || []
  alias_token = as_index ? line_tokens[as_index + 1] : nil

  module_identifiers = module_tokens.select do |line_tok|
    line_tok.type == :identifier || (allow_keywords && Token::KEYWORDS.value?(line_tok.type))
  end
  return nil if module_identifiers.empty?

  module_name = module_identifiers.map(&:lexeme).join('.')
  return { module_name: module_name, role: :module_path } if module_identifiers.include?(tok)
  return { module_name: module_name, role: :alias } if alias_token == tok

  nil
end

#imported_module_binding_for_member(tokens, index, facts) ⇒ Object



1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 1160

def imported_module_binding_for_member(tokens, index, facts)
  dot_index = previous_non_trivia_token_index(tokens, index)
  return nil unless dot_index && tokens[dot_index].type == :dot

  receiver_index = previous_non_trivia_token_index(tokens, dot_index)
  return nil unless receiver_index

  receiver = tokens[receiver_index]
  return nil unless receiver.type == :identifier

  facts.imports[receiver.lexeme]
end

#imported_module_function_value_member_access_site?(facts, tokens, index) ⇒ Boolean

Returns:

  • (Boolean)


1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 1144

def imported_module_function_value_member_access_site?(facts, tokens, index)
  dot_index = previous_non_trivia_token_index(tokens, index)
  return false unless dot_index && tokens[dot_index].type == :dot

  receiver_index = previous_non_trivia_token_index(tokens, dot_index)
  return false unless receiver_index

  receiver = tokens[receiver_index]
  return false unless receiver.type == :identifier

  facts.callable_value_member_access_sites.fetch(
    [receiver.lexeme, receiver.line, receiver.column, tokens[index].lexeme],
    false,
  )
end

#inside_type_params?(tokens, comma_index) ⇒ Boolean

Returns:

  • (Boolean)


610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 610

def inside_type_params?(tokens, comma_index)
  i = comma_index - 1
  while i >= 0
    t = tokens[i]
    break if t.type == :lbracket
    return false if t.type == :newline || t.type == :rbracket || t.type == :lparen
    i -= 1
  end
  return false if i < 0

  prev = previous_non_trivia_token_index(tokens, i)
  return true if prev && %i[struct variant enum flags function fn proc].include?(tokens[prev].type)
  return true if prev && tokens[prev].type == :rbracket
  return true if prev && tokens[prev].type == :identifier

  false
end

#keyword_field_declaration_token?(tokens, index) ⇒ Boolean

Returns:

  • (Boolean)


583
584
585
586
587
588
589
590
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 583

def keyword_field_declaration_token?(tokens, index)
  return false if match_arm_binding_token?(tokens, index)
  return false if destructure_let_binding?(tokens, index)
  return false if STANDS_ALONE_WITH_COLON.include?(tokens[index].type)

  next_tok = next_non_trivia_token(tokens, index + 1)
  next_tok&.type == :colon
end

#keyword_lifetime_or_type_param?(tokens, index) ⇒ Boolean

Returns:

  • (Boolean)


599
600
601
602
603
604
605
606
607
608
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 599

def keyword_lifetime_or_type_param?(tokens, index)
  prev_index = previous_non_trivia_token_index(tokens, index)
  return false unless prev_index

  prev_type = tokens[prev_index].type
  return true if prev_type == :at
  return true if prev_type == :lbracket
  return true if prev_type == :comma && inside_type_params?(tokens, prev_index)
  false
end

#keyword_member_access?(tokens, index) ⇒ Boolean

Returns:

  • (Boolean)


592
593
594
595
596
597
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 592

def keyword_member_access?(tokens, index)
  prev_index = previous_non_trivia_token_index(tokens, index)
  return false unless prev_index

  tokens[prev_index].type == :dot
end

#keyword_named_argument_token?(tokens, index) ⇒ Boolean

Returns:

  • (Boolean)


628
629
630
631
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 628

def keyword_named_argument_token?(tokens, index)
  next_tok = next_non_trivia_token(tokens, index + 1)
  next_tok&.type == :equal
end

#keyword_type_annotation?(tokens, index) ⇒ Boolean

Returns:

  • (Boolean)


633
634
635
636
637
638
639
640
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 633

def keyword_type_annotation?(tokens, index)
  tok = tokens[index]
  prev_index = previous_non_trivia_token_index(tokens, index)
  return false unless prev_index
  return false unless %i[colon arrow].include?(tokens[prev_index].type)

  tokens[prev_index].line == tok.line
end

#known_type_name?(facts, name) ⇒ Boolean

Returns:

  • (Boolean)


1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 1073

def known_type_name?(facts, name)
  return false unless facts
  memo_key = [:known_type, facts.object_id, name]
  return semantic_build_memo(memo_key) if semantic_build_memo?(memo_key)

  result = if facts.types.key?(name)
    true
  else
    found = false
    facts.types.each_value do |type|
      if type.respond_to?(:nested_types) && type.nested_types.key?(name)
        found = true
        break
      end
    end
    found
  end

  store_semantic_build_memo(memo_key, result)
end

#lexically_declared_free_function_name?(tokens, name) ⇒ Boolean

Returns:

  • (Boolean)


764
765
766
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 764

def lexically_declared_free_function_name?(tokens, name)
  lexically_declared_free_function_names(tokens).include?(name)
end

#lexically_declared_free_function_names(tokens) ⇒ Object



768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 768

def lexically_declared_free_function_names(tokens)
  cache = @lexically_declared_free_function_name_cache ||= {}
  cached = cache[tokens.object_id]
  return cached if cached

  cache[tokens.object_id] = tokens.each_with_index.each_with_object(Set.new) do |(token, index), names|
    next unless token.type == :identifier

    prev_index = previous_non_trivia_token_index(tokens, index)
    next unless prev_index

    prev_tok = tokens[prev_index]
    next unless [:function, :fn, :proc].include?(prev_tok.type)
    next unless first_non_trivia_token_on_line?(tokens, prev_index)

    names << token.lexeme
  end
end

#local_semantic_value_binding(facts, token, allow_same_line_future: false) ⇒ Object



982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 982

def local_semantic_value_binding(facts, token, allow_same_line_future: false)
  char = token.column - 1
  [token.line - 1, token.line].uniq.each do |line|
    frame = enclosing_completion_frame(facts, line)
    next unless frame

    snapshot = latest_completion_snapshot(frame, line, char)
    binding = snapshot&.bindings&.dig(token.lexeme)
    return binding if binding

    next unless allow_same_line_future

    future_snapshot = same_line_future_completion_snapshot(frame, line, char)
    binding = future_snapshot&.bindings&.dig(token.lexeme)
    return binding if binding
  end

  nil
end

#mark_attribute_name_override(overrides, token_indices_by_position, tokens, parts, line:, column:, declaration: false) ⇒ Object



1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 1653

def mark_attribute_name_override(overrides, token_indices_by_position, tokens, parts, line:, column:, declaration: false)
  current_index = token_indices_by_position[[line, column]]
  return unless current_index

  parts.each_with_index do |part, part_index|
    token = tokens[current_index]
    return unless token&.lexeme == part

    if part_index == parts.length - 1
      modifiers = []
      modifiers << 'declaration' if declaration
      overrides[[token.line, token.column]] = [:decorator, modifiers]
      return
    end

    overrides[[token.line, token.column]] = [:namespace, []]
    dot_index = next_non_trivia_token_index(tokens, current_index + 1)
    return unless dot_index && tokens[dot_index].type == :dot

    current_index = next_non_trivia_token_index(tokens, dot_index + 1)
    return unless current_index
  end
end

#mark_attribute_reflection_name_overrides(overrides, token_indices_by_position, tokens, call_expression) ⇒ Object



1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 1621

def mark_attribute_reflection_name_overrides(overrides, token_indices_by_position, tokens, call_expression)
  callee = call_expression.callee
  return unless callee.is_a?(AST::Identifier)
  return unless %w[has_attribute attribute_of].include?(callee.name)
  return unless call_expression.arguments.length >= 2

  attribute_name_expression = call_expression.arguments[1].value

  case attribute_name_expression
  when AST::Identifier
    mark_attribute_name_override(
      overrides,
      token_indices_by_position,
      tokens,
      [attribute_name_expression.name],
      line: attribute_name_expression.line,
      column: attribute_name_expression.column,
    )
  when AST::MemberAccess
    return unless attribute_name_expression.receiver.is_a?(AST::Identifier)

    mark_attribute_name_override(
      overrides,
      token_indices_by_position,
      tokens,
      [attribute_name_expression.receiver.name, attribute_name_expression.member],
      line: attribute_name_expression.receiver.line,
      column: attribute_name_expression.receiver.column,
    )
  end
end

#match_arm_binding_token?(tokens, index) ⇒ Boolean

Returns:

  • (Boolean)


561
562
563
564
565
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 561

def match_arm_binding_token?(tokens, index)
  prev_tok = previous_non_trivia_token(tokens, index)
  next_tok = next_non_trivia_token(tokens, index + 1)
  prev_tok&.type == :as && next_tok&.type == :colon
end

#matching_closer_index(tokens, opener_index, opener_type, closer_type) ⇒ Object



1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 1439

def matching_closer_index(tokens, opener_index, opener_type, closer_type)
  depth = 0
  i = opener_index
  while i < tokens.length
    tok = tokens[i]
    if tok.type == opener_type
      depth += 1
    elsif tok.type == closer_type
      depth -= 1
      return i if depth.zero?
    end
    i += 1
  end
  nil
end

#matching_opener_index(tokens, closer_index) ⇒ Object



1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 1537

def matching_opener_index(tokens, closer_index)
  closer = tokens[closer_index]
  return nil unless closer

  opener_type, closer_type = case closer.type
    when :rbracket then [:lbracket, :rbracket]
    when :rparen   then [:lparen,   :rparen]
    else return nil
  end

  depth = 0
  i = closer_index
  while i >= 0
    t = tokens[i]
    if t.type == closer_type
      depth += 1
    elsif t.type == opener_type
      depth -= 1
      return i if depth.zero?
    end
    i -= 1
  end
  nil
end

#module_declaration_info_at(tokens, index, allow_keywords: false) ⇒ Object



1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 1681

def module_declaration_info_at(tokens, index, allow_keywords: false)
  tok = tokens[index]
  return nil unless tok&.type == :identifier || (allow_keywords && Token::KEYWORDS.value?(tok.type))

  line_tokens = non_trivia_tokens_on_line(tokens, tok.line)
  return nil if line_tokens.empty? || line_tokens.first.type != :module

  path_tokens = line_tokens[1..].to_a.select do |line_tok|
    line_tok.type == :identifier || (allow_keywords && Token::KEYWORDS.value?(line_tok.type))
  end
  return nil unless path_tokens.any? { |line_tok| line_tok.equal?(tok) }

  {
    module_name: path_tokens.map(&:lexeme).join('.'),
  }
end

#module_declaration_path_token?(tokens, index, allow_keywords: false) ⇒ Boolean

Returns:

  • (Boolean)


1677
1678
1679
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 1677

def module_declaration_path_token?(tokens, index, allow_keywords: false)
  !module_declaration_info_at(tokens, index, allow_keywords:).nil?
end

#named_argument_label_in_type_constructor?(tokens, index, facts) ⇒ Boolean

Returns:

  • (Boolean)


523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 523

def named_argument_label_in_type_constructor?(tokens, index, facts)
  return false unless facts

  opener_index = parameter_list_opener_index(tokens, index)
  return false unless opener_index

  callee_index = previous_non_trivia_token_index(tokens, opener_index)
  return false unless callee_index

  if tokens[callee_index].type == :rbracket
    lbracket_index = matching_opener_index(tokens, callee_index)
    return false unless lbracket_index
    callee_index = previous_non_trivia_token_index(tokens, lbracket_index)
  end

  return false unless callee_index && tokens[callee_index].type == :identifier

  callee_name = tokens[callee_index].lexeme
  return true if facts.types.key?(callee_name) || facts.interfaces.key?(callee_name)

  dot_index = previous_non_trivia_token_index(tokens, callee_index)
  return false unless dot_index && tokens[dot_index].type == :dot

  receiver_index = previous_non_trivia_token_index(tokens, dot_index)
  return false unless receiver_index

  if tokens[receiver_index].type == :rbracket
    lbracket_index = matching_opener_index(tokens, receiver_index)
    return false unless lbracket_index
    receiver_index = previous_non_trivia_token_index(tokens, lbracket_index)
  end

  return false unless receiver_index && tokens[receiver_index].type == :identifier

  receiver_name = tokens[receiver_index].lexeme
  facts.types.key?(receiver_name) || facts.interfaces.key?(receiver_name)
end

#named_argument_label_token?(tokens, index) ⇒ Boolean

Returns:

  • (Boolean)


517
518
519
520
521
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 517

def named_argument_label_token?(tokens, index)
  prev_tok = previous_non_trivia_token(tokens, index)
  next_tok = next_non_trivia_token(tokens, index + 1)
  next_tok&.type == :equal && prev_tok && [:lparen, :comma].include?(prev_tok.type)
end

#namespace_keyword_token?(tokens, index) ⇒ Boolean

Returns:

  • (Boolean)


973
974
975
976
977
978
979
980
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 973

def namespace_keyword_token?(tokens, index)
  tok = tokens[index]
  return false unless tok && Token::KEYWORDS.value?(tok.type)

  import_path_info_at(tokens, index, allow_keywords: true) ||
    module_declaration_path_token?(tokens, index, allow_keywords: true)

end

#nested_declaration_scope_end_line(decls, index, fallback_end_line:) ⇒ Object



1434
1435
1436
1437
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 1434

def nested_declaration_scope_end_line(decls, index, fallback_end_line:)
  next_decl = decls[(index + 1)..]&.find { |candidate| candidate.line }
  next_decl ? next_decl.line - 1 : fallback_end_line
end

#next_non_trivia_token_index(tokens, index) ⇒ Object



1731
1732
1733
1734
1735
1736
1737
1738
1739
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 1731

def next_non_trivia_token_index(tokens, index)
  i = index
  while i < tokens.length
    tok = tokens[i]
    return i unless [:newline, :indent, :dedent].include?(tok.type)
    i += 1
  end
  nil
end

#next_semantic_token_result_id(uri) ⇒ Object



1765
1766
1767
1768
1769
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 1765

def next_semantic_token_result_id(uri)
  @semantic_token_result_counter ||= 0
  @semantic_token_result_counter += 1
  "#{uri}:#{@semantic_token_result_counter}"
end

#non_trivia_tokens_on_line(tokens, line) ⇒ Object



1562
1563
1564
1565
1566
1567
1568
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 1562

def non_trivia_tokens_on_line(tokens, line)
  return @tokens_by_line_cache[line] if @tokens_by_line_cache

  tokens.select do |tok|
    tok.line == line && ![:newline, :indent, :dedent, :eof].include?(tok.type)
  end
end

#parameter_declaration_token?(tokens, index) ⇒ Boolean

Returns:

  • (Boolean)


710
711
712
713
714
715
716
717
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 710

def parameter_declaration_token?(tokens, index)
  prev_tok = previous_non_trivia_token(tokens, index)
  next_tok = next_non_trivia_token(tokens, index + 1)
  next_tok&.type == :colon && prev_tok && (
    [:lparen, :comma].include?(prev_tok.type) ||
    FOREIGN_PARAM_MODE_TOKENS.include?(prev_tok.type)
  )
end

#parameter_list_opener_index(tokens, index) ⇒ Object



746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 746

def parameter_list_opener_index(tokens, index)
  depth = 0
  i = index - 1
  while i >= 0
    tok = tokens[i]
    if tok.type == :rparen
      depth += 1
    elsif tok.type == :lparen
      return i if depth.zero?

      depth -= 1
    end
    i -= 1
  end

  nil
end

#previous_non_trivia_token(tokens, index) ⇒ Object



1698
1699
1700
1701
1702
1703
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 1698

def previous_non_trivia_token(tokens, index)
  prev_index = previous_non_trivia_token_index(tokens, index)
  return nil unless prev_index

  tokens[prev_index]
end

#previous_non_trivia_token_index(tokens, index) ⇒ Object



1721
1722
1723
1724
1725
1726
1727
1728
1729
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 1721

def previous_non_trivia_token_index(tokens, index)
  i = index - 1
  while i >= 0
    tok = tokens[i]
    return i unless [:newline, :indent, :dedent].include?(tok.type)
    i -= 1
  end
  nil
end

#resolve_receiver_value_type(facts, token) ⇒ Object



1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 1058

def resolve_receiver_value_type(facts, token)
  char = token.column

  [token.line - 1, token.line].uniq.each do |line|
    receiver_type = resolve_dot_receiver_value_type(facts, token.lexeme, line, char)
    return receiver_type if receiver_type
  end

  nil
end

#resolve_struct_type_name(facts, name) ⇒ Object



1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 1111

def resolve_struct_type_name(facts, name)
  type = facts.types[name]
  return type if type.is_a?(Types::Struct)
  facts.types.each_value do |t|
    next unless t.respond_to?(:nested_types)
    found = t.nested_types[name]
    return found if found.is_a?(Types::Struct)
  end
  nil
end

#resolved_call_callee_semantic(name, token, parameter_declaration, facts) ⇒ Object



1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 1017

def resolved_call_callee_semantic(name, token, parameter_declaration, facts)
  if (binding = local_semantic_value_binding(facts, token, allow_same_line_future: parameter_declaration))
    return semantic_value_binding_entry(binding, declaration: binding.kind == :param && parameter_declaration)
  end

  if (binding = facts.values[name])
    return semantic_value_binding_entry(binding)
  end

  modifiers = []
  modifiers << 'defaultLibrary' if BUILTIN_FUNCTION_NAMES.include?(name)
  return [:function, modifiers] if BUILTIN_FUNCTION_NAMES.include?(name)
  return [:function, modifiers] if facts.functions.key?(name)
  return [:type, []] if constructible_semantic_type?(facts.types[name])

  nil
end

#semantic_build_memo(key) ⇒ Object



168
169
170
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 168

def semantic_build_memo(key)
  @semantic_token_build_cache[key][1] if @semantic_token_build_cache&.key?(key)
end

#semantic_build_memo?(key) ⇒ Boolean

Memoize facts-derived lookups for the duration of one semantic-token build. The build cache is scoped per build (set up and torn down in build_semantic_token_entries) so repeated per-token classifications do not re-scan frames/type scopes/types for every identifier token.

Returns:

  • (Boolean)


164
165
166
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 164

def semantic_build_memo?(key)
  !@semantic_token_build_cache.nil? && @semantic_token_build_cache.key?(key)
end

#semantic_modifiers_bitset(modifiers) ⇒ Object



1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 1826

def semantic_modifiers_bitset(modifiers)
  bits = 0
  Array(modifiers).each do |modifier|
    idx = SEMANTIC_TOKEN_MODIFIERS.index(modifier.to_s)
    next unless idx

    bits |= (1 << idx)
  end
  bits
end

#semantic_token_entry_equal?(a, b) ⇒ Boolean

Returns:

  • (Boolean)


1818
1819
1820
1821
1822
1823
1824
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 1818

def semantic_token_entry_equal?(a, b)
  a[:line] == b[:line] &&
    a[:start_char] == b[:start_char] &&
    a[:length] == b[:length] &&
    a[:type] == b[:type] &&
    a[:modifiers] == b[:modifiers]
end

#semantic_value_binding_entry(binding, declaration: false) ⇒ Object



1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 1002

def semantic_value_binding_entry(binding, declaration: false)
  case binding.kind
  when :param
    modifiers = []
    modifiers << 'declaration' if declaration
    [:parameter, modifiers]
  when :const, :let
    [:variable, ['readonly']]
  else
    modifiers = []
    modifiers << 'declaration' if declaration
    [:variable, modifiers]
  end
end

#simple_type_parameter_name_from_type_argument(argument) ⇒ Object



1422
1423
1424
1425
1426
1427
1428
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 1422

def simple_type_parameter_name_from_type_argument(argument)
  value = argument.respond_to?(:value) ? argument.value : nil
  return nil unless value.is_a?(AST::TypeRef)
  return nil unless value.arguments.empty? && !value.nullable && value.name.parts.length == 1

  value.name.parts.first
end

#specialized_call_with_type_args?(tokens, index) ⇒ Boolean

Returns:

  • (Boolean)


1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 1212

def specialized_call_with_type_args?(tokens, index)
  next_index = next_non_trivia_token_index(tokens, index + 1)
  return false unless next_index && tokens[next_index].type == :lbracket

  rbracket_index = matching_closer_index(tokens, next_index, :lbracket, :rbracket)
  return false unless rbracket_index

  after_bracket_index = next_non_trivia_token_index(tokens, rbracket_index + 1)
  after_bracket_index && tokens[after_bracket_index].type == :lparen
end

#static_type_member_access?(tokens, index, facts) ⇒ Boolean

Returns:

  • (Boolean)


1173
1174
1175
1176
1177
1178
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 1173

def static_type_member_access?(tokens, index, facts)
  receiver_info = dot_type_receiver_info(tokens, index, facts)
  return false unless receiver_info

  !static_method_binding_for_receiver(facts, receiver_info[:type], tokens[index].lexeme).nil?
end

#store_semantic_build_memo(key, value) ⇒ Object



172
173
174
175
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 172

def store_semantic_build_memo(key, value)
  @semantic_token_build_cache[key] = [:ok, value] if @semantic_token_build_cache
  value
end

#struct_event_declaration_token?(tokens, index) ⇒ Boolean

Returns:

  • (Boolean)


669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 669

def struct_event_declaration_token?(tokens, index)
  tok = tokens[index]
  return false unless tok&.type == :identifier

  prev_tok = previous_non_trivia_token(tokens, index)
  return false unless prev_tok&.type == :event

  line_tokens = non_trivia_tokens_on_line(tokens, tok.line)
  line_start = line_tokens.first
  return false unless line_start && line_start.column > 1

  i = index - 1
  while i >= 0
    current = tokens[i]
    i -= 1
    next if [:newline, :indent, :dedent, :eof].include?(current.type)
    next if current.line == tok.line
    next if current.column >= line_start.column

    header_line_toks = non_trivia_tokens_on_line(tokens, current.line)
    return header_line_toks.first&.type == :struct
  end

  false
end

#token_semantic_entries(token, semantic_type, modifiers) ⇒ Object



322
323
324
325
326
327
328
329
330
331
332
333
334
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 322

def token_semantic_entries(token, semantic_type, modifiers)
  token.lexeme.split("\n", -1).each_with_index.filter_map do |segment, index|
    next if segment.empty?

    {
      line: token.line - 1 + index,
      start_char: index.zero? ? (token.column - 1) : 0,
      length: segment.length,
      type: semantic_type,
      modifiers: modifiers
    }
  end
end

#type_name_member_access?(tokens, index, facts = nil) ⇒ Boolean

Returns:

  • (Boolean)


1499
1500
1501
1502
1503
1504
1505
1506
1507
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 1499

def type_name_member_access?(tokens, index, facts = nil)
  dot_index = previous_non_trivia_token_index(tokens, index)
  return false unless dot_index && tokens[dot_index].type == :dot

  receiver_index = previous_non_trivia_token_index(tokens, dot_index)
  return false unless receiver_index

  type_name_receiver_token?(tokens, receiver_index, facts)
end

#type_name_receiver_token?(tokens, index, facts = nil) ⇒ Boolean

Returns:

  • (Boolean)


1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 1509

def type_name_receiver_token?(tokens, index, facts = nil)
  receiver = tokens[index]

  if receiver.type == :identifier
    return true if receiver.lexeme.match?(/\A[A-Z]/)
    return true if facts && facts.types.key?(receiver.lexeme)

    if facts
      module_binding = imported_module_binding_for_member(tokens, index, facts)
      return true if module_binding && module_binding.types.key?(receiver.lexeme)
    end

    return false
  end

  if receiver.type == :rbracket
    lbracket_i = matching_opener_index(tokens, index)
    return false unless lbracket_i

    base_index = previous_non_trivia_token_index(tokens, lbracket_i)
    return false unless base_index

    return type_name_receiver_token?(tokens, base_index, facts)
  end

  false
end

#type_parameter_declaration_info_on_line(tokens, line) ⇒ Object



1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 1300

def type_parameter_declaration_info_on_line(tokens, line)
  line_tokens = non_trivia_tokens_on_line(tokens, line)
  return nil if line_tokens.empty?

  header_index = line_tokens.index { |line_tok| generic_type_parameter_header_token?(line_tok.type) }
  return nil unless header_index

  name_index = ((header_index + 1)...line_tokens.length).find { |i| line_tokens[i].type == :identifier }
  return nil unless name_index

  lbracket_index = name_index + 1
  return nil unless line_tokens[lbracket_index]&.type == :lbracket

  depth = 0
  type_param_tokens = []
  expect_name = false
  i = lbracket_index
  while i < line_tokens.length
    tok = line_tokens[i]
    case tok.type
    when :lbracket
      depth += 1
      expect_name = true if depth == 1
    when :rbracket
      depth -= 1
      return {
        names: type_param_tokens.map(&:lexeme),
        tokens: type_param_tokens,
      } if depth.zero?
    when :comma
      expect_name = true if depth == 1
    when :at
      expect_name = false if depth == 1
    when :implements
      expect_name = false if depth == 1
    else
      if depth == 1 && expect_name && tok.type == :identifier
        type_param_tokens << tok
        expect_name = false
      end
    end
    i += 1
  end

  nil
end

#type_parameter_declaration_token?(facts, tokens, index) ⇒ Boolean

Returns:

  • (Boolean)


1259
1260
1261
1262
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 1259

def type_parameter_declaration_token?(facts, tokens, index)
  info = type_parameter_declaration_info_on_line(tokens, tokens[index].line)
  info && info[:tokens].any? { |token| token.equal?(tokens[index]) }
end

#type_parameter_names_in_scope(facts, line) ⇒ Object



1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 1351

def type_parameter_names_in_scope(facts, line)
  memo_key = [:type_param_names, facts.object_id, line]
  return semantic_build_memo(memo_key) if semantic_build_memo?(memo_key)

  scopes = @type_parameter_scope_cache ||= {}
  cached = scopes[facts.object_id]
  unless cached
    decls = Array(facts.ast&.declarations)
    cached = decls.each_with_index.flat_map do |decl, index|
      type_parameter_scopes_for_declaration(
        decl,
        end_line: declaration_scope_end_line(decls, index),
      )
    end
    scopes[facts.object_id] = cached
  end

  result = []
  cached.reverse_each do |scope|
    if line >= scope[:start_line] && line <= scope[:end_line]
      result = scope[:names]
      break
    end
  end

  store_semantic_build_memo(memo_key, result)
end

#type_parameter_reference_token?(facts, tokens, index) ⇒ Boolean

Returns:

  • (Boolean)


1264
1265
1266
1267
1268
1269
1270
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 1264

def type_parameter_reference_token?(facts, tokens, index)
  tok = tokens[index]
  return false unless type_parameter_names_in_scope(facts, tok.line).include?(tok.lexeme)
  return false if type_parameter_declaration_token?(facts, tokens, index)

  identifier_in_type_parameter_reference_position?(tokens, index)
end

#type_parameter_scopes_for_declaration(decl, end_line: Float::INFINITY) ⇒ Object



1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 1379

def type_parameter_scopes_for_declaration(decl, end_line: Float::INFINITY)
  if decl.is_a?(AST::ExtendingBlock)
    receiver_names = generic_type_parameter_names_for_extending_block(decl)
    methods = Array(decl.methods)
    return methods.each_with_index.filter_map do |method, index|
      names = receiver_names + generic_type_parameter_names_for_declaration(method)
      next if names.empty? || method.line.nil?

      {
        start_line: method.line,
        end_line: nested_declaration_scope_end_line(methods, index, fallback_end_line: end_line),
        names: names.uniq,
      }
    end
  end

  names = generic_type_parameter_names_for_declaration(decl)
  return [] if names.empty? || decl.line.nil?

  [{
    start_line: decl.line,
    end_line: end_line,
    names: names,
  }]
end

#variant_enum_member_declaration?(tokens, index) ⇒ Boolean

Returns:

  • (Boolean)


1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 1479

def variant_enum_member_declaration?(tokens, index)
  tok = tokens[index]
  line_tokens = non_trivia_tokens_on_line(tokens, tok.line)
  return false unless line_tokens.first.equal?(tok) && tok.column > 1

  i = index - 1
  while i >= 0
    t = tokens[i]
    i -= 1
    next if [:newline, :indent, :dedent, :eof].include?(t.type)
    next if t.line == tok.line
    next if t.column >= tok.column

    header_line_toks = non_trivia_tokens_on_line(tokens, t.line)
    header_kind = header_line_toks.find { |header_tok| [:variant, :enum, :flags].include?(header_tok.type) }
    return !header_kind.nil?
  end
  false
end

#variant_payload_field_declaration_token?(tokens, index) ⇒ Boolean

Returns:

  • (Boolean)


695
696
697
698
699
700
701
702
703
704
705
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 695

def variant_payload_field_declaration_token?(tokens, index)
  return false unless parameter_declaration_token?(tokens, index)

  opener_index = parameter_list_opener_index(tokens, index)
  return false unless opener_index

  head_index = previous_non_trivia_token_index(tokens, opener_index)
  return false unless head_index

  variant_enum_member_declaration?(tokens, head_index)
end

#walk_ast_nodes(node, &block) ⇒ Object



1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
# File 'lib/milk_tea/lsp/server/semantic_tokens.rb', line 1607

def walk_ast_nodes(node, &block)
  case node
  when Array
    node.each { |entry| walk_ast_nodes(entry, &block) }
  when String, Symbol, Numeric, TrueClass, FalseClass, NilClass
    nil
  else
    return unless node.class.name&.start_with?("MilkTea::AST::")

    yield node
    node.to_h.each_value { |value| walk_ast_nodes(value, &block) }
  end
end