aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_hir_ty/src/diagnostics.rs
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ra_hir_ty/src/diagnostics.rs')
-rw-r--r--crates/ra_hir_ty/src/diagnostics.rs470
1 files changed, 0 insertions, 470 deletions
diff --git a/crates/ra_hir_ty/src/diagnostics.rs b/crates/ra_hir_ty/src/diagnostics.rs
deleted file mode 100644
index 45e31033e..000000000
--- a/crates/ra_hir_ty/src/diagnostics.rs
+++ /dev/null
@@ -1,470 +0,0 @@
1//! FIXME: write short doc here
2mod expr;
3mod match_check;
4mod unsafe_check;
5
6use std::any::Any;
7
8use hir_def::DefWithBodyId;
9use hir_expand::diagnostics::{Diagnostic, DiagnosticSink};
10use hir_expand::{name::Name, HirFileId, InFile};
11use ra_prof::profile;
12use ra_syntax::{ast, AstPtr, SyntaxNodePtr};
13use stdx::format_to;
14
15use crate::db::HirDatabase;
16
17pub use crate::diagnostics::expr::{record_literal_missing_fields, record_pattern_missing_fields};
18
19pub fn validate_body(db: &dyn HirDatabase, owner: DefWithBodyId, sink: &mut DiagnosticSink<'_>) {
20 let _p = profile("validate_body");
21 let infer = db.infer(owner);
22 infer.add_diagnostics(db, owner, sink);
23 let mut validator = expr::ExprValidator::new(owner, infer.clone(), sink);
24 validator.validate_body(db);
25 let mut validator = unsafe_check::UnsafeValidator::new(owner, infer, sink);
26 validator.validate_body(db);
27}
28
29#[derive(Debug)]
30pub struct NoSuchField {
31 pub file: HirFileId,
32 pub field: AstPtr<ast::RecordExprField>,
33}
34
35impl Diagnostic for NoSuchField {
36 fn name(&self) -> &'static str {
37 "no-such-field"
38 }
39
40 fn message(&self) -> String {
41 "no such field".to_string()
42 }
43
44 fn display_source(&self) -> InFile<SyntaxNodePtr> {
45 InFile::new(self.file, self.field.clone().into())
46 }
47
48 fn as_any(&self) -> &(dyn Any + Send + 'static) {
49 self
50 }
51}
52
53#[derive(Debug)]
54pub struct MissingFields {
55 pub file: HirFileId,
56 pub field_list_parent: AstPtr<ast::RecordExpr>,
57 pub field_list_parent_path: Option<AstPtr<ast::Path>>,
58 pub missed_fields: Vec<Name>,
59}
60
61impl Diagnostic for MissingFields {
62 fn name(&self) -> &'static str {
63 "missing-structure-fields"
64 }
65 fn message(&self) -> String {
66 let mut buf = String::from("Missing structure fields:\n");
67 for field in &self.missed_fields {
68 format_to!(buf, "- {}\n", field);
69 }
70 buf
71 }
72
73 fn display_source(&self) -> InFile<SyntaxNodePtr> {
74 InFile {
75 file_id: self.file,
76 value: self
77 .field_list_parent_path
78 .clone()
79 .map(SyntaxNodePtr::from)
80 .unwrap_or_else(|| self.field_list_parent.clone().into()),
81 }
82 }
83
84 fn as_any(&self) -> &(dyn Any + Send + 'static) {
85 self
86 }
87}
88
89#[derive(Debug)]
90pub struct MissingPatFields {
91 pub file: HirFileId,
92 pub field_list_parent: AstPtr<ast::RecordPat>,
93 pub field_list_parent_path: Option<AstPtr<ast::Path>>,
94 pub missed_fields: Vec<Name>,
95}
96
97impl Diagnostic for MissingPatFields {
98 fn name(&self) -> &'static str {
99 "missing-pat-fields"
100 }
101 fn message(&self) -> String {
102 let mut buf = String::from("Missing structure fields:\n");
103 for field in &self.missed_fields {
104 format_to!(buf, "- {}\n", field);
105 }
106 buf
107 }
108 fn display_source(&self) -> InFile<SyntaxNodePtr> {
109 InFile {
110 file_id: self.file,
111 value: self
112 .field_list_parent_path
113 .clone()
114 .map(SyntaxNodePtr::from)
115 .unwrap_or_else(|| self.field_list_parent.clone().into()),
116 }
117 }
118 fn as_any(&self) -> &(dyn Any + Send + 'static) {
119 self
120 }
121}
122
123#[derive(Debug)]
124pub struct MissingMatchArms {
125 pub file: HirFileId,
126 pub match_expr: AstPtr<ast::Expr>,
127 pub arms: AstPtr<ast::MatchArmList>,
128}
129
130impl Diagnostic for MissingMatchArms {
131 fn name(&self) -> &'static str {
132 "missing-match-arm"
133 }
134 fn message(&self) -> String {
135 String::from("Missing match arm")
136 }
137 fn display_source(&self) -> InFile<SyntaxNodePtr> {
138 InFile { file_id: self.file, value: self.match_expr.clone().into() }
139 }
140 fn as_any(&self) -> &(dyn Any + Send + 'static) {
141 self
142 }
143}
144
145#[derive(Debug)]
146pub struct MissingOkInTailExpr {
147 pub file: HirFileId,
148 pub expr: AstPtr<ast::Expr>,
149}
150
151impl Diagnostic for MissingOkInTailExpr {
152 fn name(&self) -> &'static str {
153 "missing-ok-in-tail-expr"
154 }
155 fn message(&self) -> String {
156 "wrap return expression in Ok".to_string()
157 }
158 fn display_source(&self) -> InFile<SyntaxNodePtr> {
159 InFile { file_id: self.file, value: self.expr.clone().into() }
160 }
161 fn as_any(&self) -> &(dyn Any + Send + 'static) {
162 self
163 }
164}
165
166#[derive(Debug)]
167pub struct BreakOutsideOfLoop {
168 pub file: HirFileId,
169 pub expr: AstPtr<ast::Expr>,
170}
171
172impl Diagnostic for BreakOutsideOfLoop {
173 fn name(&self) -> &'static str {
174 "break-outside-of-loop"
175 }
176 fn message(&self) -> String {
177 "break outside of loop".to_string()
178 }
179 fn display_source(&self) -> InFile<SyntaxNodePtr> {
180 InFile { file_id: self.file, value: self.expr.clone().into() }
181 }
182 fn as_any(&self) -> &(dyn Any + Send + 'static) {
183 self
184 }
185}
186
187#[derive(Debug)]
188pub struct MissingUnsafe {
189 pub file: HirFileId,
190 pub expr: AstPtr<ast::Expr>,
191}
192
193impl Diagnostic for MissingUnsafe {
194 fn name(&self) -> &'static str {
195 "missing-unsafe"
196 }
197 fn message(&self) -> String {
198 format!("This operation is unsafe and requires an unsafe function or block")
199 }
200 fn display_source(&self) -> InFile<SyntaxNodePtr> {
201 InFile { file_id: self.file, value: self.expr.clone().into() }
202 }
203 fn as_any(&self) -> &(dyn Any + Send + 'static) {
204 self
205 }
206}
207
208#[derive(Debug)]
209pub struct MismatchedArgCount {
210 pub file: HirFileId,
211 pub call_expr: AstPtr<ast::Expr>,
212 pub expected: usize,
213 pub found: usize,
214}
215
216impl Diagnostic for MismatchedArgCount {
217 fn name(&self) -> &'static str {
218 "mismatched-arg-count"
219 }
220 fn message(&self) -> String {
221 let s = if self.expected == 1 { "" } else { "s" };
222 format!("Expected {} argument{}, found {}", self.expected, s, self.found)
223 }
224 fn display_source(&self) -> InFile<SyntaxNodePtr> {
225 InFile { file_id: self.file, value: self.call_expr.clone().into() }
226 }
227 fn as_any(&self) -> &(dyn Any + Send + 'static) {
228 self
229 }
230 fn is_experimental(&self) -> bool {
231 true
232 }
233}
234
235#[cfg(test)]
236mod tests {
237 use hir_def::{db::DefDatabase, AssocItemId, ModuleDefId};
238 use hir_expand::{
239 db::AstDatabase,
240 diagnostics::{Diagnostic, DiagnosticSinkBuilder},
241 };
242 use ra_db::{fixture::WithFixture, FileId, SourceDatabase, SourceDatabaseExt};
243 use ra_syntax::{TextRange, TextSize};
244 use rustc_hash::FxHashMap;
245
246 use crate::{diagnostics::validate_body, test_db::TestDB};
247
248 impl TestDB {
249 fn diagnostics<F: FnMut(&dyn Diagnostic)>(&self, mut cb: F) {
250 let crate_graph = self.crate_graph();
251 for krate in crate_graph.iter() {
252 let crate_def_map = self.crate_def_map(krate);
253
254 let mut fns = Vec::new();
255 for (module_id, _) in crate_def_map.modules.iter() {
256 for decl in crate_def_map[module_id].scope.declarations() {
257 if let ModuleDefId::FunctionId(f) = decl {
258 fns.push(f)
259 }
260 }
261
262 for impl_id in crate_def_map[module_id].scope.impls() {
263 let impl_data = self.impl_data(impl_id);
264 for item in impl_data.items.iter() {
265 if let AssocItemId::FunctionId(f) = item {
266 fns.push(*f)
267 }
268 }
269 }
270 }
271
272 for f in fns {
273 let mut sink = DiagnosticSinkBuilder::new().build(&mut cb);
274 validate_body(self, f.into(), &mut sink);
275 }
276 }
277 }
278 }
279
280 pub(crate) fn check_diagnostics(ra_fixture: &str) {
281 let db = TestDB::with_files(ra_fixture);
282 let annotations = db.extract_annotations();
283
284 let mut actual: FxHashMap<FileId, Vec<(TextRange, String)>> = FxHashMap::default();
285 db.diagnostics(|d| {
286 let src = d.display_source();
287 let root = db.parse_or_expand(src.file_id).unwrap();
288 // FIXME: macros...
289 let file_id = src.file_id.original_file(&db);
290 let range = src.value.to_node(&root).text_range();
291 let message = d.message().to_owned();
292 actual.entry(file_id).or_default().push((range, message));
293 });
294
295 for (file_id, diags) in actual.iter_mut() {
296 diags.sort_by_key(|it| it.0.start());
297 let text = db.file_text(*file_id);
298 // For multiline spans, place them on line start
299 for (range, content) in diags {
300 if text[*range].contains('\n') {
301 *range = TextRange::new(range.start(), range.start() + TextSize::from(1));
302 *content = format!("... {}", content);
303 }
304 }
305 }
306
307 assert_eq!(annotations, actual);
308 }
309
310 #[test]
311 fn no_such_field_diagnostics() {
312 check_diagnostics(
313 r#"
314struct S { foo: i32, bar: () }
315impl S {
316 fn new() -> S {
317 S {
318 //^ Missing structure fields:
319 //| - bar
320 foo: 92,
321 baz: 62,
322 //^^^^^^^ no such field
323 }
324 }
325}
326"#,
327 );
328 }
329 #[test]
330 fn no_such_field_with_feature_flag_diagnostics() {
331 check_diagnostics(
332 r#"
333//- /lib.rs crate:foo cfg:feature=foo
334struct MyStruct {
335 my_val: usize,
336 #[cfg(feature = "foo")]
337 bar: bool,
338}
339
340impl MyStruct {
341 #[cfg(feature = "foo")]
342 pub(crate) fn new(my_val: usize, bar: bool) -> Self {
343 Self { my_val, bar }
344 }
345 #[cfg(not(feature = "foo"))]
346 pub(crate) fn new(my_val: usize, _bar: bool) -> Self {
347 Self { my_val }
348 }
349}
350"#,
351 );
352 }
353
354 #[test]
355 fn no_such_field_enum_with_feature_flag_diagnostics() {
356 check_diagnostics(
357 r#"
358//- /lib.rs crate:foo cfg:feature=foo
359enum Foo {
360 #[cfg(not(feature = "foo"))]
361 Buz,
362 #[cfg(feature = "foo")]
363 Bar,
364 Baz
365}
366
367fn test_fn(f: Foo) {
368 match f {
369 Foo::Bar => {},
370 Foo::Baz => {},
371 }
372}
373"#,
374 );
375 }
376
377 #[test]
378 fn no_such_field_with_feature_flag_diagnostics_on_struct_lit() {
379 check_diagnostics(
380 r#"
381//- /lib.rs crate:foo cfg:feature=foo
382struct S {
383 #[cfg(feature = "foo")]
384 foo: u32,
385 #[cfg(not(feature = "foo"))]
386 bar: u32,
387}
388
389impl S {
390 #[cfg(feature = "foo")]
391 fn new(foo: u32) -> Self {
392 Self { foo }
393 }
394 #[cfg(not(feature = "foo"))]
395 fn new(bar: u32) -> Self {
396 Self { bar }
397 }
398 fn new2(bar: u32) -> Self {
399 #[cfg(feature = "foo")]
400 { Self { foo: bar } }
401 #[cfg(not(feature = "foo"))]
402 { Self { bar } }
403 }
404 fn new2(val: u32) -> Self {
405 Self {
406 #[cfg(feature = "foo")]
407 foo: val,
408 #[cfg(not(feature = "foo"))]
409 bar: val,
410 }
411 }
412}
413"#,
414 );
415 }
416
417 #[test]
418 fn no_such_field_with_type_macro() {
419 check_diagnostics(
420 r#"
421macro_rules! Type { () => { u32 }; }
422struct Foo { bar: Type![] }
423
424impl Foo {
425 fn new() -> Self {
426 Foo { bar: 0 }
427 }
428}
429"#,
430 );
431 }
432
433 #[test]
434 fn missing_record_pat_field_diagnostic() {
435 check_diagnostics(
436 r#"
437struct S { foo: i32, bar: () }
438fn baz(s: S) {
439 let S { foo: _ } = s;
440 //^ Missing structure fields:
441 //| - bar
442}
443"#,
444 );
445 }
446
447 #[test]
448 fn missing_record_pat_field_no_diagnostic_if_not_exhaustive() {
449 check_diagnostics(
450 r"
451struct S { foo: i32, bar: () }
452fn baz(s: S) -> i32 {
453 match s {
454 S { foo, .. } => foo,
455 }
456}
457",
458 )
459 }
460
461 #[test]
462 fn break_outside_of_loop() {
463 check_diagnostics(
464 r#"
465fn foo() { break; }
466 //^^^^^ break outside of loop
467"#,
468 );
469 }
470}