diff options
-rw-r--r-- | crates/ra_assists/src/auto_import.rs | 1 | ||||
-rw-r--r-- | crates/ra_hir/src/code_model.rs | 4 | ||||
-rw-r--r-- | crates/ra_hir/src/diagnostics.rs | 38 | ||||
-rw-r--r-- | crates/ra_hir/src/path.rs | 38 | ||||
-rw-r--r-- | crates/ra_hir/src/ty.rs | 100 | ||||
-rw-r--r-- | crates/ra_hir/src/ty/infer.rs | 47 | ||||
-rw-r--r-- | crates/ra_hir/src/ty/lower.rs | 83 | ||||
-rw-r--r-- | crates/ra_hir/src/ty/tests.rs | 101 | ||||
-rw-r--r-- | crates/ra_hir/src/ty/traits.rs | 8 | ||||
-rw-r--r-- | crates/ra_hir/src/ty/traits/chalk.rs | 51 | ||||
-rw-r--r-- | crates/ra_ide_api/src/diagnostics.rs | 2 | ||||
-rw-r--r-- | crates/ra_lsp_server/src/main_loop.rs | 1 | ||||
-rw-r--r-- | crates/ra_lsp_server/src/main_loop/handlers.rs | 116 | ||||
-rw-r--r-- | crates/ra_lsp_server/src/req.rs | 21 | ||||
-rw-r--r-- | crates/ra_parser/src/grammar/expressions.rs | 19 | ||||
-rw-r--r-- | crates/ra_syntax/src/ast/extensions.rs | 10 | ||||
-rw-r--r-- | crates/ra_syntax/test_data/parser/inline/ok/0138_expression_after_block.rs | 4 | ||||
-rw-r--r-- | crates/ra_syntax/test_data/parser/inline/ok/0138_expression_after_block.txt | 65 | ||||
-rw-r--r-- | editors/emacs/ra-emacs-lsp.el | 73 |
19 files changed, 572 insertions, 210 deletions
diff --git a/crates/ra_assists/src/auto_import.rs b/crates/ra_assists/src/auto_import.rs index a32e2f9b6..1158adbbc 100644 --- a/crates/ra_assists/src/auto_import.rs +++ b/crates/ra_assists/src/auto_import.rs | |||
@@ -71,6 +71,7 @@ fn compare_path_segment(a: &SmolStr, b: &ast::PathSegment) -> bool { | |||
71 | ast::PathSegmentKind::SelfKw => a == "self", | 71 | ast::PathSegmentKind::SelfKw => a == "self", |
72 | ast::PathSegmentKind::SuperKw => a == "super", | 72 | ast::PathSegmentKind::SuperKw => a == "super", |
73 | ast::PathSegmentKind::CrateKw => a == "crate", | 73 | ast::PathSegmentKind::CrateKw => a == "crate", |
74 | ast::PathSegmentKind::Type { .. } => false, // not allowed in imports | ||
74 | } | 75 | } |
75 | } else { | 76 | } else { |
76 | false | 77 | false |
diff --git a/crates/ra_hir/src/code_model.rs b/crates/ra_hir/src/code_model.rs index 779764590..89fc1d1a1 100644 --- a/crates/ra_hir/src/code_model.rs +++ b/crates/ra_hir/src/code_model.rs | |||
@@ -838,6 +838,10 @@ impl TypeAlias { | |||
838 | self.id.module(db) | 838 | self.id.module(db) |
839 | } | 839 | } |
840 | 840 | ||
841 | pub fn krate(self, db: &impl DefDatabase) -> Option<Crate> { | ||
842 | self.module(db).krate(db) | ||
843 | } | ||
844 | |||
841 | /// The containing impl block, if this is a method. | 845 | /// The containing impl block, if this is a method. |
842 | pub fn impl_block(self, db: &impl DefDatabase) -> Option<ImplBlock> { | 846 | pub fn impl_block(self, db: &impl DefDatabase) -> Option<ImplBlock> { |
843 | let module_impls = db.impls_in_module(self.module(db)); | 847 | let module_impls = db.impls_in_module(self.module(db)); |
diff --git a/crates/ra_hir/src/diagnostics.rs b/crates/ra_hir/src/diagnostics.rs index 0290483b3..f6240830f 100644 --- a/crates/ra_hir/src/diagnostics.rs +++ b/crates/ra_hir/src/diagnostics.rs | |||
@@ -3,7 +3,7 @@ use std::{any::Any, fmt}; | |||
3 | use ra_syntax::{ast, AstNode, AstPtr, SyntaxNode, SyntaxNodePtr, TextRange}; | 3 | use ra_syntax::{ast, AstNode, AstPtr, SyntaxNode, SyntaxNodePtr, TextRange}; |
4 | use relative_path::RelativePathBuf; | 4 | use relative_path::RelativePathBuf; |
5 | 5 | ||
6 | use crate::{HirDatabase, HirFileId, Name}; | 6 | use crate::{HirDatabase, HirFileId, Name, Source}; |
7 | 7 | ||
8 | /// Diagnostic defines hir API for errors and warnings. | 8 | /// Diagnostic defines hir API for errors and warnings. |
9 | /// | 9 | /// |
@@ -19,10 +19,9 @@ use crate::{HirDatabase, HirFileId, Name}; | |||
19 | /// instance of `Diagnostic` on demand. | 19 | /// instance of `Diagnostic` on demand. |
20 | pub trait Diagnostic: Any + Send + Sync + fmt::Debug + 'static { | 20 | pub trait Diagnostic: Any + Send + Sync + fmt::Debug + 'static { |
21 | fn message(&self) -> String; | 21 | fn message(&self) -> String; |
22 | fn file(&self) -> HirFileId; | 22 | fn source(&self) -> Source<SyntaxNodePtr>; |
23 | fn syntax_node_ptr(&self) -> SyntaxNodePtr; | ||
24 | fn highlight_range(&self) -> TextRange { | 23 | fn highlight_range(&self) -> TextRange { |
25 | self.syntax_node_ptr().range() | 24 | self.source().ast.range() |
26 | } | 25 | } |
27 | fn as_any(&self) -> &(dyn Any + Send + 'static); | 26 | fn as_any(&self) -> &(dyn Any + Send + 'static); |
28 | } | 27 | } |
@@ -34,8 +33,8 @@ pub trait AstDiagnostic { | |||
34 | 33 | ||
35 | impl dyn Diagnostic { | 34 | impl dyn Diagnostic { |
36 | pub fn syntax_node(&self, db: &impl HirDatabase) -> SyntaxNode { | 35 | pub fn syntax_node(&self, db: &impl HirDatabase) -> SyntaxNode { |
37 | let node = db.parse_or_expand(self.file()).unwrap(); | 36 | let node = db.parse_or_expand(self.source().file_id).unwrap(); |
38 | self.syntax_node_ptr().to_node(&node) | 37 | self.source().ast.to_node(&node) |
39 | } | 38 | } |
40 | 39 | ||
41 | pub fn downcast_ref<D: Diagnostic>(&self) -> Option<&D> { | 40 | pub fn downcast_ref<D: Diagnostic>(&self) -> Option<&D> { |
@@ -87,12 +86,11 @@ impl Diagnostic for NoSuchField { | |||
87 | fn message(&self) -> String { | 86 | fn message(&self) -> String { |
88 | "no such field".to_string() | 87 | "no such field".to_string() |
89 | } | 88 | } |
90 | fn file(&self) -> HirFileId { | 89 | |
91 | self.file | 90 | fn source(&self) -> Source<SyntaxNodePtr> { |
92 | } | 91 | Source { file_id: self.file, ast: self.field.into() } |
93 | fn syntax_node_ptr(&self) -> SyntaxNodePtr { | ||
94 | self.field.into() | ||
95 | } | 92 | } |
93 | |||
96 | fn as_any(&self) -> &(dyn Any + Send + 'static) { | 94 | fn as_any(&self) -> &(dyn Any + Send + 'static) { |
97 | self | 95 | self |
98 | } | 96 | } |
@@ -109,11 +107,8 @@ impl Diagnostic for UnresolvedModule { | |||
109 | fn message(&self) -> String { | 107 | fn message(&self) -> String { |
110 | "unresolved module".to_string() | 108 | "unresolved module".to_string() |
111 | } | 109 | } |
112 | fn file(&self) -> HirFileId { | 110 | fn source(&self) -> Source<SyntaxNodePtr> { |
113 | self.file | 111 | Source { file_id: self.file, ast: self.decl.into() } |
114 | } | ||
115 | fn syntax_node_ptr(&self) -> SyntaxNodePtr { | ||
116 | self.decl.into() | ||
117 | } | 112 | } |
118 | fn as_any(&self) -> &(dyn Any + Send + 'static) { | 113 | fn as_any(&self) -> &(dyn Any + Send + 'static) { |
119 | self | 114 | self |
@@ -131,11 +126,8 @@ impl Diagnostic for MissingFields { | |||
131 | fn message(&self) -> String { | 126 | fn message(&self) -> String { |
132 | "fill structure fields".to_string() | 127 | "fill structure fields".to_string() |
133 | } | 128 | } |
134 | fn file(&self) -> HirFileId { | 129 | fn source(&self) -> Source<SyntaxNodePtr> { |
135 | self.file | 130 | Source { file_id: self.file, ast: self.field_list.into() } |
136 | } | ||
137 | fn syntax_node_ptr(&self) -> SyntaxNodePtr { | ||
138 | self.field_list.into() | ||
139 | } | 131 | } |
140 | fn as_any(&self) -> &(dyn Any + Send + 'static) { | 132 | fn as_any(&self) -> &(dyn Any + Send + 'static) { |
141 | self | 133 | self |
@@ -146,8 +138,8 @@ impl AstDiagnostic for MissingFields { | |||
146 | type AST = ast::NamedFieldList; | 138 | type AST = ast::NamedFieldList; |
147 | 139 | ||
148 | fn ast(&self, db: &impl HirDatabase) -> Self::AST { | 140 | fn ast(&self, db: &impl HirDatabase) -> Self::AST { |
149 | let root = db.parse_or_expand(self.file()).unwrap(); | 141 | let root = db.parse_or_expand(self.source().file_id).unwrap(); |
150 | let node = self.syntax_node_ptr().to_node(&root); | 142 | let node = self.source().ast.to_node(&root); |
151 | ast::NamedFieldList::cast(node).unwrap() | 143 | ast::NamedFieldList::cast(node).unwrap() |
152 | } | 144 | } |
153 | } | 145 | } |
diff --git a/crates/ra_hir/src/path.rs b/crates/ra_hir/src/path.rs index 882db7681..5ee71e421 100644 --- a/crates/ra_hir/src/path.rs +++ b/crates/ra_hir/src/path.rs | |||
@@ -25,6 +25,12 @@ pub struct PathSegment { | |||
25 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] | 25 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] |
26 | pub struct GenericArgs { | 26 | pub struct GenericArgs { |
27 | pub args: Vec<GenericArg>, | 27 | pub args: Vec<GenericArg>, |
28 | /// This specifies whether the args contain a Self type as the first | ||
29 | /// element. This is the case for path segments like `<T as Trait>`, where | ||
30 | /// `T` is actually a type parameter for the path `Trait` specifying the | ||
31 | /// Self type. Otherwise, when we have a path `Trait<X, Y>`, the Self type | ||
32 | /// is left out. | ||
33 | pub has_self_type: bool, | ||
28 | // someday also bindings | 34 | // someday also bindings |
29 | } | 35 | } |
30 | 36 | ||
@@ -74,6 +80,28 @@ impl Path { | |||
74 | let segment = PathSegment { name: name.as_name(), args_and_bindings: args }; | 80 | let segment = PathSegment { name: name.as_name(), args_and_bindings: args }; |
75 | segments.push(segment); | 81 | segments.push(segment); |
76 | } | 82 | } |
83 | ast::PathSegmentKind::Type { type_ref, trait_ref } => { | ||
84 | assert!(path.qualifier().is_none()); // this can only occur at the first segment | ||
85 | |||
86 | // FIXME: handle <T> syntax (type segments without trait) | ||
87 | |||
88 | // <T as Trait<A>>::Foo desugars to Trait<Self=T, A>::Foo | ||
89 | let path = Path::from_ast(trait_ref?.path()?)?; | ||
90 | kind = path.kind; | ||
91 | let mut prefix_segments = path.segments; | ||
92 | prefix_segments.reverse(); | ||
93 | segments.extend(prefix_segments); | ||
94 | // Insert the type reference (T in the above example) as Self parameter for the trait | ||
95 | let self_type = TypeRef::from_ast(type_ref?); | ||
96 | let mut last_segment = segments.last_mut()?; | ||
97 | if last_segment.args_and_bindings.is_none() { | ||
98 | last_segment.args_and_bindings = Some(Arc::new(GenericArgs::empty())); | ||
99 | }; | ||
100 | let args = last_segment.args_and_bindings.as_mut().unwrap(); | ||
101 | let mut args_inner = Arc::make_mut(args); | ||
102 | args_inner.has_self_type = true; | ||
103 | args_inner.args.insert(0, GenericArg::Type(self_type)); | ||
104 | } | ||
77 | ast::PathSegmentKind::CrateKw => { | 105 | ast::PathSegmentKind::CrateKw => { |
78 | kind = PathKind::Crate; | 106 | kind = PathKind::Crate; |
79 | break; | 107 | break; |
@@ -144,11 +172,15 @@ impl GenericArgs { | |||
144 | } | 172 | } |
145 | // lifetimes and assoc type args ignored for now | 173 | // lifetimes and assoc type args ignored for now |
146 | if !args.is_empty() { | 174 | if !args.is_empty() { |
147 | Some(GenericArgs { args }) | 175 | Some(GenericArgs { args, has_self_type: false }) |
148 | } else { | 176 | } else { |
149 | None | 177 | None |
150 | } | 178 | } |
151 | } | 179 | } |
180 | |||
181 | pub(crate) fn empty() -> GenericArgs { | ||
182 | GenericArgs { args: Vec::new(), has_self_type: false } | ||
183 | } | ||
152 | } | 184 | } |
153 | 185 | ||
154 | impl From<Name> for Path { | 186 | impl From<Name> for Path { |
@@ -236,6 +268,10 @@ fn convert_path(prefix: Option<Path>, path: ast::Path) -> Option<Path> { | |||
236 | } | 268 | } |
237 | Path { kind: PathKind::Super, segments: Vec::new() } | 269 | Path { kind: PathKind::Super, segments: Vec::new() } |
238 | } | 270 | } |
271 | ast::PathSegmentKind::Type { .. } => { | ||
272 | // not allowed in imports | ||
273 | return None; | ||
274 | } | ||
239 | }; | 275 | }; |
240 | Some(res) | 276 | Some(res) |
241 | } | 277 | } |
diff --git a/crates/ra_hir/src/ty.rs b/crates/ra_hir/src/ty.rs index 82589e504..642dd02cb 100644 --- a/crates/ra_hir/src/ty.rs +++ b/crates/ra_hir/src/ty.rs | |||
@@ -94,6 +94,12 @@ pub enum TypeCtor { | |||
94 | 94 | ||
95 | /// A tuple type. For example, `(i32, bool)`. | 95 | /// A tuple type. For example, `(i32, bool)`. |
96 | Tuple { cardinality: u16 }, | 96 | Tuple { cardinality: u16 }, |
97 | |||
98 | /// Represents an associated item like `Iterator::Item`. This is used | ||
99 | /// when we have tried to normalize a projection like `T::Item` but | ||
100 | /// couldn't find a better representation. In that case, we generate | ||
101 | /// an **application type** like `(Iterator::Item)<T>`. | ||
102 | AssociatedType(TypeAlias), | ||
97 | } | 103 | } |
98 | 104 | ||
99 | /// A nominal type with (maybe 0) type parameters. This might be a primitive | 105 | /// A nominal type with (maybe 0) type parameters. This might be a primitive |
@@ -114,6 +120,12 @@ pub struct ProjectionTy { | |||
114 | pub parameters: Substs, | 120 | pub parameters: Substs, |
115 | } | 121 | } |
116 | 122 | ||
123 | #[derive(Clone, PartialEq, Eq, Debug, Hash)] | ||
124 | pub struct UnselectedProjectionTy { | ||
125 | pub type_name: Name, | ||
126 | pub parameters: Substs, | ||
127 | } | ||
128 | |||
117 | /// A type. | 129 | /// A type. |
118 | /// | 130 | /// |
119 | /// See also the `TyKind` enum in rustc (librustc/ty/sty.rs), which represents | 131 | /// See also the `TyKind` enum in rustc (librustc/ty/sty.rs), which represents |
@@ -127,6 +139,18 @@ pub enum Ty { | |||
127 | /// several other things. | 139 | /// several other things. |
128 | Apply(ApplicationTy), | 140 | Apply(ApplicationTy), |
129 | 141 | ||
142 | /// A "projection" type corresponds to an (unnormalized) | ||
143 | /// projection like `<P0 as Trait<P1..Pn>>::Foo`. Note that the | ||
144 | /// trait and all its parameters are fully known. | ||
145 | Projection(ProjectionTy), | ||
146 | |||
147 | /// This is a variant of a projection in which the trait is | ||
148 | /// **not** known. It corresponds to a case where people write | ||
149 | /// `T::Item` without specifying the trait. We would then try to | ||
150 | /// figure out the trait by looking at all the traits that are in | ||
151 | /// scope. | ||
152 | UnselectedProjection(UnselectedProjectionTy), | ||
153 | |||
130 | /// A type parameter; for example, `T` in `fn f<T>(x: T) {} | 154 | /// A type parameter; for example, `T` in `fn f<T>(x: T) {} |
131 | Param { | 155 | Param { |
132 | /// The index of the parameter (starting with parameters from the | 156 | /// The index of the parameter (starting with parameters from the |
@@ -352,6 +376,16 @@ impl Ty { | |||
352 | t.walk(f); | 376 | t.walk(f); |
353 | } | 377 | } |
354 | } | 378 | } |
379 | Ty::Projection(p_ty) => { | ||
380 | for t in p_ty.parameters.iter() { | ||
381 | t.walk(f); | ||
382 | } | ||
383 | } | ||
384 | Ty::UnselectedProjection(p_ty) => { | ||
385 | for t in p_ty.parameters.iter() { | ||
386 | t.walk(f); | ||
387 | } | ||
388 | } | ||
355 | Ty::Param { .. } | Ty::Bound(_) | Ty::Infer(_) | Ty::Unknown => {} | 389 | Ty::Param { .. } | Ty::Bound(_) | Ty::Infer(_) | Ty::Unknown => {} |
356 | } | 390 | } |
357 | f(self); | 391 | f(self); |
@@ -362,6 +396,12 @@ impl Ty { | |||
362 | Ty::Apply(a_ty) => { | 396 | Ty::Apply(a_ty) => { |
363 | a_ty.parameters.walk_mut(f); | 397 | a_ty.parameters.walk_mut(f); |
364 | } | 398 | } |
399 | Ty::Projection(p_ty) => { | ||
400 | p_ty.parameters.walk_mut(f); | ||
401 | } | ||
402 | Ty::UnselectedProjection(p_ty) => { | ||
403 | p_ty.parameters.walk_mut(f); | ||
404 | } | ||
365 | Ty::Param { .. } | Ty::Bound(_) | Ty::Infer(_) | Ty::Unknown => {} | 405 | Ty::Param { .. } | Ty::Bound(_) | Ty::Infer(_) | Ty::Unknown => {} |
366 | } | 406 | } |
367 | f(self); | 407 | f(self); |
@@ -572,15 +612,61 @@ impl HirDisplay for ApplicationTy { | |||
572 | write!(f, ">")?; | 612 | write!(f, ">")?; |
573 | } | 613 | } |
574 | } | 614 | } |
615 | TypeCtor::AssociatedType(type_alias) => { | ||
616 | let trait_name = type_alias | ||
617 | .parent_trait(f.db) | ||
618 | .and_then(|t| t.name(f.db)) | ||
619 | .unwrap_or_else(Name::missing); | ||
620 | let name = type_alias.name(f.db); | ||
621 | write!(f, "{}::{}", trait_name, name)?; | ||
622 | if self.parameters.len() > 0 { | ||
623 | write!(f, "<")?; | ||
624 | f.write_joined(&*self.parameters.0, ", ")?; | ||
625 | write!(f, ">")?; | ||
626 | } | ||
627 | } | ||
575 | } | 628 | } |
576 | Ok(()) | 629 | Ok(()) |
577 | } | 630 | } |
578 | } | 631 | } |
579 | 632 | ||
633 | impl HirDisplay for ProjectionTy { | ||
634 | fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result { | ||
635 | let trait_name = self | ||
636 | .associated_ty | ||
637 | .parent_trait(f.db) | ||
638 | .and_then(|t| t.name(f.db)) | ||
639 | .unwrap_or_else(Name::missing); | ||
640 | write!(f, "<{} as {}", self.parameters[0].display(f.db), trait_name,)?; | ||
641 | if self.parameters.len() > 1 { | ||
642 | write!(f, "<")?; | ||
643 | f.write_joined(&self.parameters[1..], ", ")?; | ||
644 | write!(f, ">")?; | ||
645 | } | ||
646 | write!(f, ">::{}", self.associated_ty.name(f.db))?; | ||
647 | Ok(()) | ||
648 | } | ||
649 | } | ||
650 | |||
651 | impl HirDisplay for UnselectedProjectionTy { | ||
652 | fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result { | ||
653 | write!(f, "{}", self.parameters[0].display(f.db))?; | ||
654 | if self.parameters.len() > 1 { | ||
655 | write!(f, "<")?; | ||
656 | f.write_joined(&self.parameters[1..], ", ")?; | ||
657 | write!(f, ">")?; | ||
658 | } | ||
659 | write!(f, "::{}", self.type_name)?; | ||
660 | Ok(()) | ||
661 | } | ||
662 | } | ||
663 | |||
580 | impl HirDisplay for Ty { | 664 | impl HirDisplay for Ty { |
581 | fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result { | 665 | fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result { |
582 | match self { | 666 | match self { |
583 | Ty::Apply(a_ty) => a_ty.hir_fmt(f)?, | 667 | Ty::Apply(a_ty) => a_ty.hir_fmt(f)?, |
668 | Ty::Projection(p_ty) => p_ty.hir_fmt(f)?, | ||
669 | Ty::UnselectedProjection(p_ty) => p_ty.hir_fmt(f)?, | ||
584 | Ty::Param { name, .. } => write!(f, "{}", name)?, | 670 | Ty::Param { name, .. } => write!(f, "{}", name)?, |
585 | Ty::Bound(idx) => write!(f, "?{}", idx)?, | 671 | Ty::Bound(idx) => write!(f, "?{}", idx)?, |
586 | Ty::Unknown => write!(f, "{{unknown}}")?, | 672 | Ty::Unknown => write!(f, "{{unknown}}")?, |
@@ -606,3 +692,17 @@ impl HirDisplay for TraitRef { | |||
606 | Ok(()) | 692 | Ok(()) |
607 | } | 693 | } |
608 | } | 694 | } |
695 | |||
696 | impl HirDisplay for Obligation { | ||
697 | fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result { | ||
698 | match self { | ||
699 | Obligation::Trait(tr) => write!(f, "Implements({})", tr.display(f.db)), | ||
700 | Obligation::Projection(proj) => write!( | ||
701 | f, | ||
702 | "Normalize({} => {})", | ||
703 | proj.projection_ty.display(f.db), | ||
704 | proj.ty.display(f.db) | ||
705 | ), | ||
706 | } | ||
707 | } | ||
708 | } | ||
diff --git a/crates/ra_hir/src/ty/infer.rs b/crates/ra_hir/src/ty/infer.rs index 594c5bc79..675df4a22 100644 --- a/crates/ra_hir/src/ty/infer.rs +++ b/crates/ra_hir/src/ty/infer.rs | |||
@@ -245,7 +245,8 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> { | |||
245 | &self.resolver, | 245 | &self.resolver, |
246 | type_ref, | 246 | type_ref, |
247 | ); | 247 | ); |
248 | self.insert_type_vars(ty) | 248 | let ty = self.insert_type_vars(ty); |
249 | self.normalize_associated_types_in(ty) | ||
249 | } | 250 | } |
250 | 251 | ||
251 | fn unify_substs(&mut self, substs1: &Substs, substs2: &Substs, depth: usize) -> bool { | 252 | fn unify_substs(&mut self, substs1: &Substs, substs2: &Substs, depth: usize) -> bool { |
@@ -411,6 +412,32 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> { | |||
411 | ty | 412 | ty |
412 | } | 413 | } |
413 | 414 | ||
415 | /// Recurses through the given type, normalizing associated types mentioned | ||
416 | /// in it by replacing them by type variables and registering obligations to | ||
417 | /// resolve later. This should be done once for every type we get from some | ||
418 | /// type annotation (e.g. from a let type annotation, field type or function | ||
419 | /// call). `make_ty` handles this already, but e.g. for field types we need | ||
420 | /// to do it as well. | ||
421 | fn normalize_associated_types_in(&mut self, ty: Ty) -> Ty { | ||
422 | let ty = self.resolve_ty_as_possible(&mut vec![], ty); | ||
423 | ty.fold(&mut |ty| match ty { | ||
424 | Ty::Projection(proj_ty) => self.normalize_projection_ty(proj_ty), | ||
425 | Ty::UnselectedProjection(proj_ty) => { | ||
426 | // FIXME use Chalk's unselected projection support | ||
427 | Ty::UnselectedProjection(proj_ty) | ||
428 | } | ||
429 | _ => ty, | ||
430 | }) | ||
431 | } | ||
432 | |||
433 | fn normalize_projection_ty(&mut self, proj_ty: ProjectionTy) -> Ty { | ||
434 | let var = self.new_type_var(); | ||
435 | let predicate = ProjectionPredicate { projection_ty: proj_ty.clone(), ty: var.clone() }; | ||
436 | let obligation = Obligation::Projection(predicate); | ||
437 | self.obligations.push(obligation); | ||
438 | var | ||
439 | } | ||
440 | |||
414 | /// Resolves the type completely; type variables without known type are | 441 | /// Resolves the type completely; type variables without known type are |
415 | /// replaced by Ty::Unknown. | 442 | /// replaced by Ty::Unknown. |
416 | fn resolve_ty_completely(&mut self, tv_stack: &mut Vec<TypeVarId>, ty: Ty) -> Ty { | 443 | fn resolve_ty_completely(&mut self, tv_stack: &mut Vec<TypeVarId>, ty: Ty) -> Ty { |
@@ -549,6 +576,7 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> { | |||
549 | let substs = Ty::substs_from_path(self.db, &self.resolver, path, typable); | 576 | let substs = Ty::substs_from_path(self.db, &self.resolver, path, typable); |
550 | let ty = ty.subst(&substs); | 577 | let ty = ty.subst(&substs); |
551 | let ty = self.insert_type_vars(ty); | 578 | let ty = self.insert_type_vars(ty); |
579 | let ty = self.normalize_associated_types_in(ty); | ||
552 | Some(ty) | 580 | Some(ty) |
553 | } | 581 | } |
554 | Resolution::LocalBinding(pat) => { | 582 | Resolution::LocalBinding(pat) => { |
@@ -670,6 +698,7 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> { | |||
670 | .and_then(|d| d.field(self.db, &Name::tuple_field_name(i))) | 698 | .and_then(|d| d.field(self.db, &Name::tuple_field_name(i))) |
671 | .map_or(Ty::Unknown, |field| field.ty(self.db)) | 699 | .map_or(Ty::Unknown, |field| field.ty(self.db)) |
672 | .subst(&substs); | 700 | .subst(&substs); |
701 | let expected_ty = self.normalize_associated_types_in(expected_ty); | ||
673 | self.infer_pat(subpat, &expected_ty, default_bm); | 702 | self.infer_pat(subpat, &expected_ty, default_bm); |
674 | } | 703 | } |
675 | 704 | ||
@@ -697,6 +726,7 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> { | |||
697 | let matching_field = def.and_then(|it| it.field(self.db, &subpat.name)); | 726 | let matching_field = def.and_then(|it| it.field(self.db, &subpat.name)); |
698 | let expected_ty = | 727 | let expected_ty = |
699 | matching_field.map_or(Ty::Unknown, |field| field.ty(self.db)).subst(&substs); | 728 | matching_field.map_or(Ty::Unknown, |field| field.ty(self.db)).subst(&substs); |
729 | let expected_ty = self.normalize_associated_types_in(expected_ty); | ||
700 | self.infer_pat(subpat.pat, &expected_ty, default_bm); | 730 | self.infer_pat(subpat.pat, &expected_ty, default_bm); |
701 | } | 731 | } |
702 | 732 | ||
@@ -927,9 +957,11 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> { | |||
927 | self.unify(&expected_receiver_ty, &actual_receiver_ty); | 957 | self.unify(&expected_receiver_ty, &actual_receiver_ty); |
928 | 958 | ||
929 | let param_iter = param_tys.into_iter().chain(repeat(Ty::Unknown)); | 959 | let param_iter = param_tys.into_iter().chain(repeat(Ty::Unknown)); |
930 | for (arg, param) in args.iter().zip(param_iter) { | 960 | for (arg, param_ty) in args.iter().zip(param_iter) { |
931 | self.infer_expr(*arg, &Expectation::has_type(param)); | 961 | let param_ty = self.normalize_associated_types_in(param_ty); |
962 | self.infer_expr(*arg, &Expectation::has_type(param_ty)); | ||
932 | } | 963 | } |
964 | let ret_ty = self.normalize_associated_types_in(ret_ty); | ||
933 | ret_ty | 965 | ret_ty |
934 | } | 966 | } |
935 | 967 | ||
@@ -1020,9 +1052,11 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> { | |||
1020 | }; | 1052 | }; |
1021 | self.register_obligations_for_call(&callee_ty); | 1053 | self.register_obligations_for_call(&callee_ty); |
1022 | let param_iter = param_tys.into_iter().chain(repeat(Ty::Unknown)); | 1054 | let param_iter = param_tys.into_iter().chain(repeat(Ty::Unknown)); |
1023 | for (arg, param) in args.iter().zip(param_iter) { | 1055 | for (arg, param_ty) in args.iter().zip(param_iter) { |
1024 | self.infer_expr(*arg, &Expectation::has_type(param)); | 1056 | let param_ty = self.normalize_associated_types_in(param_ty); |
1057 | self.infer_expr(*arg, &Expectation::has_type(param_ty)); | ||
1025 | } | 1058 | } |
1059 | let ret_ty = self.normalize_associated_types_in(ret_ty); | ||
1026 | ret_ty | 1060 | ret_ty |
1027 | } | 1061 | } |
1028 | Expr::MethodCall { receiver, args, method_name, generic_args } => self | 1062 | Expr::MethodCall { receiver, args, method_name, generic_args } => self |
@@ -1120,7 +1154,8 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> { | |||
1120 | _ => None, | 1154 | _ => None, |
1121 | }) | 1155 | }) |
1122 | .unwrap_or(Ty::Unknown); | 1156 | .unwrap_or(Ty::Unknown); |
1123 | self.insert_type_vars(ty) | 1157 | let ty = self.insert_type_vars(ty); |
1158 | self.normalize_associated_types_in(ty) | ||
1124 | } | 1159 | } |
1125 | Expr::Await { expr } => { | 1160 | Expr::Await { expr } => { |
1126 | let inner_ty = self.infer_expr(*expr, &Expectation::none()); | 1161 | let inner_ty = self.infer_expr(*expr, &Expectation::none()); |
diff --git a/crates/ra_hir/src/ty/lower.rs b/crates/ra_hir/src/ty/lower.rs index 894ba0695..debedcbb8 100644 --- a/crates/ra_hir/src/ty/lower.rs +++ b/crates/ra_hir/src/ty/lower.rs | |||
@@ -8,7 +8,7 @@ | |||
8 | use std::iter; | 8 | use std::iter; |
9 | use std::sync::Arc; | 9 | use std::sync::Arc; |
10 | 10 | ||
11 | use super::{FnSig, GenericPredicate, Substs, TraitRef, Ty, TypeCtor}; | 11 | use super::{FnSig, GenericPredicate, ProjectionTy, Substs, TraitRef, Ty, TypeCtor}; |
12 | use crate::{ | 12 | use crate::{ |
13 | adt::VariantDef, | 13 | adt::VariantDef, |
14 | generics::HasGenericParams, | 14 | generics::HasGenericParams, |
@@ -64,7 +64,8 @@ impl Ty { | |||
64 | 64 | ||
65 | pub(crate) fn from_hir_path(db: &impl HirDatabase, resolver: &Resolver, path: &Path) -> Self { | 65 | pub(crate) fn from_hir_path(db: &impl HirDatabase, resolver: &Resolver, path: &Path) -> Self { |
66 | // Resolve the path (in type namespace) | 66 | // Resolve the path (in type namespace) |
67 | let resolution = resolver.resolve_path_without_assoc_items(db, path).take_types(); | 67 | let (resolution, remaining_index) = resolver.resolve_path_segments(db, path).into_inner(); |
68 | let resolution = resolution.take_types(); | ||
68 | 69 | ||
69 | let def = match resolution { | 70 | let def = match resolution { |
70 | Some(Resolution::Def(def)) => def, | 71 | Some(Resolution::Def(def)) => def, |
@@ -73,6 +74,10 @@ impl Ty { | |||
73 | panic!("path resolved to local binding in type ns"); | 74 | panic!("path resolved to local binding in type ns"); |
74 | } | 75 | } |
75 | Some(Resolution::GenericParam(idx)) => { | 76 | Some(Resolution::GenericParam(idx)) => { |
77 | if remaining_index.is_some() { | ||
78 | // e.g. T::Item | ||
79 | return Ty::Unknown; | ||
80 | } | ||
76 | return Ty::Param { | 81 | return Ty::Param { |
77 | idx, | 82 | idx, |
78 | // FIXME: maybe return name in resolution? | 83 | // FIXME: maybe return name in resolution? |
@@ -83,18 +88,54 @@ impl Ty { | |||
83 | }; | 88 | }; |
84 | } | 89 | } |
85 | Some(Resolution::SelfType(impl_block)) => { | 90 | Some(Resolution::SelfType(impl_block)) => { |
91 | if remaining_index.is_some() { | ||
92 | // e.g. Self::Item | ||
93 | return Ty::Unknown; | ||
94 | } | ||
86 | return impl_block.target_ty(db); | 95 | return impl_block.target_ty(db); |
87 | } | 96 | } |
88 | None => return Ty::Unknown, | 97 | None => { |
98 | // path did not resolve | ||
99 | return Ty::Unknown; | ||
100 | } | ||
89 | }; | 101 | }; |
90 | 102 | ||
91 | let typable: TypableDef = match def.into() { | 103 | if let ModuleDef::Trait(trait_) = def { |
92 | None => return Ty::Unknown, | 104 | let segment = match remaining_index { |
93 | Some(it) => it, | 105 | None => path.segments.last().expect("resolved path has at least one element"), |
94 | }; | 106 | Some(i) => &path.segments[i - 1], |
95 | let ty = db.type_for_def(typable, Namespace::Types); | 107 | }; |
96 | let substs = Ty::substs_from_path(db, resolver, path, typable); | 108 | let trait_ref = TraitRef::from_resolved_path(db, resolver, trait_, segment, None); |
97 | ty.subst(&substs) | 109 | if let Some(remaining_index) = remaining_index { |
110 | if remaining_index == path.segments.len() - 1 { | ||
111 | let segment = &path.segments[remaining_index]; | ||
112 | let associated_ty = | ||
113 | match trait_ref.trait_.associated_type_by_name(db, segment.name.clone()) { | ||
114 | Some(t) => t, | ||
115 | None => { | ||
116 | // associated type not found | ||
117 | return Ty::Unknown; | ||
118 | } | ||
119 | }; | ||
120 | // FIXME handle type parameters on the segment | ||
121 | Ty::Projection(ProjectionTy { associated_ty, parameters: trait_ref.substs }) | ||
122 | } else { | ||
123 | // FIXME more than one segment remaining, is this possible? | ||
124 | Ty::Unknown | ||
125 | } | ||
126 | } else { | ||
127 | // FIXME dyn Trait without the dyn | ||
128 | Ty::Unknown | ||
129 | } | ||
130 | } else { | ||
131 | let typable: TypableDef = match def.into() { | ||
132 | None => return Ty::Unknown, | ||
133 | Some(it) => it, | ||
134 | }; | ||
135 | let ty = db.type_for_def(typable, Namespace::Types); | ||
136 | let substs = Ty::substs_from_path(db, resolver, path, typable); | ||
137 | ty.subst(&substs) | ||
138 | } | ||
98 | } | 139 | } |
99 | 140 | ||
100 | pub(super) fn substs_from_path_segment( | 141 | pub(super) fn substs_from_path_segment( |
@@ -219,14 +260,25 @@ impl TraitRef { | |||
219 | Resolution::Def(ModuleDef::Trait(tr)) => tr, | 260 | Resolution::Def(ModuleDef::Trait(tr)) => tr, |
220 | _ => return None, | 261 | _ => return None, |
221 | }; | 262 | }; |
222 | let mut substs = Self::substs_from_path(db, resolver, path, resolved); | 263 | let segment = path.segments.last().expect("path should have at least one segment"); |
264 | Some(TraitRef::from_resolved_path(db, resolver, resolved, segment, explicit_self_ty)) | ||
265 | } | ||
266 | |||
267 | fn from_resolved_path( | ||
268 | db: &impl HirDatabase, | ||
269 | resolver: &Resolver, | ||
270 | resolved: Trait, | ||
271 | segment: &PathSegment, | ||
272 | explicit_self_ty: Option<Ty>, | ||
273 | ) -> Self { | ||
274 | let mut substs = TraitRef::substs_from_path(db, resolver, segment, resolved); | ||
223 | if let Some(self_ty) = explicit_self_ty { | 275 | if let Some(self_ty) = explicit_self_ty { |
224 | // FIXME this could be nicer | 276 | // FIXME this could be nicer |
225 | let mut substs_vec = substs.0.to_vec(); | 277 | let mut substs_vec = substs.0.to_vec(); |
226 | substs_vec[0] = self_ty; | 278 | substs_vec[0] = self_ty; |
227 | substs.0 = substs_vec.into(); | 279 | substs.0 = substs_vec.into(); |
228 | } | 280 | } |
229 | Some(TraitRef { trait_: resolved, substs }) | 281 | TraitRef { trait_: resolved, substs } |
230 | } | 282 | } |
231 | 283 | ||
232 | pub(crate) fn from_hir( | 284 | pub(crate) fn from_hir( |
@@ -245,11 +297,12 @@ impl TraitRef { | |||
245 | fn substs_from_path( | 297 | fn substs_from_path( |
246 | db: &impl HirDatabase, | 298 | db: &impl HirDatabase, |
247 | resolver: &Resolver, | 299 | resolver: &Resolver, |
248 | path: &Path, | 300 | segment: &PathSegment, |
249 | resolved: Trait, | 301 | resolved: Trait, |
250 | ) -> Substs { | 302 | ) -> Substs { |
251 | let segment = path.segments.last().expect("path should have at least one segment"); | 303 | let has_self_param = |
252 | substs_from_path_segment(db, resolver, segment, Some(resolved.into()), true) | 304 | segment.args_and_bindings.as_ref().map(|a| a.has_self_type).unwrap_or(false); |
305 | substs_from_path_segment(db, resolver, segment, Some(resolved.into()), !has_self_param) | ||
253 | } | 306 | } |
254 | 307 | ||
255 | pub(crate) fn for_trait(db: &impl HirDatabase, trait_: Trait) -> TraitRef { | 308 | pub(crate) fn for_trait(db: &impl HirDatabase, trait_: Trait) -> TraitRef { |
diff --git a/crates/ra_hir/src/ty/tests.rs b/crates/ra_hir/src/ty/tests.rs index d5f7a4d25..28727bb18 100644 --- a/crates/ra_hir/src/ty/tests.rs +++ b/crates/ra_hir/src/ty/tests.rs | |||
@@ -2508,15 +2508,55 @@ struct S; | |||
2508 | impl Iterable for S { type Item = u32; } | 2508 | impl Iterable for S { type Item = u32; } |
2509 | fn test<T: Iterable>() { | 2509 | fn test<T: Iterable>() { |
2510 | let x: <S as Iterable>::Item = 1; | 2510 | let x: <S as Iterable>::Item = 1; |
2511 | let y: T::Item = no_matter; | 2511 | let y: <T as Iterable>::Item = no_matter; |
2512 | let z: T::Item = no_matter; | ||
2512 | } | 2513 | } |
2513 | "#), | 2514 | "#), |
2514 | @r###" | 2515 | @r###" |
2515 | [108; 181) '{ ...ter; }': () | 2516 | ⋮ |
2516 | [118; 119) 'x': i32 | 2517 | ⋮[108; 227) '{ ...ter; }': () |
2517 | [145; 146) '1': i32 | 2518 | ⋮[118; 119) 'x': u32 |
2518 | [156; 157) 'y': {unknown} | 2519 | ⋮[145; 146) '1': u32 |
2519 | [169; 178) 'no_matter': {unknown}"### | 2520 | ⋮[156; 157) 'y': {unknown} |
2521 | ⋮[183; 192) 'no_matter': {unknown} | ||
2522 | ⋮[202; 203) 'z': {unknown} | ||
2523 | ⋮[215; 224) 'no_matter': {unknown} | ||
2524 | "### | ||
2525 | ); | ||
2526 | } | ||
2527 | |||
2528 | #[test] | ||
2529 | fn infer_return_associated_type() { | ||
2530 | assert_snapshot_matches!( | ||
2531 | infer(r#" | ||
2532 | trait Iterable { | ||
2533 | type Item; | ||
2534 | } | ||
2535 | struct S; | ||
2536 | impl Iterable for S { type Item = u32; } | ||
2537 | fn foo1<T: Iterable>(t: T) -> T::Item {} | ||
2538 | fn foo2<T: Iterable>(t: T) -> <T as Iterable>::Item {} | ||
2539 | fn test() { | ||
2540 | let x = foo1(S); | ||
2541 | let y = foo2(S); | ||
2542 | } | ||
2543 | "#), | ||
2544 | @r###" | ||
2545 | ⋮ | ||
2546 | ⋮[106; 107) 't': T | ||
2547 | ⋮[123; 125) '{}': () | ||
2548 | ⋮[147; 148) 't': T | ||
2549 | ⋮[178; 180) '{}': () | ||
2550 | ⋮[191; 236) '{ ...(S); }': () | ||
2551 | ⋮[201; 202) 'x': {unknown} | ||
2552 | ⋮[205; 209) 'foo1': fn foo1<S>(T) -> {unknown} | ||
2553 | ⋮[205; 212) 'foo1(S)': {unknown} | ||
2554 | ⋮[210; 211) 'S': S | ||
2555 | ⋮[222; 223) 'y': u32 | ||
2556 | ⋮[226; 230) 'foo2': fn foo2<S>(T) -> <T as Iterable>::Item | ||
2557 | ⋮[226; 233) 'foo2(S)': u32 | ||
2558 | ⋮[231; 232) 'S': S | ||
2559 | "### | ||
2520 | ); | 2560 | ); |
2521 | } | 2561 | } |
2522 | 2562 | ||
@@ -3141,6 +3181,55 @@ fn test<T: Trait>(t: T) { (*t)<|>; } | |||
3141 | assert_eq!(t, "i128"); | 3181 | assert_eq!(t, "i128"); |
3142 | } | 3182 | } |
3143 | 3183 | ||
3184 | #[test] | ||
3185 | fn associated_type_placeholder() { | ||
3186 | let t = type_at( | ||
3187 | r#" | ||
3188 | //- /main.rs | ||
3189 | pub trait ApplyL { | ||
3190 | type Out; | ||
3191 | } | ||
3192 | |||
3193 | pub struct RefMutL<T>; | ||
3194 | |||
3195 | impl<T> ApplyL for RefMutL<T> { | ||
3196 | type Out = <T as ApplyL>::Out; | ||
3197 | } | ||
3198 | |||
3199 | fn test<T: ApplyL>() { | ||
3200 | let y: <RefMutL<T> as ApplyL>::Out = no_matter; | ||
3201 | y<|>; | ||
3202 | } | ||
3203 | "#, | ||
3204 | ); | ||
3205 | // inside the generic function, the associated type gets normalized to a placeholder `ApplL::Out<T>` [https://rust-lang.github.io/rustc-guide/traits/associated-types.html#placeholder-associated-types]. | ||
3206 | // FIXME: fix type parameter names going missing when going through Chalk | ||
3207 | assert_eq!(t, "ApplyL::Out<[missing name]>"); | ||
3208 | } | ||
3209 | |||
3210 | #[test] | ||
3211 | fn associated_type_placeholder_2() { | ||
3212 | let t = type_at( | ||
3213 | r#" | ||
3214 | //- /main.rs | ||
3215 | pub trait ApplyL { | ||
3216 | type Out; | ||
3217 | } | ||
3218 | fn foo<T: ApplyL>(t: T) -> <T as ApplyL>::Out; | ||
3219 | |||
3220 | fn test<T: ApplyL>(t: T) { | ||
3221 | let y = foo(t); | ||
3222 | y<|>; | ||
3223 | } | ||
3224 | "#, | ||
3225 | ); | ||
3226 | // FIXME here Chalk doesn't normalize the type to a placeholder. I think we | ||
3227 | // need to add a rule like Normalize(<T as ApplyL>::Out -> ApplyL::Out<T>) | ||
3228 | // to the trait env ourselves here; probably Chalk can't do this by itself. | ||
3229 | // assert_eq!(t, "ApplyL::Out<[missing name]>"); | ||
3230 | assert_eq!(t, "{unknown}"); | ||
3231 | } | ||
3232 | |||
3144 | fn type_at_pos(db: &MockDatabase, pos: FilePosition) -> String { | 3233 | fn type_at_pos(db: &MockDatabase, pos: FilePosition) -> String { |
3145 | let file = db.parse(pos.file_id).ok().unwrap(); | 3234 | let file = db.parse(pos.file_id).ok().unwrap(); |
3146 | let expr = algo::find_node_at_offset::<ast::Expr>(file.syntax(), pos.offset).unwrap(); | 3235 | let expr = algo::find_node_at_offset::<ast::Expr>(file.syntax(), pos.offset).unwrap(); |
diff --git a/crates/ra_hir/src/ty/traits.rs b/crates/ra_hir/src/ty/traits.rs index 0769e6e17..fde5d8a47 100644 --- a/crates/ra_hir/src/ty/traits.rs +++ b/crates/ra_hir/src/ty/traits.rs | |||
@@ -7,7 +7,7 @@ use parking_lot::Mutex; | |||
7 | use ra_prof::profile; | 7 | use ra_prof::profile; |
8 | use rustc_hash::FxHashSet; | 8 | use rustc_hash::FxHashSet; |
9 | 9 | ||
10 | use super::{Canonical, GenericPredicate, ProjectionTy, TraitRef, Ty}; | 10 | use super::{Canonical, GenericPredicate, HirDisplay, ProjectionTy, TraitRef, Ty}; |
11 | use crate::{db::HirDatabase, Crate, ImplBlock, Trait}; | 11 | use crate::{db::HirDatabase, Crate, ImplBlock, Trait}; |
12 | 12 | ||
13 | use self::chalk::{from_chalk, ToChalk}; | 13 | use self::chalk::{from_chalk, ToChalk}; |
@@ -61,7 +61,6 @@ fn solve( | |||
61 | ) -> Option<chalk_solve::Solution> { | 61 | ) -> Option<chalk_solve::Solution> { |
62 | let context = ChalkContext { db, krate }; | 62 | let context = ChalkContext { db, krate }; |
63 | let solver = db.trait_solver(krate); | 63 | let solver = db.trait_solver(krate); |
64 | debug!("solve goal: {:?}", goal); | ||
65 | let solution = solver.lock().solve(&context, goal); | 64 | let solution = solver.lock().solve(&context, goal); |
66 | debug!("solve({:?}) => {:?}", goal, solution); | 65 | debug!("solve({:?}) => {:?}", goal, solution); |
67 | solution | 66 | solution |
@@ -120,10 +119,11 @@ pub struct ProjectionPredicate { | |||
120 | pub(crate) fn trait_solve_query( | 119 | pub(crate) fn trait_solve_query( |
121 | db: &impl HirDatabase, | 120 | db: &impl HirDatabase, |
122 | krate: Crate, | 121 | krate: Crate, |
123 | trait_ref: Canonical<InEnvironment<Obligation>>, | 122 | goal: Canonical<InEnvironment<Obligation>>, |
124 | ) -> Option<Solution> { | 123 | ) -> Option<Solution> { |
125 | let _p = profile("trait_solve_query"); | 124 | let _p = profile("trait_solve_query"); |
126 | let canonical = trait_ref.to_chalk(db).cast(); | 125 | debug!("trait_solve_query({})", goal.value.value.display(db)); |
126 | let canonical = goal.to_chalk(db).cast(); | ||
127 | // We currently don't deal with universes (I think / hope they're not yet | 127 | // We currently don't deal with universes (I think / hope they're not yet |
128 | // relevant for our use cases?) | 128 | // relevant for our use cases?) |
129 | let u_canonical = chalk_ir::UCanonical { canonical, universes: 1 }; | 129 | let u_canonical = chalk_ir::UCanonical { canonical, universes: 1 }; |
diff --git a/crates/ra_hir/src/ty/traits/chalk.rs b/crates/ra_hir/src/ty/traits/chalk.rs index 9e7ae0724..6df7094c5 100644 --- a/crates/ra_hir/src/ty/traits/chalk.rs +++ b/crates/ra_hir/src/ty/traits/chalk.rs | |||
@@ -45,11 +45,33 @@ impl ToChalk for Ty { | |||
45 | fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::Ty { | 45 | fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::Ty { |
46 | match self { | 46 | match self { |
47 | Ty::Apply(apply_ty) => { | 47 | Ty::Apply(apply_ty) => { |
48 | let struct_id = apply_ty.ctor.to_chalk(db); | 48 | let name = match apply_ty.ctor { |
49 | let name = TypeName::TypeKindId(struct_id.into()); | 49 | TypeCtor::AssociatedType(type_alias) => { |
50 | let type_id = type_alias.to_chalk(db); | ||
51 | TypeName::AssociatedType(type_id) | ||
52 | } | ||
53 | _ => { | ||
54 | // other TypeCtors get interned and turned into a chalk StructId | ||
55 | let struct_id = apply_ty.ctor.to_chalk(db); | ||
56 | TypeName::TypeKindId(struct_id.into()) | ||
57 | } | ||
58 | }; | ||
50 | let parameters = apply_ty.parameters.to_chalk(db); | 59 | let parameters = apply_ty.parameters.to_chalk(db); |
51 | chalk_ir::ApplicationTy { name, parameters }.cast() | 60 | chalk_ir::ApplicationTy { name, parameters }.cast() |
52 | } | 61 | } |
62 | Ty::Projection(proj_ty) => { | ||
63 | let associated_ty_id = proj_ty.associated_ty.to_chalk(db); | ||
64 | let parameters = proj_ty.parameters.to_chalk(db); | ||
65 | chalk_ir::ProjectionTy { associated_ty_id, parameters }.cast() | ||
66 | } | ||
67 | Ty::UnselectedProjection(proj_ty) => { | ||
68 | let type_name = lalrpop_intern::intern(&proj_ty.type_name.to_string()); | ||
69 | let parameters = proj_ty.parameters.to_chalk(db); | ||
70 | chalk_ir::Ty::UnselectedProjection(chalk_ir::UnselectedProjectionTy { | ||
71 | type_name, | ||
72 | parameters, | ||
73 | }) | ||
74 | } | ||
53 | Ty::Param { idx, .. } => { | 75 | Ty::Param { idx, .. } => { |
54 | PlaceholderIndex { ui: UniverseIndex::ROOT, idx: idx as usize }.to_ty() | 76 | PlaceholderIndex { ui: UniverseIndex::ROOT, idx: idx as usize }.to_ty() |
55 | } | 77 | } |
@@ -66,15 +88,21 @@ impl ToChalk for Ty { | |||
66 | fn from_chalk(db: &impl HirDatabase, chalk: chalk_ir::Ty) -> Self { | 88 | fn from_chalk(db: &impl HirDatabase, chalk: chalk_ir::Ty) -> Self { |
67 | match chalk { | 89 | match chalk { |
68 | chalk_ir::Ty::Apply(apply_ty) => { | 90 | chalk_ir::Ty::Apply(apply_ty) => { |
91 | // FIXME this is kind of hacky due to the fact that | ||
92 | // TypeName::Placeholder is a Ty::Param on our side | ||
69 | match apply_ty.name { | 93 | match apply_ty.name { |
70 | TypeName::TypeKindId(TypeKindId::StructId(struct_id)) => { | 94 | TypeName::TypeKindId(TypeKindId::StructId(struct_id)) => { |
71 | let ctor = from_chalk(db, struct_id); | 95 | let ctor = from_chalk(db, struct_id); |
72 | let parameters = from_chalk(db, apply_ty.parameters); | 96 | let parameters = from_chalk(db, apply_ty.parameters); |
73 | Ty::Apply(ApplicationTy { ctor, parameters }) | 97 | Ty::Apply(ApplicationTy { ctor, parameters }) |
74 | } | 98 | } |
99 | TypeName::AssociatedType(type_id) => { | ||
100 | let ctor = TypeCtor::AssociatedType(from_chalk(db, type_id)); | ||
101 | let parameters = from_chalk(db, apply_ty.parameters); | ||
102 | Ty::Apply(ApplicationTy { ctor, parameters }) | ||
103 | } | ||
75 | // FIXME handle TypeKindId::Trait/Type here | 104 | // FIXME handle TypeKindId::Trait/Type here |
76 | TypeName::TypeKindId(_) => unimplemented!(), | 105 | TypeName::TypeKindId(_) => unimplemented!(), |
77 | TypeName::AssociatedType(_) => unimplemented!(), | ||
78 | TypeName::Placeholder(idx) => { | 106 | TypeName::Placeholder(idx) => { |
79 | assert_eq!(idx.ui, UniverseIndex::ROOT); | 107 | assert_eq!(idx.ui, UniverseIndex::ROOT); |
80 | Ty::Param { idx: idx.idx as u32, name: crate::Name::missing() } | 108 | Ty::Param { idx: idx.idx as u32, name: crate::Name::missing() } |
@@ -389,11 +417,12 @@ where | |||
389 | &self, | 417 | &self, |
390 | projection: &'p chalk_ir::ProjectionTy, | 418 | projection: &'p chalk_ir::ProjectionTy, |
391 | ) -> (Arc<AssociatedTyDatum>, &'p [Parameter], &'p [Parameter]) { | 419 | ) -> (Arc<AssociatedTyDatum>, &'p [Parameter], &'p [Parameter]) { |
392 | debug!("split_projection {:?}", projection); | 420 | let proj_ty: ProjectionTy = from_chalk(self.db, projection.clone()); |
393 | unimplemented!() | 421 | debug!("split_projection {:?} = {}", projection, proj_ty.display(self.db)); |
422 | // we don't support GATs, so I think this should always be correct currently | ||
423 | (self.db.associated_ty_data(projection.associated_ty_id), &projection.parameters, &[]) | ||
394 | } | 424 | } |
395 | fn custom_clauses(&self) -> Vec<chalk_ir::ProgramClause> { | 425 | fn custom_clauses(&self) -> Vec<chalk_ir::ProgramClause> { |
396 | debug!("custom_clauses"); | ||
397 | vec![] | 426 | vec![] |
398 | } | 427 | } |
399 | fn all_structs(&self) -> Vec<chalk_ir::StructId> { | 428 | fn all_structs(&self) -> Vec<chalk_ir::StructId> { |
@@ -529,6 +558,16 @@ pub(crate) fn struct_datum_query( | |||
529 | adt.krate(db) != Some(krate), | 558 | adt.krate(db) != Some(krate), |
530 | ) | 559 | ) |
531 | } | 560 | } |
561 | TypeCtor::AssociatedType(type_alias) => { | ||
562 | let generic_params = type_alias.generic_params(db); | ||
563 | let bound_vars = Substs::bound_vars(&generic_params); | ||
564 | let where_clauses = convert_where_clauses(db, type_alias.into(), &bound_vars); | ||
565 | ( | ||
566 | generic_params.count_params_including_parent(), | ||
567 | where_clauses, | ||
568 | type_alias.krate(db) != Some(krate), | ||
569 | ) | ||
570 | } | ||
532 | }; | 571 | }; |
533 | let flags = chalk_rust_ir::StructFlags { | 572 | let flags = chalk_rust_ir::StructFlags { |
534 | upstream, | 573 | upstream, |
diff --git a/crates/ra_ide_api/src/diagnostics.rs b/crates/ra_ide_api/src/diagnostics.rs index 028dc3d4f..98b840b26 100644 --- a/crates/ra_ide_api/src/diagnostics.rs +++ b/crates/ra_ide_api/src/diagnostics.rs | |||
@@ -48,7 +48,7 @@ pub(crate) fn diagnostics(db: &RootDatabase, file_id: FileId) -> Vec<Diagnostic> | |||
48 | }) | 48 | }) |
49 | }) | 49 | }) |
50 | .on::<hir::diagnostics::UnresolvedModule, _>(|d| { | 50 | .on::<hir::diagnostics::UnresolvedModule, _>(|d| { |
51 | let source_root = db.file_source_root(d.file().original_file(db)); | 51 | let source_root = db.file_source_root(d.source().file_id.original_file(db)); |
52 | let create_file = FileSystemEdit::CreateFile { source_root, path: d.candidate.clone() }; | 52 | let create_file = FileSystemEdit::CreateFile { source_root, path: d.candidate.clone() }; |
53 | let fix = SourceChange::file_system_edit("create module", create_file); | 53 | let fix = SourceChange::file_system_edit("create module", create_file); |
54 | res.borrow_mut().push(Diagnostic { | 54 | res.borrow_mut().push(Diagnostic { |
diff --git a/crates/ra_lsp_server/src/main_loop.rs b/crates/ra_lsp_server/src/main_loop.rs index 9d540a87e..b9c99a223 100644 --- a/crates/ra_lsp_server/src/main_loop.rs +++ b/crates/ra_lsp_server/src/main_loop.rs | |||
@@ -346,7 +346,6 @@ fn on_request( | |||
346 | })? | 346 | })? |
347 | .on::<req::AnalyzerStatus>(handlers::handle_analyzer_status)? | 347 | .on::<req::AnalyzerStatus>(handlers::handle_analyzer_status)? |
348 | .on::<req::SyntaxTree>(handlers::handle_syntax_tree)? | 348 | .on::<req::SyntaxTree>(handlers::handle_syntax_tree)? |
349 | .on::<req::ExtendSelection>(handlers::handle_extend_selection)? | ||
350 | .on::<req::OnTypeFormatting>(handlers::handle_on_type_formatting)? | 349 | .on::<req::OnTypeFormatting>(handlers::handle_on_type_formatting)? |
351 | .on::<req::DocumentSymbolRequest>(handlers::handle_document_symbol)? | 350 | .on::<req::DocumentSymbolRequest>(handlers::handle_document_symbol)? |
352 | .on::<req::WorkspaceSymbol>(handlers::handle_workspace_symbol)? | 351 | .on::<req::WorkspaceSymbol>(handlers::handle_workspace_symbol)? |
diff --git a/crates/ra_lsp_server/src/main_loop/handlers.rs b/crates/ra_lsp_server/src/main_loop/handlers.rs index 686ee5d12..a3d3f167c 100644 --- a/crates/ra_lsp_server/src/main_loop/handlers.rs +++ b/crates/ra_lsp_server/src/main_loop/handlers.rs | |||
@@ -9,7 +9,7 @@ use lsp_types::{ | |||
9 | TextEdit, WorkspaceEdit, | 9 | TextEdit, WorkspaceEdit, |
10 | }; | 10 | }; |
11 | use ra_ide_api::{ | 11 | use ra_ide_api::{ |
12 | AssistId, Cancelable, FileId, FilePosition, FileRange, FoldKind, Query, RunnableKind, | 12 | AssistId, FileId, FilePosition, FileRange, FoldKind, Query, Runnable, RunnableKind, |
13 | }; | 13 | }; |
14 | use ra_prof::profile; | 14 | use ra_prof::profile; |
15 | use ra_syntax::{AstNode, SyntaxKind, TextRange, TextUnit}; | 15 | use ra_syntax::{AstNode, SyntaxKind, TextRange, TextUnit}; |
@@ -45,27 +45,6 @@ pub fn handle_syntax_tree(world: WorldSnapshot, params: req::SyntaxTreeParams) - | |||
45 | Ok(res) | 45 | Ok(res) |
46 | } | 46 | } |
47 | 47 | ||
48 | // FIXME: drop this API | ||
49 | pub fn handle_extend_selection( | ||
50 | world: WorldSnapshot, | ||
51 | params: req::ExtendSelectionParams, | ||
52 | ) -> Result<req::ExtendSelectionResult> { | ||
53 | log::error!( | ||
54 | "extend selection is deprecated and will be removed soon, | ||
55 | use the new selection range API in LSP", | ||
56 | ); | ||
57 | let file_id = params.text_document.try_conv_with(&world)?; | ||
58 | let line_index = world.analysis().file_line_index(file_id)?; | ||
59 | let selections = params | ||
60 | .selections | ||
61 | .into_iter() | ||
62 | .map_conv_with(&line_index) | ||
63 | .map(|range| FileRange { file_id, range }) | ||
64 | .map(|frange| world.analysis().extend_selection(frange).map(|it| it.conv_with(&line_index))) | ||
65 | .collect::<Cancelable<Vec<_>>>()?; | ||
66 | Ok(req::ExtendSelectionResult { selections }) | ||
67 | } | ||
68 | |||
69 | pub fn handle_selection_range( | 48 | pub fn handle_selection_range( |
70 | world: WorldSnapshot, | 49 | world: WorldSnapshot, |
71 | params: req::SelectionRangeParams, | 50 | params: req::SelectionRangeParams, |
@@ -325,27 +304,7 @@ pub fn handle_runnables( | |||
325 | continue; | 304 | continue; |
326 | } | 305 | } |
327 | } | 306 | } |
328 | 307 | res.push(to_lsp_runnable(&world, file_id, runnable)?); | |
329 | let args = runnable_args(&world, file_id, &runnable.kind)?; | ||
330 | |||
331 | let r = req::Runnable { | ||
332 | range: runnable.range.conv_with(&line_index), | ||
333 | label: match &runnable.kind { | ||
334 | RunnableKind::Test { name } => format!("test {}", name), | ||
335 | RunnableKind::TestMod { path } => format!("test-mod {}", path), | ||
336 | RunnableKind::Bench { name } => format!("bench {}", name), | ||
337 | RunnableKind::Bin => "run binary".to_string(), | ||
338 | }, | ||
339 | bin: "cargo".to_string(), | ||
340 | args, | ||
341 | env: { | ||
342 | let mut m = FxHashMap::default(); | ||
343 | m.insert("RUST_BACKTRACE".to_string(), "short".to_string()); | ||
344 | m | ||
345 | }, | ||
346 | cwd: workspace_root.map(|root| root.to_string_lossy().to_string()), | ||
347 | }; | ||
348 | res.push(r); | ||
349 | } | 308 | } |
350 | let mut check_args = vec!["check".to_string()]; | 309 | let mut check_args = vec!["check".to_string()]; |
351 | let label; | 310 | let label; |
@@ -693,42 +652,27 @@ pub fn handle_code_lens( | |||
693 | let line_index = world.analysis().file_line_index(file_id)?; | 652 | let line_index = world.analysis().file_line_index(file_id)?; |
694 | 653 | ||
695 | let mut lenses: Vec<CodeLens> = Default::default(); | 654 | let mut lenses: Vec<CodeLens> = Default::default(); |
696 | let workspace_root = world.workspace_root_for(file_id); | ||
697 | 655 | ||
698 | // Gather runnables | 656 | // Gather runnables |
699 | for runnable in world.analysis().runnables(file_id)? { | 657 | for runnable in world.analysis().runnables(file_id)? { |
700 | let title = match &runnable.kind { | 658 | let title = match &runnable.kind { |
701 | RunnableKind::Test { .. } | RunnableKind::TestMod { .. } => Some("▶️Run Test"), | 659 | RunnableKind::Test { .. } | RunnableKind::TestMod { .. } => "▶️Run Test", |
702 | RunnableKind::Bench { .. } => Some("Run Bench"), | 660 | RunnableKind::Bench { .. } => "Run Bench", |
703 | RunnableKind::Bin => Some("️Run"), | 661 | RunnableKind::Bin => "Run", |
662 | } | ||
663 | .to_string(); | ||
664 | let r = to_lsp_runnable(&world, file_id, runnable)?; | ||
665 | let lens = CodeLens { | ||
666 | range: r.range, | ||
667 | command: Some(Command { | ||
668 | title, | ||
669 | command: "rust-analyzer.runSingle".into(), | ||
670 | arguments: Some(vec![to_value(r).unwrap()]), | ||
671 | }), | ||
672 | data: None, | ||
704 | }; | 673 | }; |
705 | 674 | ||
706 | if let Some(title) = title { | 675 | lenses.push(lens); |
707 | let args = runnable_args(&world, file_id, &runnable.kind)?; | ||
708 | let range = runnable.range.conv_with(&line_index); | ||
709 | |||
710 | // This represents the actual command that will be run. | ||
711 | let r: req::Runnable = req::Runnable { | ||
712 | range, | ||
713 | label: Default::default(), | ||
714 | bin: "cargo".into(), | ||
715 | args, | ||
716 | env: Default::default(), | ||
717 | cwd: workspace_root.map(|root| root.to_string_lossy().to_string()), | ||
718 | }; | ||
719 | |||
720 | let lens = CodeLens { | ||
721 | range, | ||
722 | command: Some(Command { | ||
723 | title: title.into(), | ||
724 | command: "rust-analyzer.runSingle".into(), | ||
725 | arguments: Some(vec![to_value(r).unwrap()]), | ||
726 | }), | ||
727 | data: None, | ||
728 | }; | ||
729 | |||
730 | lenses.push(lens); | ||
731 | } | ||
732 | } | 676 | } |
733 | 677 | ||
734 | // Handle impls | 678 | // Handle impls |
@@ -856,6 +800,32 @@ pub fn publish_decorations( | |||
856 | Ok(req::PublishDecorationsParams { uri, decorations: highlight(&world, file_id)? }) | 800 | Ok(req::PublishDecorationsParams { uri, decorations: highlight(&world, file_id)? }) |
857 | } | 801 | } |
858 | 802 | ||
803 | fn to_lsp_runnable( | ||
804 | world: &WorldSnapshot, | ||
805 | file_id: FileId, | ||
806 | runnable: Runnable, | ||
807 | ) -> Result<req::Runnable> { | ||
808 | let args = runnable_args(world, file_id, &runnable.kind)?; | ||
809 | let line_index = world.analysis().file_line_index(file_id)?; | ||
810 | let label = match &runnable.kind { | ||
811 | RunnableKind::Test { name } => format!("test {}", name), | ||
812 | RunnableKind::TestMod { path } => format!("test-mod {}", path), | ||
813 | RunnableKind::Bench { name } => format!("bench {}", name), | ||
814 | RunnableKind::Bin => "run binary".to_string(), | ||
815 | }; | ||
816 | Ok(req::Runnable { | ||
817 | range: runnable.range.conv_with(&line_index), | ||
818 | label, | ||
819 | bin: "cargo".to_string(), | ||
820 | args, | ||
821 | env: { | ||
822 | let mut m = FxHashMap::default(); | ||
823 | m.insert("RUST_BACKTRACE".to_string(), "short".to_string()); | ||
824 | m | ||
825 | }, | ||
826 | cwd: world.workspace_root_for(file_id).map(|root| root.to_string_lossy().to_string()), | ||
827 | }) | ||
828 | } | ||
859 | fn highlight(world: &WorldSnapshot, file_id: FileId) -> Result<Vec<Decoration>> { | 829 | fn highlight(world: &WorldSnapshot, file_id: FileId) -> Result<Vec<Decoration>> { |
860 | let line_index = world.analysis().file_line_index(file_id)?; | 830 | let line_index = world.analysis().file_line_index(file_id)?; |
861 | let res = world | 831 | let res = world |
diff --git a/crates/ra_lsp_server/src/req.rs b/crates/ra_lsp_server/src/req.rs index 6b986bcc9..b2f3c509d 100644 --- a/crates/ra_lsp_server/src/req.rs +++ b/crates/ra_lsp_server/src/req.rs | |||
@@ -43,27 +43,6 @@ pub struct SyntaxTreeParams { | |||
43 | pub range: Option<Range>, | 43 | pub range: Option<Range>, |
44 | } | 44 | } |
45 | 45 | ||
46 | pub enum ExtendSelection {} | ||
47 | |||
48 | impl Request for ExtendSelection { | ||
49 | type Params = ExtendSelectionParams; | ||
50 | type Result = ExtendSelectionResult; | ||
51 | const METHOD: &'static str = "rust-analyzer/extendSelection"; | ||
52 | } | ||
53 | |||
54 | #[derive(Deserialize, Debug)] | ||
55 | #[serde(rename_all = "camelCase")] | ||
56 | pub struct ExtendSelectionParams { | ||
57 | pub text_document: TextDocumentIdentifier, | ||
58 | pub selections: Vec<Range>, | ||
59 | } | ||
60 | |||
61 | #[derive(Serialize, Debug)] | ||
62 | #[serde(rename_all = "camelCase")] | ||
63 | pub struct ExtendSelectionResult { | ||
64 | pub selections: Vec<Range>, | ||
65 | } | ||
66 | |||
67 | pub enum SelectionRangeRequest {} | 46 | pub enum SelectionRangeRequest {} |
68 | 47 | ||
69 | impl Request for SelectionRangeRequest { | 48 | impl Request for SelectionRangeRequest { |
diff --git a/crates/ra_parser/src/grammar/expressions.rs b/crates/ra_parser/src/grammar/expressions.rs index aa959864a..0495f34ae 100644 --- a/crates/ra_parser/src/grammar/expressions.rs +++ b/crates/ra_parser/src/grammar/expressions.rs | |||
@@ -359,11 +359,14 @@ fn lhs( | |||
359 | return Some((m.complete(p, RANGE_EXPR), BlockLike::NotBlock)); | 359 | return Some((m.complete(p, RANGE_EXPR), BlockLike::NotBlock)); |
360 | } | 360 | } |
361 | _ => { | 361 | _ => { |
362 | // test expression_after_block | ||
363 | // fn foo() { | ||
364 | // let mut p = F{x: 5}; | ||
365 | // {p}.x = 10; | ||
366 | // } | ||
367 | // | ||
362 | let (lhs, blocklike) = atom::atom_expr(p, r)?; | 368 | let (lhs, blocklike) = atom::atom_expr(p, r)?; |
363 | return Some(( | 369 | return Some(postfix_expr(p, lhs, blocklike, !(r.prefer_stmt && blocklike.is_block()))); |
364 | postfix_expr(p, lhs, !(r.prefer_stmt && blocklike.is_block())), | ||
365 | blocklike, | ||
366 | )); | ||
367 | } | 370 | } |
368 | }; | 371 | }; |
369 | expr_bp(p, r, 255, dollar_lvl); | 372 | expr_bp(p, r, 255, dollar_lvl); |
@@ -376,8 +379,9 @@ fn postfix_expr( | |||
376 | // Calls are disallowed if the type is a block and we prefer statements because the call cannot be disambiguated from a tuple | 379 | // Calls are disallowed if the type is a block and we prefer statements because the call cannot be disambiguated from a tuple |
377 | // E.g. `while true {break}();` is parsed as | 380 | // E.g. `while true {break}();` is parsed as |
378 | // `while true {break}; ();` | 381 | // `while true {break}; ();` |
382 | mut block_like: BlockLike, | ||
379 | mut allow_calls: bool, | 383 | mut allow_calls: bool, |
380 | ) -> CompletedMarker { | 384 | ) -> (CompletedMarker, BlockLike) { |
381 | loop { | 385 | loop { |
382 | lhs = match p.current() { | 386 | lhs = match p.current() { |
383 | // test stmt_postfix_expr_ambiguity | 387 | // test stmt_postfix_expr_ambiguity |
@@ -417,9 +421,10 @@ fn postfix_expr( | |||
417 | T![as] => cast_expr(p, lhs), | 421 | T![as] => cast_expr(p, lhs), |
418 | _ => break, | 422 | _ => break, |
419 | }; | 423 | }; |
420 | allow_calls = true | 424 | allow_calls = true; |
425 | block_like = BlockLike::NotBlock; | ||
421 | } | 426 | } |
422 | lhs | 427 | (lhs, block_like) |
423 | } | 428 | } |
424 | 429 | ||
425 | // test call_expr | 430 | // test call_expr |
diff --git a/crates/ra_syntax/src/ast/extensions.rs b/crates/ra_syntax/src/ast/extensions.rs index d4873b39a..2a59cf653 100644 --- a/crates/ra_syntax/src/ast/extensions.rs +++ b/crates/ra_syntax/src/ast/extensions.rs | |||
@@ -91,6 +91,7 @@ impl ast::Attr { | |||
91 | #[derive(Debug, Clone, PartialEq, Eq)] | 91 | #[derive(Debug, Clone, PartialEq, Eq)] |
92 | pub enum PathSegmentKind { | 92 | pub enum PathSegmentKind { |
93 | Name(ast::NameRef), | 93 | Name(ast::NameRef), |
94 | Type { type_ref: Option<ast::TypeRef>, trait_ref: Option<ast::PathType> }, | ||
94 | SelfKw, | 95 | SelfKw, |
95 | SuperKw, | 96 | SuperKw, |
96 | CrateKw, | 97 | CrateKw, |
@@ -112,6 +113,15 @@ impl ast::PathSegment { | |||
112 | T![self] => PathSegmentKind::SelfKw, | 113 | T![self] => PathSegmentKind::SelfKw, |
113 | T![super] => PathSegmentKind::SuperKw, | 114 | T![super] => PathSegmentKind::SuperKw, |
114 | T![crate] => PathSegmentKind::CrateKw, | 115 | T![crate] => PathSegmentKind::CrateKw, |
116 | T![<] => { | ||
117 | // <T> or <T as Trait> | ||
118 | // T is any TypeRef, Trait has to be a PathType | ||
119 | let mut type_refs = | ||
120 | self.syntax().children().filter(|node| ast::TypeRef::can_cast(node.kind())); | ||
121 | let type_ref = type_refs.next().and_then(ast::TypeRef::cast); | ||
122 | let trait_ref = type_refs.next().and_then(ast::PathType::cast); | ||
123 | PathSegmentKind::Type { type_ref, trait_ref } | ||
124 | } | ||
115 | _ => return None, | 125 | _ => return None, |
116 | } | 126 | } |
117 | }; | 127 | }; |
diff --git a/crates/ra_syntax/test_data/parser/inline/ok/0138_expression_after_block.rs b/crates/ra_syntax/test_data/parser/inline/ok/0138_expression_after_block.rs new file mode 100644 index 000000000..76007e3ee --- /dev/null +++ b/crates/ra_syntax/test_data/parser/inline/ok/0138_expression_after_block.rs | |||
@@ -0,0 +1,4 @@ | |||
1 | fn foo() { | ||
2 | let mut p = F{x: 5}; | ||
3 | {p}.x = 10; | ||
4 | } | ||
diff --git a/crates/ra_syntax/test_data/parser/inline/ok/0138_expression_after_block.txt b/crates/ra_syntax/test_data/parser/inline/ok/0138_expression_after_block.txt new file mode 100644 index 000000000..08128f365 --- /dev/null +++ b/crates/ra_syntax/test_data/parser/inline/ok/0138_expression_after_block.txt | |||
@@ -0,0 +1,65 @@ | |||
1 | SOURCE_FILE@[0; 52) | ||
2 | FN_DEF@[0; 51) | ||
3 | FN_KW@[0; 2) "fn" | ||
4 | WHITESPACE@[2; 3) " " | ||
5 | NAME@[3; 6) | ||
6 | IDENT@[3; 6) "foo" | ||
7 | PARAM_LIST@[6; 8) | ||
8 | L_PAREN@[6; 7) "(" | ||
9 | R_PAREN@[7; 8) ")" | ||
10 | WHITESPACE@[8; 9) " " | ||
11 | BLOCK@[9; 51) | ||
12 | L_CURLY@[9; 10) "{" | ||
13 | WHITESPACE@[10; 14) "\n " | ||
14 | LET_STMT@[14; 34) | ||
15 | LET_KW@[14; 17) "let" | ||
16 | WHITESPACE@[17; 18) " " | ||
17 | BIND_PAT@[18; 23) | ||
18 | MUT_KW@[18; 21) "mut" | ||
19 | WHITESPACE@[21; 22) " " | ||
20 | NAME@[22; 23) | ||
21 | IDENT@[22; 23) "p" | ||
22 | WHITESPACE@[23; 24) " " | ||
23 | EQ@[24; 25) "=" | ||
24 | WHITESPACE@[25; 26) " " | ||
25 | STRUCT_LIT@[26; 33) | ||
26 | PATH@[26; 27) | ||
27 | PATH_SEGMENT@[26; 27) | ||
28 | NAME_REF@[26; 27) | ||
29 | IDENT@[26; 27) "F" | ||
30 | NAMED_FIELD_LIST@[27; 33) | ||
31 | L_CURLY@[27; 28) "{" | ||
32 | NAMED_FIELD@[28; 32) | ||
33 | NAME_REF@[28; 29) | ||
34 | IDENT@[28; 29) "x" | ||
35 | COLON@[29; 30) ":" | ||
36 | WHITESPACE@[30; 31) " " | ||
37 | LITERAL@[31; 32) | ||
38 | INT_NUMBER@[31; 32) "5" | ||
39 | R_CURLY@[32; 33) "}" | ||
40 | SEMI@[33; 34) ";" | ||
41 | WHITESPACE@[34; 38) "\n " | ||
42 | EXPR_STMT@[38; 49) | ||
43 | BIN_EXPR@[38; 48) | ||
44 | FIELD_EXPR@[38; 43) | ||
45 | BLOCK_EXPR@[38; 41) | ||
46 | BLOCK@[38; 41) | ||
47 | L_CURLY@[38; 39) "{" | ||
48 | PATH_EXPR@[39; 40) | ||
49 | PATH@[39; 40) | ||
50 | PATH_SEGMENT@[39; 40) | ||
51 | NAME_REF@[39; 40) | ||
52 | IDENT@[39; 40) "p" | ||
53 | R_CURLY@[40; 41) "}" | ||
54 | DOT@[41; 42) "." | ||
55 | NAME_REF@[42; 43) | ||
56 | IDENT@[42; 43) "x" | ||
57 | WHITESPACE@[43; 44) " " | ||
58 | EQ@[44; 45) "=" | ||
59 | WHITESPACE@[45; 46) " " | ||
60 | LITERAL@[46; 48) | ||
61 | INT_NUMBER@[46; 48) "10" | ||
62 | SEMI@[48; 49) ";" | ||
63 | WHITESPACE@[49; 50) "\n" | ||
64 | R_CURLY@[50; 51) "}" | ||
65 | WHITESPACE@[51; 52) "\n" | ||
diff --git a/editors/emacs/ra-emacs-lsp.el b/editors/emacs/ra-emacs-lsp.el index d7656476e..79822c8ce 100644 --- a/editors/emacs/ra-emacs-lsp.el +++ b/editors/emacs/ra-emacs-lsp.el | |||
@@ -14,7 +14,7 @@ | |||
14 | ;; - 'hover' type information & documentation (with lsp-ui) | 14 | ;; - 'hover' type information & documentation (with lsp-ui) |
15 | ;; - implements source changes (for code actions etc.), except for file system changes | 15 | ;; - implements source changes (for code actions etc.), except for file system changes |
16 | ;; - implements joinLines (you need to bind rust-analyzer-join-lines to a key) | 16 | ;; - implements joinLines (you need to bind rust-analyzer-join-lines to a key) |
17 | ;; - implements extendSelection (either bind rust-analyzer-extend-selection to a key, or use expand-region) | 17 | ;; - implements selectionRanges (either bind lsp-extend-selection to a key, or use expand-region) |
18 | ;; - provides rust-analyzer-inlay-hints-mode for inline type hints | 18 | ;; - provides rust-analyzer-inlay-hints-mode for inline type hints |
19 | 19 | ||
20 | ;; What's missing: | 20 | ;; What's missing: |
@@ -79,6 +79,10 @@ | |||
79 | :ignore-messages nil | 79 | :ignore-messages nil |
80 | :server-id 'rust-analyzer)) | 80 | :server-id 'rust-analyzer)) |
81 | 81 | ||
82 | (defun rust-analyzer--initialized? () | ||
83 | (when-let ((workspace (lsp-find-workspace 'rust-analyzer (buffer-file-name)))) | ||
84 | (eq 'initialized (lsp--workspace-status workspace)))) | ||
85 | |||
82 | (with-eval-after-load 'company-lsp | 86 | (with-eval-after-load 'company-lsp |
83 | ;; company-lsp provides a snippet handler for rust by default that adds () after function calls, which RA does better | 87 | ;; company-lsp provides a snippet handler for rust by default that adds () after function calls, which RA does better |
84 | (setq company-lsp--snippet-functions (cl-delete "rust" company-lsp--snippet-functions :key #'car :test #'equal))) | 88 | (setq company-lsp--snippet-functions (cl-delete "rust" company-lsp--snippet-functions :key #'car :test #'equal))) |
@@ -99,39 +103,13 @@ | |||
99 | (rust-analyzer--join-lines-params))) | 103 | (rust-analyzer--join-lines-params))) |
100 | (rust-analyzer--apply-source-change))) | 104 | (rust-analyzer--apply-source-change))) |
101 | 105 | ||
102 | ;; extend selection | 106 | ;; selection ranges |
103 | |||
104 | (defun rust-analyzer-extend-selection () | ||
105 | (interactive) | ||
106 | (-let (((&hash "start" "end") (rust-analyzer--extend-selection))) | ||
107 | (rust-analyzer--goto-lsp-loc start) | ||
108 | (set-mark (point)) | ||
109 | (rust-analyzer--goto-lsp-loc end) | ||
110 | (exchange-point-and-mark))) | ||
111 | |||
112 | (defun rust-analyzer--extend-selection-params () | ||
113 | "Extend selection params." | ||
114 | (list :textDocument (lsp--text-document-identifier) | ||
115 | :selections | ||
116 | (vector | ||
117 | (if (use-region-p) | ||
118 | (lsp--region-to-range (region-beginning) (region-end)) | ||
119 | (lsp--region-to-range (point) (point)))))) | ||
120 | |||
121 | (defun rust-analyzer--extend-selection () | ||
122 | (-> | ||
123 | (lsp-send-request | ||
124 | (lsp-make-request | ||
125 | "rust-analyzer/extendSelection" | ||
126 | (rust-analyzer--extend-selection-params))) | ||
127 | (ht-get "selections") | ||
128 | (seq-first))) | ||
129 | 107 | ||
130 | (defun rust-analyzer--add-er-expansion () | 108 | (defun rust-analyzer--add-er-expansion () |
131 | (make-variable-buffer-local 'er/try-expand-list) | 109 | (make-variable-buffer-local 'er/try-expand-list) |
132 | (setq er/try-expand-list (append | 110 | (setq er/try-expand-list (append |
133 | er/try-expand-list | 111 | er/try-expand-list |
134 | '(rust-analyzer-extend-selection)))) | 112 | '(lsp-extend-selection)))) |
135 | 113 | ||
136 | (with-eval-after-load 'expand-region | 114 | (with-eval-after-load 'expand-region |
137 | ;; add the expansion for all existing rust-mode buffers. If expand-region is | 115 | ;; add the expansion for all existing rust-mode buffers. If expand-region is |
@@ -229,21 +207,22 @@ | |||
229 | (pop-to-buffer buf)))))) | 207 | (pop-to-buffer buf)))))) |
230 | 208 | ||
231 | ;; inlay hints | 209 | ;; inlay hints |
232 | (defun rust-analyzer--update-inlay-hints () | 210 | (defun rust-analyzer--update-inlay-hints (buffer) |
233 | (lsp-send-request-async | 211 | (if (and (rust-analyzer--initialized?) (eq buffer (current-buffer))) |
234 | (lsp-make-request "rust-analyzer/inlayHints" | 212 | (lsp-send-request-async |
235 | (list :textDocument (lsp--text-document-identifier))) | 213 | (lsp-make-request "rust-analyzer/inlayHints" |
236 | (lambda (res) | 214 | (list :textDocument (lsp--text-document-identifier))) |
237 | (remove-overlays (point-min) (point-max) 'rust-analyzer--inlay-hint t) | 215 | (lambda (res) |
238 | (dolist (hint res) | 216 | (remove-overlays (point-min) (point-max) 'rust-analyzer--inlay-hint t) |
239 | (-let* (((&hash "range" "label" "kind") hint) | 217 | (dolist (hint res) |
240 | ((beg . end) (lsp--range-to-region range)) | 218 | (-let* (((&hash "range" "label" "kind") hint) |
241 | (overlay (make-overlay beg end))) | 219 | ((beg . end) (lsp--range-to-region range)) |
242 | (overlay-put overlay 'rust-analyzer--inlay-hint t) | 220 | (overlay (make-overlay beg end))) |
243 | (overlay-put overlay 'evaporate t) | 221 | (overlay-put overlay 'rust-analyzer--inlay-hint t) |
244 | (overlay-put overlay 'after-string (propertize (concat ": " label) | 222 | (overlay-put overlay 'evaporate t) |
245 | 'font-lock-face 'font-lock-comment-face))))) | 223 | (overlay-put overlay 'after-string (propertize (concat ": " label) |
246 | 'tick) | 224 | 'font-lock-face 'font-lock-comment-face))))) |
225 | 'tick)) | ||
247 | nil) | 226 | nil) |
248 | 227 | ||
249 | (defvar-local rust-analyzer--inlay-hints-timer nil) | 228 | (defvar-local rust-analyzer--inlay-hints-timer nil) |
@@ -252,17 +231,19 @@ | |||
252 | (when rust-analyzer--inlay-hints-timer | 231 | (when rust-analyzer--inlay-hints-timer |
253 | (cancel-timer rust-analyzer--inlay-hints-timer)) | 232 | (cancel-timer rust-analyzer--inlay-hints-timer)) |
254 | (setq rust-analyzer--inlay-hints-timer | 233 | (setq rust-analyzer--inlay-hints-timer |
255 | (run-with-idle-timer 0.1 nil #'rust-analyzer--update-inlay-hints))) | 234 | (run-with-idle-timer 0.1 nil #'rust-analyzer--update-inlay-hints (current-buffer)))) |
256 | 235 | ||
257 | (define-minor-mode rust-analyzer-inlay-hints-mode | 236 | (define-minor-mode rust-analyzer-inlay-hints-mode |
258 | "Mode for showing inlay hints." | 237 | "Mode for showing inlay hints." |
259 | nil nil nil | 238 | nil nil nil |
260 | (cond | 239 | (cond |
261 | (rust-analyzer-inlay-hints-mode | 240 | (rust-analyzer-inlay-hints-mode |
262 | (rust-analyzer--update-inlay-hints) | 241 | (rust-analyzer--update-inlay-hints (current-buffer)) |
242 | (add-hook 'lsp-after-initialize-hook #'rust-analyzer--inlay-hints-change-handler nil t) | ||
263 | (add-hook 'after-change-functions #'rust-analyzer--inlay-hints-change-handler nil t)) | 243 | (add-hook 'after-change-functions #'rust-analyzer--inlay-hints-change-handler nil t)) |
264 | (t | 244 | (t |
265 | (remove-overlays (point-min) (point-max) 'rust-analyzer--inlay-hint t) | 245 | (remove-overlays (point-min) (point-max) 'rust-analyzer--inlay-hint t) |
246 | (remove-hook 'lsp-after-initialize-hook #'rust-analyzer--inlay-hints-change-handler t) | ||
266 | (remove-hook 'after-change-functions #'rust-analyzer--inlay-hints-change-handler t)))) | 247 | (remove-hook 'after-change-functions #'rust-analyzer--inlay-hints-change-handler t)))) |
267 | 248 | ||
268 | 249 | ||