Map our diagnostics to rustc and clippy's ones

This commit is contained in:
hkalbasi 2023-06-15 01:47:22 +03:30
parent 9c967d3809
commit e55a1f1916
44 changed files with 628 additions and 251 deletions

View file

@ -67,24 +67,61 @@ mod handlers {
#[cfg(test)]
mod tests;
use std::collections::HashMap;
use hir::{diagnostics::AnyDiagnostic, InFile, Semantics};
use ide_db::{
assists::{Assist, AssistId, AssistKind, AssistResolveStrategy},
base_db::{FileId, FileRange, SourceDatabase},
generated::lints::{LintGroup, CLIPPY_LINT_GROUPS, DEFAULT_LINT_GROUPS},
imports::insert_use::InsertUseConfig,
label::Label,
source_change::SourceChange,
FxHashSet, RootDatabase,
syntax_helpers::node_ext::parse_tt_as_comma_sep_paths,
FxHashMap, FxHashSet, RootDatabase,
};
use once_cell::sync::Lazy;
use stdx::never;
use syntax::{
algo::find_node_at_range,
ast::{self, AstNode},
SyntaxNode, SyntaxNodePtr, TextRange,
};
use syntax::{algo::find_node_at_range, ast::AstNode, SyntaxNodePtr, TextRange};
// FIXME: Make this an enum
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct DiagnosticCode(pub &'static str);
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum DiagnosticCode {
RustcHardError(&'static str),
RustcLint(&'static str),
Clippy(&'static str),
Ra(&'static str, Severity),
}
impl DiagnosticCode {
pub fn as_str(&self) -> &str {
self.0
pub fn url(&self) -> String {
match self {
DiagnosticCode::RustcHardError(e) => {
format!("https://doc.rust-lang.org/stable/error_codes/{e}.html")
}
DiagnosticCode::RustcLint(e) => {
format!("https://doc.rust-lang.org/rustc/?search={e}")
}
DiagnosticCode::Clippy(e) => {
format!("https://rust-lang.github.io/rust-clippy/master/#/{e}")
}
DiagnosticCode::Ra(e, _) => {
format!("https://rust-analyzer.github.io/manual.html#{e}")
}
}
}
pub fn as_str(&self) -> &'static str {
match self {
DiagnosticCode::RustcHardError(r)
| DiagnosticCode::RustcLint(r)
| DiagnosticCode::Clippy(r)
| DiagnosticCode::Ra(r, _) => r,
}
}
}
@ -97,29 +134,51 @@ pub struct Diagnostic {
pub unused: bool,
pub experimental: bool,
pub fixes: Option<Vec<Assist>>,
// The node that will be affected by `#[allow]` and similar attributes.
pub main_node: Option<InFile<SyntaxNode>>,
}
impl Diagnostic {
fn new(code: &'static str, message: impl Into<String>, range: TextRange) -> Diagnostic {
fn new(code: DiagnosticCode, message: impl Into<String>, range: TextRange) -> Diagnostic {
let message = message.into();
Diagnostic {
code: DiagnosticCode(code),
code,
message,
range,
severity: Severity::Error,
severity: match code {
DiagnosticCode::RustcHardError(_) => Severity::Error,
// FIXME: Rustc lints are not always warning, but the ones that are currently implemented are all warnings.
DiagnosticCode::RustcLint(_) => Severity::Warning,
// FIXME: We can make this configurable, and if the user uses `cargo clippy` on flycheck, we can
// make it normal warning.
DiagnosticCode::Clippy(_) => Severity::WeakWarning,
DiagnosticCode::Ra(_, s) => s,
},
unused: false,
experimental: false,
fixes: None,
main_node: None,
}
}
fn new_with_syntax_node_ptr(
ctx: &DiagnosticsContext<'_>,
code: DiagnosticCode,
message: impl Into<String>,
node: InFile<SyntaxNodePtr>,
) -> Diagnostic {
let file_id = node.file_id;
Diagnostic::new(code, message, ctx.sema.diagnostics_display_range(node.clone()).range)
.with_main_node(node.map(|x| x.to_node(&ctx.sema.parse_or_expand(file_id))))
}
fn experimental(mut self) -> Diagnostic {
self.experimental = true;
self
}
fn severity(mut self, severity: Severity) -> Diagnostic {
self.severity = severity;
fn with_main_node(mut self, main_node: InFile<SyntaxNode>) -> Diagnostic {
self.main_node = Some(main_node);
self
}
@ -134,12 +193,12 @@ impl Diagnostic {
}
}
#[derive(Debug, Copy, Clone)]
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum Severity {
Error,
// We don't actually emit this one yet, but we should at some point.
// Warning,
Warning,
WeakWarning,
Allow,
}
#[derive(Clone, Debug, PartialEq, Eq)]
@ -228,11 +287,13 @@ pub fn diagnostics(
let mut res = Vec::new();
// [#34344] Only take first 128 errors to prevent slowing down editor/ide, the number 128 is chosen arbitrarily.
res.extend(
parse.errors().iter().take(128).map(|err| {
Diagnostic::new("syntax-error", format!("Syntax Error: {err}"), err.range())
}),
);
res.extend(parse.errors().iter().take(128).map(|err| {
Diagnostic::new(
DiagnosticCode::RustcHardError("syntax-error"),
format!("Syntax Error: {err}"),
err.range(),
)
}));
let parse = sema.parse(file_id);
@ -271,7 +332,7 @@ pub fn diagnostics(
res.extend(d.errors.iter().take(32).map(|err| {
{
Diagnostic::new(
"syntax-error",
DiagnosticCode::RustcHardError("syntax-error"),
format!("Syntax Error in Expansion: {err}"),
ctx.resolve_precise_location(&d.node.clone(), d.precise_location),
)
@ -309,14 +370,168 @@ pub fn diagnostics(
res.push(d)
}
let mut diagnostics_of_range =
res.iter_mut().filter_map(|x| Some((x.main_node.clone()?, x))).collect::<FxHashMap<_, _>>();
let mut rustc_stack: FxHashMap<String, Vec<Severity>> = FxHashMap::default();
let mut clippy_stack: FxHashMap<String, Vec<Severity>> = FxHashMap::default();
handle_lint_attributes(
&ctx.sema,
parse.syntax(),
&mut rustc_stack,
&mut clippy_stack,
&mut diagnostics_of_range,
);
res.retain(|d| {
!ctx.config.disabled.contains(d.code.as_str())
d.severity != Severity::Allow
&& !ctx.config.disabled.contains(d.code.as_str())
&& !(ctx.config.disable_experimental && d.experimental)
});
res
}
// `__RA_EVERY_LINT` is a fake lint group to allow every lint in proc macros
static RUSTC_LINT_GROUPS_DICT: Lazy<HashMap<&str, Vec<&str>>> =
Lazy::new(|| build_group_dict(DEFAULT_LINT_GROUPS, &["warnings", "__RA_EVERY_LINT"], ""));
static CLIPPY_LINT_GROUPS_DICT: Lazy<HashMap<&str, Vec<&str>>> =
Lazy::new(|| build_group_dict(CLIPPY_LINT_GROUPS, &["__RA_EVERY_LINT"], "clippy::"));
fn build_group_dict(
lint_group: &'static [LintGroup],
all_groups: &'static [&'static str],
prefix: &'static str,
) -> HashMap<&'static str, Vec<&'static str>> {
let mut r: HashMap<&str, Vec<&str>> = HashMap::new();
for g in lint_group {
for child in g.children {
r.entry(child.strip_prefix(prefix).unwrap())
.or_default()
.push(g.lint.label.strip_prefix(prefix).unwrap());
}
}
for (lint, groups) in r.iter_mut() {
groups.push(lint);
groups.extend_from_slice(all_groups);
}
r
}
fn handle_lint_attributes(
sema: &Semantics<'_, RootDatabase>,
root: &SyntaxNode,
rustc_stack: &mut FxHashMap<String, Vec<Severity>>,
clippy_stack: &mut FxHashMap<String, Vec<Severity>>,
diagnostics_of_range: &mut FxHashMap<InFile<SyntaxNode>, &mut Diagnostic>,
) {
let file_id = sema.hir_file_for(root);
for ev in root.preorder() {
match ev {
syntax::WalkEvent::Enter(node) => {
for attr in node.children().filter_map(ast::Attr::cast) {
parse_lint_attribute(attr, rustc_stack, clippy_stack, |stack, severity| {
stack.push(severity);
});
}
if let Some(x) =
diagnostics_of_range.get_mut(&InFile { file_id, value: node.clone() })
{
const EMPTY_LINTS: &[&str] = &[];
let (names, stack) = match x.code {
DiagnosticCode::RustcLint(name) => (
RUSTC_LINT_GROUPS_DICT.get(name).map_or(EMPTY_LINTS, |x| &**x),
&mut *rustc_stack,
),
DiagnosticCode::Clippy(name) => (
CLIPPY_LINT_GROUPS_DICT.get(name).map_or(EMPTY_LINTS, |x| &**x),
&mut *clippy_stack,
),
_ => continue,
};
for &name in names {
if let Some(s) = stack.get(name).and_then(|x| x.last()) {
x.severity = *s;
}
}
}
if let Some(item) = ast::Item::cast(node.clone()) {
if let Some(me) = sema.expand_attr_macro(&item) {
for stack in [&mut *rustc_stack, &mut *clippy_stack] {
stack
.entry("__RA_EVERY_LINT".to_owned())
.or_default()
.push(Severity::Allow);
}
handle_lint_attributes(
sema,
&me,
rustc_stack,
clippy_stack,
diagnostics_of_range,
);
for stack in [&mut *rustc_stack, &mut *clippy_stack] {
stack.entry("__RA_EVERY_LINT".to_owned()).or_default().pop();
}
}
}
if let Some(mc) = ast::MacroCall::cast(node) {
if let Some(me) = sema.expand(&mc) {
handle_lint_attributes(
sema,
&me,
rustc_stack,
clippy_stack,
diagnostics_of_range,
);
}
}
}
syntax::WalkEvent::Leave(node) => {
for attr in node.children().filter_map(ast::Attr::cast) {
parse_lint_attribute(attr, rustc_stack, clippy_stack, |stack, severity| {
if stack.pop() != Some(severity) {
never!("Mismatched serevity in walking lint attributes");
}
});
}
}
}
}
}
fn parse_lint_attribute(
attr: ast::Attr,
rustc_stack: &mut FxHashMap<String, Vec<Severity>>,
clippy_stack: &mut FxHashMap<String, Vec<Severity>>,
job: impl Fn(&mut Vec<Severity>, Severity),
) {
let Some((tag, args_tt)) = attr.as_simple_call() else {
return;
};
let serevity = match tag.as_str() {
"allow" => Severity::Allow,
"warn" => Severity::Warning,
"forbid" | "deny" => Severity::Error,
_ => return,
};
for lint in parse_tt_as_comma_sep_paths(args_tt).into_iter().flatten() {
if let Some(lint) = lint.as_single_name_ref() {
job(rustc_stack.entry(lint.to_string()).or_default(), serevity);
}
if let Some(tool) = lint.qualifier().and_then(|x| x.as_single_name_ref()) {
if let Some(name_ref) = &lint.segment().and_then(|x| x.name_ref()) {
if tool.to_string() == "clippy" {
job(clippy_stack.entry(name_ref.to_string()).or_default(), serevity);
}
}
}
}
}
fn fix(id: &'static str, label: &str, source_change: SourceChange, target: TextRange) -> Assist {
let mut res = unresolved_fix(id, label, target);
res.source_change = Some(source_change);