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_smol_str())
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_smol_str() == 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_smol_str()),
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)) => {
479 to_lower_snake_case(&e.name(sema.db).to_smol_str()) == param_name
485 fn get_string_representation(expr: &ast::Expr) -> Option<String> {
487 ast::Expr::MethodCallExpr(method_call_expr) => {
488 let name_ref = method_call_expr.name_ref()?;
489 match name_ref.text().as_str() {
490 "clone" | "as_ref" => method_call_expr.receiver().map(|rec| rec.to_string()),
491 name_ref => Some(name_ref.to_owned()),
494 ast::Expr::FieldExpr(field_expr) => Some(field_expr.name_ref()?.to_string()),
495 ast::Expr::PathExpr(path_expr) => Some(path_expr.path()?.segment()?.to_string()),
496 ast::Expr::PrefixExpr(prefix_expr) => get_string_representation(&prefix_expr.expr()?),
497 ast::Expr::RefExpr(ref_expr) => get_string_representation(&ref_expr.expr()?),
502 fn is_obvious_param(param_name: &str) -> bool {
503 // avoid displaying hints for common functions like map, filter, etc.
504 // or other obvious words used in std
505 let is_obvious_param_name =
506 matches!(param_name, "predicate" | "value" | "pat" | "rhs" | "other");
507 param_name.len() == 1 || is_obvious_param_name
511 sema: &Semantics<RootDatabase>,
513 ) -> Option<(hir::Callable, ast::ArgList)> {
515 ast::Expr::CallExpr(expr) => {
516 let descended = sema.descend_node_into_attributes(expr.clone()).pop();
517 let expr = descended.as_ref().unwrap_or(expr);
518 sema.type_of_expr(&expr.expr()?)?.original.as_callable(sema.db).zip(expr.arg_list())
520 ast::Expr::MethodCallExpr(expr) => {
521 let descended = sema.descend_node_into_attributes(expr.clone()).pop();
522 let expr = descended.as_ref().unwrap_or(expr);
523 sema.resolve_method_call_as_callable(expr).zip(expr.arg_list())
531 use expect_test::{expect, Expect};
532 use test_utils::extract_annotations;
534 use crate::{fixture, inlay_hints::InlayHintsConfig};
536 const TEST_CONFIG: InlayHintsConfig = InlayHintsConfig {
538 parameter_hints: true,
539 chaining_hints: true,
544 fn check(ra_fixture: &str) {
545 check_with_config(TEST_CONFIG, ra_fixture);
549 fn check_params(ra_fixture: &str) {
552 parameter_hints: true,
554 chaining_hints: false,
562 fn check_types(ra_fixture: &str) {
565 parameter_hints: false,
567 chaining_hints: false,
575 fn check_chains(ra_fixture: &str) {
578 parameter_hints: false,
580 chaining_hints: true,
588 fn check_with_config(config: InlayHintsConfig, ra_fixture: &str) {
589 let (analysis, file_id) = fixture::file(ra_fixture);
590 let expected = extract_annotations(&*analysis.file_text(file_id).unwrap());
591 let inlay_hints = analysis.inlay_hints(&config, file_id).unwrap();
593 inlay_hints.into_iter().map(|it| (it.range, it.label.to_string())).collect::<Vec<_>>();
594 assert_eq!(expected, actual, "\nExpected:\n{:#?}\n\nActual:\n{:#?}", expected, actual);
598 fn check_expect(config: InlayHintsConfig, ra_fixture: &str, expect: Expect) {
599 let (analysis, file_id) = fixture::file(ra_fixture);
600 let inlay_hints = analysis.inlay_hints(&config, file_id).unwrap();
601 expect.assert_debug_eq(&inlay_hints)
605 fn hints_disabled() {
609 parameter_hints: false,
610 chaining_hints: false,
614 fn foo(a: i32, b: i32) -> i32 { a + b }
621 // Parameter hint tests
624 fn param_hints_only() {
627 fn foo(a: i32, b: i32) -> i32 { a + b }
640 fn param_name_similar_to_fn_name_still_hints() {
643 fn max(x: i32, y: i32) -> i32 { x + y }
656 fn param_name_similar_to_fn_name() {
659 fn param_with_underscore(with_underscore: i32) -> i32 { with_underscore }
661 let _x = param_with_underscore(
668 fn param_with_underscore(underscore: i32) -> i32 { underscore }
670 let _x = param_with_underscore(
678 fn param_name_same_as_fn_name() {
681 fn foo(foo: i32) -> i32 { foo }
691 fn never_hide_param_when_multiple_params() {
694 fn foo(foo: i32, bar: i32) -> i32 { bar + baz }
707 fn param_hints_look_through_as_ref_and_clone() {
710 fn foo(bar: i32, baz: f32) {}
716 foo(bar.clone(), bar.clone());
718 foo(bar.as_ref(), bar.as_ref());
726 fn self_param_hints() {
732 fn foo(self: Self) {}
733 fn bar(self: &Self) {}
747 fn param_name_hints_show_for_literals() {
749 r#"pub fn test(a: i32, b: i32) -> [i32; 2] { [a, b] }
762 fn function_call_parameter_hint() {
771 struct NavigationTarget {}
776 fn method(&self, mut param: i32) -> i32 { param * 2 }
781 focus_range: Option<TextRange>,
782 full_range: TextRange,
784 docs: Option<String>,
785 ) -> NavigationTarget {
790 fn test_func(mut foo: i32, bar: i32, msg: &str, _: i32, last: i32) -> i32 {
796 let _: i32 = test_func(1, 2, "hello", 3, not_literal);
797 //^ foo ^ bar ^^^^^^^ msg ^^^^^^^^^^^ last
798 let t: Test = Test {};
801 Test::method(&t, 3456);
811 //^^^^^^^^^^^^ full_range
822 fn parameter_hint_heuristics() {
825 fn check(ra_fixture_thing: &str) {}
828 fn filter(predicate: i32) {}
830 fn strip_suffix(suffix: &str) {}
831 fn stripsuffix(suffix: &str) {}
832 fn same(same: u32) {}
833 fn same2(_same2: u32) {}
835 fn enum_matches_param_name(completion_kind: CompletionKind) {}
837 fn foo(param: u32) {}
838 fn bar(param_eter: u32) {}
840 enum CompletionKind {
844 fn non_ident_pat((a, b): (u32, u32)) {}
858 enum_matches_param_name(CompletionKind::Keyword);
872 let param_eter_end = 0;
874 let start_param_eter = 0;
875 bar(start_param_eter);
878 //^^^^^^^^^^^ param_eter
880 non_ident_pat((0, 0));
888 fn type_hints_only() {
891 fn foo(a: i32, b: i32) -> i32 { a + b }
900 fn type_hints_bindings_after_at() {
905 let ref foo @ bar @ ref mut baz = 0;
911 if let x @ Some(_) = Some(0) {}
913 let foo @ (bar, baz) = (3, 3);
922 fn default_generic_types_should_not_be_displayed() {
925 struct Test<K, T = u8> { k: K, t: T }
928 let zz = Test { t: 23u8, k: 33 };
933 //^^^^ || -> Test<i32>
939 fn shorten_iterators_in_associated_params() {
942 //- minicore: iterators
945 pub struct SomeIter<T> {}
947 impl<T> SomeIter<T> {
948 pub fn new() -> Self { SomeIter {} }
949 pub fn push(&mut self, t: T) {}
952 impl<T> Iterator for SomeIter<T> {
954 fn next(&mut self) -> Option<Self::Item> {
960 let mut some_iter = SomeIter::new();
961 //^^^^^^^^^ SomeIter<Take<Repeat<i32>>>
962 some_iter.push(iter::repeat(2).take(2));
963 let iter_of_iters = some_iter.take(2);
964 //^^^^^^^^^^^^^ impl Iterator<Item = impl Iterator<Item = i32>>
971 fn infer_call_method_return_associated_types_with_generic() {
975 fn default() -> Self;
981 pub fn quux<T: Foo>() -> T::Bar {
982 let y = Default::default();
995 //- minicore: fn, sized
996 fn foo() -> impl Fn() { loop {} }
997 fn foo1() -> impl Fn(f64) { loop {} }
998 fn foo2() -> impl Fn(f64, f64) { loop {} }
999 fn foo3() -> impl Fn(f64, f64) -> u32 { loop {} }
1000 fn foo4() -> &'static dyn Fn(f64, f64) -> u32 { loop {} }
1001 fn foo5() -> &'static dyn Fn(&'static dyn Fn(f64, f64) -> u32, f64) -> u32 { loop {} }
1002 fn foo6() -> impl Fn(f64, f64) -> u32 + Sized { loop {} }
1003 fn foo7() -> *const (impl Fn(f64, f64) -> u32 + Sized) { loop {} }
1011 // ^^^ impl Fn(f64, f64)
1013 // ^^^ impl Fn(f64, f64) -> u32
1015 // ^^^ &dyn Fn(f64, f64) -> u32
1017 // ^^^ &dyn Fn(&dyn Fn(f64, f64) -> u32, f64) -> u32
1019 // ^^^ impl Fn(f64, f64) -> u32
1021 // ^^^ *const impl Fn(f64, f64) -> u32
1028 fn fn_hints_ptr_rpit_fn_parentheses() {
1031 //- minicore: fn, sized
1034 fn foo1() -> *const impl Fn() { loop {} }
1035 fn foo2() -> *const (impl Fn() + Sized) { loop {} }
1036 fn foo3() -> *const (impl Fn() + ?Sized) { loop {} }
1037 fn foo4() -> *const (impl Sized + Fn()) { loop {} }
1038 fn foo5() -> *const (impl ?Sized + Fn()) { loop {} }
1039 fn foo6() -> *const (impl Fn() + Trait) { loop {} }
1040 fn foo7() -> *const (impl Fn() + Sized + Trait) { loop {} }
1041 fn foo8() -> *const (impl Fn() + ?Sized + Trait) { loop {} }
1042 fn foo9() -> *const (impl Fn() -> u8 + ?Sized) { loop {} }
1043 fn foo10() -> *const (impl Fn() + Sized + ?Sized) { loop {} }
1047 // ^^^ *const impl Fn()
1049 // ^^^ *const impl Fn()
1051 // ^^^ *const (impl Fn() + ?Sized)
1053 // ^^^ *const impl Fn()
1055 // ^^^ *const (impl Fn() + ?Sized)
1057 // ^^^ *const (impl Fn() + Trait)
1059 // ^^^ *const (impl Fn() + Trait)
1061 // ^^^ *const (impl Fn() + Trait + ?Sized)
1063 // ^^^ *const (impl Fn() -> u8 + ?Sized)
1065 // ^^^ *const impl Fn()
1072 fn unit_structs_have_no_type_hints() {
1075 //- minicore: result
1076 struct SyntheticSyntax;
1081 Err(SyntheticSyntax) => (),
1088 fn let_statement() {
1091 #[derive(PartialEq)]
1092 enum Option<T> { None, Some(T) }
1094 #[derive(PartialEq)]
1095 struct Test { a: Option<u32>, b: u8 }
1098 struct InnerStruct {}
1108 let test = InnerStruct {};
1111 let test = unresolved();
1113 let test = (42, 'a');
1115 let (a, (b, (c,)) = (2, (3, (9.2,));
1127 //- minicore: option
1128 struct Test { a: Option<u32>, b: u8 }
1131 let test = Some(Test { a: Some(3), b: 1 });
1133 if let None = &test {};
1134 if let test = &test {};
1135 //^^^^ &Option<Test>
1136 if let Some(test) = &test {};
1138 if let Some(Test { a, b }) = &test {};
1139 //^ &Option<u32> ^ &u8
1140 if let Some(Test { a: x, b: y }) = &test {};
1141 //^ &Option<u32> ^ &u8
1142 if let Some(Test { a: Some(x), b: y }) = &test {};
1144 if let Some(Test { a: None, b: y }) = &test {};
1146 if let Some(Test { b: y, .. }) = &test {};
1157 //- minicore: option
1158 struct Test { a: Option<u32>, b: u8 }
1161 let test = Some(Test { a: Some(3), b: 1 });
1163 while let Some(Test { a: Some(x), b: y }) = &test {};
1170 fn match_arm_list() {
1173 //- minicore: option
1174 struct Test { a: Option<u32>, b: u8 }
1177 match Some(Test { a: Some(3), b: 1 }) {
1181 Some(Test { a: Some(x), b: y }) => (),
1190 fn incomplete_for_no_hint() {
1194 let data = &[1i32, 2, 3];
1201 pub struct Vec<T> {}
1204 pub fn new() -> Self { Vec {} }
1205 pub fn push(&mut self, t: T) {}
1208 impl<T> IntoIterator for Vec<T> {
1213 let mut data = Vec::new();
1218 println!("Unit expr");
1225 fn complete_for_hint() {
1228 //- minicore: iterator
1229 pub struct Vec<T> {}
1232 pub fn new() -> Self { Vec {} }
1233 pub fn push(&mut self, t: T) {}
1236 impl<T> IntoIterator for Vec<T> {
1241 let mut data = Vec::new();
1255 fn multi_dyn_trait_bounds() {
1258 pub struct Vec<T> {}
1261 pub fn new() -> Self { Vec {} }
1264 pub struct Box<T> {}
1270 // The block expression wrapping disables the constructor hint hiding logic
1271 let _v = { Vec::<Box<&(dyn Display + Sync)>>::new() };
1272 //^^ Vec<Box<&(dyn Display + Sync)>>
1273 let _v = { Vec::<Box<*const (dyn Display + Sync)>>::new() };
1274 //^^ Vec<Box<*const (dyn Display + Sync)>>
1275 let _v = { Vec::<Box<dyn Display + Sync>>::new() };
1276 //^^ Vec<Box<dyn Display + Sync>>
1283 fn shorten_iterator_hints() {
1286 //- minicore: iterators
1291 impl Iterator for MyIter {
1293 fn next(&mut self) -> Option<Self::Item> {
1301 let _x = iter::repeat(0);
1302 //^^ impl Iterator<Item = i32>
1303 fn generic<T: Clone>(t: T) {
1304 let _x = iter::repeat(t);
1305 //^^ impl Iterator<Item = T>
1306 let _chained = iter::repeat(t).take(10);
1307 //^^^^^^^^ impl Iterator<Item = T>
1315 fn skip_constructor_type_hints() {
1319 use core::ops::ControlFlow;
1322 struct TupleStruct();
1328 fn try_new() -> ControlFlow<(), Self> {
1329 ControlFlow::Continue(Struct)
1333 struct Generic<T>(T);
1341 let strukt = Struct::new();
1342 let tuple_struct = TupleStruct();
1343 let generic0 = Generic::new();
1344 // ^^^^^^^^ Generic<i32>
1345 let generic1 = Generic::<i32>::new();
1346 let generic2 = <Generic<i32>>::new();
1349 fn fallible() -> ControlFlow<()> {
1350 let strukt = Struct::try_new()?;
1363 (0..2).for_each(|increment| { start += increment; });
1367 //^^^^^^^^ |…| -> i32
1372 let _: i32 = multiply(1, 2);
1373 let multiply_ref = &multiply;
1374 //^^^^^^^^^^^^ &|…| -> i32
1376 let return_42 = || 42;
1377 //^^^^^^^^^ || -> i32
1383 fn hint_truncation() {
1385 InlayHintsConfig { max_length: Some(8), ..TEST_CONFIG },
1389 struct VeryLongOuterName<T>(T);
1394 let b = VeryLongOuterName(0usize);
1395 //^ VeryLongOuterName<…>
1396 let c = Smol(Smol(0u32))
1402 // Chaining hint tests
1405 fn chaining_hints_ignore_comments() {
1408 parameter_hints: false,
1410 chaining_hints: true,
1415 impl A { fn into_b(self) -> B { self.0 } }
1417 impl B { fn into_c(self) -> C { self.0 } }
1422 .into_b() // This is a comment
1423 // This is another comment
1445 fn chaining_hints_without_newlines() {
1449 impl A { fn into_b(self) -> B { self.0 } }
1451 impl B { fn into_c(self) -> C { self.0 } }
1455 let c = A(B(C)).into_b().into_c();
1461 fn struct_access_chaining_hints() {
1464 parameter_hints: false,
1466 chaining_hints: true,
1470 struct A { pub b: B }
1471 struct B { pub c: C }
1476 fn foo(&self) -> i32 { 42 }
1480 let x = A { b: B { c: C(true) } }
1505 fn generic_chaining_hints() {
1508 parameter_hints: false,
1510 chaining_hints: true,
1517 struct X<T,R>(T, R);
1520 fn new(t: T) -> Self { A(t) }
1521 fn into_b(self) -> B<T> { B(self.0) }
1524 fn into_c(self) -> C<T> { C(self.0) }
1527 let c = A::new(X(42, true))
1537 label: "B<X<i32, bool>>",
1542 label: "A<X<i32, bool>>",
1550 fn shorten_iterator_chaining_hints() {
1553 parameter_hints: false,
1555 chaining_hints: true,
1559 //- minicore: iterators
1564 impl Iterator for MyIter {
1566 fn next(&mut self) -> Option<Self::Item> {
1572 let _x = MyIter.by_ref()
1584 label: "impl Iterator<Item = ()>",
1589 label: "impl Iterator<Item = ()>",
1594 label: "impl Iterator<Item = ()>",
1599 label: "&mut MyIter",
1607 fn hints_in_attr_call() {
1611 //- proc_macros: identity, input_replace
1614 fn chain(self) -> Self {
1618 #[proc_macros::identity]
1620 let strukt = Struct;
1625 Struct::chain(strukt);
1647 kind: ParameterHint,