Class: MilkTea::LSP::Diagnostics
- Inherits:
-
Object
- Object
- MilkTea::LSP::Diagnostics
- Defined in:
- lib/milk_tea/lsp/diagnostics.rb
Overview
Collects parse and semantic errors and formats them as LSP Diagnostics
Class Attribute Summary collapse
-
.position_encoding ⇒ Object
Returns the value of attribute position_encoding.
-
.protocol ⇒ Object
Returns the value of attribute protocol.
Class Method Summary collapse
- .client_char_to_internal(line_text, client_char) ⇒ Object
- .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
- .diagnostic_code(error) ⇒ Object
- .diagnostic_message_to_client(message, code) ⇒ Object
- .diagnostic_stage(error) ⇒ Object
- .elapsed_ms(start_time) ⇒ Object
- .extract_column(error) ⇒ Object
- .extract_length(error) ⇒ Object
- .extract_line(error) ⇒ Object
- .extract_quoted_name(message) ⇒ Object
-
.extract_warning_range(warning, content) ⇒ Object
Returns [start_char, end_char] in 0-based LSP coordinates.
- .format_error(error) ⇒ Object
- .format_import_error(error, import, content: nil) ⇒ Object
- .format_tooling_diagnostic(diagnostic, content: nil, stage:) ⇒ Object
- .format_warning(warning, content: nil) ⇒ Object
- .import_path_span(import, content) ⇒ Object
- .log_diagnostics_warning(message) ⇒ Object
- .log_perf_breakdown(name, elapsed_ms_value, detail) ⇒ Object
- .monotonic_time ⇒ Object
- .path_to_uri(path) ⇒ Object
- .perf_breakdown_logging?(elapsed_ms_value) ⇒ Boolean
- .perf_logging? ⇒ Boolean
- .perf_verbose? ⇒ Boolean
- .redundant_unknown_import_diagnostic?(diagnostic, unresolved_import_paths) ⇒ Boolean
- .resolve_imported_modules(uri, ast, diagnostics, resolution:, effective_platform:, shared_module_cache: nil, source_overrides: nil, workspace_root_path: nil, content: nil) ⇒ Object
- .uri_to_path(uri) ⇒ Object
Class Attribute Details
.position_encoding ⇒ Object
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 |
.protocol ⇒ Object
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
602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 |
# File 'lib/milk_tea/lsp/diagnostics.rb', line 602 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 |
# 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 ast = if path && File.file?(path) parse_result = Parser.parse_collecting_errors(content, path: uri) 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. diagnostics << format_error(SemanticError.new(resolution., 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., 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, ) 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.respond_to?(: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.(path) : nil sema_snapshot.diagnostics.reject { |diagnostic| redundant_unknown_import_diagnostic?(diagnostic, unresolved_import_paths) } .each do |diagnostic| if target_path && diagnostic.path && File.(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.}") 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.}") end rescue MilkTea::LexError => e diagnostics << format_error(e) rescue StandardError => e log_diagnostics_warning("Error collecting diagnostics: #{e.}") 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.}") 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
494 495 496 497 498 499 500 501 502 503 504 505 506 507 |
# File 'lib/milk_tea/lsp/diagnostics.rb', line 494 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
587 588 589 590 591 592 593 594 595 596 597 598 599 600 |
# File 'lib/milk_tea/lsp/diagnostics.rb', line 587 def self.(, code) return unless .is_a?(String) code_spans = [] if code.to_s.start_with?('sema') .scan(/`([^`]+)`/) { |m| code_spans << m[0] } .scan(/'([A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*)'/) { |m| code_spans << m[0] unless code_spans.include?(m[0]) } end return if code_spans.empty? markdown = .gsub(/`([^`]+)`/, '`\1`') { kind: 'markdown', value: markdown } end |
.diagnostic_stage(error) ⇒ Object
509 510 511 512 513 514 515 516 517 518 519 520 521 522 |
# File 'lib/milk_tea/lsp/diagnostics.rb', line 509 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
244 245 246 |
# File 'lib/milk_tea/lsp/diagnostics.rb', line 244 def self.elapsed_ms(start_time) ((monotonic_time - start_time) * 1000).round(1) end |
.extract_column(error) ⇒ Object
552 553 554 555 556 557 558 559 560 561 562 563 |
# File 'lib/milk_tea/lsp/diagnostics.rb', line 552 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
565 566 567 568 569 570 571 572 573 574 |
# File 'lib/milk_tea/lsp/diagnostics.rb', line 565 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
539 540 541 542 543 544 545 546 547 548 549 550 |
# File 'lib/milk_tea/lsp/diagnostics.rb', line 539 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
426 427 428 429 |
# File 'lib/milk_tea/lsp/diagnostics.rb', line 426 def self.extract_quoted_name() match = .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.
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 |
# File 'lib/milk_tea/lsp/diagnostics.rb', line 395 def self.extract_warning_range(warning, content) if warning.respond_to?(:column) && 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..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
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 |
# File 'lib/milk_tea/lsp/diagnostics.rb', line 431 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: (error..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
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 |
# File 'lib/milk_tea/lsp/diagnostics.rb', line 464 def self.format_import_error(error, import, content: nil) return format_error(SemanticError.new(error.)) 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: (error..to_s, code), source: 'milk-tea', data: { stage: diagnostic_stage(error) } } end |
.format_tooling_diagnostic(diagnostic, content: nil, stage:) ⇒ Object
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 |
# File 'lib/milk_tea/lsp/diagnostics.rb', line 366 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..to_s, diagnostic.code), source: 'milk-tea', data: { stage: stage } } end |
.format_warning(warning, content: nil) ⇒ Object
362 363 364 |
# File 'lib/milk_tea/lsp/diagnostics.rb', line 362 def self.format_warning(warning, content: nil) format_tooling_diagnostic(warning.to_diagnostic, content:, stage: 'lint') end |
.import_path_span(import, content) ⇒ Object
524 525 526 527 528 529 530 531 532 533 534 535 536 537 |
# File 'lib/milk_tea/lsp/diagnostics.rb', line 524 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
576 577 578 579 580 581 582 583 584 585 |
# File 'lib/milk_tea/lsp/diagnostics.rb', line 576 def self.log_diagnostics_warning() return unless @protocol @protocol.write_notification('window/logMessage', { type: 2, message: , }) rescue StandardError nil end |
.log_perf_breakdown(name, elapsed_ms_value, detail) ⇒ Object
248 249 250 251 252 |
# File 'lib/milk_tea/lsp/diagnostics.rb', line 248 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_time ⇒ Object
240 241 242 |
# File 'lib/milk_tea/lsp/diagnostics.rb', line 240 def self.monotonic_time Process.clock_gettime(Process::CLOCK_MONOTONIC) end |
.path_to_uri(path) ⇒ Object
214 215 216 217 |
# File 'lib/milk_tea/lsp/diagnostics.rb', line 214 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
236 237 238 |
# File 'lib/milk_tea/lsp/diagnostics.rb', line 236 def self.perf_breakdown_logging?(elapsed_ms_value) perf_logging? && (perf_verbose? || elapsed_ms_value > Workspace::PERF_LOG_THRESHOLD_MS) end |
.perf_logging? ⇒ Boolean
228 229 230 |
# File 'lib/milk_tea/lsp/diagnostics.rb', line 228 def self.perf_logging? @perf_logging ||= !ENV.fetch('MILK_TEA_LSP_PERF', nil).to_s.empty? end |
.perf_verbose? ⇒ Boolean
232 233 234 |
# File 'lib/milk_tea/lsp/diagnostics.rb', line 232 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
205 206 207 208 209 210 211 212 |
# File 'lib/milk_tea/lsp/diagnostics.rb', line 205 def self.redundant_unknown_import_diagnostic?(diagnostic, unresolved_import_paths) return false unless diagnostic&..to_s.start_with?("unknown import ") import_path = diagnostic..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) ⇒ Object
170 171 172 173 174 175 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 |
# File 'lib/milk_tea/lsp/diagnostics.rb', line 170 def self.resolve_imported_modules(uri, ast, diagnostics, resolution:, effective_platform:, shared_module_cache: nil, source_overrides: nil, workspace_root_path: nil, content: nil) 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 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.)) 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.)) end { modules: {}, unresolved_import_paths: [], module_name: nil } end |
.uri_to_path(uri) ⇒ Object
219 220 221 222 223 224 225 226 |
# File 'lib/milk_tea/lsp/diagnostics.rb', line 219 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 |