diff options
-rw-r--r-- | crates/ra_assists/src/handlers/add_function.rs | 174 | ||||
-rw-r--r-- | crates/ra_hir/src/code_model.rs | 9 | ||||
-rw-r--r-- | crates/ra_hir_ty/src/display.rs | 176 | ||||
-rw-r--r-- | crates/ra_hir_ty/src/tests.rs | 17 | ||||
-rw-r--r-- | crates/ra_hir_ty/src/tests/display_source_code.rs | 23 |
5 files changed, 300 insertions, 99 deletions
diff --git a/crates/ra_assists/src/handlers/add_function.rs b/crates/ra_assists/src/handlers/add_function.rs index 6b5616aa9..95faf0f4f 100644 --- a/crates/ra_assists/src/handlers/add_function.rs +++ b/crates/ra_assists/src/handlers/add_function.rs | |||
@@ -43,16 +43,12 @@ pub(crate) fn add_function(acc: &mut Assists, ctx: &AssistContext) -> Option<()> | |||
43 | return None; | 43 | return None; |
44 | } | 44 | } |
45 | 45 | ||
46 | let target_module = if let Some(qualifier) = path.qualifier() { | 46 | let target_module = match path.qualifier() { |
47 | if let Some(hir::PathResolution::Def(hir::ModuleDef::Module(module))) = | 47 | Some(qualifier) => match ctx.sema.resolve_path(&qualifier) { |
48 | ctx.sema.resolve_path(&qualifier) | 48 | Some(hir::PathResolution::Def(hir::ModuleDef::Module(module))) => Some(module), |
49 | { | 49 | _ => return None, |
50 | Some(module.definition_source(ctx.sema.db)) | 50 | }, |
51 | } else { | 51 | None => None, |
52 | return None; | ||
53 | } | ||
54 | } else { | ||
55 | None | ||
56 | }; | 52 | }; |
57 | 53 | ||
58 | let function_builder = FunctionBuilder::from_call(&ctx, &call, &path, target_module)?; | 54 | let function_builder = FunctionBuilder::from_call(&ctx, &call, &path, target_module)?; |
@@ -83,25 +79,29 @@ struct FunctionBuilder { | |||
83 | } | 79 | } |
84 | 80 | ||
85 | impl FunctionBuilder { | 81 | impl FunctionBuilder { |
86 | /// Prepares a generated function that matches `call` in `generate_in` | 82 | /// Prepares a generated function that matches `call`. |
87 | /// (or as close to `call` as possible, if `generate_in` is `None`) | 83 | /// The function is generated in `target_module` or next to `call` |
88 | fn from_call( | 84 | fn from_call( |
89 | ctx: &AssistContext, | 85 | ctx: &AssistContext, |
90 | call: &ast::CallExpr, | 86 | call: &ast::CallExpr, |
91 | path: &ast::Path, | 87 | path: &ast::Path, |
92 | target_module: Option<hir::InFile<hir::ModuleSource>>, | 88 | target_module: Option<hir::Module>, |
93 | ) -> Option<Self> { | 89 | ) -> Option<Self> { |
94 | let needs_pub = target_module.is_some(); | ||
95 | let mut file = ctx.frange.file_id; | 90 | let mut file = ctx.frange.file_id; |
96 | let target = if let Some(target_module) = target_module { | 91 | let target = match &target_module { |
97 | let (in_file, target) = next_space_for_fn_in_module(ctx.sema.db, target_module)?; | 92 | Some(target_module) => { |
98 | file = in_file; | 93 | let module_source = target_module.definition_source(ctx.db); |
99 | target | 94 | let (in_file, target) = next_space_for_fn_in_module(ctx.sema.db, &module_source)?; |
100 | } else { | 95 | file = in_file; |
101 | next_space_for_fn_after_call_site(&call)? | 96 | target |
97 | } | ||
98 | None => next_space_for_fn_after_call_site(&call)?, | ||
102 | }; | 99 | }; |
100 | let needs_pub = target_module.is_some(); | ||
101 | let target_module = target_module.or_else(|| ctx.sema.scope(target.syntax()).module())?; | ||
103 | let fn_name = fn_name(&path)?; | 102 | let fn_name = fn_name(&path)?; |
104 | let (type_params, params) = fn_args(ctx, &call)?; | 103 | let (type_params, params) = fn_args(ctx, target_module, &call)?; |
104 | |||
105 | Some(Self { target, fn_name, type_params, params, file, needs_pub }) | 105 | Some(Self { target, fn_name, type_params, params, file, needs_pub }) |
106 | } | 106 | } |
107 | 107 | ||
@@ -144,6 +144,15 @@ enum GeneratedFunctionTarget { | |||
144 | InEmptyItemList(ast::ItemList), | 144 | InEmptyItemList(ast::ItemList), |
145 | } | 145 | } |
146 | 146 | ||
147 | impl GeneratedFunctionTarget { | ||
148 | fn syntax(&self) -> &SyntaxNode { | ||
149 | match self { | ||
150 | GeneratedFunctionTarget::BehindItem(it) => it, | ||
151 | GeneratedFunctionTarget::InEmptyItemList(it) => it.syntax(), | ||
152 | } | ||
153 | } | ||
154 | } | ||
155 | |||
147 | fn fn_name(call: &ast::Path) -> Option<ast::Name> { | 156 | fn fn_name(call: &ast::Path) -> Option<ast::Name> { |
148 | let name = call.segment()?.syntax().to_string(); | 157 | let name = call.segment()?.syntax().to_string(); |
149 | Some(ast::make::name(&name)) | 158 | Some(ast::make::name(&name)) |
@@ -152,17 +161,17 @@ fn fn_name(call: &ast::Path) -> Option<ast::Name> { | |||
152 | /// Computes the type variables and arguments required for the generated function | 161 | /// Computes the type variables and arguments required for the generated function |
153 | fn fn_args( | 162 | fn fn_args( |
154 | ctx: &AssistContext, | 163 | ctx: &AssistContext, |
164 | target_module: hir::Module, | ||
155 | call: &ast::CallExpr, | 165 | call: &ast::CallExpr, |
156 | ) -> Option<(Option<ast::TypeParamList>, ast::ParamList)> { | 166 | ) -> Option<(Option<ast::TypeParamList>, ast::ParamList)> { |
157 | let mut arg_names = Vec::new(); | 167 | let mut arg_names = Vec::new(); |
158 | let mut arg_types = Vec::new(); | 168 | let mut arg_types = Vec::new(); |
159 | for arg in call.arg_list()?.args() { | 169 | for arg in call.arg_list()?.args() { |
160 | let arg_name = match fn_arg_name(&arg) { | 170 | arg_names.push(match fn_arg_name(&arg) { |
161 | Some(name) => name, | 171 | Some(name) => name, |
162 | None => String::from("arg"), | 172 | None => String::from("arg"), |
163 | }; | 173 | }); |
164 | arg_names.push(arg_name); | 174 | arg_types.push(match fn_arg_type(ctx, target_module, &arg) { |
165 | arg_types.push(match fn_arg_type(ctx, &arg) { | ||
166 | Some(ty) => ty, | 175 | Some(ty) => ty, |
167 | None => String::from("()"), | 176 | None => String::from("()"), |
168 | }); | 177 | }); |
@@ -218,12 +227,21 @@ fn fn_arg_name(fn_arg: &ast::Expr) -> Option<String> { | |||
218 | } | 227 | } |
219 | } | 228 | } |
220 | 229 | ||
221 | fn fn_arg_type(ctx: &AssistContext, fn_arg: &ast::Expr) -> Option<String> { | 230 | fn fn_arg_type( |
231 | ctx: &AssistContext, | ||
232 | target_module: hir::Module, | ||
233 | fn_arg: &ast::Expr, | ||
234 | ) -> Option<String> { | ||
222 | let ty = ctx.sema.type_of_expr(fn_arg)?; | 235 | let ty = ctx.sema.type_of_expr(fn_arg)?; |
223 | if ty.is_unknown() { | 236 | if ty.is_unknown() { |
224 | return None; | 237 | return None; |
225 | } | 238 | } |
226 | Some(ty.display(ctx.sema.db).to_string()) | 239 | |
240 | if let Ok(rendered) = ty.display_source_code(ctx.db, target_module.into()) { | ||
241 | Some(rendered) | ||
242 | } else { | ||
243 | None | ||
244 | } | ||
227 | } | 245 | } |
228 | 246 | ||
229 | /// Returns the position inside the current mod or file | 247 | /// Returns the position inside the current mod or file |
@@ -252,10 +270,10 @@ fn next_space_for_fn_after_call_site(expr: &ast::CallExpr) -> Option<GeneratedFu | |||
252 | 270 | ||
253 | fn next_space_for_fn_in_module( | 271 | fn next_space_for_fn_in_module( |
254 | db: &dyn hir::db::AstDatabase, | 272 | db: &dyn hir::db::AstDatabase, |
255 | module: hir::InFile<hir::ModuleSource>, | 273 | module_source: &hir::InFile<hir::ModuleSource>, |
256 | ) -> Option<(FileId, GeneratedFunctionTarget)> { | 274 | ) -> Option<(FileId, GeneratedFunctionTarget)> { |
257 | let file = module.file_id.original_file(db); | 275 | let file = module_source.file_id.original_file(db); |
258 | let assist_item = match module.value { | 276 | let assist_item = match &module_source.value { |
259 | hir::ModuleSource::SourceFile(it) => { | 277 | hir::ModuleSource::SourceFile(it) => { |
260 | if let Some(last_item) = it.items().last() { | 278 | if let Some(last_item) = it.items().last() { |
261 | GeneratedFunctionTarget::BehindItem(last_item.syntax().clone()) | 279 | GeneratedFunctionTarget::BehindItem(last_item.syntax().clone()) |
@@ -599,8 +617,33 @@ fn bar(foo: impl Foo) { | |||
599 | } | 617 | } |
600 | 618 | ||
601 | #[test] | 619 | #[test] |
602 | #[ignore] | 620 | fn borrowed_arg() { |
603 | // FIXME print paths properly to make this test pass | 621 | check_assist( |
622 | add_function, | ||
623 | r" | ||
624 | struct Baz; | ||
625 | fn baz() -> Baz { todo!() } | ||
626 | |||
627 | fn foo() { | ||
628 | bar<|>(&baz()) | ||
629 | } | ||
630 | ", | ||
631 | r" | ||
632 | struct Baz; | ||
633 | fn baz() -> Baz { todo!() } | ||
634 | |||
635 | fn foo() { | ||
636 | bar(&baz()) | ||
637 | } | ||
638 | |||
639 | fn bar(baz: &Baz) { | ||
640 | <|>todo!() | ||
641 | } | ||
642 | ", | ||
643 | ) | ||
644 | } | ||
645 | |||
646 | #[test] | ||
604 | fn add_function_with_qualified_path_arg() { | 647 | fn add_function_with_qualified_path_arg() { |
605 | check_assist( | 648 | check_assist( |
606 | add_function, | 649 | add_function, |
@@ -609,10 +652,8 @@ mod Baz { | |||
609 | pub struct Bof; | 652 | pub struct Bof; |
610 | pub fn baz() -> Bof { Bof } | 653 | pub fn baz() -> Bof { Bof } |
611 | } | 654 | } |
612 | mod Foo { | 655 | fn foo() { |
613 | fn foo() { | 656 | <|>bar(Baz::baz()) |
614 | <|>bar(super::Baz::baz()) | ||
615 | } | ||
616 | } | 657 | } |
617 | ", | 658 | ", |
618 | r" | 659 | r" |
@@ -620,14 +661,12 @@ mod Baz { | |||
620 | pub struct Bof; | 661 | pub struct Bof; |
621 | pub fn baz() -> Bof { Bof } | 662 | pub fn baz() -> Bof { Bof } |
622 | } | 663 | } |
623 | mod Foo { | 664 | fn foo() { |
624 | fn foo() { | 665 | bar(Baz::baz()) |
625 | bar(super::Baz::baz()) | 666 | } |
626 | } | ||
627 | 667 | ||
628 | fn bar(baz: super::Baz::Bof) { | 668 | fn bar(baz: Baz::Bof) { |
629 | <|>todo!() | 669 | <|>todo!() |
630 | } | ||
631 | } | 670 | } |
632 | ", | 671 | ", |
633 | ) | 672 | ) |
@@ -809,6 +848,40 @@ fn foo() { | |||
809 | } | 848 | } |
810 | 849 | ||
811 | #[test] | 850 | #[test] |
851 | #[ignore] | ||
852 | // Ignored until local imports are supported. | ||
853 | // See https://github.com/rust-analyzer/rust-analyzer/issues/1165 | ||
854 | fn qualified_path_uses_correct_scope() { | ||
855 | check_assist( | ||
856 | add_function, | ||
857 | " | ||
858 | mod foo { | ||
859 | pub struct Foo; | ||
860 | } | ||
861 | fn bar() { | ||
862 | use foo::Foo; | ||
863 | let foo = Foo; | ||
864 | baz<|>(foo) | ||
865 | } | ||
866 | ", | ||
867 | " | ||
868 | mod foo { | ||
869 | pub struct Foo; | ||
870 | } | ||
871 | fn bar() { | ||
872 | use foo::Foo; | ||
873 | let foo = Foo; | ||
874 | baz(foo) | ||
875 | } | ||
876 | |||
877 | fn baz(foo: foo::Foo) { | ||
878 | <|>todo!() | ||
879 | } | ||
880 | ", | ||
881 | ) | ||
882 | } | ||
883 | |||
884 | #[test] | ||
812 | fn add_function_in_module_containing_other_items() { | 885 | fn add_function_in_module_containing_other_items() { |
813 | check_assist( | 886 | check_assist( |
814 | add_function, | 887 | add_function, |
@@ -920,21 +993,6 @@ fn bar(baz: ()) {} | |||
920 | } | 993 | } |
921 | 994 | ||
922 | #[test] | 995 | #[test] |
923 | fn add_function_not_applicable_if_function_path_not_singleton() { | ||
924 | // In the future this assist could be extended to generate functions | ||
925 | // if the path is in the same crate (or even the same workspace). | ||
926 | // For the beginning, I think this is fine. | ||
927 | check_assist_not_applicable( | ||
928 | add_function, | ||
929 | r" | ||
930 | fn foo() { | ||
931 | other_crate::bar<|>(); | ||
932 | } | ||
933 | ", | ||
934 | ) | ||
935 | } | ||
936 | |||
937 | #[test] | ||
938 | #[ignore] | 996 | #[ignore] |
939 | fn create_method_with_no_args() { | 997 | fn create_method_with_no_args() { |
940 | check_assist( | 998 | check_assist( |
diff --git a/crates/ra_hir/src/code_model.rs b/crates/ra_hir/src/code_model.rs index 5f480c304..be18c845c 100644 --- a/crates/ra_hir/src/code_model.rs +++ b/crates/ra_hir/src/code_model.rs | |||
@@ -22,8 +22,11 @@ use hir_expand::{ | |||
22 | MacroDefId, MacroDefKind, | 22 | MacroDefId, MacroDefKind, |
23 | }; | 23 | }; |
24 | use hir_ty::{ | 24 | use hir_ty::{ |
25 | autoderef, display::HirFormatter, expr::ExprValidator, method_resolution, ApplicationTy, | 25 | autoderef, |
26 | Canonical, InEnvironment, Substs, TraitEnvironment, Ty, TyDefId, TypeCtor, | 26 | display::{HirDisplayError, HirFormatter}, |
27 | expr::ExprValidator, | ||
28 | method_resolution, ApplicationTy, Canonical, InEnvironment, Substs, TraitEnvironment, Ty, | ||
29 | TyDefId, TypeCtor, | ||
27 | }; | 30 | }; |
28 | use ra_db::{CrateId, CrateName, Edition, FileId}; | 31 | use ra_db::{CrateId, CrateName, Edition, FileId}; |
29 | use ra_prof::profile; | 32 | use ra_prof::profile; |
@@ -1319,7 +1322,7 @@ impl Type { | |||
1319 | } | 1322 | } |
1320 | 1323 | ||
1321 | impl HirDisplay for Type { | 1324 | impl HirDisplay for Type { |
1322 | fn hir_fmt(&self, f: &mut HirFormatter) -> std::fmt::Result { | 1325 | fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> { |
1323 | self.ty.value.hir_fmt(f) | 1326 | self.ty.value.hir_fmt(f) |
1324 | } | 1327 | } |
1325 | } | 1328 | } |
diff --git a/crates/ra_hir_ty/src/display.rs b/crates/ra_hir_ty/src/display.rs index d03bbd5a7..f5edaea8c 100644 --- a/crates/ra_hir_ty/src/display.rs +++ b/crates/ra_hir_ty/src/display.rs | |||
@@ -6,28 +6,42 @@ use crate::{ | |||
6 | db::HirDatabase, utils::generics, ApplicationTy, CallableDef, FnSig, GenericPredicate, | 6 | db::HirDatabase, utils::generics, ApplicationTy, CallableDef, FnSig, GenericPredicate, |
7 | Obligation, ProjectionTy, Substs, TraitRef, Ty, TypeCtor, | 7 | Obligation, ProjectionTy, Substs, TraitRef, Ty, TypeCtor, |
8 | }; | 8 | }; |
9 | use hir_def::{generics::TypeParamProvenance, AdtId, AssocContainerId, Lookup}; | 9 | use hir_def::{ |
10 | find_path, generics::TypeParamProvenance, item_scope::ItemInNs, AdtId, AssocContainerId, | ||
11 | Lookup, ModuleId, | ||
12 | }; | ||
10 | use hir_expand::name::Name; | 13 | use hir_expand::name::Name; |
11 | 14 | ||
12 | pub struct HirFormatter<'a, 'b> { | 15 | pub struct HirFormatter<'a> { |
13 | pub db: &'a dyn HirDatabase, | 16 | pub db: &'a dyn HirDatabase, |
14 | fmt: &'a mut fmt::Formatter<'b>, | 17 | fmt: &'a mut dyn fmt::Write, |
15 | buf: String, | 18 | buf: String, |
16 | curr_size: usize, | 19 | curr_size: usize, |
17 | pub(crate) max_size: Option<usize>, | 20 | pub(crate) max_size: Option<usize>, |
18 | omit_verbose_types: bool, | 21 | omit_verbose_types: bool, |
22 | display_target: DisplayTarget, | ||
19 | } | 23 | } |
20 | 24 | ||
21 | pub trait HirDisplay { | 25 | pub trait HirDisplay { |
22 | fn hir_fmt(&self, f: &mut HirFormatter) -> fmt::Result; | 26 | fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError>; |
23 | 27 | ||
28 | /// Returns a `Display`able type that is human-readable. | ||
29 | /// Use this for showing types to the user (e.g. diagnostics) | ||
24 | fn display<'a>(&'a self, db: &'a dyn HirDatabase) -> HirDisplayWrapper<'a, Self> | 30 | fn display<'a>(&'a self, db: &'a dyn HirDatabase) -> HirDisplayWrapper<'a, Self> |
25 | where | 31 | where |
26 | Self: Sized, | 32 | Self: Sized, |
27 | { | 33 | { |
28 | HirDisplayWrapper(db, self, None, false) | 34 | HirDisplayWrapper { |
35 | db, | ||
36 | t: self, | ||
37 | max_size: None, | ||
38 | omit_verbose_types: false, | ||
39 | display_target: DisplayTarget::Diagnostics, | ||
40 | } | ||
29 | } | 41 | } |
30 | 42 | ||
43 | /// Returns a `Display`able type that is human-readable and tries to be succinct. | ||
44 | /// Use this for showing types to the user where space is constrained (e.g. doc popups) | ||
31 | fn display_truncated<'a>( | 45 | fn display_truncated<'a>( |
32 | &'a self, | 46 | &'a self, |
33 | db: &'a dyn HirDatabase, | 47 | db: &'a dyn HirDatabase, |
@@ -36,16 +50,46 @@ pub trait HirDisplay { | |||
36 | where | 50 | where |
37 | Self: Sized, | 51 | Self: Sized, |
38 | { | 52 | { |
39 | HirDisplayWrapper(db, self, max_size, true) | 53 | HirDisplayWrapper { |
54 | db, | ||
55 | t: self, | ||
56 | max_size, | ||
57 | omit_verbose_types: true, | ||
58 | display_target: DisplayTarget::Diagnostics, | ||
59 | } | ||
60 | } | ||
61 | |||
62 | /// Returns a String representation of `self` that can be inserted into the given module. | ||
63 | /// Use this when generating code (e.g. assists) | ||
64 | fn display_source_code<'a>( | ||
65 | &'a self, | ||
66 | db: &'a dyn HirDatabase, | ||
67 | module_id: ModuleId, | ||
68 | ) -> Result<String, DisplaySourceCodeError> { | ||
69 | let mut result = String::new(); | ||
70 | match self.hir_fmt(&mut HirFormatter { | ||
71 | db, | ||
72 | fmt: &mut result, | ||
73 | buf: String::with_capacity(20), | ||
74 | curr_size: 0, | ||
75 | max_size: None, | ||
76 | omit_verbose_types: false, | ||
77 | display_target: DisplayTarget::SourceCode { module_id }, | ||
78 | }) { | ||
79 | Ok(()) => {} | ||
80 | Err(HirDisplayError::FmtError) => panic!("Writing to String can't fail!"), | ||
81 | Err(HirDisplayError::DisplaySourceCodeError(e)) => return Err(e), | ||
82 | }; | ||
83 | Ok(result) | ||
40 | } | 84 | } |
41 | } | 85 | } |
42 | 86 | ||
43 | impl<'a, 'b> HirFormatter<'a, 'b> { | 87 | impl<'a> HirFormatter<'a> { |
44 | pub fn write_joined<T: HirDisplay>( | 88 | pub fn write_joined<T: HirDisplay>( |
45 | &mut self, | 89 | &mut self, |
46 | iter: impl IntoIterator<Item = T>, | 90 | iter: impl IntoIterator<Item = T>, |
47 | sep: &str, | 91 | sep: &str, |
48 | ) -> fmt::Result { | 92 | ) -> Result<(), HirDisplayError> { |
49 | let mut first = true; | 93 | let mut first = true; |
50 | for e in iter { | 94 | for e in iter { |
51 | if !first { | 95 | if !first { |
@@ -58,14 +102,14 @@ impl<'a, 'b> HirFormatter<'a, 'b> { | |||
58 | } | 102 | } |
59 | 103 | ||
60 | /// This allows using the `write!` macro directly with a `HirFormatter`. | 104 | /// This allows using the `write!` macro directly with a `HirFormatter`. |
61 | pub fn write_fmt(&mut self, args: fmt::Arguments) -> fmt::Result { | 105 | pub fn write_fmt(&mut self, args: fmt::Arguments) -> Result<(), HirDisplayError> { |
62 | // We write to a buffer first to track output size | 106 | // We write to a buffer first to track output size |
63 | self.buf.clear(); | 107 | self.buf.clear(); |
64 | fmt::write(&mut self.buf, args)?; | 108 | fmt::write(&mut self.buf, args)?; |
65 | self.curr_size += self.buf.len(); | 109 | self.curr_size += self.buf.len(); |
66 | 110 | ||
67 | // Then we write to the internal formatter from the buffer | 111 | // Then we write to the internal formatter from the buffer |
68 | self.fmt.write_str(&self.buf) | 112 | self.fmt.write_str(&self.buf).map_err(HirDisplayError::from) |
69 | } | 113 | } |
70 | 114 | ||
71 | pub fn should_truncate(&self) -> bool { | 115 | pub fn should_truncate(&self) -> bool { |
@@ -81,34 +125,76 @@ impl<'a, 'b> HirFormatter<'a, 'b> { | |||
81 | } | 125 | } |
82 | } | 126 | } |
83 | 127 | ||
84 | pub struct HirDisplayWrapper<'a, T>(&'a dyn HirDatabase, &'a T, Option<usize>, bool); | 128 | #[derive(Clone, Copy)] |
129 | enum DisplayTarget { | ||
130 | /// Display types for inlays, doc popups, autocompletion, etc... | ||
131 | /// Showing `{unknown}` or not qualifying paths is fine here. | ||
132 | /// There's no reason for this to fail. | ||
133 | Diagnostics, | ||
134 | /// Display types for inserting them in source files. | ||
135 | /// The generated code should compile, so paths need to be qualified. | ||
136 | SourceCode { module_id: ModuleId }, | ||
137 | } | ||
138 | |||
139 | #[derive(Debug)] | ||
140 | pub enum DisplaySourceCodeError { | ||
141 | PathNotFound, | ||
142 | } | ||
143 | |||
144 | pub enum HirDisplayError { | ||
145 | /// Errors that can occur when generating source code | ||
146 | DisplaySourceCodeError(DisplaySourceCodeError), | ||
147 | /// `FmtError` is required to be compatible with std::fmt::Display | ||
148 | FmtError, | ||
149 | } | ||
150 | impl From<fmt::Error> for HirDisplayError { | ||
151 | fn from(_: fmt::Error) -> Self { | ||
152 | Self::FmtError | ||
153 | } | ||
154 | } | ||
155 | |||
156 | pub struct HirDisplayWrapper<'a, T> { | ||
157 | db: &'a dyn HirDatabase, | ||
158 | t: &'a T, | ||
159 | max_size: Option<usize>, | ||
160 | omit_verbose_types: bool, | ||
161 | display_target: DisplayTarget, | ||
162 | } | ||
85 | 163 | ||
86 | impl<'a, T> fmt::Display for HirDisplayWrapper<'a, T> | 164 | impl<'a, T> fmt::Display for HirDisplayWrapper<'a, T> |
87 | where | 165 | where |
88 | T: HirDisplay, | 166 | T: HirDisplay, |
89 | { | 167 | { |
90 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | 168 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
91 | self.1.hir_fmt(&mut HirFormatter { | 169 | match self.t.hir_fmt(&mut HirFormatter { |
92 | db: self.0, | 170 | db: self.db, |
93 | fmt: f, | 171 | fmt: f, |
94 | buf: String::with_capacity(20), | 172 | buf: String::with_capacity(20), |
95 | curr_size: 0, | 173 | curr_size: 0, |
96 | max_size: self.2, | 174 | max_size: self.max_size, |
97 | omit_verbose_types: self.3, | 175 | omit_verbose_types: self.omit_verbose_types, |
98 | }) | 176 | display_target: self.display_target, |
177 | }) { | ||
178 | Ok(()) => Ok(()), | ||
179 | Err(HirDisplayError::FmtError) => Err(fmt::Error), | ||
180 | Err(HirDisplayError::DisplaySourceCodeError(_)) => { | ||
181 | // This should never happen | ||
182 | panic!("HirDisplay failed when calling Display::fmt!") | ||
183 | } | ||
184 | } | ||
99 | } | 185 | } |
100 | } | 186 | } |
101 | 187 | ||
102 | const TYPE_HINT_TRUNCATION: &str = "…"; | 188 | const TYPE_HINT_TRUNCATION: &str = "…"; |
103 | 189 | ||
104 | impl HirDisplay for &Ty { | 190 | impl HirDisplay for &Ty { |
105 | fn hir_fmt(&self, f: &mut HirFormatter) -> fmt::Result { | 191 | fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> { |
106 | HirDisplay::hir_fmt(*self, f) | 192 | HirDisplay::hir_fmt(*self, f) |
107 | } | 193 | } |
108 | } | 194 | } |
109 | 195 | ||
110 | impl HirDisplay for ApplicationTy { | 196 | impl HirDisplay for ApplicationTy { |
111 | fn hir_fmt(&self, f: &mut HirFormatter) -> fmt::Result { | 197 | fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> { |
112 | if f.should_truncate() { | 198 | if f.should_truncate() { |
113 | return write!(f, "{}", TYPE_HINT_TRUNCATION); | 199 | return write!(f, "{}", TYPE_HINT_TRUNCATION); |
114 | } | 200 | } |
@@ -191,12 +277,30 @@ impl HirDisplay for ApplicationTy { | |||
191 | } | 277 | } |
192 | } | 278 | } |
193 | TypeCtor::Adt(def_id) => { | 279 | TypeCtor::Adt(def_id) => { |
194 | let name = match def_id { | 280 | match f.display_target { |
195 | AdtId::StructId(it) => f.db.struct_data(it).name.clone(), | 281 | DisplayTarget::Diagnostics => { |
196 | AdtId::UnionId(it) => f.db.union_data(it).name.clone(), | 282 | let name = match def_id { |
197 | AdtId::EnumId(it) => f.db.enum_data(it).name.clone(), | 283 | AdtId::StructId(it) => f.db.struct_data(it).name.clone(), |
198 | }; | 284 | AdtId::UnionId(it) => f.db.union_data(it).name.clone(), |
199 | write!(f, "{}", name)?; | 285 | AdtId::EnumId(it) => f.db.enum_data(it).name.clone(), |
286 | }; | ||
287 | write!(f, "{}", name)?; | ||
288 | } | ||
289 | DisplayTarget::SourceCode { module_id } => { | ||
290 | if let Some(path) = find_path::find_path( | ||
291 | f.db.upcast(), | ||
292 | ItemInNs::Types(def_id.into()), | ||
293 | module_id, | ||
294 | ) { | ||
295 | write!(f, "{}", path)?; | ||
296 | } else { | ||
297 | return Err(HirDisplayError::DisplaySourceCodeError( | ||
298 | DisplaySourceCodeError::PathNotFound, | ||
299 | )); | ||
300 | } | ||
301 | } | ||
302 | } | ||
303 | |||
200 | if self.parameters.len() > 0 { | 304 | if self.parameters.len() > 0 { |
201 | let mut non_default_parameters = Vec::with_capacity(self.parameters.len()); | 305 | let mut non_default_parameters = Vec::with_capacity(self.parameters.len()); |
202 | let parameters_to_write = if f.omit_verbose_types() { | 306 | let parameters_to_write = if f.omit_verbose_types() { |
@@ -269,7 +373,7 @@ impl HirDisplay for ApplicationTy { | |||
269 | } | 373 | } |
270 | 374 | ||
271 | impl HirDisplay for ProjectionTy { | 375 | impl HirDisplay for ProjectionTy { |
272 | fn hir_fmt(&self, f: &mut HirFormatter) -> fmt::Result { | 376 | fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> { |
273 | if f.should_truncate() { | 377 | if f.should_truncate() { |
274 | return write!(f, "{}", TYPE_HINT_TRUNCATION); | 378 | return write!(f, "{}", TYPE_HINT_TRUNCATION); |
275 | } | 379 | } |
@@ -287,7 +391,7 @@ impl HirDisplay for ProjectionTy { | |||
287 | } | 391 | } |
288 | 392 | ||
289 | impl HirDisplay for Ty { | 393 | impl HirDisplay for Ty { |
290 | fn hir_fmt(&self, f: &mut HirFormatter) -> fmt::Result { | 394 | fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> { |
291 | if f.should_truncate() { | 395 | if f.should_truncate() { |
292 | return write!(f, "{}", TYPE_HINT_TRUNCATION); | 396 | return write!(f, "{}", TYPE_HINT_TRUNCATION); |
293 | } | 397 | } |
@@ -332,7 +436,7 @@ impl HirDisplay for Ty { | |||
332 | fn write_bounds_like_dyn_trait( | 436 | fn write_bounds_like_dyn_trait( |
333 | predicates: &[GenericPredicate], | 437 | predicates: &[GenericPredicate], |
334 | f: &mut HirFormatter, | 438 | f: &mut HirFormatter, |
335 | ) -> fmt::Result { | 439 | ) -> Result<(), HirDisplayError> { |
336 | // Note: This code is written to produce nice results (i.e. | 440 | // Note: This code is written to produce nice results (i.e. |
337 | // corresponding to surface Rust) for types that can occur in | 441 | // corresponding to surface Rust) for types that can occur in |
338 | // actual Rust. It will have weird results if the predicates | 442 | // actual Rust. It will have weird results if the predicates |
@@ -394,7 +498,7 @@ fn write_bounds_like_dyn_trait( | |||
394 | } | 498 | } |
395 | 499 | ||
396 | impl TraitRef { | 500 | impl TraitRef { |
397 | fn hir_fmt_ext(&self, f: &mut HirFormatter, use_as: bool) -> fmt::Result { | 501 | fn hir_fmt_ext(&self, f: &mut HirFormatter, use_as: bool) -> Result<(), HirDisplayError> { |
398 | if f.should_truncate() { | 502 | if f.should_truncate() { |
399 | return write!(f, "{}", TYPE_HINT_TRUNCATION); | 503 | return write!(f, "{}", TYPE_HINT_TRUNCATION); |
400 | } | 504 | } |
@@ -416,19 +520,19 @@ impl TraitRef { | |||
416 | } | 520 | } |
417 | 521 | ||
418 | impl HirDisplay for TraitRef { | 522 | impl HirDisplay for TraitRef { |
419 | fn hir_fmt(&self, f: &mut HirFormatter) -> fmt::Result { | 523 | fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> { |
420 | self.hir_fmt_ext(f, false) | 524 | self.hir_fmt_ext(f, false) |
421 | } | 525 | } |
422 | } | 526 | } |
423 | 527 | ||
424 | impl HirDisplay for &GenericPredicate { | 528 | impl HirDisplay for &GenericPredicate { |
425 | fn hir_fmt(&self, f: &mut HirFormatter) -> fmt::Result { | 529 | fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> { |
426 | HirDisplay::hir_fmt(*self, f) | 530 | HirDisplay::hir_fmt(*self, f) |
427 | } | 531 | } |
428 | } | 532 | } |
429 | 533 | ||
430 | impl HirDisplay for GenericPredicate { | 534 | impl HirDisplay for GenericPredicate { |
431 | fn hir_fmt(&self, f: &mut HirFormatter) -> fmt::Result { | 535 | fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> { |
432 | if f.should_truncate() { | 536 | if f.should_truncate() { |
433 | return write!(f, "{}", TYPE_HINT_TRUNCATION); | 537 | return write!(f, "{}", TYPE_HINT_TRUNCATION); |
434 | } | 538 | } |
@@ -452,15 +556,15 @@ impl HirDisplay for GenericPredicate { | |||
452 | } | 556 | } |
453 | 557 | ||
454 | impl HirDisplay for Obligation { | 558 | impl HirDisplay for Obligation { |
455 | fn hir_fmt(&self, f: &mut HirFormatter) -> fmt::Result { | 559 | fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> { |
456 | match self { | 560 | Ok(match self { |
457 | Obligation::Trait(tr) => write!(f, "Implements({})", tr.display(f.db)), | 561 | Obligation::Trait(tr) => write!(f, "Implements({})", tr.display(f.db))?, |
458 | Obligation::Projection(proj) => write!( | 562 | Obligation::Projection(proj) => write!( |
459 | f, | 563 | f, |
460 | "Normalize({} => {})", | 564 | "Normalize({} => {})", |
461 | proj.projection_ty.display(f.db), | 565 | proj.projection_ty.display(f.db), |
462 | proj.ty.display(f.db) | 566 | proj.ty.display(f.db) |
463 | ), | 567 | )?, |
464 | } | 568 | }) |
465 | } | 569 | } |
466 | } | 570 | } |
diff --git a/crates/ra_hir_ty/src/tests.rs b/crates/ra_hir_ty/src/tests.rs index 5af88b368..1fe05c70c 100644 --- a/crates/ra_hir_ty/src/tests.rs +++ b/crates/ra_hir_ty/src/tests.rs | |||
@@ -6,6 +6,7 @@ mod patterns; | |||
6 | mod traits; | 6 | mod traits; |
7 | mod method_resolution; | 7 | mod method_resolution; |
8 | mod macros; | 8 | mod macros; |
9 | mod display_source_code; | ||
9 | 10 | ||
10 | use std::sync::Arc; | 11 | use std::sync::Arc; |
11 | 12 | ||
@@ -16,7 +17,7 @@ use hir_def::{ | |||
16 | item_scope::ItemScope, | 17 | item_scope::ItemScope, |
17 | keys, | 18 | keys, |
18 | nameres::CrateDefMap, | 19 | nameres::CrateDefMap, |
19 | AssocItemId, DefWithBodyId, LocalModuleId, Lookup, ModuleDefId, | 20 | AssocItemId, DefWithBodyId, LocalModuleId, Lookup, ModuleDefId, ModuleId, |
20 | }; | 21 | }; |
21 | use hir_expand::{db::AstDatabase, InFile}; | 22 | use hir_expand::{db::AstDatabase, InFile}; |
22 | use insta::assert_snapshot; | 23 | use insta::assert_snapshot; |
@@ -37,6 +38,18 @@ use crate::{ | |||
37 | // update the snapshots. | 38 | // update the snapshots. |
38 | 39 | ||
39 | fn type_at_pos(db: &TestDB, pos: FilePosition) -> String { | 40 | fn type_at_pos(db: &TestDB, pos: FilePosition) -> String { |
41 | type_at_pos_displayed(db, pos, |ty, _| ty.display(db).to_string()) | ||
42 | } | ||
43 | |||
44 | fn displayed_source_at_pos(db: &TestDB, pos: FilePosition) -> String { | ||
45 | type_at_pos_displayed(db, pos, |ty, module_id| ty.display_source_code(db, module_id).unwrap()) | ||
46 | } | ||
47 | |||
48 | fn type_at_pos_displayed( | ||
49 | db: &TestDB, | ||
50 | pos: FilePosition, | ||
51 | display_fn: impl FnOnce(&Ty, ModuleId) -> String, | ||
52 | ) -> String { | ||
40 | let file = db.parse(pos.file_id).ok().unwrap(); | 53 | let file = db.parse(pos.file_id).ok().unwrap(); |
41 | let expr = algo::find_node_at_offset::<ast::Expr>(file.syntax(), pos.offset).unwrap(); | 54 | let expr = algo::find_node_at_offset::<ast::Expr>(file.syntax(), pos.offset).unwrap(); |
42 | let fn_def = expr.syntax().ancestors().find_map(ast::FnDef::cast).unwrap(); | 55 | let fn_def = expr.syntax().ancestors().find_map(ast::FnDef::cast).unwrap(); |
@@ -49,7 +62,7 @@ fn type_at_pos(db: &TestDB, pos: FilePosition) -> String { | |||
49 | if let Some(expr_id) = source_map.node_expr(InFile::new(pos.file_id.into(), &expr)) { | 62 | if let Some(expr_id) = source_map.node_expr(InFile::new(pos.file_id.into(), &expr)) { |
50 | let infer = db.infer(func.into()); | 63 | let infer = db.infer(func.into()); |
51 | let ty = &infer[expr_id]; | 64 | let ty = &infer[expr_id]; |
52 | return ty.display(db).to_string(); | 65 | return display_fn(ty, module); |
53 | } | 66 | } |
54 | panic!("Can't find expression") | 67 | panic!("Can't find expression") |
55 | } | 68 | } |
diff --git a/crates/ra_hir_ty/src/tests/display_source_code.rs b/crates/ra_hir_ty/src/tests/display_source_code.rs new file mode 100644 index 000000000..ca1748615 --- /dev/null +++ b/crates/ra_hir_ty/src/tests/display_source_code.rs | |||
@@ -0,0 +1,23 @@ | |||
1 | use super::displayed_source_at_pos; | ||
2 | use crate::test_db::TestDB; | ||
3 | use ra_db::fixture::WithFixture; | ||
4 | |||
5 | #[test] | ||
6 | fn qualify_path_to_submodule() { | ||
7 | let (db, pos) = TestDB::with_position( | ||
8 | r#" | ||
9 | //- /main.rs | ||
10 | |||
11 | mod foo { | ||
12 | pub struct Foo; | ||
13 | } | ||
14 | |||
15 | fn bar() { | ||
16 | let foo: foo::Foo = foo::Foo; | ||
17 | foo<|> | ||
18 | } | ||
19 | |||
20 | "#, | ||
21 | ); | ||
22 | assert_eq!("foo::Foo", displayed_source_at_pos(&db, pos)); | ||
23 | } | ||