Class: MilkTea::LSP::Diagnostics

Inherits:
Object
  • Object
show all
Defined in:
lib/milk_tea/lsp/diagnostics.rb

Overview

Collects parse and semantic errors and formats them as LSP Diagnostics

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.position_encodingObject

Returns the value of attribute position_encoding.



11
12
13
# File 'lib/milk_tea/lsp/diagnostics.rb', line 11

def position_encoding
  @position_encoding
end

.protocolObject

Returns the value of attribute protocol.



11
12
13
# File 'lib/milk_tea/lsp/diagnostics.rb', line 11

def protocol
  @protocol
end

Class Method Details

.client_char_to_internal(line_text, client_char) ⇒ Object



625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
# File 'lib/milk_tea/lsp/diagnostics.rb', line 625

def self.client_char_to_internal(line_text, client_char)
  return client_char if @position_encoding == 'utf-16'

  case @position_encoding
  when 'utf-8'
    bytes_seen = 0
    utf16_count = 0
    line_text.each_char do |ch|
      break if bytes_seen >= client_char
      bytes_seen += ch.bytesize
      utf16_count += ch.ord > 0xFFFF ? 2 : 1
    end
    utf16_count
  when 'utf-32'
    utf16_count = 0
    line_text.each_char.with_index do |ch, idx|
      break if idx >= client_char
      utf16_count += ch.ord > 0xFFFF ? 2 : 1
    end
    utf16_count
  else
    client_char
  end
end

.collect(uri, content, shared_module_cache: nil, source_overrides: nil, workspace_root_path: nil, dependency_resolution_mode: :auto, platform_override: nil, sema_snapshot: nil, strict_current_root_diagnostics: false, lint_tier: :full) ⇒ Object



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
57
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
93
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
126
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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# File 'lib/milk_tea/lsp/diagnostics.rb', line 15

