Cleanup diagnostic conversion code

This commit is contained in:
Aleksey Kladov 2020-07-09 15:34:37 +02:00
parent 117392e879
commit b398519011
4 changed files with 76 additions and 104 deletions

1
Cargo.lock generated
View file

@ -1435,6 +1435,7 @@ dependencies = [
"anyhow", "anyhow",
"crossbeam-channel", "crossbeam-channel",
"env_logger", "env_logger",
"expect",
"flycheck", "flycheck",
"globset", "globset",
"insta", "insta",

View file

@ -14,7 +14,8 @@ use std::{
use crossbeam_channel::{never, select, unbounded, Receiver, Sender}; use crossbeam_channel::{never, select, unbounded, Receiver, Sender};
pub use cargo_metadata::diagnostic::{ pub use cargo_metadata::diagnostic::{
Applicability, Diagnostic, DiagnosticLevel, DiagnosticSpan, DiagnosticSpanMacroExpansion, Applicability, Diagnostic, DiagnosticCode, DiagnosticLevel, DiagnosticSpan,
DiagnosticSpanMacroExpansion,
}; };
#[derive(Clone, Debug, PartialEq, Eq)] #[derive(Clone, Debug, PartialEq, Eq)]

View file

@ -59,6 +59,7 @@ winapi = "0.3.8"
[dev-dependencies] [dev-dependencies]
tempfile = "3.1.0" tempfile = "3.1.0"
insta = "0.16.0" insta = "0.16.0"
expect = { path = "../expect" }
test_utils = { path = "../test_utils" } test_utils = { path = "../test_utils" }
mbe = { path = "../ra_mbe", package = "ra_mbe" } mbe = { path = "../ra_mbe", package = "ra_mbe" }
tt = { path = "../ra_tt", package = "ra_tt" } tt = { path = "../ra_tt", package = "ra_tt" }

View file

@ -2,11 +2,7 @@
//! `cargo check` json format to the LSP diagnostic format. //! `cargo check` json format to the LSP diagnostic format.
use std::{collections::HashMap, path::Path}; use std::{collections::HashMap, path::Path};
use flycheck::{Applicability, DiagnosticLevel, DiagnosticSpan, DiagnosticSpanMacroExpansion}; use flycheck::{Applicability, DiagnosticLevel, DiagnosticSpan};
use lsp_types::{
Diagnostic, DiagnosticRelatedInformation, DiagnosticSeverity, DiagnosticTag, Location,
NumberOrString, Position, Range, TextEdit, Url,
};
use stdx::format_to; use stdx::format_to;
use crate::{lsp_ext, to_proto::url_from_abs_path}; use crate::{lsp_ext, to_proto::url_from_abs_path};
@ -14,22 +10,25 @@ use crate::{lsp_ext, to_proto::url_from_abs_path};
use super::DiagnosticsConfig; use super::DiagnosticsConfig;
/// Determines the LSP severity from a diagnostic /// Determines the LSP severity from a diagnostic
fn map_diagnostic_to_severity( fn diagnostic_severity(
config: &DiagnosticsConfig, config: &DiagnosticsConfig,
val: &flycheck::Diagnostic, level: flycheck::DiagnosticLevel,
) -> Option<DiagnosticSeverity> { code: Option<flycheck::DiagnosticCode>,
let res = match val.level { ) -> Option<lsp_types::DiagnosticSeverity> {
DiagnosticLevel::Ice => DiagnosticSeverity::Error, let res = match level {
DiagnosticLevel::Error => DiagnosticSeverity::Error, DiagnosticLevel::Ice => lsp_types::DiagnosticSeverity::Error,
DiagnosticLevel::Warning => match &val.code { DiagnosticLevel::Error => lsp_types::DiagnosticSeverity::Error,
Some(code) if config.warnings_as_hint.contains(&code.code) => DiagnosticSeverity::Hint, DiagnosticLevel::Warning => match &code {
Some(code) if config.warnings_as_info.contains(&code.code) => { Some(code) if config.warnings_as_hint.contains(&code.code) => {
DiagnosticSeverity::Information lsp_types::DiagnosticSeverity::Hint
} }
_ => DiagnosticSeverity::Warning, Some(code) if config.warnings_as_info.contains(&code.code) => {
lsp_types::DiagnosticSeverity::Information
}
_ => lsp_types::DiagnosticSeverity::Warning,
}, },
DiagnosticLevel::Note => DiagnosticSeverity::Information, DiagnosticLevel::Note => lsp_types::DiagnosticSeverity::Information,
DiagnosticLevel::Help => DiagnosticSeverity::Hint, DiagnosticLevel::Help => lsp_types::DiagnosticSeverity::Hint,
DiagnosticLevel::Unknown => return None, DiagnosticLevel::Unknown => return None,
}; };
Some(res) Some(res)
@ -40,90 +39,50 @@ fn is_from_macro(file_name: &str) -> bool {
file_name.starts_with('<') && file_name.ends_with('>') file_name.starts_with('<') && file_name.ends_with('>')
} }
/// Converts a Rust macro span to a LSP location recursively
fn map_macro_span_to_location(
span_macro: &DiagnosticSpanMacroExpansion,
workspace_root: &Path,
) -> Option<Location> {
if !is_from_macro(&span_macro.span.file_name) {
return Some(map_span_to_location(&span_macro.span, workspace_root));
}
if let Some(expansion) = &span_macro.span.expansion {
return map_macro_span_to_location(&expansion, workspace_root);
}
None
}
/// Converts a Rust span to a LSP location, resolving macro expansion site if neccesary /// Converts a Rust span to a LSP location, resolving macro expansion site if neccesary
fn map_span_to_location(span: &DiagnosticSpan, workspace_root: &Path) -> Location { fn location(workspace_root: &Path, span: &DiagnosticSpan) -> lsp_types::Location {
if span.expansion.is_some() { let mut span = span.clone();
let expansion = span.expansion.as_ref().unwrap(); while let Some(expansion) = span.expansion {
if let Some(macro_range) = map_macro_span_to_location(&expansion, workspace_root) { span = expansion.span;
return macro_range;
} }
} return location_naive(workspace_root, &span);
map_span_to_location_naive(span, workspace_root)
} }
/// Converts a Rust span to a LSP location /// Converts a Rust span to a LSP location
fn map_span_to_location_naive(span: &DiagnosticSpan, workspace_root: &Path) -> Location { fn location_naive(workspace_root: &Path, span: &DiagnosticSpan) -> lsp_types::Location {
let mut file_name = workspace_root.to_path_buf(); let file_name = workspace_root.join(&span.file_name);
file_name.push(&span.file_name);
let uri = url_from_abs_path(&file_name); let uri = url_from_abs_path(&file_name);
// FIXME: this doesn't handle UTF16 offsets correctly // FIXME: this doesn't handle UTF16 offsets correctly
let range = Range::new( let range = lsp_types::Range::new(
Position::new(span.line_start as u64 - 1, span.column_start as u64 - 1), lsp_types::Position::new(span.line_start as u64 - 1, span.column_start as u64 - 1),
Position::new(span.line_end as u64 - 1, span.column_end as u64 - 1), lsp_types::Position::new(span.line_end as u64 - 1, span.column_end as u64 - 1),
); );
Location { uri, range } lsp_types::Location { uri, range }
} }
/// Converts a secondary Rust span to a LSP related information /// Converts a secondary Rust span to a LSP related inflocation(ormation
/// ///
/// If the span is unlabelled this will return `None`. /// If the span is unlabelled this will return `None`.
fn map_secondary_span_to_related( fn diagnostic_related_information(
span: &DiagnosticSpan,
workspace_root: &Path, workspace_root: &Path,
) -> Option<DiagnosticRelatedInformation> { span: &DiagnosticSpan,
) -> Option<lsp_types::DiagnosticRelatedInformation> {
let message = span.label.clone()?; let message = span.label.clone()?;
let location = map_span_to_location(span, workspace_root); let location = location(workspace_root, span);
Some(DiagnosticRelatedInformation { location, message }) Some(lsp_types::DiagnosticRelatedInformation { location, message })
}
/// Determines if diagnostic is related to unused code
fn is_unused_or_unnecessary(rd: &flycheck::Diagnostic) -> bool {
match &rd.code {
Some(code) => match code.code.as_str() {
"dead_code" | "unknown_lints" | "unreachable_code" | "unused_attributes"
| "unused_imports" | "unused_macros" | "unused_variables" => true,
_ => false,
},
None => false,
}
}
/// Determines if diagnostic is related to deprecated code
fn is_deprecated(rd: &flycheck::Diagnostic) -> bool {
match &rd.code {
Some(code) => code.code.as_str() == "deprecated",
None => false,
}
} }
enum MappedRustChildDiagnostic { enum MappedRustChildDiagnostic {
Related(DiagnosticRelatedInformation), Related(lsp_types::DiagnosticRelatedInformation),
SuggestedFix(lsp_ext::CodeAction), SuggestedFix(lsp_ext::CodeAction),
MessageLine(String), MessageLine(String),
} }
fn map_rust_child_diagnostic( fn map_rust_child_diagnostic(
rd: &flycheck::Diagnostic,
workspace_root: &Path, workspace_root: &Path,
rd: &flycheck::Diagnostic,
) -> MappedRustChildDiagnostic { ) -> MappedRustChildDiagnostic {
let spans: Vec<&DiagnosticSpan> = rd.spans.iter().filter(|s| s.is_primary).collect(); let spans: Vec<&DiagnosticSpan> = rd.spans.iter().filter(|s| s.is_primary).collect();
if spans.is_empty() { if spans.is_empty() {
@ -132,21 +91,20 @@ fn map_rust_child_diagnostic(
return MappedRustChildDiagnostic::MessageLine(rd.message.clone()); return MappedRustChildDiagnostic::MessageLine(rd.message.clone());
} }
let mut edit_map: HashMap<Url, Vec<TextEdit>> = HashMap::new(); let mut edit_map: HashMap<lsp_types::Url, Vec<lsp_types::TextEdit>> = HashMap::new();
for &span in &spans { for &span in &spans {
match (&span.suggestion_applicability, &span.suggested_replacement) { if let (Some(Applicability::MachineApplicable), Some(suggested_replacement)) =
(Some(Applicability::MachineApplicable), Some(suggested_replacement)) => { (&span.suggestion_applicability, &span.suggested_replacement)
let location = map_span_to_location(span, workspace_root); {
let edit = TextEdit::new(location.range, suggested_replacement.clone()); let location = location(workspace_root, span);
let edit = lsp_types::TextEdit::new(location.range, suggested_replacement.clone());
edit_map.entry(location.uri).or_default().push(edit); edit_map.entry(location.uri).or_default().push(edit);
} }
_ => {}
}
} }
if edit_map.is_empty() { if edit_map.is_empty() {
MappedRustChildDiagnostic::Related(DiagnosticRelatedInformation { MappedRustChildDiagnostic::Related(lsp_types::DiagnosticRelatedInformation {
location: map_span_to_location(spans[0], workspace_root), location: location(workspace_root, spans[0]),
message: rd.message.clone(), message: rd.message.clone(),
}) })
} else { } else {
@ -167,8 +125,8 @@ fn map_rust_child_diagnostic(
#[derive(Debug)] #[derive(Debug)]
pub(crate) struct MappedRustDiagnostic { pub(crate) struct MappedRustDiagnostic {
pub(crate) location: Location, pub(crate) location: lsp_types::Location,
pub(crate) diagnostic: Diagnostic, pub(crate) diagnostic: lsp_types::Diagnostic,
pub(crate) fixes: Vec<lsp_ext::CodeAction>, pub(crate) fixes: Vec<lsp_ext::CodeAction>,
} }
@ -192,7 +150,7 @@ pub(crate) fn map_rust_diagnostic_to_lsp(
return Vec::new(); return Vec::new();
} }
let severity = map_diagnostic_to_severity(config, rd); let severity = diagnostic_severity(config, rd.level.clone(), rd.code.clone());
let mut source = String::from("rustc"); let mut source = String::from("rustc");
let mut code = rd.code.as_ref().map(|c| c.code.clone()); let mut code = rd.code.as_ref().map(|c| c.code.clone());
@ -210,7 +168,7 @@ pub(crate) fn map_rust_diagnostic_to_lsp(
let mut tags = Vec::new(); let mut tags = Vec::new();
for secondary_span in rd.spans.iter().filter(|s| !s.is_primary) { for secondary_span in rd.spans.iter().filter(|s| !s.is_primary) {
let related = map_secondary_span_to_related(secondary_span, workspace_root); let related = diagnostic_related_information(workspace_root, secondary_span);
if let Some(related) = related { if let Some(related) = related {
related_information.push(related); related_information.push(related);
} }
@ -219,7 +177,7 @@ pub(crate) fn map_rust_diagnostic_to_lsp(
let mut fixes = Vec::new(); let mut fixes = Vec::new();
let mut message = rd.message.clone(); let mut message = rd.message.clone();
for child in &rd.children { for child in &rd.children {
let child = map_rust_child_diagnostic(&child, workspace_root); let child = map_rust_child_diagnostic(workspace_root, &child);
match child { match child {
MappedRustChildDiagnostic::Related(related) => related_information.push(related), MappedRustChildDiagnostic::Related(related) => related_information.push(related),
MappedRustChildDiagnostic::SuggestedFix(code_action) => fixes.push(code_action), MappedRustChildDiagnostic::SuggestedFix(code_action) => fixes.push(code_action),
@ -233,18 +191,30 @@ pub(crate) fn map_rust_diagnostic_to_lsp(
} }
} }
if is_unused_or_unnecessary(rd) { if let Some(code) = &rd.code {
tags.push(DiagnosticTag::Unnecessary); let code = code.code.as_str();
if matches!(
code,
"dead_code"
| "unknown_lints"
| "unreachable_code"
| "unused_attributes"
| "unused_imports"
| "unused_macros"
| "unused_variables"
) {
tags.push(lsp_types::DiagnosticTag::Unnecessary);
} }
if is_deprecated(rd) { if matches!(code, "deprecated") {
tags.push(DiagnosticTag::Deprecated); tags.push(lsp_types::DiagnosticTag::Deprecated);
}
} }
primary_spans primary_spans
.iter() .iter()
.map(|primary_span| { .map(|primary_span| {
let location = map_span_to_location(&primary_span, workspace_root); let location = location(workspace_root, &primary_span);
let mut message = message.clone(); let mut message = message.clone();
if needs_primary_span_label { if needs_primary_span_label {
@ -256,17 +226,16 @@ pub(crate) fn map_rust_diagnostic_to_lsp(
// If error occurs from macro expansion, add related info pointing to // If error occurs from macro expansion, add related info pointing to
// where the error originated // where the error originated
if !is_from_macro(&primary_span.file_name) && primary_span.expansion.is_some() { if !is_from_macro(&primary_span.file_name) && primary_span.expansion.is_some() {
let def_loc = map_span_to_location_naive(&primary_span, workspace_root); related_information.push(lsp_types::DiagnosticRelatedInformation {
related_information.push(DiagnosticRelatedInformation { location: location_naive(workspace_root, &primary_span),
location: def_loc,
message: "Error originated from macro here".to_string(), message: "Error originated from macro here".to_string(),
}); });
} }
let diagnostic = Diagnostic { let diagnostic = lsp_types::Diagnostic {
range: location.range, range: location.range,
severity, severity,
code: code.clone().map(NumberOrString::String), code: code.clone().map(lsp_types::NumberOrString::String),
source: Some(source.clone()), source: Some(source.clone()),
message, message,
related_information: if related_information.is_empty() { related_information: if related_information.is_empty() {