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