aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--crates/hir/src/diagnostics.rs4
-rw-r--r--crates/hir/src/diagnostics_sink.rs109
-rw-r--r--crates/hir/src/lib.rs28
-rw-r--r--crates/ide/src/diagnostics.rs48
4 files changed, 19 insertions, 170 deletions
diff --git a/crates/hir/src/diagnostics.rs b/crates/hir/src/diagnostics.rs
index 1f6a70006..b4c505898 100644
--- a/crates/hir/src/diagnostics.rs
+++ b/crates/hir/src/diagnostics.rs
@@ -9,10 +9,6 @@ use hir_def::path::ModPath;
9use hir_expand::{name::Name, HirFileId, InFile}; 9use hir_expand::{name::Name, HirFileId, InFile};
10use syntax::{ast, AstPtr, SyntaxNodePtr, TextRange}; 10use syntax::{ast, AstPtr, SyntaxNodePtr, TextRange};
11 11
12pub use crate::diagnostics_sink::{
13 Diagnostic, DiagnosticCode, DiagnosticSink, DiagnosticSinkBuilder,
14};
15
16macro_rules! diagnostics { 12macro_rules! diagnostics {
17 ($($diag:ident,)*) => { 13 ($($diag:ident,)*) => {
18 pub enum AnyDiagnostic {$( 14 pub enum AnyDiagnostic {$(
diff --git a/crates/hir/src/diagnostics_sink.rs b/crates/hir/src/diagnostics_sink.rs
deleted file mode 100644
index 084fa8b06..000000000
--- a/crates/hir/src/diagnostics_sink.rs
+++ /dev/null
@@ -1,109 +0,0 @@
1//! Semantic errors and warnings.
2//!
3//! The `Diagnostic` trait defines a trait object which can represent any
4//! diagnostic.
5//!
6//! `DiagnosticSink` struct is used as an emitter for diagnostic. When creating
7//! a `DiagnosticSink`, you supply a callback which can react to a `dyn
8//! Diagnostic` or to any concrete diagnostic (downcasting is used internally).
9//!
10//! Because diagnostics store file offsets, it's a bad idea to store them
11//! directly in salsa. For this reason, every hir subsytem defines it's own
12//! strongly-typed closed set of diagnostics which use hir ids internally, are
13//! stored in salsa and do *not* implement the `Diagnostic` trait. Instead, a
14//! subsystem provides a separate, non-query-based API which can walk all stored
15//! values and transform them into instances of `Diagnostic`.
16
17use std::{any::Any, fmt};
18
19use hir_expand::InFile;
20use syntax::SyntaxNodePtr;
21
22#[derive(Copy, Clone, Debug, PartialEq)]
23pub struct DiagnosticCode(pub &'static str);
24
25impl DiagnosticCode {
26 pub fn as_str(&self) -> &str {
27 self.0
28 }
29}
30
31pub trait Diagnostic: Any + Send + Sync + fmt::Debug + 'static {
32 fn code(&self) -> DiagnosticCode;
33 fn message(&self) -> String;
34 /// Source element that triggered the diagnostics.
35 ///
36 /// Note that this should reflect "semantics", rather than specific span we
37 /// want to highlight. When rendering the diagnostics into an error message,
38 /// the IDE will fetch the `SyntaxNode` and will narrow the span
39 /// appropriately.
40 fn display_source(&self) -> InFile<SyntaxNodePtr>;
41 fn as_any(&self) -> &(dyn Any + Send + 'static);
42 fn is_experimental(&self) -> bool {
43 false
44 }
45}
46
47pub struct DiagnosticSink<'a> {
48 callbacks: Vec<Box<dyn FnMut(&dyn Diagnostic) -> Result<(), ()> + 'a>>,
49 filters: Vec<Box<dyn FnMut(&dyn Diagnostic) -> bool + 'a>>,
50 default_callback: Box<dyn FnMut(&dyn Diagnostic) + 'a>,
51}
52
53impl<'a> DiagnosticSink<'a> {
54 pub fn push(&mut self, d: impl Diagnostic) {
55 let d: &dyn Diagnostic = &d;
56 self._push(d);
57 }
58
59 fn _push(&mut self, d: &dyn Diagnostic) {
60 for filter in &mut self.filters {
61 if !filter(d) {
62 return;
63 }
64 }
65 for cb in &mut self.callbacks {
66 match cb(d) {
67 Ok(()) => return,
68 Err(()) => (),
69 }
70 }
71 (self.default_callback)(d)
72 }
73}
74
75pub struct DiagnosticSinkBuilder<'a> {
76 callbacks: Vec<Box<dyn FnMut(&dyn Diagnostic) -> Result<(), ()> + 'a>>,
77 filters: Vec<Box<dyn FnMut(&dyn Diagnostic) -> bool + 'a>>,
78}
79
80impl<'a> DiagnosticSinkBuilder<'a> {
81 pub fn new() -> Self {
82 Self { callbacks: Vec::new(), filters: Vec::new() }
83 }
84
85 pub fn filter<F: FnMut(&dyn Diagnostic) -> bool + 'a>(mut self, cb: F) -> Self {
86 self.filters.push(Box::new(cb));
87 self
88 }
89
90 pub fn on<D: Diagnostic, F: FnMut(&D) + 'a>(mut self, mut cb: F) -> Self {
91 let cb = move |diag: &dyn Diagnostic| match diag.as_any().downcast_ref::<D>() {
92 Some(d) => {
93 cb(d);
94 Ok(())
95 }
96 None => Err(()),
97 };
98 self.callbacks.push(Box::new(cb));
99 self
100 }
101
102 pub fn build<F: FnMut(&dyn Diagnostic) + 'a>(self, default_callback: F) -> DiagnosticSink<'a> {
103 DiagnosticSink {
104 callbacks: self.callbacks,
105 filters: self.filters,
106 default_callback: Box::new(default_callback),
107 }
108 }
109}
diff --git a/crates/hir/src/lib.rs b/crates/hir/src/lib.rs
index 7f689cd41..ce38396d0 100644
--- a/crates/hir/src/lib.rs
+++ b/crates/hir/src/lib.rs
@@ -27,7 +27,6 @@ mod attrs;
27mod has_source; 27mod has_source;
28 28
29pub mod diagnostics; 29pub mod diagnostics;
30pub mod diagnostics_sink;
31pub mod db; 30pub mod db;
32 31
33mod display; 32mod display;
@@ -78,10 +77,7 @@ use syntax::{
78}; 77};
79use tt::{Ident, Leaf, Literal, TokenTree}; 78use tt::{Ident, Leaf, Literal, TokenTree};
80 79
81use crate::{ 80use crate::db::{DefDatabase, HirDatabase};
82 db::{DefDatabase, HirDatabase},
83 diagnostics_sink::DiagnosticSink,
84};
85 81
86pub use crate::{ 82pub use crate::{
87 attrs::{HasAttrs, Namespace}, 83 attrs::{HasAttrs, Namespace},
@@ -457,15 +453,10 @@ impl Module {
457 self.id.def_map(db.upcast())[self.id.local_id].scope.visibility_of((*def).into()) 453 self.id.def_map(db.upcast())[self.id.local_id].scope.visibility_of((*def).into())
458 } 454 }
459 455
460 pub fn diagnostics( 456 pub fn diagnostics(self, db: &dyn HirDatabase, acc: &mut Vec<AnyDiagnostic>) {
461 self,
462 db: &dyn HirDatabase,
463 sink: &mut DiagnosticSink,
464 ) -> Vec<AnyDiagnostic> {
465 let _p = profile::span("Module::diagnostics").detail(|| { 457 let _p = profile::span("Module::diagnostics").detail(|| {
466 format!("{:?}", self.name(db).map_or("<unknown>".into(), |name| name.to_string())) 458 format!("{:?}", self.name(db).map_or("<unknown>".into(), |name| name.to_string()))
467 }); 459 });
468 let mut acc: Vec<AnyDiagnostic> = Vec::new();
469 let def_map = self.id.def_map(db.upcast()); 460 let def_map = self.id.def_map(db.upcast());
470 for diag in def_map.diagnostics() { 461 for diag in def_map.diagnostics() {
471 if diag.in_module != self.id.local_id { 462 if diag.in_module != self.id.local_id {
@@ -618,11 +609,11 @@ impl Module {
618 } 609 }
619 for decl in self.declarations(db) { 610 for decl in self.declarations(db) {
620 match decl { 611 match decl {
621 ModuleDef::Function(f) => acc.extend(f.diagnostics(db, sink)), 612 ModuleDef::Function(f) => f.diagnostics(db, acc),
622 ModuleDef::Module(m) => { 613 ModuleDef::Module(m) => {
623 // Only add diagnostics from inline modules 614 // Only add diagnostics from inline modules
624 if def_map[m.id.local_id].origin.is_inline() { 615 if def_map[m.id.local_id].origin.is_inline() {
625 acc.extend(m.diagnostics(db, sink)) 616 m.diagnostics(db, acc)
626 } 617 }
627 } 618 }
628 _ => acc.extend(decl.diagnostics(db)), 619 _ => acc.extend(decl.diagnostics(db)),
@@ -632,11 +623,10 @@ impl Module {
632 for impl_def in self.impl_defs(db) { 623 for impl_def in self.impl_defs(db) {
633 for item in impl_def.items(db) { 624 for item in impl_def.items(db) {
634 if let AssocItem::Function(f) = item { 625 if let AssocItem::Function(f) = item {
635 acc.extend(f.diagnostics(db, sink)); 626 f.diagnostics(db, acc);
636 } 627 }
637 } 628 }
638 } 629 }
639 acc
640 } 630 }
641 631
642 pub fn declarations(self, db: &dyn HirDatabase) -> Vec<ModuleDef> { 632 pub fn declarations(self, db: &dyn HirDatabase) -> Vec<ModuleDef> {
@@ -1035,12 +1025,7 @@ impl Function {
1035 db.function_data(self.id).is_async() 1025 db.function_data(self.id).is_async()
1036 } 1026 }
1037 1027
1038 pub fn diagnostics( 1028 pub fn diagnostics(self, db: &dyn HirDatabase, acc: &mut Vec<AnyDiagnostic>) {
1039 self,
1040 db: &dyn HirDatabase,
1041 sink: &mut DiagnosticSink,
1042 ) -> Vec<AnyDiagnostic> {
1043 let mut acc: Vec<AnyDiagnostic> = Vec::new();
1044 let krate = self.module(db).id.krate(); 1029 let krate = self.module(db).id.krate();
1045 1030
1046 let source_map = db.body_with_source_map(self.id.into()).1; 1031 let source_map = db.body_with_source_map(self.id.into()).1;
@@ -1225,7 +1210,6 @@ impl Function {
1225 for diag in hir_ty::diagnostics::validate_module_item(db, krate, self.id.into()) { 1210 for diag in hir_ty::diagnostics::validate_module_item(db, krate, self.id.into()) {
1226 acc.push(diag.into()) 1211 acc.push(diag.into())
1227 } 1212 }
1228 acc
1229 } 1213 }
1230 1214
1231 /// Whether this function declaration has a definition. 1215 /// Whether this function declaration has a definition.
diff --git a/crates/ide/src/diagnostics.rs b/crates/ide/src/diagnostics.rs
index fe6236e44..c024e3e1e 100644
--- a/crates/ide/src/diagnostics.rs
+++ b/crates/ide/src/diagnostics.rs
@@ -26,12 +26,7 @@ mod unresolved_proc_macro;
26 26
27mod field_shorthand; 27mod field_shorthand;
28 28
29use std::cell::RefCell; 29use hir::{diagnostics::AnyDiagnostic, Semantics};
30
31use hir::{
32 diagnostics::{AnyDiagnostic, DiagnosticCode, DiagnosticSinkBuilder},
33 Semantics,
34};
35use ide_assists::AssistResolveStrategy; 30use ide_assists::AssistResolveStrategy;
36use ide_db::{base_db::SourceDatabase, RootDatabase}; 31use ide_db::{base_db::SourceDatabase, RootDatabase};
37use itertools::Itertools; 32use itertools::Itertools;
@@ -45,6 +40,15 @@ use unlinked_file::UnlinkedFile;
45 40
46use crate::{Assist, AssistId, AssistKind, FileId, Label, SourceChange}; 41use crate::{Assist, AssistId, AssistKind, FileId, Label, SourceChange};
47 42
43#[derive(Copy, Clone, Debug, PartialEq)]
44pub struct DiagnosticCode(pub &'static str);
45
46impl DiagnosticCode {
47 pub fn as_str(&self) -> &str {
48 self.0
49 }
50}
51
48#[derive(Debug)] 52#[derive(Debug)]
49pub struct Diagnostic { 53pub struct Diagnostic {
50 // pub name: Option<String>, 54 // pub name: Option<String>,
@@ -113,10 +117,6 @@ impl Diagnostic {
113 fn with_unused(self, unused: bool) -> Self { 117 fn with_unused(self, unused: bool) -> Self {
114 Self { unused, ..self } 118 Self { unused, ..self }
115 } 119 }
116
117 fn with_code(self, code: Option<DiagnosticCode>) -> Self {
118 Self { code, ..self }
119 }
120} 120}
121 121
122#[derive(Debug, Copy, Clone)] 122#[derive(Debug, Copy, Clone)]
@@ -161,35 +161,13 @@ pub(crate) fn diagnostics(
161 check_unnecessary_braces_in_use_statement(&mut res, file_id, &node); 161 check_unnecessary_braces_in_use_statement(&mut res, file_id, &node);
162 field_shorthand::check(&mut res, file_id, &node); 162 field_shorthand::check(&mut res, file_id, &node);
163 } 163 }
164 let res = RefCell::new(res);
165 let sink_builder = DiagnosticSinkBuilder::new()
166 // Only collect experimental diagnostics when they're enabled.
167 .filter(|diag| !(diag.is_experimental() && config.disable_experimental))
168 .filter(|diag| !config.disabled.contains(diag.code().as_str()));
169
170 // Finalize the `DiagnosticSink` building process.
171 let mut sink = sink_builder
172 // Diagnostics not handled above get no fix and default treatment.
173 .build(|d| {
174 res.borrow_mut().push(
175 Diagnostic::error(
176 sema.diagnostics_display_range(d.display_source()).range,
177 d.message(),
178 )
179 .with_code(Some(d.code())),
180 );
181 });
182 164
183 let mut diags = Vec::new(); 165 let mut diags = Vec::new();
184 let module = sema.to_module_def(file_id); 166 let module = sema.to_module_def(file_id);
185 if let Some(m) = module { 167 if let Some(m) = module {
186 diags = m.diagnostics(db, &mut sink) 168 m.diagnostics(db, &mut diags)
187 } 169 }
188 170
189 drop(sink);
190
191 let mut res = res.into_inner();
192
193 let ctx = DiagnosticsContext { config, sema, resolve }; 171 let ctx = DiagnosticsContext { config, sema, resolve };
194 if module.is_none() { 172 if module.is_none() {
195 let d = UnlinkedFile { file: file_id }; 173 let d = UnlinkedFile { file: file_id };
@@ -350,8 +328,8 @@ mod tests {
350 ) 328 )
351 .unwrap() 329 .unwrap()
352 .pop() 330 .pop()
353 .unwrap(); 331 .expect("no diagnostics");
354 let fix = &diagnostic.fixes.unwrap()[nth]; 332 let fix = &diagnostic.fixes.expect("diagnostic misses fixes")[nth];
355 let actual = { 333 let actual = {
356 let source_change = fix.source_change.as_ref().unwrap(); 334 let source_change = fix.source_change.as_ref().unwrap();
357 let file_id = *source_change.source_file_edits.keys().next().unwrap(); 335 let file_id = *source_change.source_file_edits.keys().next().unwrap();