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 hide_named_constructor_hints: bool,
20 pub max_length: Option<usize>,
23 #[derive(Clone, Debug, PartialEq, Eq)]
31 pub struct InlayHint {
37 // Feature: Inlay Hints
39 // rust-analyzer shows additional information inline with the source code.
40 // Editors usually render this using read-only virtual text snippets interspersed with code.
42 // rust-analyzer shows hints for
44 // * types of local variables
45 // * names of function arguments
46 // * types of chained expressions
48 // **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.
49 // This approach has limitations, the caret movement and bracket highlighting near the edges of the hint may be weird:
50 // https://github.com/rust-analyzer/rust-analyzer/issues/1623[1], https://github.com/rust-analyzer/rust-analyzer/issues/3453[2].
53 // | Editor | Action Name
55 // | VS Code | **Rust Analyzer: Toggle inlay hints*
58 // image::https://user-images.githubusercontent.com/48062697/113020660-b5f98b80-917a-11eb-8d70-3be3fd558cdd.png[]
59 pub(crate) fn inlay_hints(
62 config: &InlayHintsConfig,
64 let _p = profile::span("inlay_hints");
65 let sema = Semantics::new(db);
66 let file = sema.parse(file_id);
67 let file = file.syntax();
69 let mut res = Vec::new();
71 for node in file.descendants() {
72 if let Some(expr) = ast::Expr::cast(node.clone()) {
73 get_chaining_hints(&mut res, &sema, config, &expr);
75 ast::Expr::CallExpr(it) => {
76 get_param_name_hints(&mut res, &sema, config, ast::Expr::from(it));
78 ast::Expr::MethodCallExpr(it) => {
79 get_param_name_hints(&mut res, &sema, config, ast::Expr::from(it));
83 } else if let Some(it) = ast::IdentPat::cast(node.clone()) {
84 get_bind_pat_hints(&mut res, &sema, config, &it);
90 fn get_chaining_hints(
91 acc: &mut Vec<InlayHint>,
92 sema: &Semantics<RootDatabase>,
93 config: &InlayHintsConfig,
96 if !config.chaining_hints {
100 if matches!(expr, ast::Expr::RecordExpr(_)) {
104 let descended = sema.descend_node_into_attributes(expr.clone()).pop();
105 let desc_expr = descended.as_ref().unwrap_or(expr);
106 let krate = sema.scope(desc_expr.syntax()).module().map(|it| it.krate());
107 let famous_defs = FamousDefs(sema, krate);
109 let mut tokens = expr
111 .siblings_with_tokens(Direction::Next)
112 .filter_map(NodeOrToken::into_token)
113 .filter(|t| match t.kind() {
114 SyntaxKind::WHITESPACE if !t.text().contains('\n') => false,
115 SyntaxKind::COMMENT => false,
119 // Chaining can be defined as an expression whose next sibling tokens are newline and dot
120 // Ignoring extra whitespace and comments
121 let next = tokens.next()?.kind();
122 if next == SyntaxKind::WHITESPACE {
123 let mut next_next = tokens.next()?.kind();
124 while next_next == SyntaxKind::WHITESPACE {
125 next_next = tokens.next()?.kind();
127 if next_next == T![.] {
128 let ty = sema.type_of_expr(desc_expr)?.original;
132 if matches!(expr, ast::Expr::PathExpr(_)) {
133 if let Some(hir::Adt::Struct(st)) = ty.as_adt() {
134 if st.fields(sema.db).is_empty() {
140 range: expr.syntax().text_range(),
141 kind: InlayKind::ChainingHint,
142 label: hint_iterator(sema, &famous_defs, config, &ty).unwrap_or_else(|| {
143 ty.display_truncated(sema.db, config.max_length).to_string().into()
151 fn get_param_name_hints(
152 acc: &mut Vec<InlayHint>,
153 sema: &Semantics<RootDatabase>,
154 config: &InlayHintsConfig,
157 if !config.parameter_hints {
161 let (callable, arg_list) = get_callable(sema, &expr)?;
165 .zip(arg_list.args())
166 .filter_map(|((param, _ty), arg)| {
167 // Only annotate hints for expressions that exist in the original file
168 let range = sema.original_range_opt(arg.syntax())?;
169 let param_name = match param? {
170 Either::Left(_) => "self".to_string(),
171 Either::Right(pat) => match pat {
172 ast::Pat::IdentPat(it) => it.name()?.to_string(),
176 Some((param_name, arg, range))
178 .filter(|(param_name, arg, _)| {
179 !should_hide_param_name_hint(sema, &callable, param_name, arg)
181 .map(|(param_name, _, FileRange { range, .. })| InlayHint {
183 kind: InlayKind::ParameterHint,
184 label: param_name.into(),
191 fn get_bind_pat_hints(
192 acc: &mut Vec<InlayHint>,
193 sema: &Semantics<RootDatabase>,
194 config: &InlayHintsConfig,
197 if !config.type_hints {
201 let descended = sema.descend_node_into_attributes(pat.clone()).pop();
202 let desc_pat = descended.as_ref().unwrap_or(pat);
203 let ty = sema.type_of_pat(&desc_pat.clone().into())?.original;
205 if should_not_display_type_hint(sema, pat, &ty) {
209 let krate = sema.scope(desc_pat.syntax()).module().map(|it| it.krate());
210 let famous_defs = FamousDefs(sema, krate);
211 let label = hint_iterator(sema, &famous_defs, config, &ty);
213 let label = match label {
214 Some(label) => label,
216 let ty_name = ty.display_truncated(sema.db, config.max_length).to_string();
217 if config.hide_named_constructor_hints
218 && is_named_constructor(sema, pat, &ty_name).is_some()
227 range: match pat.name() {
228 Some(name) => name.syntax().text_range(),
229 None => pat.syntax().text_range(),
231 kind: InlayKind::TypeHint,
238 fn is_named_constructor(
239 sema: &Semantics<RootDatabase>,
243 let let_node = pat.syntax().parent()?;
244 let expr = match_ast! {
246 ast::LetStmt(it) => it.initializer(),
247 ast::Condition(it) => it.expr(),
252 let expr = sema.descend_node_into_attributes(expr.clone()).pop().unwrap_or(expr);
253 // unwrap postfix expressions
254 let expr = match expr {
255 ast::Expr::TryExpr(it) => it.expr(),
256 ast::Expr::AwaitExpr(it) => it.expr(),
259 let expr = match expr {
260 ast::Expr::CallExpr(call) => match call.expr()? {
261 ast::Expr::PathExpr(p) => p,
266 let path = expr.path()?;
268 // Check for tuple-struct or tuple-variant in which case we can check the last segment
269 let callable = sema.type_of_expr(&ast::Expr::PathExpr(expr))?.original.as_callable(sema.db);
270 let callable_kind = callable.map(|it| it.kind());
271 if let Some(hir::CallableKind::TupleStruct(_) | hir::CallableKind::TupleEnumVariant(_)) =
274 if let Some(ctor) = path.segment() {
275 return (ctor.to_string() == ty_name).then(|| ());
279 // otherwise use the qualifying segment as the constructor name
280 let qual_seg = path.qualifier()?.segment()?;
281 let ctor_name = match qual_seg.kind()? {
282 ast::PathSegmentKind::Name(name_ref) => {
283 match qual_seg.generic_arg_list().map(|it| it.generic_args()) {
284 Some(generics) => format!("{}<{}>", name_ref, generics.format(", ")),
285 None => name_ref.to_string(),
288 ast::PathSegmentKind::Type { type_ref: Some(ty), trait_ref: None } => ty.to_string(),
291 (ctor_name == ty_name).then(|| ())
294 /// Checks if the type is an Iterator from std::iter and replaces its hint with an `impl Iterator<Item = Ty>`.
296 sema: &Semantics<RootDatabase>,
297 famous_defs: &FamousDefs,
298 config: &InlayHintsConfig,
300 ) -> Option<SmolStr> {
302 let strukt = ty.strip_references().as_adt()?;
303 let krate = strukt.module(db).krate();
304 if krate != famous_defs.core()? {
307 let iter_trait = famous_defs.core_iter_Iterator()?;
308 let iter_mod = famous_defs.core_iter()?;
310 // Assert that this struct comes from `core::iter`.
311 if !(strukt.visibility(db) == hir::Visibility::Public
312 && strukt.module(db).path_to_root(db).contains(&iter_mod))
317 if ty.impls_trait(db, iter_trait, &[]) {
318 let assoc_type_item = iter_trait.items(db).into_iter().find_map(|item| match item {
319 hir::AssocItem::TypeAlias(alias) if alias.name(db) == known::Item => Some(alias),
322 if let Some(ty) = ty.normalize_trait_assoc_type(db, &[], assoc_type_item) {
323 const LABEL_START: &str = "impl Iterator<Item = ";
324 const LABEL_END: &str = ">";
326 let ty_display = hint_iterator(sema, famous_defs, config, &ty)
327 .map(|assoc_type_impl| assoc_type_impl.to_string())
329 ty.display_truncated(
333 .map(|len| len.saturating_sub(LABEL_START.len() + LABEL_END.len())),
337 return Some(format!("{}{}{}", LABEL_START, ty_display, LABEL_END).into());
344 fn pat_is_enum_variant(db: &RootDatabase, bind_pat: &ast::IdentPat, pat_ty: &hir::Type) -> bool {
345 if let Some(hir::Adt::Enum(enum_data)) = pat_ty.as_adt() {
346 let pat_text = bind_pat.to_string();
350 .map(|variant| variant.name(db).to_smol_str())
351 .any(|enum_name| enum_name == pat_text)
357 fn should_not_display_type_hint(
358 sema: &Semantics<RootDatabase>,
359 bind_pat: &ast::IdentPat,
364 if pat_ty.is_unknown() {
368 if let Some(hir::Adt::Struct(s)) = pat_ty.as_adt() {
369 if s.fields(db).is_empty() && s.name(db).to_smol_str() == bind_pat.to_string() {
374 for node in bind_pat.syntax().ancestors() {
377 ast::LetStmt(it) => return it.ty().is_some(),
378 ast::Param(it) => return it.ty().is_some(),
379 ast::MatchArm(_it) => return pat_is_enum_variant(db, bind_pat, pat_ty),
381 return it.condition().and_then(|condition| condition.pat()).is_some()
382 && pat_is_enum_variant(db, bind_pat, pat_ty);
384 ast::WhileExpr(it) => {
385 return it.condition().and_then(|condition| condition.pat()).is_some()
386 && pat_is_enum_variant(db, bind_pat, pat_ty);
388 ast::ForExpr(it) => {
389 // We *should* display hint only if user provided "in {expr}" and we know the type of expr (and it's not unit).
390 // Type of expr should be iterable.
391 return it.in_token().is_none() ||
393 .and_then(|iterable_expr| sema.type_of_expr(&iterable_expr))
394 .map(TypeInfo::original)
395 .map_or(true, |iterable_ty| iterable_ty.is_unknown() || iterable_ty.is_unit())
404 fn should_hide_param_name_hint(
405 sema: &Semantics<RootDatabase>,
406 callable: &hir::Callable,
408 argument: &ast::Expr,
410 // These are to be tested in the `parameter_hint_heuristics` test
412 // - the parameter name is a suffix of the function's name
413 // - the argument is an enum whose name is equal to the parameter
414 // - exact argument<->parameter match(ignoring leading underscore) or parameter is a prefix/suffix
415 // of argument with _ splitting it off
416 // - param starts with `ra_fixture`
417 // - param is a well known name in a unary function
419 let param_name = param_name.trim_start_matches('_');
420 if param_name.is_empty() {
424 let fn_name = match callable.kind() {
425 hir::CallableKind::Function(it) => Some(it.name(sema.db).to_smol_str()),
428 let fn_name = fn_name.as_deref();
429 is_param_name_suffix_of_fn_name(param_name, callable, fn_name)
430 || is_enum_name_similar_to_param_name(sema, argument, param_name)
431 || is_argument_similar_to_param_name(argument, param_name)
432 || param_name.starts_with("ra_fixture")
433 || (callable.n_params() == 1 && is_obvious_param(param_name))
436 fn is_argument_similar_to_param_name(argument: &ast::Expr, param_name: &str) -> bool {
437 // check whether param_name and argument are the same or
438 // whether param_name is a prefix/suffix of argument(split at `_`)
439 let argument = match get_string_representation(argument) {
440 Some(argument) => argument,
441 None => return false,
444 // std is honestly too panic happy...
445 let str_split_at = |str: &str, at| str.is_char_boundary(at).then(|| argument.split_at(at));
447 let param_name = param_name.trim_start_matches('_');
448 let argument = argument.trim_start_matches('_');
450 match str_split_at(argument, param_name.len()) {
451 Some((prefix, rest)) if prefix.eq_ignore_ascii_case(param_name) => {
452 return rest.is_empty() || rest.starts_with('_');
456 match argument.len().checked_sub(param_name.len()).and_then(|at| str_split_at(argument, at)) {
457 Some((rest, suffix)) if param_name.eq_ignore_ascii_case(suffix) => {
458 return rest.is_empty() || rest.ends_with('_');
465 /// Hide the parameter name of a unary function if it is a `_` - prefixed suffix of the function's name, or equal.
467 /// `fn strip_suffix(suffix)` will be hidden.
468 /// `fn stripsuffix(suffix)` will not be hidden.
469 fn is_param_name_suffix_of_fn_name(
472 fn_name: Option<&str>,
474 match (callable.n_params(), fn_name) {
475 (1, Some(function)) => {
476 function == param_name
479 .checked_sub(param_name.len())
480 .and_then(|at| function.is_char_boundary(at).then(|| function.split_at(at)))
481 .map_or(false, |(prefix, suffix)| {
482 suffix.eq_ignore_ascii_case(param_name) && prefix.ends_with('_')
489 fn is_enum_name_similar_to_param_name(
490 sema: &Semantics<RootDatabase>,
491 argument: &ast::Expr,
494 match sema.type_of_expr(argument).and_then(|t| t.original.as_adt()) {
495 Some(hir::Adt::Enum(e)) => {
496 to_lower_snake_case(&e.name(sema.db).to_smol_str()) == param_name
502 fn get_string_representation(expr: &ast::Expr) -> Option<String> {
504 ast::Expr::MethodCallExpr(method_call_expr) => {
505 let name_ref = method_call_expr.name_ref()?;
506 match name_ref.text().as_str() {
507 "clone" | "as_ref" => method_call_expr.receiver().map(|rec| rec.to_string()),
508 name_ref => Some(name_ref.to_owned()),
511 ast::Expr::FieldExpr(field_expr) => Some(field_expr.name_ref()?.to_string()),
512 ast::Expr::PathExpr(path_expr) => Some(path_expr.path()?.segment()?.to_string()),
513 ast::Expr::PrefixExpr(prefix_expr) => get_string_representation(&prefix_expr.expr()?),
514 ast::Expr::RefExpr(ref_expr) => get_string_representation(&ref_expr.expr()?),
519 fn is_obvious_param(param_name: &str) -> bool {
520 // avoid displaying hints for common functions like map, filter, etc.
521 // or other obvious words used in std
522 let is_obvious_param_name =
523 matches!(param_name, "predicate" | "value" | "pat" | "rhs" | "other");
524 param_name.len() == 1 || is_obvious_param_name
528 sema: &Semantics<RootDatabase>,
530 ) -> Option<(hir::Callable, ast::ArgList)> {
532 ast::Expr::CallExpr(expr) => {
533 let descended = sema.descend_node_into_attributes(expr.clone()).pop();
534 let expr = descended.as_ref().unwrap_or(expr);
535 sema.type_of_expr(&expr.expr()?)?.original.as_callable(sema.db).zip(expr.arg_list())
537 ast::Expr::MethodCallExpr(expr) => {
538 let descended = sema.descend_node_into_attributes(expr.clone()).pop();
539 let expr = descended.as_ref().unwrap_or(expr);
540 sema.resolve_method_call_as_callable(expr).zip(expr.arg_list())
548 use expect_test::{expect, Expect};
549 use test_utils::extract_annotations;
551 use crate::{fixture, inlay_hints::InlayHintsConfig};
553 const TEST_CONFIG: InlayHintsConfig = InlayHintsConfig {
555 parameter_hints: true,
556 chaining_hints: true,
557 hide_named_constructor_hints: false,
562 fn check(ra_fixture: &str) {
563 check_with_config(TEST_CONFIG, ra_fixture);
567 fn check_params(ra_fixture: &str) {
570 parameter_hints: true,
572 chaining_hints: false,
573 hide_named_constructor_hints: false,
581 fn check_types(ra_fixture: &str) {
584 parameter_hints: false,
586 chaining_hints: false,
587 hide_named_constructor_hints: false,
595 fn check_chains(ra_fixture: &str) {
598 parameter_hints: false,
600 chaining_hints: true,
601 hide_named_constructor_hints: false,
609 fn check_with_config(config: InlayHintsConfig, ra_fixture: &str) {
610 let (analysis, file_id) = fixture::file(ra_fixture);
611 let expected = extract_annotations(&*analysis.file_text(file_id).unwrap());
612 let inlay_hints = analysis.inlay_hints(&config, file_id).unwrap();
614 inlay_hints.into_iter().map(|it| (it.range, it.label.to_string())).collect::<Vec<_>>();
615 assert_eq!(expected, actual, "\nExpected:\n{:#?}\n\nActual:\n{:#?}", expected, actual);
619 fn check_expect(config: InlayHintsConfig, ra_fixture: &str, expect: Expect) {
620 let (analysis, file_id) = fixture::file(ra_fixture);
621 let inlay_hints = analysis.inlay_hints(&config, file_id).unwrap();
622 expect.assert_debug_eq(&inlay_hints)
626 fn hints_disabled() {
630 parameter_hints: false,
631 chaining_hints: false,
632 hide_named_constructor_hints: false,
636 fn foo(a: i32, b: i32) -> i32 { a + b }
643 // Parameter hint tests
646 fn param_hints_only() {
649 fn foo(a: i32, b: i32) -> i32 { a + b }
662 fn param_name_similar_to_fn_name_still_hints() {
665 fn max(x: i32, y: i32) -> i32 { x + y }
678 fn param_name_similar_to_fn_name() {
681 fn param_with_underscore(with_underscore: i32) -> i32 { with_underscore }
683 let _x = param_with_underscore(
690 fn param_with_underscore(underscore: i32) -> i32 { underscore }
692 let _x = param_with_underscore(
700 fn param_name_same_as_fn_name() {
703 fn foo(foo: i32) -> i32 { foo }
713 fn never_hide_param_when_multiple_params() {
716 fn foo(foo: i32, bar: i32) -> i32 { bar + baz }
729 fn param_hints_look_through_as_ref_and_clone() {
732 fn foo(bar: i32, baz: f32) {}
738 foo(bar.clone(), bar.clone());
740 foo(bar.as_ref(), bar.as_ref());
748 fn self_param_hints() {
754 fn foo(self: Self) {}
755 fn bar(self: &Self) {}
769 fn param_name_hints_show_for_literals() {
771 r#"pub fn test(a: i32, b: i32) -> [i32; 2] { [a, b] }
784 fn function_call_parameter_hint() {
793 struct NavigationTarget {}
798 fn method(&self, mut param: i32) -> i32 { param * 2 }
803 focus_range: Option<TextRange>,
804 full_range: TextRange,
806 docs: Option<String>,
807 ) -> NavigationTarget {
812 fn test_func(mut foo: i32, bar: i32, msg: &str, _: i32, last: i32) -> i32 {
818 let _: i32 = test_func(1, 2, "hello", 3, not_literal);
819 //^ foo ^ bar ^^^^^^^ msg ^^^^^^^^^^^ last
820 let t: Test = Test {};
823 Test::method(&t, 3456);
833 //^^^^^^^^^^^^ full_range
844 fn parameter_hint_heuristics() {
847 fn check(ra_fixture_thing: &str) {}
850 fn filter(predicate: i32) {}
852 fn strip_suffix(suffix: &str) {}
853 fn stripsuffix(suffix: &str) {}
854 fn same(same: u32) {}
855 fn same2(_same2: u32) {}
857 fn enum_matches_param_name(completion_kind: CompletionKind) {}
859 fn foo(param: u32) {}
860 fn bar(param_eter: u32) {}
862 enum CompletionKind {
866 fn non_ident_pat((a, b): (u32, u32)) {}
869 const PARAM: u32 = 0;
883 enum_matches_param_name(CompletionKind::Keyword);
897 let param_eter_end = 0;
899 let start_param_eter = 0;
900 bar(start_param_eter);
903 //^^^^^^^^^^^ param_eter
905 non_ident_pat((0, 0));
913 fn type_hints_only() {
916 fn foo(a: i32, b: i32) -> i32 { a + b }
925 fn type_hints_bindings_after_at() {
930 let ref foo @ bar @ ref mut baz = 0;
936 if let x @ Some(_) = Some(0) {}
938 let foo @ (bar, baz) = (3, 3);
947 fn default_generic_types_should_not_be_displayed() {
950 struct Test<K, T = u8> { k: K, t: T }
953 let zz = Test { t: 23u8, k: 33 };
958 //^^^^ || -> Test<i32>
964 fn shorten_iterators_in_associated_params() {
967 //- minicore: iterators
970 pub struct SomeIter<T> {}
972 impl<T> SomeIter<T> {
973 pub fn new() -> Self { SomeIter {} }
974 pub fn push(&mut self, t: T) {}
977 impl<T> Iterator for SomeIter<T> {
979 fn next(&mut self) -> Option<Self::Item> {
985 let mut some_iter = SomeIter::new();
986 //^^^^^^^^^ SomeIter<Take<Repeat<i32>>>
987 some_iter.push(iter::repeat(2).take(2));
988 let iter_of_iters = some_iter.take(2);
989 //^^^^^^^^^^^^^ impl Iterator<Item = impl Iterator<Item = i32>>
996 fn infer_call_method_return_associated_types_with_generic() {
1000 fn default() -> Self;
1006 pub fn quux<T: Foo>() -> T::Bar {
1007 let y = Default::default();
1020 //- minicore: fn, sized
1021 fn foo() -> impl Fn() { loop {} }
1022 fn foo1() -> impl Fn(f64) { loop {} }
1023 fn foo2() -> impl Fn(f64, f64) { loop {} }
1024 fn foo3() -> impl Fn(f64, f64) -> u32 { loop {} }
1025 fn foo4() -> &'static dyn Fn(f64, f64) -> u32 { loop {} }
1026 fn foo5() -> &'static dyn Fn(&'static dyn Fn(f64, f64) -> u32, f64) -> u32 { loop {} }
1027 fn foo6() -> impl Fn(f64, f64) -> u32 + Sized { loop {} }
1028 fn foo7() -> *const (impl Fn(f64, f64) -> u32 + Sized) { loop {} }
1036 // ^^^ impl Fn(f64, f64)
1038 // ^^^ impl Fn(f64, f64) -> u32
1040 // ^^^ &dyn Fn(f64, f64) -> u32
1042 // ^^^ &dyn Fn(&dyn Fn(f64, f64) -> u32, f64) -> u32
1044 // ^^^ impl Fn(f64, f64) -> u32
1046 // ^^^ *const impl Fn(f64, f64) -> u32
1053 fn fn_hints_ptr_rpit_fn_parentheses() {
1056 //- minicore: fn, sized
1059 fn foo1() -> *const impl Fn() { loop {} }
1060 fn foo2() -> *const (impl Fn() + Sized) { loop {} }
1061 fn foo3() -> *const (impl Fn() + ?Sized) { loop {} }
1062 fn foo4() -> *const (impl Sized + Fn()) { loop {} }
1063 fn foo5() -> *const (impl ?Sized + Fn()) { loop {} }
1064 fn foo6() -> *const (impl Fn() + Trait) { loop {} }
1065 fn foo7() -> *const (impl Fn() + Sized + Trait) { loop {} }
1066 fn foo8() -> *const (impl Fn() + ?Sized + Trait) { loop {} }
1067 fn foo9() -> *const (impl Fn() -> u8 + ?Sized) { loop {} }
1068 fn foo10() -> *const (impl Fn() + Sized + ?Sized) { loop {} }
1072 // ^^^ *const impl Fn()
1074 // ^^^ *const impl Fn()
1076 // ^^^ *const (impl Fn() + ?Sized)
1078 // ^^^ *const impl Fn()
1080 // ^^^ *const (impl Fn() + ?Sized)
1082 // ^^^ *const (impl Fn() + Trait)
1084 // ^^^ *const (impl Fn() + Trait)
1086 // ^^^ *const (impl Fn() + Trait + ?Sized)
1088 // ^^^ *const (impl Fn() -> u8 + ?Sized)
1090 // ^^^ *const impl Fn()
1097 fn unit_structs_have_no_type_hints() {
1100 //- minicore: result
1101 struct SyntheticSyntax;
1106 Err(SyntheticSyntax) => (),
1113 fn let_statement() {
1116 #[derive(PartialEq)]
1117 enum Option<T> { None, Some(T) }
1119 #[derive(PartialEq)]
1120 struct Test { a: Option<u32>, b: u8 }
1123 struct InnerStruct {}
1133 let test = InnerStruct {};
1136 let test = unresolved();
1138 let test = (42, 'a');
1140 let (a, (b, (c,)) = (2, (3, (9.2,));
1152 //- minicore: option
1153 struct Test { a: Option<u32>, b: u8 }
1156 let test = Some(Test { a: Some(3), b: 1 });
1158 if let None = &test {};
1159 if let test = &test {};
1160 //^^^^ &Option<Test>
1161 if let Some(test) = &test {};
1163 if let Some(Test { a, b }) = &test {};
1164 //^ &Option<u32> ^ &u8
1165 if let Some(Test { a: x, b: y }) = &test {};
1166 //^ &Option<u32> ^ &u8
1167 if let Some(Test { a: Some(x), b: y }) = &test {};
1169 if let Some(Test { a: None, b: y }) = &test {};
1171 if let Some(Test { b: y, .. }) = &test {};
1182 //- minicore: option
1183 struct Test { a: Option<u32>, b: u8 }
1186 let test = Some(Test { a: Some(3), b: 1 });
1188 while let Some(Test { a: Some(x), b: y }) = &test {};
1195 fn match_arm_list() {
1198 //- minicore: option
1199 struct Test { a: Option<u32>, b: u8 }
1202 match Some(Test { a: Some(3), b: 1 }) {
1206 Some(Test { a: Some(x), b: y }) => (),
1215 fn incomplete_for_no_hint() {
1219 let data = &[1i32, 2, 3];
1226 pub struct Vec<T> {}
1229 pub fn new() -> Self { Vec {} }
1230 pub fn push(&mut self, t: T) {}
1233 impl<T> IntoIterator for Vec<T> {
1238 let mut data = Vec::new();
1243 println!("Unit expr");
1250 fn complete_for_hint() {
1253 //- minicore: iterator
1254 pub struct Vec<T> {}
1257 pub fn new() -> Self { Vec {} }
1258 pub fn push(&mut self, t: T) {}
1261 impl<T> IntoIterator for Vec<T> {
1266 let mut data = Vec::new();
1280 fn multi_dyn_trait_bounds() {
1283 pub struct Vec<T> {}
1286 pub fn new() -> Self { Vec {} }
1289 pub struct Box<T> {}
1295 // The block expression wrapping disables the constructor hint hiding logic
1296 let _v = { Vec::<Box<&(dyn Display + Sync)>>::new() };
1297 //^^ Vec<Box<&(dyn Display + Sync)>>
1298 let _v = { Vec::<Box<*const (dyn Display + Sync)>>::new() };
1299 //^^ Vec<Box<*const (dyn Display + Sync)>>
1300 let _v = { Vec::<Box<dyn Display + Sync>>::new() };
1301 //^^ Vec<Box<dyn Display + Sync>>
1308 fn shorten_iterator_hints() {
1311 //- minicore: iterators
1316 impl Iterator for MyIter {
1318 fn next(&mut self) -> Option<Self::Item> {
1326 let _x = iter::repeat(0);
1327 //^^ impl Iterator<Item = i32>
1328 fn generic<T: Clone>(t: T) {
1329 let _x = iter::repeat(t);
1330 //^^ impl Iterator<Item = T>
1331 let _chained = iter::repeat(t).take(10);
1332 //^^^^^^^^ impl Iterator<Item = T>
1340 fn skip_constructor_type_hints() {
1344 parameter_hints: true,
1345 chaining_hints: true,
1346 hide_named_constructor_hints: true,
1351 use core::ops::ControlFlow;
1354 struct TupleStruct();
1360 fn try_new() -> ControlFlow<(), Self> {
1361 ControlFlow::Continue(Struct)
1365 struct Generic<T>(T);
1373 let strukt = Struct::new();
1374 let tuple_struct = TupleStruct();
1375 let generic0 = Generic::new();
1376 // ^^^^^^^^ Generic<i32>
1377 let generic1 = Generic::<i32>::new();
1378 let generic2 = <Generic<i32>>::new();
1381 fn fallible() -> ControlFlow<()> {
1382 let strukt = Struct::try_new()?;
1389 fn shows_constructor_type_hints_when_enabled() {
1393 use core::ops::ControlFlow;
1396 struct TupleStruct();
1402 fn try_new() -> ControlFlow<(), Self> {
1403 ControlFlow::Continue(Struct)
1407 struct Generic<T>(T);
1415 let strukt = Struct::new();
1417 let tuple_struct = TupleStruct();
1418 // ^^^^^^^^^^^^ TupleStruct
1419 let generic0 = Generic::new();
1420 // ^^^^^^^^ Generic<i32>
1421 let generic1 = Generic::<i32>::new();
1422 // ^^^^^^^^ Generic<i32>
1423 let generic2 = <Generic<i32>>::new();
1424 // ^^^^^^^^ Generic<i32>
1427 fn fallible() -> ControlFlow<()> {
1428 let strukt = Struct::try_new()?;
1442 (0..2).for_each(|increment| { start += increment; });
1446 //^^^^^^^^ |i32, i32| -> i32
1451 let _: i32 = multiply(1, 2);
1452 let multiply_ref = &multiply;
1453 //^^^^^^^^^^^^ &|i32, i32| -> i32
1455 let return_42 = || 42;
1456 //^^^^^^^^^ || -> i32
1462 fn hint_truncation() {
1464 InlayHintsConfig { max_length: Some(8), ..TEST_CONFIG },
1468 struct VeryLongOuterName<T>(T);
1473 let b = VeryLongOuterName(0usize);
1474 //^ VeryLongOuterName<…>
1475 let c = Smol(Smol(0u32))
1481 // Chaining hint tests
1484 fn chaining_hints_ignore_comments() {
1487 parameter_hints: false,
1489 chaining_hints: true,
1490 hide_named_constructor_hints: false,
1495 impl A { fn into_b(self) -> B { self.0 } }
1497 impl B { fn into_c(self) -> C { self.0 } }
1502 .into_b() // This is a comment
1503 // This is another comment
1525 fn chaining_hints_without_newlines() {
1529 impl A { fn into_b(self) -> B { self.0 } }
1531 impl B { fn into_c(self) -> C { self.0 } }
1535 let c = A(B(C)).into_b().into_c();
1541 fn struct_access_chaining_hints() {
1544 parameter_hints: false,
1546 chaining_hints: true,
1547 hide_named_constructor_hints: false,
1551 struct A { pub b: B }
1552 struct B { pub c: C }
1557 fn foo(&self) -> i32 { 42 }
1561 let x = A { b: B { c: C(true) } }
1586 fn generic_chaining_hints() {
1589 parameter_hints: false,
1591 chaining_hints: true,
1592 hide_named_constructor_hints: false,
1599 struct X<T,R>(T, R);
1602 fn new(t: T) -> Self { A(t) }
1603 fn into_b(self) -> B<T> { B(self.0) }
1606 fn into_c(self) -> C<T> { C(self.0) }
1609 let c = A::new(X(42, true))
1619 label: "B<X<i32, bool>>",
1624 label: "A<X<i32, bool>>",
1632 fn shorten_iterator_chaining_hints() {
1635 parameter_hints: false,
1637 chaining_hints: true,
1638 hide_named_constructor_hints: false,
1642 //- minicore: iterators
1647 impl Iterator for MyIter {
1649 fn next(&mut self) -> Option<Self::Item> {
1655 let _x = MyIter.by_ref()
1667 label: "impl Iterator<Item = ()>",
1672 label: "impl Iterator<Item = ()>",
1677 label: "impl Iterator<Item = ()>",
1682 label: "&mut MyIter",
1690 fn hints_in_attr_call() {
1694 //- proc_macros: identity, input_replace
1697 fn chain(self) -> Self {
1701 #[proc_macros::identity]
1703 let strukt = Struct;
1708 Struct::chain(strukt);
1730 kind: ParameterHint,