aboutsummaryrefslogtreecommitdiff
path: root/crates/ide/src
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ide/src')
-rw-r--r--crates/ide/src/diagnostics.rs80
-rw-r--r--crates/ide/src/lib.rs28
2 files changed, 99 insertions, 9 deletions
diff --git a/crates/ide/src/diagnostics.rs b/crates/ide/src/diagnostics.rs
index a3ec98178..a54df37db 100644
--- a/crates/ide/src/diagnostics.rs
+++ b/crates/ide/src/diagnostics.rs
@@ -16,7 +16,7 @@ use syntax::{
16}; 16};
17use text_edit::TextEdit; 17use text_edit::TextEdit;
18 18
19use crate::{Diagnostic, FileId, Fix, SourceFileEdit}; 19use crate::{AnalysisConfig, Diagnostic, FileId, Fix, SourceFileEdit};
20 20
21mod diagnostics_with_fix; 21mod diagnostics_with_fix;
22use diagnostics_with_fix::DiagnosticWithFix; 22use diagnostics_with_fix::DiagnosticWithFix;
@@ -31,6 +31,7 @@ pub(crate) fn diagnostics(
31 db: &RootDatabase, 31 db: &RootDatabase,
32 file_id: FileId, 32 file_id: FileId,
33 enable_experimental: bool, 33 enable_experimental: bool,
34 analysis_config: &AnalysisConfig,
34) -> Vec<Diagnostic> { 35) -> Vec<Diagnostic> {
35 let _p = profile::span("diagnostics"); 36 let _p = profile::span("diagnostics");
36 let sema = Semantics::new(db); 37 let sema = Semantics::new(db);
@@ -39,6 +40,7 @@ pub(crate) fn diagnostics(
39 40
40 // [#34344] Only take first 128 errors to prevent slowing down editor/ide, the number 128 is chosen arbitrarily. 41 // [#34344] Only take first 128 errors to prevent slowing down editor/ide, the number 128 is chosen arbitrarily.
41 res.extend(parse.errors().iter().take(128).map(|err| Diagnostic { 42 res.extend(parse.errors().iter().take(128).map(|err| Diagnostic {
43 name: None,
42 range: err.range(), 44 range: err.range(),
43 message: format!("Syntax Error: {}", err), 45 message: format!("Syntax Error: {}", err),
44 severity: Severity::Error, 46 severity: Severity::Error,
@@ -50,7 +52,7 @@ pub(crate) fn diagnostics(
50 check_struct_shorthand_initialization(&mut res, file_id, &node); 52 check_struct_shorthand_initialization(&mut res, file_id, &node);
51 } 53 }
52 let res = RefCell::new(res); 54 let res = RefCell::new(res);
53 let mut sink = DiagnosticSinkBuilder::new() 55 let mut sink_builder = DiagnosticSinkBuilder::new()
54 .on::<hir::diagnostics::UnresolvedModule, _>(|d| { 56 .on::<hir::diagnostics::UnresolvedModule, _>(|d| {
55 res.borrow_mut().push(diagnostic_with_fix(d, &sema)); 57 res.borrow_mut().push(diagnostic_with_fix(d, &sema));
56 }) 58 })
@@ -64,10 +66,20 @@ pub(crate) fn diagnostics(
64 res.borrow_mut().push(diagnostic_with_fix(d, &sema)); 66 res.borrow_mut().push(diagnostic_with_fix(d, &sema));
65 }) 67 })
66 // Only collect experimental diagnostics when they're enabled. 68 // Only collect experimental diagnostics when they're enabled.
67 .filter(|diag| !diag.is_experimental() || enable_experimental) 69 .filter(|diag| !diag.is_experimental() || enable_experimental);
70
71 if !analysis_config.disabled_diagnostics.is_empty() {
72 // Do not collect disabled diagnostics.
73 sink_builder =
74 sink_builder.filter(|diag| !analysis_config.disabled_diagnostics.contains(diag.name()));
75 }
76
77 // Finalize the `DiagnosticSink` building process.
78 let mut sink = sink_builder
68 // Diagnostics not handled above get no fix and default treatment. 79 // Diagnostics not handled above get no fix and default treatment.
69 .build(|d| { 80 .build(|d| {
70 res.borrow_mut().push(Diagnostic { 81 res.borrow_mut().push(Diagnostic {
82 name: Some(d.name().into()),
71 message: d.message(), 83 message: d.message(),
72 range: sema.diagnostics_display_range(d).range, 84 range: sema.diagnostics_display_range(d).range,
73 severity: Severity::Error, 85 severity: Severity::Error,
@@ -84,6 +96,7 @@ pub(crate) fn diagnostics(
84 96
85fn diagnostic_with_fix<D: DiagnosticWithFix>(d: &D, sema: &Semantics<RootDatabase>) -> Diagnostic { 97fn diagnostic_with_fix<D: DiagnosticWithFix>(d: &D, sema: &Semantics<RootDatabase>) -> Diagnostic {
86 Diagnostic { 98 Diagnostic {
99 name: Some(d.name().into()),
87 range: sema.diagnostics_display_range(d).range, 100 range: sema.diagnostics_display_range(d).range,
88 message: d.message(), 101 message: d.message(),
89 severity: Severity::Error, 102 severity: Severity::Error,
@@ -110,6 +123,7 @@ fn check_unnecessary_braces_in_use_statement(
110 }); 123 });
111 124
112 acc.push(Diagnostic { 125 acc.push(Diagnostic {
126 name: None,
113 range: use_range, 127 range: use_range,
114 message: "Unnecessary braces in use statement".to_string(), 128 message: "Unnecessary braces in use statement".to_string(),
115 severity: Severity::WeakWarning, 129 severity: Severity::WeakWarning,
@@ -156,6 +170,7 @@ fn check_struct_shorthand_initialization(
156 170
157 let field_range = record_field.syntax().text_range(); 171 let field_range = record_field.syntax().text_range();
158 acc.push(Diagnostic { 172 acc.push(Diagnostic {
173 name: None,
159 range: field_range, 174 range: field_range,
160 message: "Shorthand struct initialization".to_string(), 175 message: "Shorthand struct initialization".to_string(),
161 severity: Severity::WeakWarning, 176 severity: Severity::WeakWarning,
@@ -173,10 +188,14 @@ fn check_struct_shorthand_initialization(
173 188
174#[cfg(test)] 189#[cfg(test)]
175mod tests { 190mod tests {
191 use std::collections::HashSet;
176 use stdx::trim_indent; 192 use stdx::trim_indent;
177 use test_utils::assert_eq_text; 193 use test_utils::assert_eq_text;
178 194
179 use crate::mock_analysis::{analysis_and_position, single_file, MockAnalysis}; 195 use crate::{
196 mock_analysis::{analysis_and_position, single_file, MockAnalysis},
197 AnalysisConfig,
198 };
180 use expect::{expect, Expect}; 199 use expect::{expect, Expect};
181 200
182 /// Takes a multi-file input fixture with annotated cursor positions, 201 /// Takes a multi-file input fixture with annotated cursor positions,
@@ -240,6 +259,51 @@ mod tests {
240 assert_eq!(diagnostics.len(), 0, "unexpected diagnostics:\n{:#?}", diagnostics); 259 assert_eq!(diagnostics.len(), 0, "unexpected diagnostics:\n{:#?}", diagnostics);
241 } 260 }
242 261
262 /// Takes a multi-file input fixture with annotated cursor position and the list of disabled diagnostics,
263 /// and checks that provided diagnostics aren't spawned during analysis.
264 fn check_disabled_diagnostics(ra_fixture: &str, disabled_diagnostics: &[&'static str]) {
265 let disabled_diagnostics: HashSet<_> =
266 disabled_diagnostics.into_iter().map(|diag| diag.to_string()).collect();
267
268 let mock = MockAnalysis::with_files(ra_fixture);
269 let files = mock.files().map(|(it, _)| it).collect::<Vec<_>>();
270 let mut analysis = mock.analysis();
271 analysis.set_config(AnalysisConfig { disabled_diagnostics: disabled_diagnostics.clone() });
272
273 let diagnostics = files
274 .clone()
275 .into_iter()
276 .flat_map(|file_id| analysis.diagnostics(file_id, true).unwrap())
277 .collect::<Vec<_>>();
278
279 // First, we have to check that diagnostic is not emitted when it's added to the disabled diagnostics list.
280 for diagnostic in diagnostics {
281 if let Some(name) = diagnostic.name {
282 assert!(!disabled_diagnostics.contains(&name), "Diagnostic {} is disabled", name);
283 }
284 }
285
286 // Then, we must reset the config and repeat the check, so that we'll be sure that without
287 // config these diagnostics are emitted.
288 // This is required for tests to not become outdated if e.g. diagnostics name changes:
289 // without this additional run the test will pass simply because a diagnostic with an old name
290 // will no longer exist.
291 analysis.set_config(AnalysisConfig { disabled_diagnostics: Default::default() });
292
293 let diagnostics = files
294 .into_iter()
295 .flat_map(|file_id| analysis.diagnostics(file_id, true).unwrap())
296 .collect::<Vec<_>>();
297
298 assert!(
299 diagnostics
300 .into_iter()
301 .filter_map(|diag| diag.name)
302 .any(|name| disabled_diagnostics.contains(&name)),
303 "At least one of the diagnostics was not emitted even without config; are the diagnostics names correct?"
304 );
305 }
306
243 fn check_expect(ra_fixture: &str, expect: Expect) { 307 fn check_expect(ra_fixture: &str, expect: Expect) {
244 let (analysis, file_id) = single_file(ra_fixture); 308 let (analysis, file_id) = single_file(ra_fixture);
245 let diagnostics = analysis.diagnostics(file_id, true).unwrap(); 309 let diagnostics = analysis.diagnostics(file_id, true).unwrap();
@@ -502,6 +566,9 @@ fn test_fn() {
502 expect![[r#" 566 expect![[r#"
503 [ 567 [
504 Diagnostic { 568 Diagnostic {
569 name: Some(
570 "unresolved-module",
571 ),
505 message: "unresolved module", 572 message: "unresolved module",
506 range: 0..8, 573 range: 0..8,
507 severity: Error, 574 severity: Error,
@@ -675,4 +742,9 @@ struct Foo {
675 ", 742 ",
676 ) 743 )
677 } 744 }
745
746 #[test]
747 fn test_disabled_diagnostics() {
748 check_disabled_diagnostics(r#"mod foo;"#, &["unresolved-module"]);
749 }
678} 750}
diff --git a/crates/ide/src/lib.rs b/crates/ide/src/lib.rs
index eb6389529..b762c994e 100644
--- a/crates/ide/src/lib.rs
+++ b/crates/ide/src/lib.rs
@@ -44,7 +44,7 @@ mod syntax_highlighting;
44mod syntax_tree; 44mod syntax_tree;
45mod typing; 45mod typing;
46 46
47use std::sync::Arc; 47use std::{collections::HashSet, sync::Arc};
48 48
49use base_db::{ 49use base_db::{
50 salsa::{self, ParallelDatabase}, 50 salsa::{self, ParallelDatabase},
@@ -99,8 +99,15 @@ pub use text_edit::{Indel, TextEdit};
99 99
100pub type Cancelable<T> = Result<T, Canceled>; 100pub type Cancelable<T> = Result<T, Canceled>;
101 101
102/// Configuration parameters for the analysis run.
103#[derive(Debug, Default, Clone)]
104pub struct AnalysisConfig {
105 pub disabled_diagnostics: HashSet<String>,
106}
107
102#[derive(Debug)] 108#[derive(Debug)]
103pub struct Diagnostic { 109pub struct Diagnostic {
110 pub name: Option<String>,
104 pub message: String, 111 pub message: String,
105 pub range: TextRange, 112 pub range: TextRange,
106 pub severity: Severity, 113 pub severity: Severity,
@@ -144,11 +151,16 @@ impl<T> RangeInfo<T> {
144#[derive(Debug)] 151#[derive(Debug)]
145pub struct AnalysisHost { 152pub struct AnalysisHost {
146 db: RootDatabase, 153 db: RootDatabase,
154 config: AnalysisConfig,
147} 155}
148 156
149impl AnalysisHost { 157impl AnalysisHost {
150 pub fn new(lru_capacity: Option<usize>) -> AnalysisHost { 158 pub fn new(lru_capacity: Option<usize>) -> Self {
151 AnalysisHost { db: RootDatabase::new(lru_capacity) } 159 Self::with_config(lru_capacity, AnalysisConfig::default())
160 }
161
162 pub fn with_config(lru_capacity: Option<usize>, config: AnalysisConfig) -> Self {
163 AnalysisHost { db: RootDatabase::new(lru_capacity), config }
152 } 164 }
153 165
154 pub fn update_lru_capacity(&mut self, lru_capacity: Option<usize>) { 166 pub fn update_lru_capacity(&mut self, lru_capacity: Option<usize>) {
@@ -158,7 +170,7 @@ impl AnalysisHost {
158 /// Returns a snapshot of the current state, which you can query for 170 /// Returns a snapshot of the current state, which you can query for
159 /// semantic information. 171 /// semantic information.
160 pub fn analysis(&self) -> Analysis { 172 pub fn analysis(&self) -> Analysis {
161 Analysis { db: self.db.snapshot() } 173 Analysis { db: self.db.snapshot(), config: self.config.clone() }
162 } 174 }
163 175
164 /// Applies changes to the current state of the world. If there are 176 /// Applies changes to the current state of the world. If there are
@@ -202,6 +214,7 @@ impl Default for AnalysisHost {
202#[derive(Debug)] 214#[derive(Debug)]
203pub struct Analysis { 215pub struct Analysis {
204 db: salsa::Snapshot<RootDatabase>, 216 db: salsa::Snapshot<RootDatabase>,
217 config: AnalysisConfig,
205} 218}
206 219
207// As a general design guideline, `Analysis` API are intended to be independent 220// As a general design guideline, `Analysis` API are intended to be independent
@@ -497,7 +510,7 @@ impl Analysis {
497 file_id: FileId, 510 file_id: FileId,
498 enable_experimental: bool, 511 enable_experimental: bool,
499 ) -> Cancelable<Vec<Diagnostic>> { 512 ) -> Cancelable<Vec<Diagnostic>> {
500 self.with_db(|db| diagnostics::diagnostics(db, file_id, enable_experimental)) 513 self.with_db(|db| diagnostics::diagnostics(db, file_id, enable_experimental, &self.config))
501 } 514 }
502 515
503 /// Returns the edit required to rename reference at the position to the new 516 /// Returns the edit required to rename reference at the position to the new
@@ -526,6 +539,11 @@ impl Analysis {
526 }) 539 })
527 } 540 }
528 541
542 /// Sets the provided config.
543 pub fn set_config(&mut self, config: AnalysisConfig) {
544 self.config = config;
545 }
546
529 /// Performs an operation on that may be Canceled. 547 /// Performs an operation on that may be Canceled.
530 fn with_db<F, T>(&self, f: F) -> Cancelable<T> 548 fn with_db<F, T>(&self, f: F) -> Cancelable<T>
531 where 549 where