def self.collect(uri, content, shared_module_cache: nil, source_overrides: nil, workspace_root_path: nil, dependency_resolution_mode: :auto, platform_override: nil, sema_snapshot: nil, strict_current_root_diagnostics: false, lint_tier: :full)
  total_start = perf_logging? ? monotonic_time : nil
  diagnostics = []
  sema_facts = nil
  unresolved_import_paths = []
  normalized_lint_tier = Linter.normalize_lint_tier(lint_tier)
  parse_ms = 0.0
  imports_ms = 0.0
  sema_ms = 0.0
  strict_root_ms = 0.0
  lint_ms = 0.0
  lint_profile = total_start ? Linter::Profile.new : nil
  path = uri_to_path(uri)
  resolution = DependencyResolution.resolve(path, mode: dependency_resolution_mode)
  effective_platform = effective_platform_for_path(path, platform_override:)

  # Parse
  begin
    parse_start = total_start ? monotonic_time : nil
    parse_errors = []
    ast = if path && File.file?(path)
            parse_result = Parser.parse_collecting_errors(content, path: uri)
            parse_errors = parse_result.errors
            parse_result.errors.each { |error| diagnostics << format_error(error) }
            parse_result.ast
          else
            Parser.parse(content, path: uri)
          end
    parse_ms = elapsed_ms(parse_start) if parse_start
    return { diagnostics: diagnostics, facts: sema_facts, sema_snapshot: sema_snapshot } unless ast

    if resolution.error_message
      diagnostics << format_error(SemanticError.new(resolution.error_message, line: 1, column: 1))
      return { diagnostics: diagnostics, facts: sema_facts, sema_snapshot: sema_snapshot }
    end

    conflict_error = root_platform_conflict_error(path, effective_platform)
    if conflict_error
      diagnostics << format_error(SemanticError.new(conflict_error.message, line: 1, column: 1))
      return { diagnostics: diagnostics, facts: sema_facts, sema_snapshot: sema_snapshot }
    end

    imports_start = total_start ? monotonic_time : nil
    imported_modules = resolve_imported_modules(
      uri,
      ast,
      diagnostics,
      resolution:,
      effective_platform:,
      shared_module_cache: shared_module_cache,
      source_overrides: source_overrides,
      workspace_root_path: workspace_root_path,
      content: content,
      # A file whose own parse recovered with errors can poison the loader's
      # program-check cache and yield no facts on the standard path; skip the
      # program check and resolve imports directly for those files.
      skip_program_check: !parse_errors.empty?,
    )
    imports_ms = elapsed_ms(imports_start) if imports_start
    unresolved_import_paths = imported_modules.fetch(:unresolved_import_paths)
    inferred_module_name = imported_modules[:module_name]

    # Wrap AST with module name before sema so facts.module_name is non-nil.
    unless ast.respond_to?(:module_name) && ast.module_name
      mn_parts = inferred_module_name ? inferred_module_name.split('.') : []
      ast = AST::SourceFile.new(
        module_name: mn_parts.any? ? AST::QualifiedName.new(parts: mn_parts) : nil,
        module_kind: ast.respond_to?(:module_kind) ? ast.module_kind : nil,
        imports: ast.respond_to?(:imports) ? (ast.imports || []) : [],
        directives: ast.respond_to?(:directives) ? (ast.directives || []) : [],
        declarations: ast.respond_to?(:declarations) ? (ast.declarations || []) : [],
        line: ast.line || 1,
        node_ids: ast.respond_to?(:node_ids) ? ast.node_ids : {},
      )
    end

    # Semantic analysis — collect errors from all functions, not just first.
    begin
      sema_start = total_start ? monotonic_time : nil
      sema_snapshot ||= SemanticAnalyzer.tooling_snapshot(ast, imported_modules: imported_modules.fetch(:modules), path: path, allow_missing_imports: true)
      sema_facts = sema_snapshot.facts
      cross_by_uri = {}
      target_path = path.is_a?(String) ? File.expand_path(path) : nil
      sema_snapshot.diagnostics.reject { |diagnostic| redundant_unknown_import_diagnostic?(diagnostic, unresolved_import_paths) }
        .each do |diagnostic|
          if target_path && diagnostic.path && File.expand_path(diagnostic.path) != target_path
            target_uri = path_to_uri(diagnostic.path)
            (cross_by_uri[target_uri] ||= []) << format_tooling_diagnostic(diagnostic, stage: 'sema')
          else
            diagnostics << format_tooling_diagnostic(diagnostic, stage: 'sema')
          end
        end
      sema_ms = elapsed_ms(sema_start) if sema_start
    rescue StandardError => e
      log_diagnostics_warning("Error collecting diagnostics: #{e.message}")
    end

    begin
      if strict_current_root_diagnostics && normalized_lint_tier == :full
        strict_root_start = total_start ? monotonic_time : nil
        collect_strict_root_diagnostics(
          path,
          ast,
          sema_facts,
          diagnostics,
          resolution:,
          effective_platform:,
          shared_module_cache:,
          source_overrides:,
          workspace_root_path:,
        ).each do |diagnostic|
          diagnostics << diagnostic
        end
        strict_root_ms = elapsed_ms(strict_root_start) if strict_root_start
      end
    rescue StandardError => e
      log_diagnostics_warning("Error collecting strict root diagnostics: #{e.message}")
    end
  rescue MilkTea::LexError => e
    diagnostics << format_error(e)
  rescue StandardError => e
    log_diagnostics_warning("Error collecting diagnostics: #{e.message}")
  end

  # Lint warnings (severity: 2 = Warning)
  begin
    lint_start = total_start ? monotonic_time : nil
    Linter.lint_source(
      content,
      path: uri,
      sema_facts: sema_facts,
      unresolved_import_paths: unresolved_import_paths,
      profile: lint_profile,
      lint_tier: normalized_lint_tier,
    ).each do |w|
      diagnostics << format_warning(w, content: content)
    end
    lint_ms = elapsed_ms(lint_start) if lint_start
  rescue MilkTea::LexError, MilkTea::ParseError
    # Best-effort only while the user is mid-edit; lex/parse failures are
    # already reported by the main diagnostics path.
  rescue StandardError => e
    log_diagnostics_warning("Error collecting lint diagnostics: #{e.message}")
  end

  { diagnostics: diagnostics, cross_file_diagnostics: cross_by_uri, facts: sema_facts, sema_snapshot: sema_snapshot }
ensure
  if total_start
    lint_breakdown = lint_profile&.summary(limit: 12)
    detail = "uri=#{uri} lint_tier=#{normalized_lint_tier} diagnostics=#{diagnostics.length} facts=#{sema_facts ? 'ok' : 'nil'} stages_ms=parse:#{parse_ms},imports:#{imports_ms},sema:#{sema_ms},strict_root:#{strict_root_ms},lint:#{lint_ms}"
    detail += " lint_passes_ms=#{lint_breakdown}" unless lint_breakdown.nil? || lint_breakdown.empty?
    log_perf_breakdown(
      'diagnostics.collect',
      elapsed_ms(total_start),
      detail,
    )
  end
end

.diagnostic_code(error) ⇒ Object



517
518
519
520
521
522
523
524
525
526
527
528
529
530
# File 'lib/milk_tea/lsp/diagnostics.rb', line 517

