]> git.lizzy.rs Git - rust.git/blob - crates/ide/src/signature_help.rs
6045a787ecc23cf26647113e8cf24ee214130535
[rust.git] / crates / ide / src / signature_help.rs
1 //! This module provides primitives for showing type and function parameter information when editing
2 //! a call or use-site.
3
4 use std::collections::BTreeSet;
5
6 use either::Either;
7 use hir::{AssocItem, GenericParam, HasAttrs, HirDisplay, Semantics, Trait};
8 use ide_db::{active_parameter::callable_for_node, base_db::FilePosition};
9 use stdx::format_to;
10 use syntax::{
11     algo,
12     ast::{self, HasArgList},
13     match_ast, AstNode, Direction, SyntaxToken, TextRange, TextSize,
14 };
15
16 use crate::RootDatabase;
17
18 /// Contains information about an item signature as seen from a use site.
19 ///
20 /// This includes the "active parameter", which is the parameter whose value is currently being
21 /// edited.
22 #[derive(Debug)]
23 pub struct SignatureHelp {
24     pub doc: Option<String>,
25     pub signature: String,
26     pub active_parameter: Option<usize>,
27     parameters: Vec<TextRange>,
28 }
29
30 impl SignatureHelp {
31     pub fn parameter_labels(&self) -> impl Iterator<Item = &str> + '_ {
32         self.parameters.iter().map(move |&it| &self.signature[it])
33     }
34
35     pub fn parameter_ranges(&self) -> &[TextRange] {
36         &self.parameters
37     }
38
39     fn push_call_param(&mut self, param: &str) {
40         self.push_param('(', param);
41     }
42
43     fn push_generic_param(&mut self, param: &str) {
44         self.push_param('<', param);
45     }
46
47     fn push_param(&mut self, opening_delim: char, param: &str) {
48         if !self.signature.ends_with(opening_delim) {
49             self.signature.push_str(", ");
50         }
51         let start = TextSize::of(&self.signature);
52         self.signature.push_str(param);
53         let end = TextSize::of(&self.signature);
54         self.parameters.push(TextRange::new(start, end))
55     }
56 }
57
58 /// Computes parameter information for the given position.
59 pub(crate) fn signature_help(db: &RootDatabase, position: FilePosition) -> Option<SignatureHelp> {
60     let sema = Semantics::new(db);
61     let file = sema.parse(position.file_id);
62     let file = file.syntax();
63     let token = file
64         .token_at_offset(position.offset)
65         .left_biased()
66         // if the cursor is sandwiched between two space tokens and the call is unclosed
67         // this prevents us from leaving the CallExpression
68         .and_then(|tok| algo::skip_trivia_token(tok, Direction::Prev))?;
69     let token = sema.descend_into_macros_single(token);
70
71     for node in token.parent_ancestors() {
72         match_ast! {
73             match node {
74                 ast::ArgList(arg_list) => {
75                     let cursor_outside = arg_list.r_paren_token().as_ref() == Some(&token);
76                     if cursor_outside {
77                         continue;
78                     }
79                     return signature_help_for_call(&sema, arg_list, token);
80                 },
81                 ast::GenericArgList(garg_list) => {
82                     let cursor_outside = garg_list.r_angle_token().as_ref() == Some(&token);
83                     if cursor_outside {
84                         continue;
85                     }
86                     return signature_help_for_generics(&sema, garg_list, token);
87                 },
88                 _ => (),
89             }
90         }
91
92         // Stop at multi-line expressions, since the signature of the outer call is not very
93         // helpful inside them.
94         if let Some(expr) = ast::Expr::cast(node.clone()) {
95             if expr.syntax().text().contains_char('\n') {
96                 return None;
97             }
98         }
99     }
100
101     None
102 }
103
104 fn signature_help_for_call(
105     sema: &Semantics<'_, RootDatabase>,
106     arg_list: ast::ArgList,
107     token: SyntaxToken,
108 ) -> Option<SignatureHelp> {
109     // Find the calling expression and its NameRef
110     let mut node = arg_list.syntax().parent()?;
111     let calling_node = loop {
112         if let Some(callable) = ast::CallableExpr::cast(node.clone()) {
113             if callable
114                 .arg_list()
115                 .map_or(false, |it| it.syntax().text_range().contains(token.text_range().start()))
116             {
117                 break callable;
118             }
119         }
120
121         node = node.parent()?;
122     };
123
124     let (callable, active_parameter) = callable_for_node(sema, &calling_node, &token)?;
125
126     let mut res =
127         SignatureHelp { doc: None, signature: String::new(), parameters: vec![], active_parameter };
128
129     let db = sema.db;
130     let mut fn_params = None;
131     match callable.kind() {
132         hir::CallableKind::Function(func) => {
133             res.doc = func.docs(db).map(|it| it.into());
134             format_to!(res.signature, "fn {}", func.name(db));
135             fn_params = Some(match callable.receiver_param(db) {
136                 Some(_self) => func.params_without_self(db),
137                 None => func.assoc_fn_params(db),
138             });
139         }
140         hir::CallableKind::TupleStruct(strukt) => {
141             res.doc = strukt.docs(db).map(|it| it.into());
142             format_to!(res.signature, "struct {}", strukt.name(db));
143         }
144         hir::CallableKind::TupleEnumVariant(variant) => {
145             res.doc = variant.docs(db).map(|it| it.into());
146             format_to!(
147                 res.signature,
148                 "enum {}::{}",
149                 variant.parent_enum(db).name(db),
150                 variant.name(db)
151             );
152         }
153         hir::CallableKind::Closure | hir::CallableKind::FnPtr | hir::CallableKind::Other => (),
154     }
155
156     res.signature.push('(');
157     {
158         if let Some(self_param) = callable.receiver_param(db) {
159             format_to!(res.signature, "{}", self_param)
160         }
161         let mut buf = String::new();
162         for (idx, (pat, ty)) in callable.params(db).into_iter().enumerate() {
163             buf.clear();
164             if let Some(pat) = pat {
165                 match pat {
166                     Either::Left(_self) => format_to!(buf, "self: "),
167                     Either::Right(pat) => format_to!(buf, "{}: ", pat),
168                 }
169             }
170             // APITs (argument position `impl Trait`s) are inferred as {unknown} as the user is
171             // in the middle of entering call arguments.
172             // In that case, fall back to render definitions of the respective parameters.
173             // This is overly conservative: we do not substitute known type vars
174             // (see FIXME in tests::impl_trait) and falling back on any unknowns.
175             match (ty.contains_unknown(), fn_params.as_deref()) {
176                 (true, Some(fn_params)) => format_to!(buf, "{}", fn_params[idx].ty().display(db)),
177                 _ => format_to!(buf, "{}", ty.display(db)),
178             }
179             res.push_call_param(&buf);
180         }
181     }
182     res.signature.push(')');
183
184     let mut render = |ret_type: hir::Type| {
185         if !ret_type.is_unit() {
186             format_to!(res.signature, " -> {}", ret_type.display(db));
187         }
188     };
189     match callable.kind() {
190         hir::CallableKind::Function(func) if callable.return_type().contains_unknown() => {
191             render(func.ret_type(db))
192         }
193         hir::CallableKind::Function(_)
194         | hir::CallableKind::Closure
195         | hir::CallableKind::FnPtr
196         | hir::CallableKind::Other => render(callable.return_type()),
197         hir::CallableKind::TupleStruct(_) | hir::CallableKind::TupleEnumVariant(_) => {}
198     }
199     Some(res)
200 }
201
202 fn signature_help_for_generics(
203     sema: &Semantics<'_, RootDatabase>,
204     garg_list: ast::GenericArgList,
205     token: SyntaxToken,
206 ) -> Option<SignatureHelp> {
207     let arg_list = garg_list
208         .syntax()
209         .ancestors()
210         .filter_map(ast::GenericArgList::cast)
211         .find(|list| list.syntax().text_range().contains(token.text_range().start()))?;
212
213     let mut active_parameter = arg_list
214         .generic_args()
215         .take_while(|arg| arg.syntax().text_range().end() <= token.text_range().start())
216         .count();
217
218     let first_arg_is_non_lifetime = arg_list
219         .generic_args()
220         .next()
221         .map_or(false, |arg| !matches!(arg, ast::GenericArg::LifetimeArg(_)));
222
223     let mut generics_def = if let Some(path) =
224         arg_list.syntax().ancestors().find_map(ast::Path::cast)
225     {
226         let res = sema.resolve_path(&path)?;
227         let generic_def: hir::GenericDef = match res {
228             hir::PathResolution::Def(hir::ModuleDef::Adt(it)) => it.into(),
229             hir::PathResolution::Def(hir::ModuleDef::Function(it)) => it.into(),
230             hir::PathResolution::Def(hir::ModuleDef::Trait(it)) => it.into(),
231             hir::PathResolution::Def(hir::ModuleDef::TypeAlias(it)) => it.into(),
232             hir::PathResolution::Def(hir::ModuleDef::Variant(it)) => it.into(),
233             hir::PathResolution::Def(hir::ModuleDef::BuiltinType(_))
234             | hir::PathResolution::Def(hir::ModuleDef::Const(_))
235             | hir::PathResolution::Def(hir::ModuleDef::Macro(_))
236             | hir::PathResolution::Def(hir::ModuleDef::Module(_))
237             | hir::PathResolution::Def(hir::ModuleDef::Static(_)) => return None,
238             hir::PathResolution::BuiltinAttr(_)
239             | hir::PathResolution::ToolModule(_)
240             | hir::PathResolution::Local(_)
241             | hir::PathResolution::TypeParam(_)
242             | hir::PathResolution::ConstParam(_)
243             | hir::PathResolution::SelfType(_)
244             | hir::PathResolution::DeriveHelper(_) => return None,
245         };
246
247         generic_def
248     } else if let Some(method_call) = arg_list.syntax().parent().and_then(ast::MethodCallExpr::cast)
249     {
250         // recv.method::<$0>()
251         let method = sema.resolve_method_call(&method_call)?;
252         method.into()
253     } else {
254         return None;
255     };
256
257     let mut res = SignatureHelp {
258         doc: None,
259         signature: String::new(),
260         parameters: vec![],
261         active_parameter: None,
262     };
263
264     let db = sema.db;
265     match generics_def {
266         hir::GenericDef::Function(it) => {
267             res.doc = it.docs(db).map(|it| it.into());
268             format_to!(res.signature, "fn {}", it.name(db));
269         }
270         hir::GenericDef::Adt(hir::Adt::Enum(it)) => {
271             res.doc = it.docs(db).map(|it| it.into());
272             format_to!(res.signature, "enum {}", it.name(db));
273         }
274         hir::GenericDef::Adt(hir::Adt::Struct(it)) => {
275             res.doc = it.docs(db).map(|it| it.into());
276             format_to!(res.signature, "struct {}", it.name(db));
277         }
278         hir::GenericDef::Adt(hir::Adt::Union(it)) => {
279             res.doc = it.docs(db).map(|it| it.into());
280             format_to!(res.signature, "union {}", it.name(db));
281         }
282         hir::GenericDef::Trait(it) => {
283             res.doc = it.docs(db).map(|it| it.into());
284             format_to!(res.signature, "trait {}", it.name(db));
285         }
286         hir::GenericDef::TypeAlias(it) => {
287             res.doc = it.docs(db).map(|it| it.into());
288             format_to!(res.signature, "type {}", it.name(db));
289         }
290         hir::GenericDef::Variant(it) => {
291             // In paths, generics of an enum can be specified *after* one of its variants.
292             // eg. `None::<u8>`
293             // We'll use the signature of the enum, but include the docs of the variant.
294             res.doc = it.docs(db).map(|it| it.into());
295             let it = it.parent_enum(db);
296             format_to!(res.signature, "enum {}", it.name(db));
297             generics_def = it.into();
298         }
299         // These don't have generic args that can be specified
300         hir::GenericDef::Impl(_) | hir::GenericDef::Const(_) => return None,
301     }
302
303     let params = generics_def.params(sema.db);
304     let num_lifetime_params =
305         params.iter().take_while(|param| matches!(param, GenericParam::LifetimeParam(_))).count();
306     if first_arg_is_non_lifetime {
307         // Lifetime parameters were omitted.
308         active_parameter += num_lifetime_params;
309     }
310     res.active_parameter = Some(active_parameter);
311
312     res.signature.push('<');
313     let mut buf = String::new();
314     for param in params {
315         if let hir::GenericParam::TypeParam(ty) = param {
316             if ty.is_implicit(db) {
317                 continue;
318             }
319         }
320
321         buf.clear();
322         format_to!(buf, "{}", param.display(db));
323         res.push_generic_param(&buf);
324     }
325     if let hir::GenericDef::Trait(tr) = generics_def {
326         add_assoc_type_bindings(db, &mut res, tr, arg_list);
327     }
328     res.signature.push('>');
329
330     Some(res)
331 }
332
333 fn add_assoc_type_bindings(
334     db: &RootDatabase,
335     res: &mut SignatureHelp,
336     tr: Trait,
337     args: ast::GenericArgList,
338 ) {
339     if args.syntax().ancestors().find_map(ast::TypeBound::cast).is_none() {
340         // Assoc type bindings are only valid in type bound position.
341         return;
342     }
343
344     let present_bindings = args
345         .generic_args()
346         .filter_map(|arg| match arg {
347             ast::GenericArg::AssocTypeArg(arg) => arg.name_ref().map(|n| n.to_string()),
348             _ => None,
349         })
350         .collect::<BTreeSet<_>>();
351
352     let mut buf = String::new();
353     for binding in &present_bindings {
354         buf.clear();
355         format_to!(buf, "{} = …", binding);
356         res.push_generic_param(&buf);
357     }
358
359     for item in tr.items_with_supertraits(db) {
360         if let AssocItem::TypeAlias(ty) = item {
361             let name = ty.name(db).to_smol_str();
362             if !present_bindings.contains(&*name) {
363                 buf.clear();
364                 format_to!(buf, "{} = …", name);
365                 res.push_generic_param(&buf);
366             }
367         }
368     }
369 }
370
371 #[cfg(test)]
372 mod tests {
373     use std::iter;
374
375     use expect_test::{expect, Expect};
376     use ide_db::base_db::{fixture::ChangeFixture, FilePosition};
377     use stdx::format_to;
378
379     use crate::RootDatabase;
380
381     /// Creates analysis from a multi-file fixture, returns positions marked with $0.
382     pub(crate) fn position(ra_fixture: &str) -> (RootDatabase, FilePosition) {
383         let change_fixture = ChangeFixture::parse(ra_fixture);
384         let mut database = RootDatabase::default();
385         database.apply_change(change_fixture.change);
386         let (file_id, range_or_offset) =
387             change_fixture.file_position.expect("expected a marker ($0)");
388         let offset = range_or_offset.expect_offset();
389         (database, FilePosition { file_id, offset })
390     }
391
392     fn check(ra_fixture: &str, expect: Expect) {
393         let fixture = format!(
394             r#"
395 //- minicore: sized, fn
396 {ra_fixture}
397             "#
398         );
399         let (db, position) = position(&fixture);
400         let sig_help = crate::signature_help::signature_help(&db, position);
401         let actual = match sig_help {
402             Some(sig_help) => {
403                 let mut rendered = String::new();
404                 if let Some(docs) = &sig_help.doc {
405                     format_to!(rendered, "{}\n------\n", docs.as_str());
406                 }
407                 format_to!(rendered, "{}\n", sig_help.signature);
408                 let mut offset = 0;
409                 for (i, range) in sig_help.parameter_ranges().iter().enumerate() {
410                     let is_active = sig_help.active_parameter == Some(i);
411
412                     let start = u32::from(range.start());
413                     let gap = start.checked_sub(offset).unwrap_or_else(|| {
414                         panic!("parameter ranges out of order: {:?}", sig_help.parameter_ranges())
415                     });
416                     rendered.extend(iter::repeat(' ').take(gap as usize));
417                     let param_text = &sig_help.signature[*range];
418                     let width = param_text.chars().count(); // …
419                     let marker = if is_active { '^' } else { '-' };
420                     rendered.extend(iter::repeat(marker).take(width));
421                     offset += gap + u32::from(range.len());
422                 }
423                 if !sig_help.parameter_ranges().is_empty() {
424                     format_to!(rendered, "\n");
425                 }
426                 rendered
427             }
428             None => String::new(),
429         };
430         expect.assert_eq(&actual);
431     }
432
433     #[test]
434     fn test_fn_signature_two_args() {
435         check(
436             r#"
437 fn foo(x: u32, y: u32) -> u32 {x + y}
438 fn bar() { foo($03, ); }
439 "#,
440             expect![[r#"
441                 fn foo(x: u32, y: u32) -> u32
442                        ^^^^^^  ------
443             "#]],
444         );
445         check(
446             r#"
447 fn foo(x: u32, y: u32) -> u32 {x + y}
448 fn bar() { foo(3$0, ); }
449 "#,
450             expect![[r#"
451                 fn foo(x: u32, y: u32) -> u32
452                        ^^^^^^  ------
453             "#]],
454         );
455         check(
456             r#"
457 fn foo(x: u32, y: u32) -> u32 {x + y}
458 fn bar() { foo(3,$0 ); }
459 "#,
460             expect![[r#"
461                 fn foo(x: u32, y: u32) -> u32
462                        ------  ^^^^^^
463             "#]],
464         );
465         check(
466             r#"
467 fn foo(x: u32, y: u32) -> u32 {x + y}
468 fn bar() { foo(3, $0); }
469 "#,
470             expect![[r#"
471                 fn foo(x: u32, y: u32) -> u32
472                        ------  ^^^^^^
473             "#]],
474         );
475     }
476
477     #[test]
478     fn test_fn_signature_two_args_empty() {
479         check(
480             r#"
481 fn foo(x: u32, y: u32) -> u32 {x + y}
482 fn bar() { foo($0); }
483 "#,
484             expect![[r#"
485                 fn foo(x: u32, y: u32) -> u32
486                        ^^^^^^  ------
487             "#]],
488         );
489     }
490
491     #[test]
492     fn test_fn_signature_two_args_first_generics() {
493         check(
494             r#"
495 fn foo<T, U: Copy + Display>(x: T, y: U) -> u32
496     where T: Copy + Display, U: Debug
497 { x + y }
498
499 fn bar() { foo($03, ); }
500 "#,
501             expect![[r#"
502                 fn foo(x: i32, y: U) -> u32
503                        ^^^^^^  ----
504             "#]],
505         );
506     }
507
508     #[test]
509     fn test_fn_signature_no_params() {
510         check(
511             r#"
512 fn foo<T>() -> T where T: Copy + Display {}
513 fn bar() { foo($0); }
514 "#,
515             expect![[r#"
516                 fn foo() -> T
517             "#]],
518         );
519     }
520
521     #[test]
522     fn test_fn_signature_for_impl() {
523         check(
524             r#"
525 struct F;
526 impl F { pub fn new() { } }
527 fn bar() {
528     let _ : F = F::new($0);
529 }
530 "#,
531             expect![[r#"
532                 fn new()
533             "#]],
534         );
535     }
536
537     #[test]
538     fn test_fn_signature_for_method_self() {
539         check(
540             r#"
541 struct S;
542 impl S { pub fn do_it(&self) {} }
543
544 fn bar() {
545     let s: S = S;
546     s.do_it($0);
547 }
548 "#,
549             expect![[r#"
550                 fn do_it(&self)
551             "#]],
552         );
553     }
554
555     #[test]
556     fn test_fn_signature_for_method_with_arg() {
557         check(
558             r#"
559 struct S;
560 impl S {
561     fn foo(&self, x: i32) {}
562 }
563
564 fn main() { S.foo($0); }
565 "#,
566             expect![[r#"
567                 fn foo(&self, x: i32)
568                               ^^^^^^
569             "#]],
570         );
571     }
572
573     #[test]
574     fn test_fn_signature_for_generic_method() {
575         check(
576             r#"
577 struct S<T>(T);
578 impl<T> S<T> {
579     fn foo(&self, x: T) {}
580 }
581
582 fn main() { S(1u32).foo($0); }
583 "#,
584             expect![[r#"
585                 fn foo(&self, x: u32)
586                               ^^^^^^
587             "#]],
588         );
589     }
590
591     #[test]
592     fn test_fn_signature_for_method_with_arg_as_assoc_fn() {
593         check(
594             r#"
595 struct S;
596 impl S {
597     fn foo(&self, x: i32) {}
598 }
599
600 fn main() { S::foo($0); }
601 "#,
602             expect![[r#"
603                 fn foo(self: &S, x: i32)
604                        ^^^^^^^^  ------
605             "#]],
606         );
607     }
608
609     #[test]
610     fn test_fn_signature_with_docs_simple() {
611         check(
612             r#"
613 /// test
614 // non-doc-comment
615 fn foo(j: u32) -> u32 {
616     j
617 }
618
619 fn bar() {
620     let _ = foo($0);
621 }
622 "#,
623             expect![[r#"
624                 test
625                 ------
626                 fn foo(j: u32) -> u32
627                        ^^^^^^
628             "#]],
629         );
630     }
631
632     #[test]
633     fn test_fn_signature_with_docs() {
634         check(
635             r#"
636 /// Adds one to the number given.
637 ///
638 /// # Examples
639 ///
640 /// ```
641 /// let five = 5;
642 ///
643 /// assert_eq!(6, my_crate::add_one(5));
644 /// ```
645 pub fn add_one(x: i32) -> i32 {
646     x + 1
647 }
648
649 pub fn do() {
650     add_one($0
651 }"#,
652             expect![[r##"
653                 Adds one to the number given.
654
655                 # Examples
656
657                 ```
658                 let five = 5;
659
660                 assert_eq!(6, my_crate::add_one(5));
661                 ```
662                 ------
663                 fn add_one(x: i32) -> i32
664                            ^^^^^^
665             "##]],
666         );
667     }
668
669     #[test]
670     fn test_fn_signature_with_docs_impl() {
671         check(
672             r#"
673 struct addr;
674 impl addr {
675     /// Adds one to the number given.
676     ///
677     /// # Examples
678     ///
679     /// ```
680     /// let five = 5;
681     ///
682     /// assert_eq!(6, my_crate::add_one(5));
683     /// ```
684     pub fn add_one(x: i32) -> i32 {
685         x + 1
686     }
687 }
688
689 pub fn do_it() {
690     addr {};
691     addr::add_one($0);
692 }
693 "#,
694             expect![[r##"
695                 Adds one to the number given.
696
697                 # Examples
698
699                 ```
700                 let five = 5;
701
702                 assert_eq!(6, my_crate::add_one(5));
703                 ```
704                 ------
705                 fn add_one(x: i32) -> i32
706                            ^^^^^^
707             "##]],
708         );
709     }
710
711     #[test]
712     fn test_fn_signature_with_docs_from_actix() {
713         check(
714             r#"
715 trait Actor {
716     /// Actor execution context type
717     type Context;
718 }
719 trait WriteHandler<E>
720 where
721     Self: Actor
722 {
723     /// Method is called when writer finishes.
724     ///
725     /// By default this method stops actor's `Context`.
726     fn finished(&mut self, ctx: &mut Self::Context) {}
727 }
728
729 fn foo(mut r: impl WriteHandler<()>) {
730     r.finished($0);
731 }
732 "#,
733             expect![[r#"
734                 Method is called when writer finishes.
735
736                 By default this method stops actor's `Context`.
737                 ------
738                 fn finished(&mut self, ctx: &mut <impl WriteHandler<()> as Actor>::Context)
739                                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
740             "#]],
741         );
742     }
743
744     #[test]
745     fn call_info_bad_offset() {
746         check(
747             r#"
748 fn foo(x: u32, y: u32) -> u32 {x + y}
749 fn bar() { foo $0 (3, ); }
750 "#,
751             expect![[""]],
752         );
753     }
754
755     #[test]
756     fn outside_of_arg_list() {
757         check(
758             r#"
759 fn foo(a: u8) {}
760 fn f() {
761     foo(123)$0
762 }
763 "#,
764             expect![[]],
765         );
766         check(
767             r#"
768 fn foo<T>(a: u8) {}
769 fn f() {
770     foo::<u32>$0()
771 }
772 "#,
773             expect![[]],
774         );
775         check(
776             r#"
777 fn foo(a: u8) -> u8 {a}
778 fn bar(a: u8) -> u8 {a}
779 fn f() {
780     foo(bar(123)$0)
781 }
782 "#,
783             expect![[r#"
784                 fn foo(a: u8) -> u8
785                        ^^^^^
786             "#]],
787         );
788         check(
789             r#"
790 struct Vec<T>(T);
791 struct Vec2<T>(T);
792 fn f() {
793     let _: Vec2<Vec<u8>$0>
794 }
795 "#,
796             expect![[r#"
797                 struct Vec2<T>
798                             ^
799             "#]],
800         );
801     }
802
803     #[test]
804     fn test_nested_method_in_lambda() {
805         check(
806             r#"
807 struct Foo;
808 impl Foo { fn bar(&self, _: u32) { } }
809
810 fn bar(_: u32) { }
811
812 fn main() {
813     let foo = Foo;
814     std::thread::spawn(move || foo.bar($0));
815 }
816 "#,
817             expect![[r#"
818                 fn bar(&self, _: u32)
819                               ^^^^^^
820             "#]],
821         );
822     }
823
824     #[test]
825     fn works_for_tuple_structs() {
826         check(
827             r#"
828 /// A cool tuple struct
829 struct S(u32, i32);
830 fn main() {
831     let s = S(0, $0);
832 }
833 "#,
834             expect![[r#"
835                 A cool tuple struct
836                 ------
837                 struct S(u32, i32)
838                          ---  ^^^
839             "#]],
840         );
841     }
842
843     #[test]
844     fn generic_struct() {
845         check(
846             r#"
847 struct S<T>(T);
848 fn main() {
849     let s = S($0);
850 }
851 "#,
852             expect![[r#"
853                 struct S({unknown})
854                          ^^^^^^^^^
855             "#]],
856         );
857     }
858
859     #[test]
860     fn works_for_enum_variants() {
861         check(
862             r#"
863 enum E {
864     /// A Variant
865     A(i32),
866     /// Another
867     B,
868     /// And C
869     C { a: i32, b: i32 }
870 }
871
872 fn main() {
873     let a = E::A($0);
874 }
875 "#,
876             expect![[r#"
877                 A Variant
878                 ------
879                 enum E::A(i32)
880                           ^^^
881             "#]],
882         );
883     }
884
885     #[test]
886     fn cant_call_struct_record() {
887         check(
888             r#"
889 struct S { x: u32, y: i32 }
890 fn main() {
891     let s = S($0);
892 }
893 "#,
894             expect![[""]],
895         );
896     }
897
898     #[test]
899     fn cant_call_enum_record() {
900         check(
901             r#"
902 enum E {
903     /// A Variant
904     A(i32),
905     /// Another
906     B,
907     /// And C
908     C { a: i32, b: i32 }
909 }
910
911 fn main() {
912     let a = E::C($0);
913 }
914 "#,
915             expect![[""]],
916         );
917     }
918
919     #[test]
920     fn fn_signature_for_call_in_macro() {
921         check(
922             r#"
923 macro_rules! id { ($($tt:tt)*) => { $($tt)* } }
924 fn foo() { }
925 id! {
926     fn bar() { foo($0); }
927 }
928 "#,
929             expect![[r#"
930                 fn foo()
931             "#]],
932         );
933     }
934
935     #[test]
936     fn call_info_for_lambdas() {
937         check(
938             r#"
939 struct S;
940 fn foo(s: S) -> i32 { 92 }
941 fn main() {
942     (|s| foo(s))($0)
943 }
944         "#,
945             expect![[r#"
946                 (s: S) -> i32
947                  ^^^^
948             "#]],
949         )
950     }
951
952     #[test]
953     fn call_info_for_fn_ptr() {
954         check(
955             r#"
956 fn main(f: fn(i32, f64) -> char) {
957     f(0, $0)
958 }
959         "#,
960             expect![[r#"
961                 (i32, f64) -> char
962                  ---  ^^^
963             "#]],
964         )
965     }
966
967     #[test]
968     fn call_info_for_unclosed_call() {
969         check(
970             r#"
971 fn foo(foo: u32, bar: u32) {}
972 fn main() {
973     foo($0
974 }"#,
975             expect![[r#"
976                 fn foo(foo: u32, bar: u32)
977                        ^^^^^^^^  --------
978             "#]],
979         );
980         // check with surrounding space
981         check(
982             r#"
983 fn foo(foo: u32, bar: u32) {}
984 fn main() {
985     foo( $0
986 }"#,
987             expect![[r#"
988                 fn foo(foo: u32, bar: u32)
989                        ^^^^^^^^  --------
990             "#]],
991         )
992     }
993
994     #[test]
995     fn test_multiline_argument() {
996         check(
997             r#"
998 fn callee(a: u8, b: u8) {}
999 fn main() {
1000     callee(match 0 {
1001         0 => 1,$0
1002     })
1003 }"#,
1004             expect![[r#""#]],
1005         );
1006         check(
1007             r#"
1008 fn callee(a: u8, b: u8) {}
1009 fn main() {
1010     callee(match 0 {
1011         0 => 1,
1012     },$0)
1013 }"#,
1014             expect![[r#"
1015                 fn callee(a: u8, b: u8)
1016                           -----  ^^^^^
1017             "#]],
1018         );
1019         check(
1020             r#"
1021 fn callee(a: u8, b: u8) {}
1022 fn main() {
1023     callee($0match 0 {
1024         0 => 1,
1025     })
1026 }"#,
1027             expect![[r#"
1028                 fn callee(a: u8, b: u8)
1029                           ^^^^^  -----
1030             "#]],
1031         );
1032     }
1033
1034     #[test]
1035     fn test_generics_simple() {
1036         check(
1037             r#"
1038 /// Option docs.
1039 enum Option<T> {
1040     Some(T),
1041     None,
1042 }
1043
1044 fn f() {
1045     let opt: Option<$0
1046 }
1047         "#,
1048             expect![[r#"
1049                 Option docs.
1050                 ------
1051                 enum Option<T>
1052                             ^
1053             "#]],
1054         );
1055     }
1056
1057     #[test]
1058     fn test_generics_on_variant() {
1059         check(
1060             r#"
1061 /// Option docs.
1062 enum Option<T> {
1063     /// Some docs.
1064     Some(T),
1065     /// None docs.
1066     None,
1067 }
1068
1069 use Option::*;
1070
1071 fn f() {
1072     None::<$0
1073 }
1074         "#,
1075             expect![[r#"
1076                 None docs.
1077                 ------
1078                 enum Option<T>
1079                             ^
1080             "#]],
1081         );
1082     }
1083
1084     #[test]
1085     fn test_lots_of_generics() {
1086         check(
1087             r#"
1088 trait Tr<T> {}
1089
1090 struct S<T>(T);
1091
1092 impl<T> S<T> {
1093     fn f<G, H>(g: G, h: impl Tr<G>) where G: Tr<()> {}
1094 }
1095
1096 fn f() {
1097     S::<u8>::f::<(), $0
1098 }
1099         "#,
1100             expect![[r#"
1101                 fn f<G: Tr<()>, H>
1102                      ---------  ^
1103             "#]],
1104         );
1105     }
1106
1107     #[test]
1108     fn test_generics_in_trait_ufcs() {
1109         check(
1110             r#"
1111 trait Tr {
1112     fn f<T: Tr, U>() {}
1113 }
1114
1115 struct S;
1116
1117 impl Tr for S {}
1118
1119 fn f() {
1120     <S as Tr>::f::<$0
1121 }
1122         "#,
1123             expect![[r#"
1124                 fn f<T: Tr, U>
1125                      ^^^^^  -
1126             "#]],
1127         );
1128     }
1129
1130     #[test]
1131     fn test_generics_in_method_call() {
1132         check(
1133             r#"
1134 struct S;
1135
1136 impl S {
1137     fn f<T>(&self) {}
1138 }
1139
1140 fn f() {
1141     S.f::<$0
1142 }
1143         "#,
1144             expect![[r#"
1145                 fn f<T>
1146                      ^
1147             "#]],
1148         );
1149     }
1150
1151     #[test]
1152     fn test_generic_param_in_method_call() {
1153         check(
1154             r#"
1155 struct Foo;
1156 impl Foo {
1157     fn test<V>(&mut self, val: V) {}
1158 }
1159 fn sup() {
1160     Foo.test($0)
1161 }
1162 "#,
1163             expect![[r#"
1164                 fn test(&mut self, val: V)
1165                                    ^^^^^^
1166             "#]],
1167         );
1168     }
1169
1170     #[test]
1171     fn test_generic_kinds() {
1172         check(
1173             r#"
1174 fn callee<'a, const A: u8, T, const C: u8>() {}
1175
1176 fn f() {
1177     callee::<'static, $0
1178 }
1179         "#,
1180             expect![[r#"
1181                 fn callee<'a, const A: u8, T, const C: u8>
1182                           --  ^^^^^^^^^^^  -  -----------
1183             "#]],
1184         );
1185         check(
1186             r#"
1187 fn callee<'a, const A: u8, T, const C: u8>() {}
1188
1189 fn f() {
1190     callee::<NON_LIFETIME$0
1191 }
1192         "#,
1193             expect![[r#"
1194                 fn callee<'a, const A: u8, T, const C: u8>
1195                           --  ^^^^^^^^^^^  -  -----------
1196             "#]],
1197         );
1198     }
1199
1200     #[test]
1201     fn test_trait_assoc_types() {
1202         check(
1203             r#"
1204 trait Trait<'a, T> {
1205     type Assoc;
1206 }
1207 fn f() -> impl Trait<(), $0
1208             "#,
1209             expect![[r#"
1210                 trait Trait<'a, T, Assoc = …>
1211                             --  -  ^^^^^^^^^
1212             "#]],
1213         );
1214         check(
1215             r#"
1216 trait Iterator {
1217     type Item;
1218 }
1219 fn f() -> impl Iterator<$0
1220             "#,
1221             expect![[r#"
1222                 trait Iterator<Item = …>
1223                                ^^^^^^^^
1224             "#]],
1225         );
1226         check(
1227             r#"
1228 trait Iterator {
1229     type Item;
1230 }
1231 fn f() -> impl Iterator<Item = $0
1232             "#,
1233             expect![[r#"
1234                 trait Iterator<Item = …>
1235                                ^^^^^^^^
1236             "#]],
1237         );
1238         check(
1239             r#"
1240 trait Tr {
1241     type A;
1242     type B;
1243 }
1244 fn f() -> impl Tr<$0
1245             "#,
1246             expect![[r#"
1247                 trait Tr<A = …, B = …>
1248                          ^^^^^  -----
1249             "#]],
1250         );
1251         check(
1252             r#"
1253 trait Tr {
1254     type A;
1255     type B;
1256 }
1257 fn f() -> impl Tr<B$0
1258             "#,
1259             expect![[r#"
1260                 trait Tr<A = …, B = …>
1261                          ^^^^^  -----
1262             "#]],
1263         );
1264         check(
1265             r#"
1266 trait Tr {
1267     type A;
1268     type B;
1269 }
1270 fn f() -> impl Tr<B = $0
1271             "#,
1272             expect![[r#"
1273                 trait Tr<B = …, A = …>
1274                          ^^^^^  -----
1275             "#]],
1276         );
1277         check(
1278             r#"
1279 trait Tr {
1280     type A;
1281     type B;
1282 }
1283 fn f() -> impl Tr<B = (), $0
1284             "#,
1285             expect![[r#"
1286                 trait Tr<B = …, A = …>
1287                          -----  ^^^^^
1288             "#]],
1289         );
1290     }
1291
1292     #[test]
1293     fn test_supertrait_assoc() {
1294         check(
1295             r#"
1296 trait Super {
1297     type SuperTy;
1298 }
1299 trait Sub: Super + Super {
1300     type SubTy;
1301 }
1302 fn f() -> impl Sub<$0
1303             "#,
1304             expect![[r#"
1305                 trait Sub<SubTy = …, SuperTy = …>
1306                           ^^^^^^^^^  -----------
1307             "#]],
1308         );
1309     }
1310
1311     #[test]
1312     fn no_assoc_types_outside_type_bounds() {
1313         check(
1314             r#"
1315 trait Tr<T> {
1316     type Assoc;
1317 }
1318
1319 impl Tr<$0
1320         "#,
1321             expect![[r#"
1322             trait Tr<T>
1323                      ^
1324         "#]],
1325         );
1326     }
1327
1328     #[test]
1329     fn impl_trait() {
1330         // FIXME: Substitute type vars in impl trait (`U` -> `i8`)
1331         check(
1332             r#"
1333 trait Trait<T> {}
1334 struct Wrap<T>(T);
1335 fn foo<U>(x: Wrap<impl Trait<U>>) {}
1336 fn f() {
1337     foo::<i8>($0)
1338 }
1339 "#,
1340             expect![[r#"
1341                 fn foo(x: Wrap<impl Trait<U>>)
1342                        ^^^^^^^^^^^^^^^^^^^^^^
1343             "#]],
1344         );
1345     }
1346
1347     #[test]
1348     fn fully_qualified_syntax() {
1349         check(
1350             r#"
1351 fn f() {
1352     trait A { fn foo(&self, other: Self); }
1353     A::foo(&self$0, other);
1354 }
1355 "#,
1356             expect![[r#"
1357                 fn foo(self: &Self, other: Self)
1358                        ^^^^^^^^^^^  -----------
1359             "#]],
1360         );
1361     }
1362
1363     #[test]
1364     fn help_for_generic_call() {
1365         check(
1366             r#"
1367 fn f<F: FnOnce(u8, u16) -> i32>(f: F) {
1368     f($0)
1369 }
1370 "#,
1371             expect![[r#"
1372                 (u8, u16) -> i32
1373                  ^^  ---
1374             "#]],
1375         );
1376         check(
1377             r#"
1378 fn f<T, F: FnOnce(&T, u16) -> &T>(f: F) {
1379     f($0)
1380 }
1381 "#,
1382             expect![[r#"
1383                 (&T, u16) -> &T
1384                  ^^  ---
1385             "#]],
1386         );
1387     }
1388
1389     #[test]
1390     fn regression_13579() {
1391         check(
1392             r#"
1393 fn f() {
1394     take(2)($0);
1395 }
1396
1397 fn take<C, Error>(
1398     count: C
1399 ) -> impl Fn() -> C  {
1400     move || count
1401 }
1402 "#,
1403             expect![[r#"
1404                 () -> i32
1405             "#]],
1406         );
1407     }
1408 }