aboutsummaryrefslogtreecommitdiff
path: root/crates/hir
diff options
context:
space:
mode:
authorbors[bot] <26634292+bors[bot]@users.noreply.github.com>2021-06-13 20:06:18 +0100
committerGitHub <[email protected]>2021-06-13 20:06:18 +0100
commit8c5c0ef7b910ffafc9c684cb7076149ab79f4bdd (patch)
treecb85647c41d797b885ac579312043df4b3112648 /crates/hir
parent76530664e7f01091e0d820eb49bf59db1f06115c (diff)
parentff52167c9a8dd6f99a56a35eae8d634d0ddf1286 (diff)
Merge #9256
9256: internal: kill diagnostic sink r=matklad a=matklad bors r+ 🤖 Co-authored-by: Aleksey Kladov <[email protected]>
Diffstat (limited to 'crates/hir')
-rw-r--r--crates/hir/src/diagnostics.rs46
-rw-r--r--crates/hir/src/diagnostics_sink.rs109
-rw-r--r--crates/hir/src/lib.rs63
3 files changed, 18 insertions, 200 deletions
diff --git a/crates/hir/src/diagnostics.rs b/crates/hir/src/diagnostics.rs
index c2d608eb5..b4c505898 100644
--- a/crates/hir/src/diagnostics.rs
+++ b/crates/hir/src/diagnostics.rs
@@ -3,18 +3,12 @@
3//! 3//!
4//! This probably isn't the best way to do this -- ideally, diagnistics should 4//! This probably isn't the best way to do this -- ideally, diagnistics should
5//! be expressed in terms of hir types themselves. 5//! be expressed in terms of hir types themselves.
6use std::any::Any;
7
8use cfg::{CfgExpr, CfgOptions}; 6use cfg::{CfgExpr, CfgOptions};
9use either::Either; 7use either::Either;
10use hir_def::path::ModPath; 8use hir_def::path::ModPath;
11use hir_expand::{name::Name, HirFileId, InFile}; 9use hir_expand::{name::Name, HirFileId, InFile};
12use syntax::{ast, AstPtr, SyntaxNodePtr, TextRange}; 10use syntax::{ast, AstPtr, SyntaxNodePtr, TextRange};
13 11
14pub use crate::diagnostics_sink::{
15 Diagnostic, DiagnosticCode, DiagnosticSink, DiagnosticSinkBuilder,
16};
17
18macro_rules! diagnostics { 12macro_rules! diagnostics {
19 ($($diag:ident,)*) => { 13 ($($diag:ident,)*) => {
20 pub enum AnyDiagnostic {$( 14 pub enum AnyDiagnostic {$(
@@ -38,6 +32,7 @@ diagnostics![
38 MacroError, 32 MacroError,
39 MismatchedArgCount, 33 MismatchedArgCount,
40 MissingFields, 34 MissingFields,
35 MissingMatchArms,
41 MissingOkOrSomeInTailExpr, 36 MissingOkOrSomeInTailExpr,
42 MissingUnsafe, 37 MissingUnsafe,
43 NoSuchField, 38 NoSuchField,
@@ -149,9 +144,6 @@ pub struct MissingOkOrSomeInTailExpr {
149 pub required: String, 144 pub required: String,
150} 145}
151 146
152// Diagnostic: missing-match-arm
153//
154// This diagnostic is triggered if `match` block is missing one or more match arms.
155#[derive(Debug)] 147#[derive(Debug)]
156pub struct MissingMatchArms { 148pub struct MissingMatchArms {
157 pub file: HirFileId, 149 pub file: HirFileId,
@@ -159,40 +151,4 @@ pub struct MissingMatchArms {
159 pub arms: AstPtr<ast::MatchArmList>, 151 pub arms: AstPtr<ast::MatchArmList>,
160} 152}
161 153
162impl Diagnostic for MissingMatchArms {
163 fn code(&self) -> DiagnosticCode {
164 DiagnosticCode("missing-match-arm")
165 }
166 fn message(&self) -> String {
167 String::from("Missing match arm")
168 }
169 fn display_source(&self) -> InFile<SyntaxNodePtr> {
170 InFile { file_id: self.file, value: self.match_expr.clone().into() }
171 }
172 fn as_any(&self) -> &(dyn Any + Send + 'static) {
173 self
174 }
175}
176
177#[derive(Debug)]
178pub struct InternalBailedOut {
179 pub file: HirFileId,
180 pub pat_syntax_ptr: SyntaxNodePtr,
181}
182
183impl Diagnostic for InternalBailedOut {
184 fn code(&self) -> DiagnosticCode {
185 DiagnosticCode("internal:match-check-bailed-out")
186 }
187 fn message(&self) -> String {
188 format!("Internal: match check bailed out")
189 }
190 fn display_source(&self) -> InFile<SyntaxNodePtr> {
191 InFile { file_id: self.file, value: self.pat_syntax_ptr.clone() }
192 }
193 fn as_any(&self) -> &(dyn Any + Send + 'static) {
194 self
195 }
196}
197
198pub use hir_ty::diagnostics::IncorrectCase; 154pub use hir_ty::diagnostics::IncorrectCase;
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 fc147ade3..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,16 +77,13 @@ 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},
88 diagnostics::{ 84 diagnostics::{
89 AnyDiagnostic, BreakOutsideOfLoop, InactiveCode, IncorrectCase, InternalBailedOut, 85 AnyDiagnostic, BreakOutsideOfLoop, InactiveCode, IncorrectCase, MacroError,
90 MacroError, MismatchedArgCount, MissingFields, MissingMatchArms, MissingOkOrSomeInTailExpr, 86 MismatchedArgCount, MissingFields, MissingMatchArms, MissingOkOrSomeInTailExpr,
91 MissingUnsafe, NoSuchField, RemoveThisSemicolon, ReplaceFilterMapNextWithFindMap, 87 MissingUnsafe, NoSuchField, RemoveThisSemicolon, ReplaceFilterMapNextWithFindMap,
92 UnimplementedBuiltinMacro, UnresolvedExternCrate, UnresolvedImport, UnresolvedMacroCall, 88 UnimplementedBuiltinMacro, UnresolvedExternCrate, UnresolvedImport, UnresolvedMacroCall,
93 UnresolvedModule, UnresolvedProcMacro, 89 UnresolvedModule, UnresolvedProcMacro,
@@ -457,16 +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 internal_diagnostics: bool,
465 ) -> Vec<AnyDiagnostic> {
466 let _p = profile::span("Module::diagnostics").detail(|| { 457 let _p = profile::span("Module::diagnostics").detail(|| {
467 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()))
468 }); 459 });
469 let mut acc: Vec<AnyDiagnostic> = Vec::new();
470 let def_map = self.id.def_map(db.upcast()); 460 let def_map = self.id.def_map(db.upcast());
471 for diag in def_map.diagnostics() { 461 for diag in def_map.diagnostics() {
472 if diag.in_module != self.id.local_id { 462 if diag.in_module != self.id.local_id {
@@ -619,11 +609,11 @@ impl Module {
619 } 609 }
620 for decl in self.declarations(db) { 610 for decl in self.declarations(db) {
621 match decl { 611 match decl {
622 ModuleDef::Function(f) => acc.extend(f.diagnostics(db, sink, internal_diagnostics)), 612 ModuleDef::Function(f) => f.diagnostics(db, acc),
623 ModuleDef::Module(m) => { 613 ModuleDef::Module(m) => {
624 // Only add diagnostics from inline modules 614 // Only add diagnostics from inline modules
625 if def_map[m.id.local_id].origin.is_inline() { 615 if def_map[m.id.local_id].origin.is_inline() {
626 acc.extend(m.diagnostics(db, sink, internal_diagnostics)) 616 m.diagnostics(db, acc)
627 } 617 }
628 } 618 }
629 _ => acc.extend(decl.diagnostics(db)), 619 _ => acc.extend(decl.diagnostics(db)),
@@ -633,11 +623,10 @@ impl Module {
633 for impl_def in self.impl_defs(db) { 623 for impl_def in self.impl_defs(db) {
634 for item in impl_def.items(db) { 624 for item in impl_def.items(db) {
635 if let AssocItem::Function(f) = item { 625 if let AssocItem::Function(f) = item {
636 acc.extend(f.diagnostics(db, sink, internal_diagnostics)); 626 f.diagnostics(db, acc);
637 } 627 }
638 } 628 }
639 } 629 }
640 acc
641 } 630 }
642 631
643 pub fn declarations(self, db: &dyn HirDatabase) -> Vec<ModuleDef> { 632 pub fn declarations(self, db: &dyn HirDatabase) -> Vec<ModuleDef> {
@@ -1036,13 +1025,7 @@ impl Function {
1036 db.function_data(self.id).is_async() 1025 db.function_data(self.id).is_async()
1037 } 1026 }
1038 1027
1039 pub fn diagnostics( 1028 pub fn diagnostics(self, db: &dyn HirDatabase, acc: &mut Vec<AnyDiagnostic>) {
1040 self,
1041 db: &dyn HirDatabase,
1042 sink: &mut DiagnosticSink,
1043 internal_diagnostics: bool,
1044 ) -> Vec<AnyDiagnostic> {
1045 let mut acc: Vec<AnyDiagnostic> = Vec::new();
1046 let krate = self.module(db).id.krate(); 1029 let krate = self.module(db).id.krate();
1047 1030
1048 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;
@@ -1100,9 +1083,7 @@ impl Function {
1100 } 1083 }
1101 } 1084 }
1102 1085
1103 for diagnostic in 1086 for diagnostic in BodyValidationDiagnostic::collect(db, self.id.into()) {
1104 BodyValidationDiagnostic::collect(db, self.id.into(), internal_diagnostics)
1105 {
1106 match diagnostic { 1087 match diagnostic {
1107 BodyValidationDiagnostic::RecordMissingFields { 1088 BodyValidationDiagnostic::RecordMissingFields {
1108 record, 1089 record,
@@ -1209,36 +1190,26 @@ impl Function {
1209 if let (Some(match_expr), Some(arms)) = 1190 if let (Some(match_expr), Some(arms)) =
1210 (match_expr.expr(), match_expr.match_arm_list()) 1191 (match_expr.expr(), match_expr.match_arm_list())
1211 { 1192 {
1212 sink.push(MissingMatchArms { 1193 acc.push(
1213 file: source_ptr.file_id, 1194 MissingMatchArms {
1214 match_expr: AstPtr::new(&match_expr), 1195 file: source_ptr.file_id,
1215 arms: AstPtr::new(&arms), 1196 match_expr: AstPtr::new(&match_expr),
1216 }) 1197 arms: AstPtr::new(&arms),
1198 }
1199 .into(),
1200 )
1217 } 1201 }
1218 } 1202 }
1219 } 1203 }
1220 Err(SyntheticSyntax) => (), 1204 Err(SyntheticSyntax) => (),
1221 } 1205 }
1222 } 1206 }
1223 BodyValidationDiagnostic::InternalBailedOut { pat } => {
1224 match source_map.pat_syntax(pat) {
1225 Ok(source_ptr) => {
1226 let pat_syntax_ptr = source_ptr.value.either(Into::into, Into::into);
1227 sink.push(InternalBailedOut {
1228 file: source_ptr.file_id,
1229 pat_syntax_ptr,
1230 });
1231 }
1232 Err(SyntheticSyntax) => (),
1233 }
1234 }
1235 } 1207 }
1236 } 1208 }
1237 1209
1238 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()) {
1239 acc.push(diag.into()) 1211 acc.push(diag.into())
1240 } 1212 }
1241 acc
1242 } 1213 }
1243 1214
1244 /// Whether this function declaration has a definition. 1215 /// Whether this function declaration has a definition.