def self.diagnostic_code(error)
  case error
  when MilkTea::LexError
    'lex/error'
  when MilkTea::ParseError
    'parse/error'
  when MilkTea::ModuleLoadError
    'import/load-error'
  when MilkTea::SemanticError
    'sema/error'
  else
    'tooling/error'
  end
end

.diagnostic_message_to_client(message, code) ⇒ Object



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

def self.diagnostic_message_to_client(message, code)
  return message unless message.is_a?(String)

  code_spans = []
  if code.to_s.start_with?('sema')
    message.scan(/`([^`]+)`/) { |m| code_spans << m[0] }
    message.scan(/'([A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*)'/) { |m| code_spans << m[0] unless code_spans.include?(m[0]) }
  end

  return message if code_spans.empty?

  markdown = message.gsub(/`([^`]+)`/, '`\1`')
  { kind: 'markdown', value: markdown }
end

.diagnostic_stage(error) ⇒ Object



532
533
534
535
536
537
538
539
540
541
542
543
544
545
# File 'lib/milk_tea/lsp/diagnostics.rb', line 532

def self.diagnostic_stage(error)
  case error
  when MilkTea::LexError
    'lex'
  when MilkTea::ParseError
    'parse'
  when MilkTea::ModuleLoadError
    'import'
  when MilkTea::SemanticError
    'sema'
  else
    'tooling'
  end
end

.elapsed_ms(start_time) ⇒ Object



267
268
269
# File 'lib/milk_tea/lsp/diagnostics.rb', line 267

def self.elapsed_ms(start_time)
  ((monotonic_time - start_time) * 1000).round(1)
end

.extract_column(error) ⇒ Object



575
576
577
578
579
580
581
582
583
584
585
586
# File 'lib/milk_tea/lsp/diagnostics.rb', line 575

def self.extract_column(error)
  case error
  when MilkTea::LexError
    error.column || 1
  when MilkTea::ParseError
    error.token&.column || 1
  when MilkTea::SemanticError
    error.column || 1
  else
    1
  end
end

.extract_length(error) ⇒ Object



588
589
590
591
592
593
594
595
596
597
# File 'lib/milk_tea/lsp/diagnostics.rb', line 588

def self.extract_length(error)
  case error
  when MilkTea::ParseError
    error.token&.lexeme.to_s.length
  when MilkTea::SemanticError
    error.length || 1
  else
    1
  end
end

.extract_line(error) ⇒ Object



562
563
564
565
566
567
568
569
570
571
572
573
# File 'lib/milk_tea/lsp/diagnostics.rb', line 562

def self.extract_line(error)
  case error
  when MilkTea::LexError
    error.line || 1
  when MilkTea::ParseError
    error.token&.line || 1
  when MilkTea::SemanticError
    error.line || 1
  else
    1
  end
end

.extract_quoted_name(message) ⇒ Object



449
450
451
452
# File 'lib/milk_tea/lsp/diagnostics.rb', line 449

def self.extract_quoted_name(message)
  match = message.match(/'([^']+)'/)
  match && match[1]
end

.extract_warning_range(warning, content) ⇒ Object

Returns [start_char, end_char] in 0-based LSP coordinates. Falls back to [0, 1] when a precise token span cannot be inferred.



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
# File 'lib/milk_tea/lsp/diagnostics.rb', line 418

