2 use hir::{known, Callable, HasVisibility, HirDisplay, Semantics, TypeInfo};
3 use ide_db::RootDatabase;
4 use ide_db::{base_db::FileRange, helpers::FamousDefs};
5 use itertools::Itertools;
6 use stdx::to_lower_snake_case;
8 ast::{self, AstNode, HasArgList, HasName},
9 match_ast, Direction, NodeOrToken, SmolStr, SyntaxKind, TextRange, T,
14 #[derive(Clone, Debug, PartialEq, Eq)]
15 pub struct InlayHintsConfig {
17 pub parameter_hints: bool,
18 pub chaining_hints: bool,
19 pub max_length: Option<usize>,
22 #[derive(Clone, Debug, PartialEq, Eq)]
30 pub struct InlayHint {
36 // Feature: Inlay Hints
38 // rust-analyzer shows additional information inline with the source code.
39 // Editors usually render this using read-only virtual text snippets interspersed with code.
41 // rust-analyzer shows hints for
43 // * types of local variables
44 // * names of function arguments
45 // * types of chained expressions
47 // **Note:** VS Code does not have native support for inlay hints https://github.com/microsoft/vscode/issues/16221[yet] and the hints are implemented using decorations.
48 // This approach has limitations, the caret movement and bracket highlighting near the edges of the hint may be weird:
49 // https://github.com/rust-analyzer/rust-analyzer/issues/1623[1], https://github.com/rust-analyzer/rust-analyzer/issues/3453[2].
52 // | Editor | Action Name
54 // | VS Code | **Rust Analyzer: Toggle inlay hints*
57 // image::https://user-images.githubusercontent.com/48062697/113020660-b5f98b80-917a-11eb-8d70-3be3fd558cdd.png[]
58 pub(crate) fn inlay_hints(
61 config: &InlayHintsConfig,
63 let _p = profile::span("inlay_hints");
64 let sema = Semantics::new(db);
65 let file = sema.parse(file_id);
66 let file = file.syntax();
68 let mut res = Vec::new();
70 for node in file.descendants() {
71 if let Some(expr) = ast::Expr::cast(node.clone()) {
72 get_chaining_hints(&mut res, &sema, config, &expr);
74 ast::Expr::CallExpr(it) => {
75 get_param_name_hints(&mut res, &sema, config, ast::Expr::from(it));
77 ast::Expr::MethodCallExpr(it) => {
78 get_param_name_hints(&mut res, &sema, config, ast::Expr::from(it));
82 } else if let Some(it) = ast::IdentPat::cast(node.clone()) {
83 get_bind_pat_hints(&mut res, &sema, config, &it);
89 fn get_chaining_hints(
90 acc: &mut Vec<InlayHint>,
91 sema: &Semantics<RootDatabase>,
92 config: &InlayHintsConfig,
95 if !config.chaining_hints {
99 if matches!(expr, ast::Expr::RecordExpr(_)) {
103 let descended = sema.descend_node_into_attributes(expr.clone()).pop();
104 let desc_expr = descended.as_ref().unwrap_or(expr);
105 let krate = sema.scope(desc_expr.syntax()).module().map(|it| it.krate());
106 let famous_defs = FamousDefs(sema, krate);
108 let mut tokens = expr
110 .siblings_with_tokens(Direction::Next)
111 .filter_map(NodeOrToken::into_token)
112 .filter(|t| match t.kind() {
113 SyntaxKind::WHITESPACE if !t.text().contains('\n') => false,
114 SyntaxKind::COMMENT => false,
118 // Chaining can be defined as an expression whose next sibling tokens are newline and dot
119 // Ignoring extra whitespace and comments
120 let next = tokens.next()?.kind();
121 if next == SyntaxKind::WHITESPACE {
122 let mut next_next = tokens.next()?.kind();
123 while next_next == SyntaxKind::WHITESPACE {
124 next_next = tokens.next()?.kind();
126 if next_next == T![.] {
127 let ty = sema.type_of_expr(desc_expr)?.original;
131 if matches!(expr, ast::Expr::PathExpr(_)) {
132 if let Some(hir::Adt::Struct(st)) = ty.as_adt() {
133 if st.fields(sema.db).is_empty() {
139 range: expr.syntax().text_range(),
140 kind: InlayKind::ChainingHint,
141 label: hint_iterator(sema, &famous_defs, config, &ty).unwrap_or_else(|| {
142 ty.display_truncated(sema.db, config.max_length).to_string().into()
150 fn get_param_name_hints(
151 acc: &mut Vec<InlayHint>,
152 sema: &Semantics<RootDatabase>,
153 config: &InlayHintsConfig,
156 if !config.parameter_hints {
160 let (callable, arg_list) = get_callable(sema, &expr)?;
164 .zip(arg_list.args())
165 .filter_map(|((param, _ty), arg)| {
166 // Only annotate hints for expressions that exist in the original file
167 let range = sema.original_range_opt(arg.syntax())?;
168 let param_name = match param? {
169 Either::Left(_) => "self".to_string(),
170 Either::Right(pat) => match pat {
171 ast::Pat::IdentPat(it) => it.name()?.to_string(),
175 Some((param_name, arg, range))
177 .filter(|(param_name, arg, _)| {
178 !should_hide_param_name_hint(sema, &callable, param_name, arg)
180 .map(|(param_name, _, FileRange { range, .. })| InlayHint {
182 kind: InlayKind::ParameterHint,
183 label: param_name.into(),
190 fn get_bind_pat_hints(
191 acc: &mut Vec<InlayHint>,
192 sema: &Semantics<RootDatabase>,
193 config: &InlayHintsConfig,
196 if !config.type_hints {
200 let descended = sema.descend_node_into_attributes(pat.clone()).pop();
201 let desc_pat = descended.as_ref().unwrap_or(pat);
202 let ty = sema.type_of_pat(&desc_pat.clone().into())?.original;
204 if should_not_display_type_hint(sema, pat, &ty) {
208 let krate = sema.scope(desc_pat.syntax()).module().map(|it| it.krate());
209 let famous_defs = FamousDefs(sema, krate);
210 let label = hint_iterator(sema, &famous_defs, config, &ty);
212 let label = match label {
213 Some(label) => label,
215 let ty_name = ty.display_truncated(sema.db, config.max_length).to_string();
216 if is_named_constructor(sema, pat, &ty_name).is_some() {
224 range: match pat.name() {
225 Some(name) => name.syntax().text_range(),
226 None => pat.syntax().text_range(),
228 kind: InlayKind::TypeHint,
235 fn is_named_constructor(
236 sema: &Semantics<RootDatabase>,
240 let let_node = pat.syntax().parent()?;
241 let expr = match_ast! {
243 ast::LetStmt(it) => it.initializer(),
244 ast::Condition(it) => it.expr(),
249 let expr = sema.descend_node_into_attributes(expr.clone()).pop().unwrap_or(expr);
250 // unwrap postfix expressions
251 let expr = match expr {
252 ast::Expr::TryExpr(it) => it.expr(),
253 ast::Expr::AwaitExpr(it) => it.expr(),
256 let expr = match expr {
257 ast::Expr::CallExpr(call) => match call.expr()? {
258 ast::Expr::PathExpr(p) => p,
263 let path = expr.path()?;
265 // Check for tuple-struct or tuple-variant in which case we can check the last segment
266 let callable = sema.type_of_expr(&ast::Expr::PathExpr(expr))?.original.as_callable(sema.db);
267 let callable_kind = callable.map(|it| it.kind());
268 if let Some(hir::CallableKind::TupleStruct(_) | hir::CallableKind::TupleEnumVariant(_)) =
271 if let Some(ctor) = path.segment() {
272 return (ctor.to_string() == ty_name).then(|| ());
276 // otherwise use the qualifying segment as the constructor name
277 let qual_seg = path.qualifier()?.segment()?;
278 let ctor_name = match qual_seg.kind()? {
279 ast::PathSegmentKind::Name(name_ref) => {
280 match qual_seg.generic_arg_list().map(|it| it.generic_args()) {
281 Some(generics) => format!("{}<{}>", name_ref, generics.format(", ")),
282 None => name_ref.to_string(),
285 ast::PathSegmentKind::Type { type_ref: Some(ty), trait_ref: None } => ty.to_string(),
288 (ctor_name == ty_name).then(|| ())
291 /// Checks if the type is an Iterator from std::iter and replaces its hint with an `impl Iterator<Item = Ty>`.
293 sema: &Semantics<RootDatabase>,
294 famous_defs: &FamousDefs,
295 config: &InlayHintsConfig,
297 ) -> Option<SmolStr> {
299 let strukt = ty.strip_references().as_adt()?;
300 let krate = strukt.module(db).krate();
301 if krate != famous_defs.core()? {
304 let iter_trait = famous_defs.core_iter_Iterator()?;
305 let iter_mod = famous_defs.core_iter()?;
307 // Assert that this struct comes from `core::iter`.
308 if !(strukt.visibility(db) == hir::Visibility::Public
309 && strukt.module(db).path_to_root(db).contains(&iter_mod))
314 if ty.impls_trait(db, iter_trait, &[]) {
315 let assoc_type_item = iter_trait.items(db).into_iter().find_map(|item| match item {
316 hir::AssocItem::TypeAlias(alias) if alias.name(db) == known::Item => Some(alias),
319 if let Some(ty) = ty.normalize_trait_assoc_type(db, &[], assoc_type_item) {
320 const LABEL_START: &str = "impl Iterator<Item = ";
321 const LABEL_END: &str = ">";
323 let ty_display = hint_iterator(sema, famous_defs, config, &ty)
324 .map(|assoc_type_impl| assoc_type_impl.to_string())
326 ty.display_truncated(
330 .map(|len| len.saturating_sub(LABEL_START.len() + LABEL_END.len())),
334 return Some(format!("{}{}{}", LABEL_START, ty_display, LABEL_END).into());
341 fn pat_is_enum_variant(db: &RootDatabase, bind_pat: &ast::IdentPat, pat_ty: &hir::Type) -> bool {
342 if let Some(hir::Adt::Enum(enum_data)) = pat_ty.as_adt() {
343 let pat_text = bind_pat.to_string();
347 .map(|variant| variant.name(db).to_string())
348 .any(|enum_name| enum_name == pat_text)
354 fn should_not_display_type_hint(
355 sema: &Semantics<RootDatabase>,
356 bind_pat: &ast::IdentPat,
361 if pat_ty.is_unknown() {
365 if let Some(hir::Adt::Struct(s)) = pat_ty.as_adt() {
366 if s.fields(db).is_empty() && s.name(db).to_string() == bind_pat.to_string() {
371 for node in bind_pat.syntax().ancestors() {
374 ast::LetStmt(it) => return it.ty().is_some(),
375 ast::Param(it) => return it.ty().is_some(),
376 ast::MatchArm(_it) => return pat_is_enum_variant(db, bind_pat, pat_ty),
378 return it.condition().and_then(|condition| condition.pat()).is_some()
379 && pat_is_enum_variant(db, bind_pat, pat_ty);
381 ast::WhileExpr(it) => {
382 return it.condition().and_then(|condition| condition.pat()).is_some()
383 && pat_is_enum_variant(db, bind_pat, pat_ty);
385 ast::ForExpr(it) => {
386 // We *should* display hint only if user provided "in {expr}" and we know the type of expr (and it's not unit).
387 // Type of expr should be iterable.
388 return it.in_token().is_none() ||
390 .and_then(|iterable_expr| sema.type_of_expr(&iterable_expr))
391 .map(TypeInfo::original)
392 .map_or(true, |iterable_ty| iterable_ty.is_unknown() || iterable_ty.is_unit())
401 fn should_hide_param_name_hint(
402 sema: &Semantics<RootDatabase>,
403 callable: &hir::Callable,
405 argument: &ast::Expr,
407 // These are to be tested in the `parameter_hint_heuristics` test
409 // - the parameter name is a suffix of the function's name
410 // - the argument is an enum whose name is equal to the parameter
411 // - exact argument<->parameter match(ignoring leading underscore) or parameter is a prefix/suffix
412 // of argument with _ splitting it off
413 // - param starts with `ra_fixture`
414 // - param is a well known name in a unary function
416 let param_name = param_name.trim_start_matches('_');
417 if param_name.is_empty() {
421 let fn_name = match callable.kind() {
422 hir::CallableKind::Function(it) => Some(it.name(sema.db).to_string()),
425 let fn_name = fn_name.as_deref();
426 is_param_name_suffix_of_fn_name(param_name, callable, fn_name)
427 || is_enum_name_similar_to_param_name(sema, argument, param_name)
428 || is_argument_similar_to_param_name(argument, param_name)
429 || param_name.starts_with("ra_fixture")
430 || (callable.n_params() == 1 && is_obvious_param(param_name))
433 fn is_argument_similar_to_param_name(argument: &ast::Expr, param_name: &str) -> bool {
434 // check whether param_name and argument are the same or
435 // whether param_name is a prefix/suffix of argument(split at `_`)
436 let argument = match get_string_representation(argument) {
437 Some(argument) => argument,
438 None => return false,
441 let param_name = param_name.trim_start_matches('_');
442 let argument = argument.trim_start_matches('_');
443 if argument.strip_prefix(param_name).map_or(false, |s| s.starts_with('_')) {
446 if argument.strip_suffix(param_name).map_or(false, |s| s.ends_with('_')) {
449 argument == param_name
452 /// Hide the parameter name of a unary function if it is a `_` - prefixed suffix of the function's name, or equal.
454 /// `fn strip_suffix(suffix)` will be hidden.
455 /// `fn stripsuffix(suffix)` will not be hidden.
456 fn is_param_name_suffix_of_fn_name(
459 fn_name: Option<&str>,
461 match (callable.n_params(), fn_name) {
462 (1, Some(function)) => {
463 function == param_name
464 || (function.len() > param_name.len()
465 && function.ends_with(param_name)
466 && function[..function.len() - param_name.len()].ends_with('_'))
472 fn is_enum_name_similar_to_param_name(
473 sema: &Semantics<RootDatabase>,
474 argument: &ast::Expr,
477 match sema.type_of_expr(argument).and_then(|t| t.original.as_adt()) {
478 Some(hir::Adt::Enum(e)) => to_lower_snake_case(&e.name(sema.db).to_string()) == param_name,
483 fn get_string_representation(expr: &ast::Expr) -> Option<String> {
485 ast::Expr::MethodCallExpr(method_call_expr) => {
486 let name_ref = method_call_expr.name_ref()?;
487 match name_ref.text().as_str() {
488 "clone" | "as_ref" => method_call_expr.receiver().map(|rec| rec.to_string()),
489 name_ref => Some(name_ref.to_owned()),
492 ast::Expr::FieldExpr(field_expr) => Some(field_expr.name_ref()?.to_string()),
493 ast::Expr::PathExpr(path_expr) => Some(path_expr.path()?.segment()?.to_string()),
494 ast::Expr::PrefixExpr(prefix_expr) => get_string_representation(&prefix_expr.expr()?),
495 ast::Expr::RefExpr(ref_expr) => get_string_representation(&ref_expr.expr()?),
500 fn is_obvious_param(param_name: &str) -> bool {
501 // avoid displaying hints for common functions like map, filter, etc.
502 // or other obvious words used in std
503 let is_obvious_param_name =
504 matches!(param_name, "predicate" | "value" | "pat" | "rhs" | "other");
505 param_name.len() == 1 || is_obvious_param_name
509 sema: &Semantics<RootDatabase>,
511 ) -> Option<(hir::Callable, ast::ArgList)> {
513 ast::Expr::CallExpr(expr) => {
514 let descended = sema.descend_node_into_attributes(expr.clone()).pop();
515 let expr = descended.as_ref().unwrap_or(expr);
516 sema.type_of_expr(&expr.expr()?)?.original.as_callable(sema.db).zip(expr.arg_list())
518 ast::Expr::MethodCallExpr(expr) => {
519 let descended = sema.descend_node_into_attributes(expr.clone()).pop();
520 let expr = descended.as_ref().unwrap_or(expr);
521 sema.resolve_method_call_as_callable(expr).zip(expr.arg_list())
529 use expect_test::{expect, Expect};
530 use test_utils::extract_annotations;
532 use crate::{fixture, inlay_hints::InlayHintsConfig};
534 const TEST_CONFIG: InlayHintsConfig = InlayHintsConfig {
536 parameter_hints: true,
537 chaining_hints: true,
542 fn check(ra_fixture: &str) {
543 check_with_config(TEST_CONFIG, ra_fixture);
547 fn check_params(ra_fixture: &str) {
550 parameter_hints: true,
552 chaining_hints: false,
560 fn check_types(ra_fixture: &str) {
563 parameter_hints: false,
565 chaining_hints: false,
573 fn check_chains(ra_fixture: &str) {
576 parameter_hints: false,
578 chaining_hints: true,
586 fn check_with_config(config: InlayHintsConfig, ra_fixture: &str) {
587 let (analysis, file_id) = fixture::file(ra_fixture);
588 let expected = extract_annotations(&*analysis.file_text(file_id).unwrap());
589 let inlay_hints = analysis.inlay_hints(&config, file_id).unwrap();
591 inlay_hints.into_iter().map(|it| (it.range, it.label.to_string())).collect::<Vec<_>>();
592 assert_eq!(expected, actual, "\nExpected:\n{:#?}\n\nActual:\n{:#?}", expected, actual);
596 fn check_expect(config: InlayHintsConfig, ra_fixture: &str, expect: Expect) {
597 let (analysis, file_id) = fixture::file(ra_fixture);
598 let inlay_hints = analysis.inlay_hints(&config, file_id).unwrap();
599 expect.assert_debug_eq(&inlay_hints)
603 fn hints_disabled() {
607 parameter_hints: false,
608 chaining_hints: false,
612 fn foo(a: i32, b: i32) -> i32 { a + b }
619 // Parameter hint tests
622 fn param_hints_only() {
625 fn foo(a: i32, b: i32) -> i32 { a + b }
638 fn param_name_similar_to_fn_name_still_hints() {
641 fn max(x: i32, y: i32) -> i32 { x + y }
654 fn param_name_similar_to_fn_name() {
657 fn param_with_underscore(with_underscore: i32) -> i32 { with_underscore }
659 let _x = param_with_underscore(
666 fn param_with_underscore(underscore: i32) -> i32 { underscore }
668 let _x = param_with_underscore(
676 fn param_name_same_as_fn_name() {
679 fn foo(foo: i32) -> i32 { foo }
689 fn never_hide_param_when_multiple_params() {
692 fn foo(foo: i32, bar: i32) -> i32 { bar + baz }
705 fn param_hints_look_through_as_ref_and_clone() {
708 fn foo(bar: i32, baz: f32) {}
714 foo(bar.clone(), bar.clone());
716 foo(bar.as_ref(), bar.as_ref());
724 fn self_param_hints() {
730 fn foo(self: Self) {}
731 fn bar(self: &Self) {}
745 fn param_name_hints_show_for_literals() {
747 r#"pub fn test(a: i32, b: i32) -> [i32; 2] { [a, b] }
760 fn function_call_parameter_hint() {
769 struct NavigationTarget {}
774 fn method(&self, mut param: i32) -> i32 { param * 2 }
779 focus_range: Option<TextRange>,
780 full_range: TextRange,
782 docs: Option<String>,
783 ) -> NavigationTarget {
788 fn test_func(mut foo: i32, bar: i32, msg: &str, _: i32, last: i32) -> i32 {
794 let _: i32 = test_func(1, 2, "hello", 3, not_literal);
795 //^ foo ^ bar ^^^^^^^ msg ^^^^^^^^^^^ last
796 let t: Test = Test {};
799 Test::method(&t, 3456);
809 //^^^^^^^^^^^^ full_range
820 fn parameter_hint_heuristics() {
823 fn check(ra_fixture_thing: &str) {}
826 fn filter(predicate: i32) {}
828 fn strip_suffix(suffix: &str) {}
829 fn stripsuffix(suffix: &str) {}
830 fn same(same: u32) {}
831 fn same2(_same2: u32) {}
833 fn enum_matches_param_name(completion_kind: CompletionKind) {}
835 fn foo(param: u32) {}
836 fn bar(param_eter: u32) {}
838 enum CompletionKind {
842 fn non_ident_pat((a, b): (u32, u32)) {}
856 enum_matches_param_name(CompletionKind::Keyword);
870 let param_eter_end = 0;
872 let start_param_eter = 0;
873 bar(start_param_eter);
876 //^^^^^^^^^^^ param_eter
878 non_ident_pat((0, 0));
886 fn type_hints_only() {
889 fn foo(a: i32, b: i32) -> i32 { a + b }
898 fn type_hints_bindings_after_at() {
903 let ref foo @ bar @ ref mut baz = 0;
909 if let x @ Some(_) = Some(0) {}
911 let foo @ (bar, baz) = (3, 3);
920 fn default_generic_types_should_not_be_displayed() {
923 struct Test<K, T = u8> { k: K, t: T }
926 let zz = Test { t: 23u8, k: 33 };
931 //^^^^ || -> Test<i32>
937 fn shorten_iterators_in_associated_params() {
940 //- minicore: iterators
943 pub struct SomeIter<T> {}
945 impl<T> SomeIter<T> {
946 pub fn new() -> Self { SomeIter {} }
947 pub fn push(&mut self, t: T) {}
950 impl<T> Iterator for SomeIter<T> {
952 fn next(&mut self) -> Option<Self::Item> {
958 let mut some_iter = SomeIter::new();
959 //^^^^^^^^^ SomeIter<Take<Repeat<i32>>>
960 some_iter.push(iter::repeat(2).take(2));
961 let iter_of_iters = some_iter.take(2);
962 //^^^^^^^^^^^^^ impl Iterator<Item = impl Iterator<Item = i32>>
969 fn infer_call_method_return_associated_types_with_generic() {
973 fn default() -> Self;
979 pub fn quux<T: Foo>() -> T::Bar {
980 let y = Default::default();
993 //- minicore: fn, sized
994 fn foo() -> impl Fn() { loop {} }
995 fn foo1() -> impl Fn(f64) { loop {} }
996 fn foo2() -> impl Fn(f64, f64) { loop {} }
997 fn foo3() -> impl Fn(f64, f64) -> u32 { loop {} }
998 fn foo4() -> &'static dyn Fn(f64, f64) -> u32 { loop {} }
999 fn foo5() -> &'static dyn Fn(&'static dyn Fn(f64, f64) -> u32, f64) -> u32 { loop {} }
1000 fn foo6() -> impl Fn(f64, f64) -> u32 + Sized { loop {} }
1001 fn foo7() -> *const (impl Fn(f64, f64) -> u32 + Sized) { loop {} }
1009 // ^^^ impl Fn(f64, f64)
1011 // ^^^ impl Fn(f64, f64) -> u32
1013 // ^^^ &dyn Fn(f64, f64) -> u32
1015 // ^^^ &dyn Fn(&dyn Fn(f64, f64) -> u32, f64) -> u32
1017 // ^^^ impl Fn(f64, f64) -> u32
1019 // ^^^ *const impl Fn(f64, f64) -> u32
1026 fn fn_hints_ptr_rpit_fn_parentheses() {
1029 //- minicore: fn, sized
1032 fn foo1() -> *const impl Fn() { loop {} }
1033 fn foo2() -> *const (impl Fn() + Sized) { loop {} }
1034 fn foo3() -> *const (impl Fn() + ?Sized) { loop {} }
1035 fn foo4() -> *const (impl Sized + Fn()) { loop {} }
1036 fn foo5() -> *const (impl ?Sized + Fn()) { loop {} }
1037 fn foo6() -> *const (impl Fn() + Trait) { loop {} }
1038 fn foo7() -> *const (impl Fn() + Sized + Trait) { loop {} }
1039 fn foo8() -> *const (impl Fn() + ?Sized + Trait) { loop {} }
1040 fn foo9() -> *const (impl Fn() -> u8 + ?Sized) { loop {} }
1041 fn foo10() -> *const (impl Fn() + Sized + ?Sized) { loop {} }
1045 // ^^^ *const impl Fn()
1047 // ^^^ *const impl Fn()
1049 // ^^^ *const (impl Fn() + ?Sized)
1051 // ^^^ *const impl Fn()
1053 // ^^^ *const (impl Fn() + ?Sized)
1055 // ^^^ *const (impl Fn() + Trait)
1057 // ^^^ *const (impl Fn() + Trait)
1059 // ^^^ *const (impl Fn() + Trait + ?Sized)
1061 // ^^^ *const (impl Fn() -> u8 + ?Sized)
1063 // ^^^ *const impl Fn()
1070 fn unit_structs_have_no_type_hints() {
1073 //- minicore: result
1074 struct SyntheticSyntax;
1079 Err(SyntheticSyntax) => (),
1086 fn let_statement() {
1089 #[derive(PartialEq)]
1090 enum Option<T> { None, Some(T) }
1092 #[derive(PartialEq)]
1093 struct Test { a: Option<u32>, b: u8 }
1096 struct InnerStruct {}
1106 let test = InnerStruct {};
1109 let test = unresolved();
1111 let test = (42, 'a');
1113 let (a, (b, (c,)) = (2, (3, (9.2,));
1125 //- minicore: option
1126 struct Test { a: Option<u32>, b: u8 }
1129 let test = Some(Test { a: Some(3), b: 1 });
1131 if let None = &test {};
1132 if let test = &test {};
1133 //^^^^ &Option<Test>
1134 if let Some(test) = &test {};
1136 if let Some(Test { a, b }) = &test {};
1137 //^ &Option<u32> ^ &u8
1138 if let Some(Test { a: x, b: y }) = &test {};
1139 //^ &Option<u32> ^ &u8
1140 if let Some(Test { a: Some(x), b: y }) = &test {};
1142 if let Some(Test { a: None, b: y }) = &test {};
1144 if let Some(Test { b: y, .. }) = &test {};
1155 //- minicore: option
1156 struct Test { a: Option<u32>, b: u8 }
1159 let test = Some(Test { a: Some(3), b: 1 });
1161 while let Some(Test { a: Some(x), b: y }) = &test {};
1168 fn match_arm_list() {
1171 //- minicore: option
1172 struct Test { a: Option<u32>, b: u8 }
1175 match Some(Test { a: Some(3), b: 1 }) {
1179 Some(Test { a: Some(x), b: y }) => (),
1188 fn incomplete_for_no_hint() {
1192 let data = &[1i32, 2, 3];
1199 pub struct Vec<T> {}
1202 pub fn new() -> Self { Vec {} }
1203 pub fn push(&mut self, t: T) {}
1206 impl<T> IntoIterator for Vec<T> {
1211 let mut data = Vec::new();
1216 println!("Unit expr");
1223 fn complete_for_hint() {
1226 //- minicore: iterator
1227 pub struct Vec<T> {}
1230 pub fn new() -> Self { Vec {} }
1231 pub fn push(&mut self, t: T) {}
1234 impl<T> IntoIterator for Vec<T> {
1239 let mut data = Vec::new();
1253 fn multi_dyn_trait_bounds() {
1256 pub struct Vec<T> {}
1259 pub fn new() -> Self { Vec {} }
1262 pub struct Box<T> {}
1268 // The block expression wrapping disables the constructor hint hiding logic
1269 let _v = { Vec::<Box<&(dyn Display + Sync)>>::new() };
1270 //^^ Vec<Box<&(dyn Display + Sync)>>
1271 let _v = { Vec::<Box<*const (dyn Display + Sync)>>::new() };
1272 //^^ Vec<Box<*const (dyn Display + Sync)>>
1273 let _v = { Vec::<Box<dyn Display + Sync>>::new() };
1274 //^^ Vec<Box<dyn Display + Sync>>
1281 fn shorten_iterator_hints() {
1284 //- minicore: iterators
1289 impl Iterator for MyIter {
1291 fn next(&mut self) -> Option<Self::Item> {
1299 let _x = iter::repeat(0);
1300 //^^ impl Iterator<Item = i32>
1301 fn generic<T: Clone>(t: T) {
1302 let _x = iter::repeat(t);
1303 //^^ impl Iterator<Item = T>
1304 let _chained = iter::repeat(t).take(10);
1305 //^^^^^^^^ impl Iterator<Item = T>
1313 fn skip_constructor_type_hints() {
1317 use core::ops::ControlFlow;
1320 struct TupleStruct();
1326 fn try_new() -> ControlFlow<(), Self> {
1327 ControlFlow::Continue(Struct)
1331 struct Generic<T>(T);
1339 let strukt = Struct::new();
1340 let tuple_struct = TupleStruct();
1341 let generic0 = Generic::new();
1342 // ^^^^^^^^ Generic<i32>
1343 let generic1 = Generic::<i32>::new();
1344 let generic2 = <Generic<i32>>::new();
1347 fn fallible() -> ControlFlow<()> {
1348 let strukt = Struct::try_new()?;
1361 (0..2).for_each(|increment| { start += increment; });
1365 //^^^^^^^^ |…| -> i32
1370 let _: i32 = multiply(1, 2);
1371 let multiply_ref = &multiply;
1372 //^^^^^^^^^^^^ &|…| -> i32
1374 let return_42 = || 42;
1375 //^^^^^^^^^ || -> i32
1381 fn hint_truncation() {
1383 InlayHintsConfig { max_length: Some(8), ..TEST_CONFIG },
1387 struct VeryLongOuterName<T>(T);
1392 let b = VeryLongOuterName(0usize);
1393 //^ VeryLongOuterName<…>
1394 let c = Smol(Smol(0u32))
1400 // Chaining hint tests
1403 fn chaining_hints_ignore_comments() {
1406 parameter_hints: false,
1408 chaining_hints: true,
1413 impl A { fn into_b(self) -> B { self.0 } }
1415 impl B { fn into_c(self) -> C { self.0 } }
1420 .into_b() // This is a comment
1421 // This is another comment
1443 fn chaining_hints_without_newlines() {
1447 impl A { fn into_b(self) -> B { self.0 } }
1449 impl B { fn into_c(self) -> C { self.0 } }
1453 let c = A(B(C)).into_b().into_c();
1459 fn struct_access_chaining_hints() {
1462 parameter_hints: false,
1464 chaining_hints: true,
1468 struct A { pub b: B }
1469 struct B { pub c: C }
1474 fn foo(&self) -> i32 { 42 }
1478 let x = A { b: B { c: C(true) } }
1503 fn generic_chaining_hints() {
1506 parameter_hints: false,
1508 chaining_hints: true,
1515 struct X<T,R>(T, R);
1518 fn new(t: T) -> Self { A(t) }
1519 fn into_b(self) -> B<T> { B(self.0) }
1522 fn into_c(self) -> C<T> { C(self.0) }
1525 let c = A::new(X(42, true))
1535 label: "B<X<i32, bool>>",
1540 label: "A<X<i32, bool>>",
1548 fn shorten_iterator_chaining_hints() {
1551 parameter_hints: false,
1553 chaining_hints: true,
1557 //- minicore: iterators
1562 impl Iterator for MyIter {
1564 fn next(&mut self) -> Option<Self::Item> {
1570 let _x = MyIter.by_ref()
1582 label: "impl Iterator<Item = ()>",
1587 label: "impl Iterator<Item = ()>",
1592 label: "impl Iterator<Item = ()>",
1597 label: "&mut MyIter",
1605 fn hints_in_attr_call() {
1609 //- proc_macros: identity, input_replace
1612 fn chain(self) -> Self {
1616 #[proc_macros::identity]
1618 let strukt = Struct;
1623 Struct::chain(strukt);
1645 kind: ParameterHint,