From 302bf97bbf1855e3c7def9ab4f9f3d338be5e3b7 Mon Sep 17 00:00:00 2001 From: Aleksey Kladov Date: Fri, 17 Apr 2020 11:38:51 +0200 Subject: Don't expose impl details of SyntaxPtr --- crates/ra_hir_ty/src/diagnostics.rs | 24 +++++++++++++++++++++++- crates/ra_hir_ty/src/expr.rs | 14 +++++++++++--- crates/ra_hir_ty/src/infer.rs | 11 +++++++++-- 3 files changed, 43 insertions(+), 6 deletions(-) (limited to 'crates/ra_hir_ty') diff --git a/crates/ra_hir_ty/src/diagnostics.rs b/crates/ra_hir_ty/src/diagnostics.rs index 927896d6f..da85bd082 100644 --- a/crates/ra_hir_ty/src/diagnostics.rs +++ b/crates/ra_hir_ty/src/diagnostics.rs @@ -3,7 +3,7 @@ use std::any::Any; use hir_expand::{db::AstDatabase, name::Name, HirFileId, InFile}; -use ra_syntax::{ast, AstNode, AstPtr, SyntaxNodePtr}; +use ra_syntax::{ast, AstNode, AstPtr, SyntaxNodePtr, TextRange}; use stdx::format_to; pub use hir_def::{diagnostics::UnresolvedModule, expr::MatchArm}; @@ -13,6 +13,7 @@ pub use hir_expand::diagnostics::{AstDiagnostic, Diagnostic, DiagnosticSink}; pub struct NoSuchField { pub file: HirFileId, pub field: AstPtr, + pub highlight_range: TextRange, } impl Diagnostic for NoSuchField { @@ -20,6 +21,10 @@ impl Diagnostic for NoSuchField { "no such field".to_string() } + fn highlight_range(&self) -> TextRange { + self.highlight_range + } + fn source(&self) -> InFile { InFile { file_id: self.file, value: self.field.clone().into() } } @@ -33,6 +38,7 @@ impl Diagnostic for NoSuchField { pub struct MissingFields { pub file: HirFileId, pub field_list: AstPtr, + pub highlight_range: TextRange, pub missed_fields: Vec, } @@ -44,6 +50,10 @@ impl Diagnostic for MissingFields { } buf } + fn highlight_range(&self) -> TextRange { + self.highlight_range + } + fn source(&self) -> InFile { InFile { file_id: self.file, value: self.field_list.clone().into() } } @@ -66,6 +76,7 @@ impl AstDiagnostic for MissingFields { pub struct MissingPatFields { pub file: HirFileId, pub field_list: AstPtr, + pub highlight_range: TextRange, pub missed_fields: Vec, } @@ -77,6 +88,9 @@ impl Diagnostic for MissingPatFields { } buf } + fn highlight_range(&self) -> TextRange { + self.highlight_range + } fn source(&self) -> InFile { InFile { file_id: self.file, value: self.field_list.clone().into() } } @@ -90,12 +104,16 @@ pub struct MissingMatchArms { pub file: HirFileId, pub match_expr: AstPtr, pub arms: AstPtr, + pub highlight_range: TextRange, } impl Diagnostic for MissingMatchArms { fn message(&self) -> String { String::from("Missing match arm") } + fn highlight_range(&self) -> TextRange { + self.highlight_range + } fn source(&self) -> InFile { InFile { file_id: self.file, value: self.match_expr.clone().into() } } @@ -108,12 +126,16 @@ impl Diagnostic for MissingMatchArms { pub struct MissingOkInTailExpr { pub file: HirFileId, pub expr: AstPtr, + pub highlight_range: TextRange, } impl Diagnostic for MissingOkInTailExpr { fn message(&self) -> String { "wrap return expression in Ok".to_string() } + fn highlight_range(&self) -> TextRange { + self.highlight_range + } fn source(&self) -> InFile { InFile { file_id: self.file, value: self.expr.clone().into() } } diff --git a/crates/ra_hir_ty/src/expr.rs b/crates/ra_hir_ty/src/expr.rs index fd59f4320..1d3950b70 100644 --- a/crates/ra_hir_ty/src/expr.rs +++ b/crates/ra_hir_ty/src/expr.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use hir_def::{path::path, resolver::HasResolver, AdtId, FunctionId}; use hir_expand::diagnostics::DiagnosticSink; -use ra_syntax::{ast, AstPtr}; +use ra_syntax::{ast, AstNode, AstPtr}; use rustc_hash::FxHashSet; use crate::{ @@ -100,6 +100,7 @@ impl<'a, 'b> ExprValidator<'a, 'b> { self.sink.push(MissingFields { file: source_ptr.file_id, field_list: AstPtr::new(&field_list), + highlight_range: field_list.syntax().text_range(), missed_fields, }) } @@ -130,6 +131,7 @@ impl<'a, 'b> ExprValidator<'a, 'b> { self.sink.push(MissingPatFields { file: source_ptr.file_id, field_list: AstPtr::new(&field_list), + highlight_range: field_list.syntax().text_range(), missed_fields, }) } @@ -213,6 +215,7 @@ impl<'a, 'b> ExprValidator<'a, 'b> { file: source_ptr.file_id, match_expr: AstPtr::new(&match_expr), arms: AstPtr::new(&arms), + highlight_range: match_expr.syntax().text_range(), }) } } @@ -244,8 +247,13 @@ impl<'a, 'b> ExprValidator<'a, 'b> { let (_, source_map) = db.body_with_source_map(self.func.into()); if let Ok(source_ptr) = source_map.expr_syntax(id) { - self.sink - .push(MissingOkInTailExpr { file: source_ptr.file_id, expr: source_ptr.value }); + let root = source_ptr.file_syntax(db.upcast()); + let highlight_range = source_ptr.value.to_node(&root).syntax().text_range(); + self.sink.push(MissingOkInTailExpr { + file: source_ptr.file_id, + expr: source_ptr.value, + highlight_range, + }); } } } diff --git a/crates/ra_hir_ty/src/infer.rs b/crates/ra_hir_ty/src/infer.rs index 246b0e9be..7e6cdefe4 100644 --- a/crates/ra_hir_ty/src/infer.rs +++ b/crates/ra_hir_ty/src/infer.rs @@ -665,6 +665,7 @@ impl Expectation { mod diagnostics { use hir_def::{expr::ExprId, src::HasSource, FunctionId, Lookup}; use hir_expand::diagnostics::DiagnosticSink; + use ra_syntax::AstNode; use crate::{db::HirDatabase, diagnostics::NoSuchField}; @@ -682,10 +683,16 @@ mod diagnostics { ) { match self { InferenceDiagnostic::NoSuchField { expr, field } => { - let file = owner.lookup(db.upcast()).source(db.upcast()).file_id; + let source = owner.lookup(db.upcast()).source(db.upcast()); let (_, source_map) = db.body_with_source_map(owner.into()); let field = source_map.field_syntax(*expr, *field); - sink.push(NoSuchField { file, field }) + let root = field.file_syntax(db.upcast()); + let highlight_range = field.value.to_node(&root).syntax().text_range(); + sink.push(NoSuchField { + file: source.file_id, + field: field.value, + highlight_range, + }) } } } -- cgit v1.2.3 From a8196ffe8466aa60dec56e77c2da717793c0debe Mon Sep 17 00:00:00 2001 From: Aleksey Kladov Date: Fri, 17 Apr 2020 13:06:02 +0200 Subject: Correctly highlight ranges of diagnostics from macros closes #2799 --- crates/ra_hir_ty/src/diagnostics.rs | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) (limited to 'crates/ra_hir_ty') diff --git a/crates/ra_hir_ty/src/diagnostics.rs b/crates/ra_hir_ty/src/diagnostics.rs index da85bd082..018c2ad3f 100644 --- a/crates/ra_hir_ty/src/diagnostics.rs +++ b/crates/ra_hir_ty/src/diagnostics.rs @@ -21,12 +21,12 @@ impl Diagnostic for NoSuchField { "no such field".to_string() } - fn highlight_range(&self) -> TextRange { - self.highlight_range + fn highlight_range(&self) -> InFile { + InFile::new(self.file, self.highlight_range) } fn source(&self) -> InFile { - InFile { file_id: self.file, value: self.field.clone().into() } + InFile::new(self.file, self.field.clone().into()) } fn as_any(&self) -> &(dyn Any + Send + 'static) { @@ -50,8 +50,8 @@ impl Diagnostic for MissingFields { } buf } - fn highlight_range(&self) -> TextRange { - self.highlight_range + fn highlight_range(&self) -> InFile { + InFile::new(self.file, self.highlight_range) } fn source(&self) -> InFile { @@ -88,8 +88,8 @@ impl Diagnostic for MissingPatFields { } buf } - fn highlight_range(&self) -> TextRange { - self.highlight_range + fn highlight_range(&self) -> InFile { + InFile::new(self.file, self.highlight_range) } fn source(&self) -> InFile { InFile { file_id: self.file, value: self.field_list.clone().into() } @@ -111,8 +111,8 @@ impl Diagnostic for MissingMatchArms { fn message(&self) -> String { String::from("Missing match arm") } - fn highlight_range(&self) -> TextRange { - self.highlight_range + fn highlight_range(&self) -> InFile { + InFile::new(self.file, self.highlight_range) } fn source(&self) -> InFile { InFile { file_id: self.file, value: self.match_expr.clone().into() } @@ -133,8 +133,8 @@ impl Diagnostic for MissingOkInTailExpr { fn message(&self) -> String { "wrap return expression in Ok".to_string() } - fn highlight_range(&self) -> TextRange { - self.highlight_range + fn highlight_range(&self) -> InFile { + InFile::new(self.file, self.highlight_range) } fn source(&self) -> InFile { InFile { file_id: self.file, value: self.expr.clone().into() } -- cgit v1.2.3 From 146f6f5a45a4bfd98ab0eb54bb30610d784433c9 Mon Sep 17 00:00:00 2001 From: Aleksey Kladov Date: Fri, 17 Apr 2020 13:55:05 +0200 Subject: Simplify Diagnostic structure It's not entirely clear what subnode ranges should mean in the presence of macros, so let's leave them out for now. We are not using them heavily anyway. --- crates/ra_hir_ty/src/diagnostics.rs | 24 +----------------------- crates/ra_hir_ty/src/expr.rs | 14 +++----------- crates/ra_hir_ty/src/infer.rs | 9 +-------- 3 files changed, 5 insertions(+), 42 deletions(-) (limited to 'crates/ra_hir_ty') diff --git a/crates/ra_hir_ty/src/diagnostics.rs b/crates/ra_hir_ty/src/diagnostics.rs index 018c2ad3f..c8fd54861 100644 --- a/crates/ra_hir_ty/src/diagnostics.rs +++ b/crates/ra_hir_ty/src/diagnostics.rs @@ -3,7 +3,7 @@ use std::any::Any; use hir_expand::{db::AstDatabase, name::Name, HirFileId, InFile}; -use ra_syntax::{ast, AstNode, AstPtr, SyntaxNodePtr, TextRange}; +use ra_syntax::{ast, AstNode, AstPtr, SyntaxNodePtr}; use stdx::format_to; pub use hir_def::{diagnostics::UnresolvedModule, expr::MatchArm}; @@ -13,7 +13,6 @@ pub use hir_expand::diagnostics::{AstDiagnostic, Diagnostic, DiagnosticSink}; pub struct NoSuchField { pub file: HirFileId, pub field: AstPtr, - pub highlight_range: TextRange, } impl Diagnostic for NoSuchField { @@ -21,10 +20,6 @@ impl Diagnostic for NoSuchField { "no such field".to_string() } - fn highlight_range(&self) -> InFile { - InFile::new(self.file, self.highlight_range) - } - fn source(&self) -> InFile { InFile::new(self.file, self.field.clone().into()) } @@ -38,7 +33,6 @@ impl Diagnostic for NoSuchField { pub struct MissingFields { pub file: HirFileId, pub field_list: AstPtr, - pub highlight_range: TextRange, pub missed_fields: Vec, } @@ -50,10 +44,6 @@ impl Diagnostic for MissingFields { } buf } - fn highlight_range(&self) -> InFile { - InFile::new(self.file, self.highlight_range) - } - fn source(&self) -> InFile { InFile { file_id: self.file, value: self.field_list.clone().into() } } @@ -76,7 +66,6 @@ impl AstDiagnostic for MissingFields { pub struct MissingPatFields { pub file: HirFileId, pub field_list: AstPtr, - pub highlight_range: TextRange, pub missed_fields: Vec, } @@ -88,9 +77,6 @@ impl Diagnostic for MissingPatFields { } buf } - fn highlight_range(&self) -> InFile { - InFile::new(self.file, self.highlight_range) - } fn source(&self) -> InFile { InFile { file_id: self.file, value: self.field_list.clone().into() } } @@ -104,16 +90,12 @@ pub struct MissingMatchArms { pub file: HirFileId, pub match_expr: AstPtr, pub arms: AstPtr, - pub highlight_range: TextRange, } impl Diagnostic for MissingMatchArms { fn message(&self) -> String { String::from("Missing match arm") } - fn highlight_range(&self) -> InFile { - InFile::new(self.file, self.highlight_range) - } fn source(&self) -> InFile { InFile { file_id: self.file, value: self.match_expr.clone().into() } } @@ -126,16 +108,12 @@ impl Diagnostic for MissingMatchArms { pub struct MissingOkInTailExpr { pub file: HirFileId, pub expr: AstPtr, - pub highlight_range: TextRange, } impl Diagnostic for MissingOkInTailExpr { fn message(&self) -> String { "wrap return expression in Ok".to_string() } - fn highlight_range(&self) -> InFile { - InFile::new(self.file, self.highlight_range) - } fn source(&self) -> InFile { InFile { file_id: self.file, value: self.expr.clone().into() } } diff --git a/crates/ra_hir_ty/src/expr.rs b/crates/ra_hir_ty/src/expr.rs index 1d3950b70..fd59f4320 100644 --- a/crates/ra_hir_ty/src/expr.rs +++ b/crates/ra_hir_ty/src/expr.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use hir_def::{path::path, resolver::HasResolver, AdtId, FunctionId}; use hir_expand::diagnostics::DiagnosticSink; -use ra_syntax::{ast, AstNode, AstPtr}; +use ra_syntax::{ast, AstPtr}; use rustc_hash::FxHashSet; use crate::{ @@ -100,7 +100,6 @@ impl<'a, 'b> ExprValidator<'a, 'b> { self.sink.push(MissingFields { file: source_ptr.file_id, field_list: AstPtr::new(&field_list), - highlight_range: field_list.syntax().text_range(), missed_fields, }) } @@ -131,7 +130,6 @@ impl<'a, 'b> ExprValidator<'a, 'b> { self.sink.push(MissingPatFields { file: source_ptr.file_id, field_list: AstPtr::new(&field_list), - highlight_range: field_list.syntax().text_range(), missed_fields, }) } @@ -215,7 +213,6 @@ impl<'a, 'b> ExprValidator<'a, 'b> { file: source_ptr.file_id, match_expr: AstPtr::new(&match_expr), arms: AstPtr::new(&arms), - highlight_range: match_expr.syntax().text_range(), }) } } @@ -247,13 +244,8 @@ impl<'a, 'b> ExprValidator<'a, 'b> { let (_, source_map) = db.body_with_source_map(self.func.into()); if let Ok(source_ptr) = source_map.expr_syntax(id) { - let root = source_ptr.file_syntax(db.upcast()); - let highlight_range = source_ptr.value.to_node(&root).syntax().text_range(); - self.sink.push(MissingOkInTailExpr { - file: source_ptr.file_id, - expr: source_ptr.value, - highlight_range, - }); + self.sink + .push(MissingOkInTailExpr { file: source_ptr.file_id, expr: source_ptr.value }); } } } diff --git a/crates/ra_hir_ty/src/infer.rs b/crates/ra_hir_ty/src/infer.rs index 7e6cdefe4..b6d9b3438 100644 --- a/crates/ra_hir_ty/src/infer.rs +++ b/crates/ra_hir_ty/src/infer.rs @@ -665,7 +665,6 @@ impl Expectation { mod diagnostics { use hir_def::{expr::ExprId, src::HasSource, FunctionId, Lookup}; use hir_expand::diagnostics::DiagnosticSink; - use ra_syntax::AstNode; use crate::{db::HirDatabase, diagnostics::NoSuchField}; @@ -686,13 +685,7 @@ mod diagnostics { let source = owner.lookup(db.upcast()).source(db.upcast()); let (_, source_map) = db.body_with_source_map(owner.into()); let field = source_map.field_syntax(*expr, *field); - let root = field.file_syntax(db.upcast()); - let highlight_range = field.value.to_node(&root).syntax().text_range(); - sink.push(NoSuchField { - file: source.file_id, - field: field.value, - highlight_range, - }) + sink.push(NoSuchField { file: source.file_id, field: field.value }) } } } -- cgit v1.2.3 From 408f914bf4d6719ae68582ae43e2de9d3cb362b0 Mon Sep 17 00:00:00 2001 From: Josh Mcguigan Date: Fri, 17 Apr 2020 05:36:44 -0700 Subject: fix panic on ellipsis in pattern --- crates/ra_hir_ty/src/tests/regression.rs | 49 ++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) (limited to 'crates/ra_hir_ty') diff --git a/crates/ra_hir_ty/src/tests/regression.rs b/crates/ra_hir_ty/src/tests/regression.rs index d69115a2f..61284d672 100644 --- a/crates/ra_hir_ty/src/tests/regression.rs +++ b/crates/ra_hir_ty/src/tests/regression.rs @@ -484,3 +484,52 @@ fn main() { assert_eq!("()", super::type_at_pos(&db, pos)); } + +#[test] +fn issue_3999_slice() { + assert_snapshot!( + infer(r#" +fn foo(params: &[usize]) { + match params { + [ps @ .., _] => {} + } +} +"#), + @r###" + [8; 14) 'params': &[usize] + [26; 81) '{ ... } }': () + [32; 79) 'match ... }': () + [38; 44) 'params': &[usize] + [55; 67) '[ps @ .., _]': [usize] + [65; 66) '_': usize + [71; 73) '{}': () + "### + ); +} + +#[test] +fn issue_3999_struct() { + // rust-analyzer should not panic on seeing this malformed + // record pattern. + assert_snapshot!( + infer(r#" +struct Bar { + a: bool, +} +fn foo(b: Bar) { + match b { + Bar { a: .. } => {}, + } +} +"#), + @r###" + [36; 37) 'b': Bar + [44; 96) '{ ... } }': () + [50; 94) 'match ... }': () + [56; 57) 'b': Bar + [68; 81) 'Bar { a: .. }': Bar + [77; 79) '..': bool + [85; 87) '{}': () + "### + ); +} -- cgit v1.2.3 From fbd95785a6746a8bf100a0417b592f5fa35df882 Mon Sep 17 00:00:00 2001 From: Florian Diebold Date: Fri, 17 Apr 2020 18:27:20 +0200 Subject: Add two more tests for associated types --- crates/ra_hir_ty/src/tests/traits.rs | 174 +++++++++++++++++++++++++++++++++++ 1 file changed, 174 insertions(+) (limited to 'crates/ra_hir_ty') diff --git a/crates/ra_hir_ty/src/tests/traits.rs b/crates/ra_hir_ty/src/tests/traits.rs index 0a889f805..dc517fc4a 100644 --- a/crates/ra_hir_ty/src/tests/traits.rs +++ b/crates/ra_hir_ty/src/tests/traits.rs @@ -2204,3 +2204,177 @@ fn test(x: Box) { ); assert_eq!(t, "()"); } + +#[test] +fn string_to_owned() { + let t = type_at( + r#" +//- /main.rs +struct String {} +pub trait ToOwned { + type Owned; + fn to_owned(&self) -> Self::Owned; +} +impl ToOwned for str { + type Owned = String; +} +fn test() { + "foo".to_owned()<|>; +} +"#, + ); + assert_eq!(t, "String"); +} + +#[test] +fn iterator_chain() { + assert_snapshot!( + infer(r#" +//- /main.rs +#[lang = "fn_once"] +trait FnOnce { + type Output; +} +#[lang = "fn_mut"] +trait FnMut: FnOnce { } + +enum Option { Some(T), None } +use Option::*; + +pub trait Iterator { + type Item; + + fn filter_map(self, f: F) -> FilterMap + where + F: FnMut(Self::Item) -> Option, + { loop {} } + + fn for_each(self, f: F) + where + F: FnMut(Self::Item), + { loop {} } +} + +pub trait IntoIterator { + type Item; + type IntoIter: Iterator; + fn into_iter(self) -> Self::IntoIter; +} + +pub struct FilterMap { } +impl Iterator for FilterMap +where + F: FnMut(I::Item) -> Option, +{ + type Item = B; +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl IntoIterator for I { + type Item = I::Item; + type IntoIter = I; + + fn into_iter(self) -> I { + self + } +} + +struct Vec {} +impl Vec { + fn new() -> Self { loop {} } +} + +impl IntoIterator for Vec { + type Item = T; + type IntoIter = IntoIter; +} + +pub struct IntoIter { } +impl Iterator for IntoIter { + type Item = T; +} + +fn main() { + Vec::::new().into_iter() + .filter_map(|x| if x > 0 { Some(x as u32) } else { None }) + .for_each(|y| { y; }); +} +"#), + @r###" + [240; 244) 'self': Self + [246; 247) 'f': F + [331; 342) '{ loop {} }': FilterMap + [333; 340) 'loop {}': ! + [338; 340) '{}': () + [363; 367) 'self': Self + [369; 370) 'f': F + [419; 430) '{ loop {} }': () + [421; 428) 'loop {}': ! + [426; 428) '{}': () + [539; 543) 'self': Self + [868; 872) 'self': I + [879; 899) '{ ... }': I + [889; 893) 'self': I + [958; 969) '{ loop {} }': Vec + [960; 967) 'loop {}': ! + [965; 967) '{}': () + [1156; 1287) '{ ... }); }': () + [1162; 1177) 'Vec::::new': fn new() -> Vec + [1162; 1179) 'Vec::<...:new()': Vec + [1162; 1191) 'Vec::<...iter()': IntoIter + [1162; 1256) 'Vec::<...one })': FilterMap, |i32| -> Option> + [1162; 1284) 'Vec::<... y; })': () + [1210; 1255) '|x| if...None }': |i32| -> Option + [1211; 1212) 'x': i32 + [1214; 1255) 'if x >...None }': Option + [1217; 1218) 'x': i32 + [1217; 1222) 'x > 0': bool + [1221; 1222) '0': i32 + [1223; 1241) '{ Some...u32) }': Option + [1225; 1229) 'Some': Some(u32) -> Option + [1225; 1239) 'Some(x as u32)': Option + [1230; 1231) 'x': i32 + [1230; 1238) 'x as u32': u32 + [1247; 1255) '{ None }': Option + [1249; 1253) 'None': Option + [1273; 1283) '|y| { y; }': |u32| -> () + [1274; 1275) 'y': u32 + [1277; 1283) '{ y; }': () + [1279; 1280) 'y': u32 + "### + ); +} + +#[test] +fn nested_assoc() { + let t = type_at( + r#" +//- /main.rs +struct Bar; +struct Foo; + +trait A { + type OutputA; +} + +impl A for Bar { + type OutputA = Foo; +} + +trait B { + type Output; + fn foo() -> Self::Output; +} + +impl B for T { + type Output = T::OutputA; + fn foo() -> Self::Output { loop {} } +} + +fn main() { + Bar::foo()<|>; +} +"#, + ); + assert_eq!(t, "Foo"); +} -- cgit v1.2.3 From 6a7fc76b89dca4d1b4e3e50047183535aee98627 Mon Sep 17 00:00:00 2001 From: Florian Diebold Date: Fri, 17 Apr 2020 19:41:37 +0200 Subject: Fix type equality for dyn Trait Fixes a lot of false type mismatches. (And as always when touching the unification code, I have to say I'm looking forward to replacing it by Chalk's...) --- crates/ra_hir_ty/src/infer/coerce.rs | 4 ++-- crates/ra_hir_ty/src/infer/unify.rs | 42 +++++++++++++++++++++++++++++++++--- crates/ra_hir_ty/src/tests/traits.rs | 24 +++++++++++++++++++++ 3 files changed, 65 insertions(+), 5 deletions(-) (limited to 'crates/ra_hir_ty') diff --git a/crates/ra_hir_ty/src/infer/coerce.rs b/crates/ra_hir_ty/src/infer/coerce.rs index 959b1e212..89200255a 100644 --- a/crates/ra_hir_ty/src/infer/coerce.rs +++ b/crates/ra_hir_ty/src/infer/coerce.rs @@ -51,7 +51,7 @@ impl<'a> InferenceContext<'a> { // Trivial cases, this should go after `never` check to // avoid infer result type to be never _ => { - if self.table.unify_inner_trivial(&from_ty, &to_ty) { + if self.table.unify_inner_trivial(&from_ty, &to_ty, 0) { return true; } } @@ -175,7 +175,7 @@ impl<'a> InferenceContext<'a> { return self.table.unify_substs(st1, st2, 0); } _ => { - if self.table.unify_inner_trivial(&derefed_ty, &to_ty) { + if self.table.unify_inner_trivial(&derefed_ty, &to_ty, 0) { return true; } } diff --git a/crates/ra_hir_ty/src/infer/unify.rs b/crates/ra_hir_ty/src/infer/unify.rs index 5f6cea8d3..ab0bc8b70 100644 --- a/crates/ra_hir_ty/src/infer/unify.rs +++ b/crates/ra_hir_ty/src/infer/unify.rs @@ -8,7 +8,8 @@ use test_utils::tested_by; use super::{InferenceContext, Obligation}; use crate::{ - BoundVar, Canonical, DebruijnIndex, InEnvironment, InferTy, Substs, Ty, TypeCtor, TypeWalk, + BoundVar, Canonical, DebruijnIndex, GenericPredicate, InEnvironment, InferTy, Substs, Ty, + TypeCtor, TypeWalk, }; impl<'a> InferenceContext<'a> { @@ -226,16 +227,26 @@ impl InferenceTable { (Ty::Apply(a_ty1), Ty::Apply(a_ty2)) if a_ty1.ctor == a_ty2.ctor => { self.unify_substs(&a_ty1.parameters, &a_ty2.parameters, depth + 1) } - _ => self.unify_inner_trivial(&ty1, &ty2), + + _ => self.unify_inner_trivial(&ty1, &ty2, depth), } } - pub(super) fn unify_inner_trivial(&mut self, ty1: &Ty, ty2: &Ty) -> bool { + pub(super) fn unify_inner_trivial(&mut self, ty1: &Ty, ty2: &Ty, depth: usize) -> bool { match (ty1, ty2) { (Ty::Unknown, _) | (_, Ty::Unknown) => true, (Ty::Placeholder(p1), Ty::Placeholder(p2)) if *p1 == *p2 => true, + (Ty::Dyn(dyn1), Ty::Dyn(dyn2)) if dyn1.len() == dyn2.len() => { + for (pred1, pred2) in dyn1.iter().zip(dyn2.iter()) { + if !self.unify_preds(pred1, pred2, depth + 1) { + return false; + } + } + true + } + (Ty::Infer(InferTy::TypeVar(tv1)), Ty::Infer(InferTy::TypeVar(tv2))) | (Ty::Infer(InferTy::IntVar(tv1)), Ty::Infer(InferTy::IntVar(tv2))) | (Ty::Infer(InferTy::FloatVar(tv1)), Ty::Infer(InferTy::FloatVar(tv2))) @@ -268,6 +279,31 @@ impl InferenceTable { } } + fn unify_preds( + &mut self, + pred1: &GenericPredicate, + pred2: &GenericPredicate, + depth: usize, + ) -> bool { + match (pred1, pred2) { + (GenericPredicate::Implemented(tr1), GenericPredicate::Implemented(tr2)) + if tr1.trait_ == tr2.trait_ => + { + self.unify_substs(&tr1.substs, &tr2.substs, depth + 1) + } + (GenericPredicate::Projection(proj1), GenericPredicate::Projection(proj2)) + if proj1.projection_ty.associated_ty == proj2.projection_ty.associated_ty => + { + self.unify_substs( + &proj1.projection_ty.parameters, + &proj2.projection_ty.parameters, + depth + 1, + ) && self.unify_inner(&proj1.ty, &proj2.ty, depth + 1) + } + _ => false, + } + } + /// If `ty` is a type variable with known type, returns that type; /// otherwise, return ty. pub fn resolve_ty_shallow<'b>(&mut self, ty: &'b Ty) -> Cow<'b, Ty> { diff --git a/crates/ra_hir_ty/src/tests/traits.rs b/crates/ra_hir_ty/src/tests/traits.rs index dc517fc4a..f6e3e07cd 100644 --- a/crates/ra_hir_ty/src/tests/traits.rs +++ b/crates/ra_hir_ty/src/tests/traits.rs @@ -2378,3 +2378,27 @@ fn main() { ); assert_eq!(t, "Foo"); } + +#[test] +fn trait_object_no_coercion() { + assert_snapshot!( + infer_with_mismatches(r#" +trait Foo {} + +fn foo(x: &dyn Foo) {} + +fn test(x: &dyn Foo) { + foo(x); +} +"#, true), + @r###" + [22; 23) 'x': &dyn Foo + [35; 37) '{}': () + [47; 48) 'x': &dyn Foo + [60; 75) '{ foo(x); }': () + [66; 69) 'foo': fn foo(&dyn Foo) + [66; 72) 'foo(x)': () + [70; 71) 'x': &dyn Foo + "### + ); +} -- cgit v1.2.3 From d3cb9ea0bfb6c9e6c8b57a46feb1de696084d994 Mon Sep 17 00:00:00 2001 From: Florian Diebold Date: Fri, 17 Apr 2020 22:48:29 +0200 Subject: Fix another crash from wrong binders Basically, if we had something like `dyn Trait` (where `T` is a type parameter) in an impl we lowered that to `dyn Trait<^0.0>`, when it should be `dyn Trait<^1.0>` because the `dyn` introduces a new binder. With one type parameter, that's just wrong, with two, it'll lead to crashes. --- crates/ra_hir_ty/src/lib.rs | 4 +-- crates/ra_hir_ty/src/lower.rs | 69 +++++++++++++++++++++++++----------- crates/ra_hir_ty/src/tests/traits.rs | 36 +++++++++++++++++++ crates/ra_hir_ty/src/traits/chalk.rs | 10 +++--- 4 files changed, 92 insertions(+), 27 deletions(-) (limited to 'crates/ra_hir_ty') diff --git a/crates/ra_hir_ty/src/lib.rs b/crates/ra_hir_ty/src/lib.rs index 2677f3af2..a4b8d6683 100644 --- a/crates/ra_hir_ty/src/lib.rs +++ b/crates/ra_hir_ty/src/lib.rs @@ -396,12 +396,12 @@ impl Substs { } /// Return Substs that replace each parameter by a bound variable. - pub(crate) fn bound_vars(generic_params: &Generics) -> Substs { + pub(crate) fn bound_vars(generic_params: &Generics, debruijn: DebruijnIndex) -> Substs { Substs( generic_params .iter() .enumerate() - .map(|(idx, _)| Ty::Bound(BoundVar::new(DebruijnIndex::INNERMOST, idx))) + .map(|(idx, _)| Ty::Bound(BoundVar::new(debruijn, idx))) .collect(), ) } diff --git a/crates/ra_hir_ty/src/lower.rs b/crates/ra_hir_ty/src/lower.rs index cc1ac8e3e..c2812e178 100644 --- a/crates/ra_hir_ty/src/lower.rs +++ b/crates/ra_hir_ty/src/lower.rs @@ -39,6 +39,7 @@ use crate::{ pub struct TyLoweringContext<'a> { pub db: &'a dyn HirDatabase, pub resolver: &'a Resolver, + in_binders: DebruijnIndex, /// Note: Conceptually, it's thinkable that we could be in a location where /// some type params should be represented as placeholders, and others /// should be converted to variables. I think in practice, this isn't @@ -53,7 +54,27 @@ impl<'a> TyLoweringContext<'a> { let impl_trait_counter = std::cell::Cell::new(0); let impl_trait_mode = ImplTraitLoweringMode::Disallowed; let type_param_mode = TypeParamLoweringMode::Placeholder; - Self { db, resolver, impl_trait_mode, impl_trait_counter, type_param_mode } + let in_binders = DebruijnIndex::INNERMOST; + Self { db, resolver, in_binders, impl_trait_mode, impl_trait_counter, type_param_mode } + } + + pub fn with_shifted_in( + &self, + debruijn: DebruijnIndex, + f: impl FnOnce(&TyLoweringContext) -> T, + ) -> T { + let new_ctx = Self { + in_binders: self.in_binders.shifted_in_from(debruijn), + impl_trait_counter: std::cell::Cell::new(self.impl_trait_counter.get()), + ..*self + }; + let result = f(&new_ctx); + self.impl_trait_counter.set(new_ctx.impl_trait_counter.get()); + result + } + + pub fn shifted_in(self, debruijn: DebruijnIndex) -> Self { + Self { in_binders: self.in_binders.shifted_in_from(debruijn), ..self } } pub fn with_impl_trait_mode(self, impl_trait_mode: ImplTraitLoweringMode) -> Self { @@ -134,22 +155,26 @@ impl Ty { } TypeRef::DynTrait(bounds) => { let self_ty = Ty::Bound(BoundVar::new(DebruijnIndex::INNERMOST, 0)); - let predicates = bounds - .iter() - .flat_map(|b| GenericPredicate::from_type_bound(ctx, b, self_ty.clone())) - .collect(); + let predicates = ctx.with_shifted_in(DebruijnIndex::ONE, |ctx| { + bounds + .iter() + .flat_map(|b| GenericPredicate::from_type_bound(ctx, b, self_ty.clone())) + .collect() + }); Ty::Dyn(predicates) } TypeRef::ImplTrait(bounds) => { match ctx.impl_trait_mode { ImplTraitLoweringMode::Opaque => { let self_ty = Ty::Bound(BoundVar::new(DebruijnIndex::INNERMOST, 0)); - let predicates = bounds - .iter() - .flat_map(|b| { - GenericPredicate::from_type_bound(ctx, b, self_ty.clone()) - }) - .collect(); + let predicates = ctx.with_shifted_in(DebruijnIndex::ONE, |ctx| { + bounds + .iter() + .flat_map(|b| { + GenericPredicate::from_type_bound(ctx, b, self_ty.clone()) + }) + .collect() + }); Ty::Opaque(predicates) } ImplTraitLoweringMode::Param => { @@ -180,7 +205,7 @@ impl Ty { (0, 0, 0, 0) }; Ty::Bound(BoundVar::new( - DebruijnIndex::INNERMOST, + ctx.in_binders, idx as usize + parent_params + self_params + list_params, )) } @@ -293,7 +318,7 @@ impl Ty { TypeParamLoweringMode::Placeholder => Ty::Placeholder(param_id), TypeParamLoweringMode::Variable => { let idx = generics.param_idx(param_id).expect("matching generics"); - Ty::Bound(BoundVar::new(DebruijnIndex::INNERMOST, idx)) + Ty::Bound(BoundVar::new(ctx.in_binders, idx)) } } } @@ -303,7 +328,9 @@ impl Ty { TypeParamLoweringMode::Placeholder => { Substs::type_params_for_generics(&generics) } - TypeParamLoweringMode::Variable => Substs::bound_vars(&generics), + TypeParamLoweringMode::Variable => { + Substs::bound_vars(&generics, ctx.in_binders) + } }; ctx.db.impl_self_ty(impl_id).subst(&substs) } @@ -313,7 +340,9 @@ impl Ty { TypeParamLoweringMode::Placeholder => { Substs::type_params_for_generics(&generics) } - TypeParamLoweringMode::Variable => Substs::bound_vars(&generics), + TypeParamLoweringMode::Variable => { + Substs::bound_vars(&generics, ctx.in_binders) + } }; ctx.db.ty(adt.into()).subst(&substs) } @@ -797,7 +826,7 @@ fn fn_sig_for_fn(db: &dyn HirDatabase, def: FunctionId) -> PolyFnSig { /// function body. fn type_for_fn(db: &dyn HirDatabase, def: FunctionId) -> Binders { let generics = generics(db.upcast(), def.into()); - let substs = Substs::bound_vars(&generics); + let substs = Substs::bound_vars(&generics, DebruijnIndex::INNERMOST); Binders::new(substs.len(), Ty::apply(TypeCtor::FnDef(def.into()), substs)) } @@ -851,7 +880,7 @@ fn type_for_struct_constructor(db: &dyn HirDatabase, def: StructId) -> Binders Binders { let generics = generics(db.upcast(), adt.into()); - let substs = Substs::bound_vars(&generics); + let substs = Substs::bound_vars(&generics, DebruijnIndex::INNERMOST); Binders::new(substs.len(), Ty::apply(TypeCtor::Adt(adt), substs)) } @@ -892,7 +921,7 @@ fn type_for_type_alias(db: &dyn HirDatabase, t: TypeAliasId) -> Binders { let ctx = TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable); let type_ref = &db.type_alias_data(t).type_ref; - let substs = Substs::bound_vars(&generics); + let substs = Substs::bound_vars(&generics, DebruijnIndex::INNERMOST); let inner = Ty::from_hir(&ctx, type_ref.as_ref().unwrap_or(&TypeRef::Error)); Binders::new(substs.len(), inner) } diff --git a/crates/ra_hir_ty/src/tests/traits.rs b/crates/ra_hir_ty/src/tests/traits.rs index 0a889f805..36f53b264 100644 --- a/crates/ra_hir_ty/src/tests/traits.rs +++ b/crates/ra_hir_ty/src/tests/traits.rs @@ -1210,6 +1210,42 @@ fn test(x: dyn Trait, y: &dyn Trait) { ); } +#[test] +fn dyn_trait_in_impl() { + assert_snapshot!( + infer(r#" +trait Trait { + fn foo(&self) -> (T, U); +} +struct S {} +impl S { + fn bar(&self) -> &dyn Trait { loop {} } +} +trait Trait2 { + fn baz(&self) -> (T, U); +} +impl Trait2 for dyn Trait { } + +fn test(s: S) { + s.bar().baz(); +} +"#), + @r###" + [33; 37) 'self': &Self + [103; 107) 'self': &S + [129; 140) '{ loop {} }': &dyn Trait + [131; 138) 'loop {}': ! + [136; 138) '{}': () + [176; 180) 'self': &Self + [252; 253) 's': S + [268; 290) '{ ...z(); }': () + [274; 275) 's': S + [274; 281) 's.bar()': &dyn Trait + [274; 287) 's.bar().baz()': (u32, i32) + "### + ); +} + #[test] fn dyn_trait_bare() { assert_snapshot!( diff --git a/crates/ra_hir_ty/src/traits/chalk.rs b/crates/ra_hir_ty/src/traits/chalk.rs index 60d70d18e..e00a82db2 100644 --- a/crates/ra_hir_ty/src/traits/chalk.rs +++ b/crates/ra_hir_ty/src/traits/chalk.rs @@ -17,7 +17,7 @@ use ra_db::{ use super::{builtin, AssocTyValue, Canonical, ChalkContext, Impl, Obligation}; use crate::{ db::HirDatabase, display::HirDisplay, method_resolution::TyFingerprint, utils::generics, - ApplicationTy, GenericPredicate, ProjectionTy, Substs, TraitRef, Ty, TypeCtor, + ApplicationTy, DebruijnIndex, GenericPredicate, ProjectionTy, Substs, TraitRef, Ty, TypeCtor, }; pub(super) mod tls; @@ -815,7 +815,7 @@ pub(crate) fn associated_ty_data_query( // Lower bounds -- we could/should maybe move this to a separate query in `lower` let type_alias_data = db.type_alias_data(type_alias); let generic_params = generics(db.upcast(), type_alias.into()); - let bound_vars = Substs::bound_vars(&generic_params); + let bound_vars = Substs::bound_vars(&generic_params, DebruijnIndex::INNERMOST); let resolver = hir_def::resolver::HasResolver::resolver(type_alias, db.upcast()); let ctx = crate::TyLoweringContext::new(db, &resolver) .with_type_param_mode(crate::lower::TypeParamLoweringMode::Variable); @@ -849,7 +849,7 @@ pub(crate) fn trait_datum_query( let trait_data = db.trait_data(trait_); debug!("trait {:?} = {:?}", trait_id, trait_data.name); let generic_params = generics(db.upcast(), trait_.into()); - let bound_vars = Substs::bound_vars(&generic_params); + let bound_vars = Substs::bound_vars(&generic_params, DebruijnIndex::INNERMOST); let flags = chalk_rust_ir::TraitFlags { auto: trait_data.auto, upstream: trait_.lookup(db.upcast()).container.module(db.upcast()).krate != krate, @@ -888,7 +888,7 @@ pub(crate) fn struct_datum_query( .as_generic_def() .map(|generic_def| { let generic_params = generics(db.upcast(), generic_def); - let bound_vars = Substs::bound_vars(&generic_params); + let bound_vars = Substs::bound_vars(&generic_params, DebruijnIndex::INNERMOST); convert_where_clauses(db, generic_def, &bound_vars) }) .unwrap_or_else(Vec::new); @@ -934,7 +934,7 @@ fn impl_def_datum( let impl_data = db.impl_data(impl_id); let generic_params = generics(db.upcast(), impl_id.into()); - let bound_vars = Substs::bound_vars(&generic_params); + let bound_vars = Substs::bound_vars(&generic_params, DebruijnIndex::INNERMOST); let trait_ = trait_ref.trait_; let impl_type = if impl_id.lookup(db.upcast()).container.module(db.upcast()).krate == krate { chalk_rust_ir::ImplType::Local -- cgit v1.2.3