def self.extract_warning_range(warning, content)
  if warning.column
    start_char = [warning.column.to_i - 1, 0].max
    len = warning.respond_to?(:length) ? warning.length.to_i : 0
    len = 1 if len <= 0
    return [start_char, start_char + len]
  end

  return [0, 1] unless content && warning.line

  lines = content.split("\n", -1)
  line_text = lines[warning.line - 1]
  return [0, 1] unless line_text

  token_name = warning.respond_to?(:symbol_name) ? warning.symbol_name : nil
  token_name ||= extract_quoted_name(warning.message.to_s)
  return [0, 1] unless token_name && !token_name.empty?

  # Prefer whole-token matches so names like "arg" don't match inside "argv".
  token_match = line_text.match(/\b#{Regexp.escape(token_name)}\b/)
  return [token_match.begin(0), token_match.end(0)] if token_match

  # Fallback for non-word symbols if any rule introduces them.
  index = line_text.index(token_name)
  return [index, index + token_name.length] if index

  [0, 1]
rescue StandardError
  [0, 1]
end

.format_error(error) ⇒ Object



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
# File 'lib/milk_tea/lsp/diagnostics.rb', line 454

def self.format_error(error)
  line = extract_line(error)
  column = extract_column(error)
  length = extract_length(error)
  start_char = [column.to_i - 1, 0].max
  end_char = start_char + [length.to_i, 1].max
  code = diagnostic_code(error)

  diagnostic = {
    range: {
      start: {
        line: (line.to_i - 1),
        character: start_char
      },
      end: {
        line: (line.to_i - 1),
        character: end_char
      }
    },
    severity: 1,  # Error
    code: code,
    message: diagnostic_message_to_client(error.message.to_s, code),
    source: 'milk-tea',
    data: {
      stage: diagnostic_stage(error)
    }
  }
  if error.respond_to?(:suggestion) && error.suggestion
    diagnostic[:data][:suggestion] = error.suggestion
  end
  diagnostic
end

.format_import_error(error, import, content: nil) ⇒ Object



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/diagnostics.rb', line 487

def self.format_import_error(error, import, content: nil)
  return format_error(SemanticError.new(error.message)) unless import

  column, length = import_path_span(import, content)
  line_index = [import.line.to_i - 1, 0].max
  start_char = [column.to_i - 1, 0].max
  end_char = start_char + [length.to_i, 1].max
  code = diagnostic_code(error)

  {
    range: {
      start: {
        line: line_index,
        character: start_char,
      },
      end: {
        line: line_index,
        character: end_char,
      }
    },
    severity: 1,
    code: code,
    message: diagnostic_message_to_client(error.message.to_s, code),
    source: 'milk-tea',
    data: {
      stage: diagnostic_stage(error)
    }
  }
end

.format_tooling_diagnostic(diagnostic, content: nil, stage:) ⇒ Object



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
# File 'lib/milk_tea/lsp/diagnostics.rb', line 389

def self.format_tooling_diagnostic(diagnostic, content: nil, stage:)
  line = diagnostic.line.to_i
  line_index = [line - 1, 0].max
  start_char, end_char = extract_warning_range(diagnostic, content)

  lsp_severity = case diagnostic.severity
  when :error   then 1
  when :warning then 2
  when :info    then 3
  when :hint    then 4
  else               2
  end
  {
    range: {
      start: { line: line_index, character: start_char },
      end:   { line: line_index, character: end_char }
    },
    severity: lsp_severity,
    code: diagnostic.code,
    message: diagnostic_message_to_client(diagnostic.message.to_s, diagnostic.code),
    source: 'milk-tea',
    data: {
      stage: stage
    }
  }
end

.format_warning(warning, content: nil) ⇒ Object



385
386
387
# File 'lib/milk_tea/lsp/diagnostics.rb', line 385

def self.format_warning(warning, content: nil)
  format_tooling_diagnostic(warning.to_diagnostic, content:, stage: 'lint')
end

.import_path_span(import, content) ⇒ Object



547
548
549
550
551
552
553
554
555
556
557
558
559
560
# File 'lib/milk_tea/lsp/diagnostics.rb', line 547

def self.import_path_span(import, content)
  return [import.column || 1, import.length || 1] unless content && import.line

  line_text = content.split("\n", -1)[import.line - 1]
  return [import.column || 1, import.length || 1] unless line_text

  path_text = import.path.to_s
  index = line_text.index(path_text)
  return [index + 1, path_text.length] if index

  [import.column || 1, import.length || 1]
rescue StandardError
  [import.column || 1, import.length || 1]
end

.log_diagnostics_warning(message) ⇒ Object



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

def self.log_diagnostics_warning(message)
  return unless @protocol

  @protocol.write_notification('window/logMessage', {
    type: 2,
    message: message,
  })
rescue StandardError
  nil
end

.log_perf_breakdown(name, elapsed_ms_value, detail) ⇒ Object



271
272
273
274
275
# File 'lib/milk_tea/lsp/diagnostics.rb', line 271

def self.log_perf_breakdown(name, elapsed_ms_value, detail)
  return unless perf_breakdown_logging?(elapsed_ms_value)

  warn "[LSP perf] breakdown #{name} #{elapsed_ms_value}ms #{detail}"
end

.monotonic_timeObject



263
264
265
# File 'lib/milk_tea/lsp/diagnostics.rb', line 263

def self.monotonic_time
  Process.clock_gettime(Process::CLOCK_MONOTONIC)
end

.path_to_uri(path) ⇒ Object



237
238
239
240
# File 'lib/milk_tea/lsp/diagnostics.rb', line 237

def self.path_to_uri(path)
  escaped_path = path.split('/').map { |seg| CGI.escape(seg).gsub('+', '%20') }.join('/')
  "file://#{escaped_path}"
end

.perf_breakdown_logging?(elapsed_ms_value) ⇒ Boolean

Returns:

  • (Boolean)


259
260
261
# File 'lib/milk_tea/lsp/diagnostics.rb', line 259

def self.perf_breakdown_logging?(elapsed_ms_value)
  perf_logging? && (perf_verbose? || elapsed_ms_value > Workspace::PERF_LOG_THRESHOLD_MS)
end

.perf_logging?Boolean

Returns:

  • (Boolean)


251
252
253
# File 'lib/milk_tea/lsp/diagnostics.rb', line 251

def self.perf_logging?
  @perf_logging ||= !ENV.fetch('MILK_TEA_LSP_PERF', nil).to_s.empty?
end

.perf_verbose?Boolean

Returns:

  • (Boolean)


255
256
257
# File 'lib/milk_tea/lsp/diagnostics.rb', line 255

def self.perf_verbose?
  @perf_verbose ||= ENV.fetch('MILK_TEA_LSP_PERF', nil).to_s == 'verbose'
end

.redundant_unknown_import_diagnostic?(diagnostic, unresolved_import_paths) ⇒ Boolean

Returns:

  • (Boolean)


228
229
230
231
232
233
234
235
# File 'lib/milk_tea/lsp/diagnostics.rb', line 228

def self.redundant_unknown_import_diagnostic?(diagnostic, unresolved_import_paths)
  return false unless diagnostic&.message.to_s.start_with?("unknown import ")

  import_path = diagnostic.message.to_s.match(/unknown import (.+)$/)&.captures&.first
  return false unless import_path

  unresolved_import_paths.include?(import_path)
end

.resolve_imported_modules(uri, ast, diagnostics, resolution:, effective_platform:, shared_module_cache: nil, source_overrides: nil, workspace_root_path: nil, content: nil, skip_program_check: false) ⇒ Object



176
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
# File 'lib/milk_tea/lsp/diagnostics.rb', line 176

def self.resolve_imported_modules(uri, ast, diagnostics, resolution:, effective_platform:, shared_module_cache: nil, source_overrides: nil, workspace_root_path: nil, content: nil, skip_program_check: false)
  path = uri_to_path(uri)
   return { modules: {}, unresolved_import_paths: [], module_name: nil } unless path && File.file?(path)

  loader = ModuleLoader.new(
    module_roots: module_roots_for_path(path, locked: resolution.locked, workspace_root_path: workspace_root_path),
    package_graph: load_package_graph(path, locked: resolution.locked),
    shared_cache: shared_module_cache,
    source_overrides: source_overrides,
    platform: effective_platform,
  )
  module_name = loader.send(:inferred_module_name_for_path, path) rescue nil

  # Run the full two-pass program check first so that @analysis_cache
  # has fully-checked analyses for all transitive modules. When the
  # import resolution below encounters a cycle member, it finds the
  # cached analysis and resolves correctly. If the program check fails
  # (e.g. missing module), fall through to the standard resolution
  # path so that prelude modules and regular errors are still reported.
  # Skipped when the file's own parse recovered with errors: the program
  # check poisons the loader cache and yields no facts on that path.
  unless skip_program_check
    begin
      loader.check_program_collecting(path)
    rescue ModuleLoadError, PackageLockError
      # best-effort — standard path below handles diagnostics
    end
  end

  resolution_result = loader.imported_modules_for_ast_collecting_errors(ast, importer_path: path)
  unresolved_import_paths = []

  resolution_result.errors.each do |entry|
    if entry.error.is_a?(ModuleLoadError)
      diagnostics << format_import_error(entry.error, entry.import, content: content)
      unresolved_import_paths << entry.import.path.to_s if entry.import
    else
      diagnostics << format_error(SemanticError.new(entry.error.message))
    end
  end

  { modules: resolution_result.modules, unresolved_import_paths: unresolved_import_paths.uniq, module_name: module_name }
rescue ModuleLoadError, PackageLockError => e
  if e.is_a?(ModuleLoadError)
    import = ast.imports.find { |candidate| candidate.path.to_s == e.path }
    diagnostics << format_import_error(e, import, content: content)
  else
    diagnostics << format_error(SemanticError.new(e.message))
  end
  { modules: {}, unresolved_import_paths: [], module_name: nil }
end

.uri_to_path(uri) ⇒ Object



242
243
244
245
246
247
248
249
# File 'lib/milk_tea/lsp/diagnostics.rb', line 242

def self.uri_to_path(uri)
  parsed = URI.parse(uri)
  return nil unless parsed.scheme == "file"

  CGI.unescape(parsed.path)
rescue URI::InvalidURIError
  nil
end