Restructure InlayHint, no longer derive properties from its kind

This commit is contained in:
Lukas Wirth 2023-05-13 10:42:26 +02:00
parent 4c5fd19ee5
commit 730286b523
15 changed files with 417 additions and 349 deletions

View file

@ -90,32 +90,34 @@ pub enum AdjustmentHintsMode {
PreferPostfix, PreferPostfix,
} }
// FIXME: Clean up this mess, the kinds are mainly used for setting different rendering properties in the lsp layer
// We should probably turns this into such a property holding struct. Or clean this up in some other form.
#[derive(Copy, Clone, Debug, PartialEq, Eq)] #[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum InlayKind { pub enum InlayKind {
Adjustment,
BindingMode, BindingMode,
Chaining, Chaining,
ClosingBrace, ClosingBrace,
ClosureReturnType,
GenericParamList,
Adjustment,
AdjustmentPostfix,
Lifetime,
ClosureCapture, ClosureCapture,
Discriminant,
GenericParamList,
Lifetime,
Parameter, Parameter,
Type, Type,
Discriminant, }
OpeningParenthesis,
ClosingParenthesis, #[derive(Debug)]
pub enum InlayHintPosition {
Before,
After,
} }
#[derive(Debug)] #[derive(Debug)]
pub struct InlayHint { pub struct InlayHint {
/// The text range this inlay hint applies to. /// The text range this inlay hint applies to.
pub range: TextRange, pub range: TextRange,
/// The kind of this inlay hint. This is used to determine side and padding of the hint for pub position: InlayHintPosition,
/// rendering purposes. pub pad_left: bool,
pub pad_right: bool,
/// The kind of this inlay hint.
pub kind: InlayKind, pub kind: InlayKind,
/// The actual label to show in the inlay hint. /// The actual label to show in the inlay hint.
pub label: InlayHintLabel, pub label: InlayHintLabel,
@ -124,20 +126,26 @@ pub struct InlayHint {
} }
impl InlayHint { impl InlayHint {
fn closing_paren(range: TextRange) -> InlayHint { fn closing_paren_after(kind: InlayKind, range: TextRange) -> InlayHint {
InlayHint { InlayHint {
range, range,
kind: InlayKind::ClosingParenthesis, kind,
label: InlayHintLabel::from(")"), label: InlayHintLabel::from(")"),
text_edit: None, text_edit: None,
position: InlayHintPosition::After,
pad_left: false,
pad_right: false,
} }
} }
fn opening_paren(range: TextRange) -> InlayHint { fn opening_paren_before(kind: InlayKind, range: TextRange) -> InlayHint {
InlayHint { InlayHint {
range, range,
kind: InlayKind::OpeningParenthesis, kind,
label: InlayHintLabel::from("("), label: InlayHintLabel::from("("),
text_edit: None, text_edit: None,
position: InlayHintPosition::Before,
pad_left: false,
pad_right: false,
} }
} }
} }
@ -303,13 +311,13 @@ impl InlayHintLabelBuilder<'_> {
fn label_of_ty( fn label_of_ty(
famous_defs @ FamousDefs(sema, _): &FamousDefs<'_, '_>, famous_defs @ FamousDefs(sema, _): &FamousDefs<'_, '_>,
config: &InlayHintsConfig, config: &InlayHintsConfig,
ty: hir::Type, ty: &hir::Type,
) -> Option<InlayHintLabel> { ) -> Option<InlayHintLabel> {
fn rec( fn rec(
sema: &Semantics<'_, RootDatabase>, sema: &Semantics<'_, RootDatabase>,
famous_defs: &FamousDefs<'_, '_>, famous_defs: &FamousDefs<'_, '_>,
mut max_length: Option<usize>, mut max_length: Option<usize>,
ty: hir::Type, ty: &hir::Type,
label_builder: &mut InlayHintLabelBuilder<'_>, label_builder: &mut InlayHintLabelBuilder<'_>,
config: &InlayHintsConfig, config: &InlayHintsConfig,
) -> Result<(), HirDisplayError> { ) -> Result<(), HirDisplayError> {
@ -342,7 +350,7 @@ fn label_of_ty(
label_builder.write_str(LABEL_ITEM)?; label_builder.write_str(LABEL_ITEM)?;
label_builder.end_location_link(); label_builder.end_location_link();
label_builder.write_str(LABEL_MIDDLE2)?; label_builder.write_str(LABEL_MIDDLE2)?;
rec(sema, famous_defs, max_length, ty, label_builder, config)?; rec(sema, famous_defs, max_length, &ty, label_builder, config)?;
label_builder.write_str(LABEL_END)?; label_builder.write_str(LABEL_END)?;
Ok(()) Ok(())
} }
@ -574,7 +582,8 @@ mod tests {
let inlay_hints = analysis.inlay_hints(&config, file_id, None).unwrap(); let inlay_hints = analysis.inlay_hints(&config, file_id, None).unwrap();
let actual = inlay_hints let actual = inlay_hints
.into_iter() .into_iter()
.map(|it| (it.range, it.label.to_string())) // FIXME: We trim the start because some inlay produces leading whitespace which is not properly supported by our annotation extraction
.map(|it| (it.range, it.label.to_string().trim_start().to_owned()))
.sorted_by_key(|(range, _)| range.start()) .sorted_by_key(|(range, _)| range.start())
.collect::<Vec<_>>(); .collect::<Vec<_>>();
expected.sort_by_key(|(range, _)| range.start()); expected.sort_by_key(|(range, _)| range.start());

View file

@ -3,6 +3,7 @@
//! let _: u32 = /* <never-to-any> */ loop {}; //! let _: u32 = /* <never-to-any> */ loop {};
//! let _: &u32 = /* &* */ &mut 0; //! let _: &u32 = /* &* */ &mut 0;
//! ``` //! ```
use either::Either;
use hir::{ use hir::{
Adjust, Adjustment, AutoBorrow, HirDisplay, Mutability, OverloadedDeref, PointerCast, Safety, Adjust, Adjustment, AutoBorrow, HirDisplay, Mutability, OverloadedDeref, PointerCast, Safety,
Semantics, Semantics,
@ -16,8 +17,8 @@ use syntax::{
}; };
use crate::{ use crate::{
AdjustmentHints, AdjustmentHintsMode, InlayHint, InlayHintLabel, InlayHintsConfig, InlayKind, AdjustmentHints, AdjustmentHintsMode, InlayHint, InlayHintLabel, InlayHintPosition,
InlayTooltip, InlayHintsConfig, InlayKind, InlayTooltip,
}; };
pub(super) fn hints( pub(super) fn hints(
@ -63,22 +64,26 @@ pub(super) fn hints(
mode_and_needs_parens_for_adjustment_hints(expr, config.adjustment_hints_mode); mode_and_needs_parens_for_adjustment_hints(expr, config.adjustment_hints_mode);
if needs_outer_parens { if needs_outer_parens {
acc.push(InlayHint::opening_paren(expr.syntax().text_range())); acc.push(InlayHint::opening_paren_before(
InlayKind::Adjustment,
expr.syntax().text_range(),
));
} }
if postfix && needs_inner_parens { if postfix && needs_inner_parens {
acc.push(InlayHint::opening_paren(expr.syntax().text_range())); acc.push(InlayHint::opening_paren_before(
acc.push(InlayHint::closing_paren(expr.syntax().text_range())); InlayKind::Adjustment,
expr.syntax().text_range(),
));
acc.push(InlayHint::closing_paren_after(InlayKind::Adjustment, expr.syntax().text_range()));
} }
let (mut tmp0, mut tmp1); let mut iter = if postfix {
let iter: &mut dyn Iterator<Item = _> = if postfix { Either::Left(adjustments.into_iter())
tmp0 = adjustments.into_iter();
&mut tmp0
} else { } else {
tmp1 = adjustments.into_iter().rev(); Either::Right(adjustments.into_iter().rev())
&mut tmp1
}; };
let iter: &mut dyn Iterator<Item = _> = iter.as_mut().either(|it| it as _, |it| it as _);
for Adjustment { source, target, kind } in iter { for Adjustment { source, target, kind } in iter {
if source == target { if source == target {
@ -134,7 +139,10 @@ pub(super) fn hints(
}; };
acc.push(InlayHint { acc.push(InlayHint {
range: expr.syntax().text_range(), range: expr.syntax().text_range(),
kind: if postfix { InlayKind::AdjustmentPostfix } else { InlayKind::Adjustment }, pad_left: false,
pad_right: false,
position: if postfix { InlayHintPosition::After } else { InlayHintPosition::Before },
kind: InlayKind::Adjustment,
label: InlayHintLabel::simple( label: InlayHintLabel::simple(
if postfix { format!(".{}", text.trim_end()) } else { text.to_owned() }, if postfix { format!(".{}", text.trim_end()) } else { text.to_owned() },
Some(InlayTooltip::Markdown(format!( Some(InlayTooltip::Markdown(format!(
@ -148,11 +156,14 @@ pub(super) fn hints(
}); });
} }
if !postfix && needs_inner_parens { if !postfix && needs_inner_parens {
acc.push(InlayHint::opening_paren(expr.syntax().text_range())); acc.push(InlayHint::opening_paren_before(
acc.push(InlayHint::closing_paren(expr.syntax().text_range())); InlayKind::Adjustment,
expr.syntax().text_range(),
));
acc.push(InlayHint::closing_paren_after(InlayKind::Adjustment, expr.syntax().text_range()));
} }
if needs_outer_parens { if needs_outer_parens {
acc.push(InlayHint::closing_paren(expr.syntax().text_range())); acc.push(InlayHint::closing_paren_after(InlayKind::Adjustment, expr.syntax().text_range()));
} }
Some(()) Some(())
} }

View file

@ -14,7 +14,7 @@ use syntax::{
use crate::{ use crate::{
inlay_hints::{closure_has_block_body, label_of_ty, ty_to_text_edit}, inlay_hints::{closure_has_block_body, label_of_ty, ty_to_text_edit},
InlayHint, InlayHintsConfig, InlayKind, InlayHint, InlayHintPosition, InlayHintsConfig, InlayKind,
}; };
pub(super) fn hints( pub(super) fn hints(
@ -36,7 +36,7 @@ pub(super) fn hints(
return None; return None;
} }
let label = label_of_ty(famous_defs, config, ty.clone())?; let mut label = label_of_ty(famous_defs, config, &ty)?;
if config.hide_named_constructor_hints if config.hide_named_constructor_hints
&& is_named_constructor(sema, pat, &label.to_string()).is_some() && is_named_constructor(sema, pat, &label.to_string()).is_some()
@ -44,31 +44,46 @@ pub(super) fn hints(
return None; return None;
} }
let type_annotation_is_valid = desc_pat let type_ascriptable = desc_pat.syntax().parent().and_then(|it| {
.syntax() ast::LetStmt::cast(it.clone())
.parent() .map(|it| it.colon_token())
.map(|it| ast::LetStmt::can_cast(it.kind()) || ast::Param::can_cast(it.kind())) .or_else(|| ast::Param::cast(it).map(|it| it.colon_token()))
.unwrap_or(false); });
let text_edit = if type_annotation_is_valid { let text_edit = if let Some(colon_token) = &type_ascriptable {
ty_to_text_edit( ty_to_text_edit(
sema, sema,
desc_pat.syntax(), desc_pat.syntax(),
&ty, &ty,
pat.syntax().text_range().end(), colon_token
String::from(": "), .as_ref()
.map_or_else(|| pat.syntax().text_range(), |t| t.text_range())
.end(),
if colon_token.is_some() { String::new() } else { String::from(": ") },
) )
} else { } else {
None None
}; };
let has_colon = matches!(type_ascriptable, Some(Some(_))) && !config.render_colons;
if !has_colon {
label.prepend_str(": ");
}
let text_range = match pat.name() {
Some(name) => name.syntax().text_range(),
None => pat.syntax().text_range(),
};
acc.push(InlayHint { acc.push(InlayHint {
range: match pat.name() { range: match type_ascriptable {
Some(name) => name.syntax().text_range(), Some(Some(t)) => text_range.cover(t.text_range()),
None => pat.syntax().text_range(), _ => text_range,
}, },
kind: InlayKind::Type, kind: InlayKind::Type,
label, label,
text_edit, text_edit,
position: InlayHintPosition::Before,
pad_left: !has_colon,
pad_right: false,
}); });
Some(()) Some(())
@ -218,7 +233,7 @@ mod tests {
fn foo(a: i32, b: i32) -> i32 { a + b } fn foo(a: i32, b: i32) -> i32 { a + b }
fn main() { fn main() {
let _x = foo(4, 4); let _x = foo(4, 4);
//^^ i32 //^^ : i32
}"#, }"#,
); );
} }
@ -230,17 +245,17 @@ fn main() {
//- minicore: option //- minicore: option
fn main() { fn main() {
let ref foo @ bar @ ref mut baz = 0; let ref foo @ bar @ ref mut baz = 0;
//^^^ &i32 //^^^ : &i32
//^^^ i32 //^^^ : i32
//^^^ &mut i32 //^^^ : &mut i32
let [x @ ..] = [0]; let [x @ ..] = [0];
//^ [i32; 1] //^ : [i32; 1]
if let x @ Some(_) = Some(0) {} if let x @ Some(_) = Some(0) {}
//^ Option<i32> //^ : Option<i32>
let foo @ (bar, baz) = (3, 3); let foo @ (bar, baz) = (3, 3);
//^^^ (i32, i32) //^^^ : (i32, i32)
//^^^ i32 //^^^ : i32
//^^^ i32 //^^^ : i32
}"#, }"#,
); );
} }
@ -253,11 +268,11 @@ struct Test<K, T = u8> { k: K, t: T }
fn main() { fn main() {
let zz = Test { t: 23u8, k: 33 }; let zz = Test { t: 23u8, k: 33 };
//^^ Test<i32> //^^ : Test<i32>
let zz_ref = &zz; let zz_ref = &zz;
//^^^^^^ &Test<i32> //^^^^^^ : &Test<i32>
let test = || zz; let test = || zz;
//^^^^ impl FnOnce() -> Test<i32> //^^^^ : impl FnOnce() -> Test<i32>
}"#, }"#,
); );
} }
@ -285,10 +300,10 @@ impl<T> Iterator for SomeIter<T> {
fn main() { fn main() {
let mut some_iter = SomeIter::new(); let mut some_iter = SomeIter::new();
//^^^^^^^^^ SomeIter<Take<Repeat<i32>>> //^^^^^^^^^ : SomeIter<Take<Repeat<i32>>>
some_iter.push(iter::repeat(2).take(2)); some_iter.push(iter::repeat(2).take(2));
let iter_of_iters = some_iter.take(2); let iter_of_iters = some_iter.take(2);
//^^^^^^^^^^^^^ impl Iterator<Item = impl Iterator<Item = i32>> //^^^^^^^^^^^^^ : impl Iterator<Item = impl Iterator<Item = i32>>
} }
"#, "#,
); );
@ -347,7 +362,7 @@ fn main(a: SliceIter<'_, Container>) {
pub fn quux<T: Foo>() -> T::Bar { pub fn quux<T: Foo>() -> T::Bar {
let y = Default::default(); let y = Default::default();
//^ <T as Foo>::Bar //^ : <T as Foo>::Bar
y y
} }
@ -371,21 +386,21 @@ fn foo7() -> *const (impl Fn(f64, f64) -> u32 + Sized) { loop {} }
fn main() { fn main() {
let foo = foo(); let foo = foo();
// ^^^ impl Fn() // ^^^ : impl Fn()
let foo = foo1(); let foo = foo1();
// ^^^ impl Fn(f64) // ^^^ : impl Fn(f64)
let foo = foo2(); let foo = foo2();
// ^^^ impl Fn(f64, f64) // ^^^ : impl Fn(f64, f64)
let foo = foo3(); let foo = foo3();
// ^^^ impl Fn(f64, f64) -> u32 // ^^^ : impl Fn(f64, f64) -> u32
let foo = foo4(); let foo = foo4();
// ^^^ &dyn Fn(f64, f64) -> u32 // ^^^ : &dyn Fn(f64, f64) -> u32
let foo = foo5(); let foo = foo5();
// ^^^ &dyn Fn(&dyn Fn(f64, f64) -> u32, f64) -> u32 // ^^^ : &dyn Fn(&dyn Fn(f64, f64) -> u32, f64) -> u32
let foo = foo6(); let foo = foo6();
// ^^^ impl Fn(f64, f64) -> u32 // ^^^ : impl Fn(f64, f64) -> u32
let foo = foo7(); let foo = foo7();
// ^^^ *const impl Fn(f64, f64) -> u32 // ^^^ : *const impl Fn(f64, f64) -> u32
} }
"#, "#,
) )
@ -408,9 +423,9 @@ fn main() {
let foo = foo(); let foo = foo();
let foo = foo1(); let foo = foo1();
let foo = foo2(); let foo = foo2();
// ^^^ impl Fn(f64, f64) // ^^^ : impl Fn(f64, f64)
let foo = foo3(); let foo = foo3();
// ^^^ impl Fn(f64, f64) -> u32 // ^^^ : impl Fn(f64, f64) -> u32
let foo = foo4(); let foo = foo4();
let foo = foo5(); let foo = foo5();
let foo = foo6(); let foo = foo6();
@ -451,25 +466,25 @@ fn foo10() -> *const (impl Fn() + Sized + ?Sized) { loop {} }
fn main() { fn main() {
let foo = foo1(); let foo = foo1();
// ^^^ *const impl Fn() // ^^^ : *const impl Fn()
let foo = foo2(); let foo = foo2();
// ^^^ *const impl Fn() // ^^^ : *const impl Fn()
let foo = foo3(); let foo = foo3();
// ^^^ *const (impl Fn() + ?Sized) // ^^^ : *const (impl Fn() + ?Sized)
let foo = foo4(); let foo = foo4();
// ^^^ *const impl Fn() // ^^^ : *const impl Fn()
let foo = foo5(); let foo = foo5();
// ^^^ *const (impl Fn() + ?Sized) // ^^^ : *const (impl Fn() + ?Sized)
let foo = foo6(); let foo = foo6();
// ^^^ *const (impl Fn() + Trait) // ^^^ : *const (impl Fn() + Trait)
let foo = foo7(); let foo = foo7();
// ^^^ *const (impl Fn() + Trait) // ^^^ : *const (impl Fn() + Trait)
let foo = foo8(); let foo = foo8();
// ^^^ *const (impl Fn() + Trait + ?Sized) // ^^^ : *const (impl Fn() + Trait + ?Sized)
let foo = foo9(); let foo = foo9();
// ^^^ *const (impl Fn() -> u8 + ?Sized) // ^^^ : *const (impl Fn() -> u8 + ?Sized)
let foo = foo10(); let foo = foo10();
// ^^^ *const impl Fn() // ^^^ : *const impl Fn()
} }
"#, "#,
) )
@ -520,24 +535,24 @@ fn main() {
struct InnerStruct {} struct InnerStruct {}
let test = 54; let test = 54;
//^^^^ i32 //^^^^ : i32
let test: i32 = 33; let test: i32 = 33;
let mut test = 33; let mut test = 33;
//^^^^ i32 //^^^^ : i32
let _ = 22; let _ = 22;
let test = "test"; let test = "test";
//^^^^ &str //^^^^ : &str
let test = InnerStruct {}; let test = InnerStruct {};
//^^^^ InnerStruct //^^^^ : InnerStruct
let test = unresolved(); let test = unresolved();
let test = (42, 'a'); let test = (42, 'a');
//^^^^ (i32, char) //^^^^ : (i32, char)
let (a, (b, (c,)) = (2, (3, (9.2,)); let (a, (b, (c,)) = (2, (3, (9.2,));
//^ i32 ^ i32 ^ f64 //^ : i32 ^ : i32 ^ : f64
let &x = &92; let &x = &92;
//^ i32 //^ : i32
}"#, }"#,
); );
} }
@ -551,22 +566,22 @@ struct Test { a: Option<u32>, b: u8 }
fn main() { fn main() {
let test = Some(Test { a: Some(3), b: 1 }); let test = Some(Test { a: Some(3), b: 1 });
//^^^^ Option<Test> //^^^^ : Option<Test>
if let None = &test {}; if let None = &test {};
if let test = &test {}; if let test = &test {};
//^^^^ &Option<Test> //^^^^ : &Option<Test>
if let Some(test) = &test {}; if let Some(test) = &test {};
//^^^^ &Test //^^^^ : &Test
if let Some(Test { a, b }) = &test {}; if let Some(Test { a, b }) = &test {};
//^ &Option<u32> ^ &u8 //^ : &Option<u32> ^ : &u8
if let Some(Test { a: x, b: y }) = &test {}; if let Some(Test { a: x, b: y }) = &test {};
//^ &Option<u32> ^ &u8 //^ : &Option<u32> ^ : &u8
if let Some(Test { a: Some(x), b: y }) = &test {}; if let Some(Test { a: Some(x), b: y }) = &test {};
//^ &u32 ^ &u8 //^ : &u32 ^ : &u8
if let Some(Test { a: None, b: y }) = &test {}; if let Some(Test { a: None, b: y }) = &test {};
//^ &u8 //^ : &u8
if let Some(Test { b: y, .. }) = &test {}; if let Some(Test { b: y, .. }) = &test {};
//^ &u8 //^ : &u8
if test == None {} if test == None {}
}"#, }"#,
); );
@ -581,9 +596,9 @@ struct Test { a: Option<u32>, b: u8 }
fn main() { fn main() {
let test = Some(Test { a: Some(3), b: 1 }); let test = Some(Test { a: Some(3), b: 1 });
//^^^^ Option<Test> //^^^^ : Option<Test>
while let Some(Test { a: Some(x), b: y }) = &test {}; while let Some(Test { a: Some(x), b: y }) = &test {};
//^ &u32 ^ &u8 //^ : &u32 ^ : &u8
}"#, }"#,
); );
} }
@ -599,9 +614,9 @@ fn main() {
match Some(Test { a: Some(3), b: 1 }) { match Some(Test { a: Some(3), b: 1 }) {
None => (), None => (),
test => (), test => (),
//^^^^ Option<Test> //^^^^ : Option<Test>
Some(Test { a: Some(x), b: y }) => (), Some(Test { a: Some(x), b: y }) => (),
//^ u32 ^ u8 //^ : u32 ^ : u8
_ => {} _ => {}
} }
}"#, }"#,
@ -633,12 +648,12 @@ impl<T> Iterator for IntoIter<T> {
fn main() { fn main() {
let mut data = Vec::new(); let mut data = Vec::new();
//^^^^ Vec<&str> //^^^^ : Vec<&str>
data.push("foo"); data.push("foo");
for i in data { for i in data {
//^ &str //^ : &str
let z = i; let z = i;
//^ &str //^ : &str
} }
} }
"#, "#,
@ -663,11 +678,11 @@ auto trait Sync {}
fn main() { fn main() {
// The block expression wrapping disables the constructor hint hiding logic // The block expression wrapping disables the constructor hint hiding logic
let _v = { Vec::<Box<&(dyn Display + Sync)>>::new() }; let _v = { Vec::<Box<&(dyn Display + Sync)>>::new() };
//^^ Vec<Box<&(dyn Display + Sync)>> //^^ : Vec<Box<&(dyn Display + Sync)>>
let _v = { Vec::<Box<*const (dyn Display + Sync)>>::new() }; let _v = { Vec::<Box<*const (dyn Display + Sync)>>::new() };
//^^ Vec<Box<*const (dyn Display + Sync)>> //^^ : Vec<Box<*const (dyn Display + Sync)>>
let _v = { Vec::<Box<dyn Display + Sync>>::new() }; let _v = { Vec::<Box<dyn Display + Sync>>::new() };
//^^ Vec<Box<dyn Display + Sync>> //^^ : Vec<Box<dyn Display + Sync>>
} }
"#, "#,
); );
@ -691,14 +706,14 @@ impl Iterator for MyIter {
fn main() { fn main() {
let _x = MyIter; let _x = MyIter;
//^^ MyIter //^^ : MyIter
let _x = iter::repeat(0); let _x = iter::repeat(0);
//^^ impl Iterator<Item = i32> //^^ : impl Iterator<Item = i32>
fn generic<T: Clone>(t: T) { fn generic<T: Clone>(t: T) {
let _x = iter::repeat(t); let _x = iter::repeat(t);
//^^ impl Iterator<Item = T> //^^ : impl Iterator<Item = T>
let _chained = iter::repeat(t).take(10); let _chained = iter::repeat(t).take(10);
//^^^^^^^^ impl Iterator<Item = T> //^^^^^^^^ : impl Iterator<Item = T>
} }
} }
"#, "#,
@ -762,20 +777,20 @@ fn main() {
let tuple_struct = TupleStruct(); let tuple_struct = TupleStruct();
let generic0 = Generic::new(); let generic0 = Generic::new();
// ^^^^^^^^ Generic<i32> // ^^^^^^^^ : Generic<i32>
let generic1 = Generic(0); let generic1 = Generic(0);
// ^^^^^^^^ Generic<i32> // ^^^^^^^^ : Generic<i32>
let generic2 = Generic::<i32>::new(); let generic2 = Generic::<i32>::new();
let generic3 = <Generic<i32>>::new(); let generic3 = <Generic<i32>>::new();
let generic4 = Generic::<i32>(0); let generic4 = Generic::<i32>(0);
let option = Some(0); let option = Some(0);
// ^^^^^^ Option<i32> // ^^^^^^ : Option<i32>
let func = times2; let func = times2;
// ^^^^ fn times2(i32) -> i32 // ^^^^ : fn times2(i32) -> i32
let closure = |x: i32| x * 2; let closure = |x: i32| x * 2;
// ^^^^^^^ impl Fn(i32) -> i32 // ^^^^^^^ : impl Fn(i32) -> i32
} }
fn fallible() -> ControlFlow<()> { fn fallible() -> ControlFlow<()> {
@ -813,72 +828,25 @@ impl Generic<i32> {
fn main() { fn main() {
let strukt = Struct::new(); let strukt = Struct::new();
// ^^^^^^ Struct // ^^^^^^ : Struct
let tuple_struct = TupleStruct(); let tuple_struct = TupleStruct();
// ^^^^^^^^^^^^ TupleStruct // ^^^^^^^^^^^^ : TupleStruct
let generic0 = Generic::new(); let generic0 = Generic::new();
// ^^^^^^^^ Generic<i32> // ^^^^^^^^ : Generic<i32>
let generic1 = Generic::<i32>::new(); let generic1 = Generic::<i32>::new();
// ^^^^^^^^ Generic<i32> // ^^^^^^^^ : Generic<i32>
let generic2 = <Generic<i32>>::new(); let generic2 = <Generic<i32>>::new();
// ^^^^^^^^ Generic<i32> // ^^^^^^^^ : Generic<i32>
} }
fn fallible() -> ControlFlow<()> { fn fallible() -> ControlFlow<()> {
let strukt = Struct::try_new()?; let strukt = Struct::try_new()?;
// ^^^^^^ Struct // ^^^^^^ : Struct
} }
"#, "#,
); );
} }
#[test]
fn closures() {
check(
r#"
fn main() {
let mut start = 0;
//^^^^^ i32
(0..2).for_each(|increment | { start += increment; });
//^^^^^^^^^ i32
let multiply =
//^^^^^^^^ impl Fn(i32, i32) -> i32
| a, b| a * b
//^ i32 ^ i32
;
let _: i32 = multiply(1, 2);
//^ a ^ b
let multiply_ref = &multiply;
//^^^^^^^^^^^^ &impl Fn(i32, i32) -> i32
let return_42 = || 42;
//^^^^^^^^^ impl Fn() -> i32
|| { 42 };
//^^ i32
}"#,
);
}
#[test]
fn return_type_hints_for_closure_without_block() {
check_with_config(
InlayHintsConfig {
closure_return_type_hints: ClosureReturnTypeHints::Always,
..DISABLED_CONFIG
},
r#"
fn main() {
let a = || { 0 };
//^^ i32
let b = || 0;
//^^ i32
}"#,
);
}
#[test] #[test]
fn closure_style() { fn closure_style() {
check_with_config( check_with_config(
@ -887,15 +855,15 @@ fn main() {
//- minicore: fn //- minicore: fn
fn main() { fn main() {
let x = || 2; let x = || 2;
//^ impl Fn() -> i32 //^ : impl Fn() -> i32
let y = |t: i32| x() + t; let y = |t: i32| x() + t;
//^ impl Fn(i32) -> i32 //^ : impl Fn(i32) -> i32
let mut t = 5; let mut t = 5;
//^ i32 //^ : i32
let z = |k: i32| { t += k; }; let z = |k: i32| { t += k; };
//^ impl FnMut(i32) //^ : impl FnMut(i32)
let p = (y, z); let p = (y, z);
//^ (impl Fn(i32) -> i32, impl FnMut(i32)) //^ : (impl Fn(i32) -> i32, impl FnMut(i32))
} }
"#, "#,
); );
@ -909,15 +877,15 @@ fn main() {
//- minicore: fn //- minicore: fn
fn main() { fn main() {
let x = || 2; let x = || 2;
//^ || -> i32 //^ : || -> i32
let y = |t: i32| x() + t; let y = |t: i32| x() + t;
//^ |i32| -> i32 //^ : |i32| -> i32
let mut t = 5; let mut t = 5;
//^ i32 //^ : i32
let z = |k: i32| { t += k; }; let z = |k: i32| { t += k; };
//^ |i32| -> () //^ : |i32| -> ()
let p = (y, z); let p = (y, z);
//^ (|i32| -> i32, |i32| -> ()) //^ : (|i32| -> i32, |i32| -> ())
} }
"#, "#,
); );
@ -931,15 +899,15 @@ fn main() {
//- minicore: fn //- minicore: fn
fn main() { fn main() {
let x = || 2; let x = || 2;
//^ {closure#0} //^ : {closure#0}
let y = |t: i32| x() + t; let y = |t: i32| x() + t;
//^ {closure#1} //^ : {closure#1}
let mut t = 5; let mut t = 5;
//^ i32 //^ : i32
let z = |k: i32| { t += k; }; let z = |k: i32| { t += k; };
//^ {closure#2} //^ : {closure#2}
let p = (y, z); let p = (y, z);
//^ ({closure#1}, {closure#2}) //^ : ({closure#1}, {closure#2})
} }
"#, "#,
); );
@ -953,15 +921,15 @@ fn main() {
//- minicore: fn //- minicore: fn
fn main() { fn main() {
let x = || 2; let x = || 2;
//^ //^ :
let y = |t: i32| x() + t; let y = |t: i32| x() + t;
//^ //^ :
let mut t = 5; let mut t = 5;
//^ i32 //^ : i32
let z = |k: i32| { t += k; }; let z = |k: i32| { t += k; };
//^ //^ :
let p = (y, z); let p = (y, z);
//^ (…, …) //^ : (…, …)
} }
"#, "#,
); );
@ -981,24 +949,24 @@ fn main() {
let multiple_2 = |x: i32| { x * 2 }; let multiple_2 = |x: i32| { x * 2 };
let multiple_2 = |x: i32| x * 2; let multiple_2 = |x: i32| x * 2;
// ^^^^^^^^^^ impl Fn(i32) -> i32 // ^^^^^^^^^^ : impl Fn(i32) -> i32
let (not) = (|x: bool| { !x }); let (not) = (|x: bool| { !x });
// ^^^ impl Fn(bool) -> bool // ^^^ : impl Fn(bool) -> bool
let (is_zero, _b) = (|x: usize| { x == 0 }, false); let (is_zero, _b) = (|x: usize| { x == 0 }, false);
// ^^^^^^^ impl Fn(usize) -> bool // ^^^^^^^ : impl Fn(usize) -> bool
// ^^ bool // ^^ : bool
let plus_one = |x| { x + 1 }; let plus_one = |x| { x + 1 };
// ^ u8 // ^ : u8
foo(plus_one); foo(plus_one);
let add_mul = bar(|x: u8| { x + 1 }); let add_mul = bar(|x: u8| { x + 1 });
// ^^^^^^^ impl FnOnce(u8) -> u8 + ?Sized // ^^^^^^^ : impl FnOnce(u8) -> u8 + ?Sized
let closure = if let Some(6) = add_mul(2).checked_sub(1) { let closure = if let Some(6) = add_mul(2).checked_sub(1) {
// ^^^^^^^ fn(i32) -> i32 // ^^^^^^^ : fn(i32) -> i32
|x: i32| { x * 2 } |x: i32| { x * 2 }
} else { } else {
|x: i32| { x * 3 } |x: i32| { x * 3 }
@ -1025,11 +993,11 @@ struct VeryLongOuterName<T>(T);
fn main() { fn main() {
let a = Smol(0u32); let a = Smol(0u32);
//^ Smol<u32> //^ : Smol<u32>
let b = VeryLongOuterName(0usize); let b = VeryLongOuterName(0usize);
//^ VeryLongOuterName<…> //^ : VeryLongOuterName<…>
let c = Smol(Smol(0u32)) let c = Smol(Smol(0u32))
//^ Smol<Smol<…>> //^ : Smol<Smol<…>>
}"#, }"#,
); );
} }

View file

@ -7,7 +7,7 @@ use ide_db::RootDatabase;
use syntax::ast::{self, AstNode}; use syntax::ast::{self, AstNode};
use crate::{InlayHint, InlayHintsConfig, InlayKind}; use crate::{InlayHint, InlayHintPosition, InlayHintsConfig, InlayKind};
pub(super) fn hints( pub(super) fn hints(
acc: &mut Vec<InlayHint>, acc: &mut Vec<InlayHint>,
@ -54,6 +54,9 @@ pub(super) fn hints(
kind: InlayKind::BindingMode, kind: InlayKind::BindingMode,
label: r.to_string().into(), label: r.to_string().into(),
text_edit: None, text_edit: None,
position: InlayHintPosition::Before,
pad_left: false,
pad_right: mut_reference,
}); });
}); });
match pat { match pat {
@ -69,11 +72,20 @@ pub(super) fn hints(
kind: InlayKind::BindingMode, kind: InlayKind::BindingMode,
label: bm.to_string().into(), label: bm.to_string().into(),
text_edit: None, text_edit: None,
position: InlayHintPosition::Before,
pad_left: false,
pad_right: true,
}); });
} }
ast::Pat::OrPat(pat) if !pattern_adjustments.is_empty() && outer_paren_pat.is_none() => { ast::Pat::OrPat(pat) if !pattern_adjustments.is_empty() && outer_paren_pat.is_none() => {
acc.push(InlayHint::opening_paren(pat.syntax().text_range())); acc.push(InlayHint::opening_paren_before(
acc.push(InlayHint::closing_paren(pat.syntax().text_range())); InlayKind::BindingMode,
pat.syntax().text_range(),
));
acc.push(InlayHint::closing_paren_after(
InlayKind::BindingMode,
pat.syntax().text_range(),
));
} }
_ => (), _ => (),
} }

View file

@ -5,7 +5,7 @@ use syntax::{
Direction, NodeOrToken, SyntaxKind, T, Direction, NodeOrToken, SyntaxKind, T,
}; };
use crate::{FileId, InlayHint, InlayHintsConfig, InlayKind}; use crate::{FileId, InlayHint, InlayHintPosition, InlayHintsConfig, InlayKind};
use super::label_of_ty; use super::label_of_ty;
@ -60,8 +60,11 @@ pub(super) fn hints(
acc.push(InlayHint { acc.push(InlayHint {
range: expr.syntax().text_range(), range: expr.syntax().text_range(),
kind: InlayKind::Chaining, kind: InlayKind::Chaining,
label: label_of_ty(famous_defs, config, ty)?, label: label_of_ty(famous_defs, config, &ty)?,
text_edit: None, text_edit: None,
position: InlayHintPosition::After,
pad_left: true,
pad_right: false,
}); });
} }
} }
@ -104,6 +107,9 @@ fn main() {
[ [
InlayHint { InlayHint {
range: 147..172, range: 147..172,
position: After,
pad_left: true,
pad_right: false,
kind: Chaining, kind: Chaining,
label: [ label: [
"", "",
@ -125,6 +131,9 @@ fn main() {
}, },
InlayHint { InlayHint {
range: 147..154, range: 147..154,
position: After,
pad_left: true,
pad_right: false,
kind: Chaining, kind: Chaining,
label: [ label: [
"", "",
@ -191,6 +200,9 @@ fn main() {
[ [
InlayHint { InlayHint {
range: 143..190, range: 143..190,
position: After,
pad_left: true,
pad_right: false,
kind: Chaining, kind: Chaining,
label: [ label: [
"", "",
@ -212,6 +224,9 @@ fn main() {
}, },
InlayHint { InlayHint {
range: 143..179, range: 143..179,
position: After,
pad_left: true,
pad_right: false,
kind: Chaining, kind: Chaining,
label: [ label: [
"", "",
@ -262,6 +277,9 @@ fn main() {
[ [
InlayHint { InlayHint {
range: 143..190, range: 143..190,
position: After,
pad_left: true,
pad_right: false,
kind: Chaining, kind: Chaining,
label: [ label: [
"", "",
@ -283,6 +301,9 @@ fn main() {
}, },
InlayHint { InlayHint {
range: 143..179, range: 143..179,
position: After,
pad_left: true,
pad_right: false,
kind: Chaining, kind: Chaining,
label: [ label: [
"", "",
@ -334,6 +355,9 @@ fn main() {
[ [
InlayHint { InlayHint {
range: 246..283, range: 246..283,
position: After,
pad_left: true,
pad_right: false,
kind: Chaining, kind: Chaining,
label: [ label: [
"", "",
@ -368,6 +392,9 @@ fn main() {
}, },
InlayHint { InlayHint {
range: 246..265, range: 246..265,
position: After,
pad_left: true,
pad_right: false,
kind: Chaining, kind: Chaining,
label: [ label: [
"", "",
@ -434,6 +461,9 @@ fn main() {
[ [
InlayHint { InlayHint {
range: 174..241, range: 174..241,
position: After,
pad_left: true,
pad_right: false,
kind: Chaining, kind: Chaining,
label: [ label: [
"impl ", "impl ",
@ -468,6 +498,9 @@ fn main() {
}, },
InlayHint { InlayHint {
range: 174..224, range: 174..224,
position: After,
pad_left: true,
pad_right: false,
kind: Chaining, kind: Chaining,
label: [ label: [
"impl ", "impl ",
@ -502,6 +535,9 @@ fn main() {
}, },
InlayHint { InlayHint {
range: 174..206, range: 174..206,
position: After,
pad_left: true,
pad_right: false,
kind: Chaining, kind: Chaining,
label: [ label: [
"impl ", "impl ",
@ -536,6 +572,9 @@ fn main() {
}, },
InlayHint { InlayHint {
range: 174..189, range: 174..189,
position: After,
pad_left: true,
pad_right: false,
kind: Chaining, kind: Chaining,
label: [ label: [
"&mut ", "&mut ",
@ -586,9 +625,12 @@ fn main() {
[ [
InlayHint { InlayHint {
range: 124..130, range: 124..130,
position: Before,
pad_left: true,
pad_right: false,
kind: Type, kind: Type,
label: [ label: [
"", ": ",
InlayHintLabelPart { InlayHintLabelPart {
text: "Struct", text: "Struct",
linked_location: Some( linked_location: Some(
@ -616,6 +658,9 @@ fn main() {
}, },
InlayHint { InlayHint {
range: 145..185, range: 145..185,
position: After,
pad_left: true,
pad_right: false,
kind: Chaining, kind: Chaining,
label: [ label: [
"", "",
@ -637,6 +682,9 @@ fn main() {
}, },
InlayHint { InlayHint {
range: 145..168, range: 145..168,
position: After,
pad_left: true,
pad_right: false,
kind: Chaining, kind: Chaining,
label: [ label: [
"", "",
@ -658,6 +706,9 @@ fn main() {
}, },
InlayHint { InlayHint {
range: 222..228, range: 222..228,
position: Before,
pad_left: false,
pad_right: true,
kind: Parameter, kind: Parameter,
label: [ label: [
InlayHintLabelPart { InlayHintLabelPart {

View file

@ -10,7 +10,7 @@ use syntax::{
match_ast, SyntaxKind, SyntaxNode, T, match_ast, SyntaxKind, SyntaxNode, T,
}; };
use crate::{FileId, InlayHint, InlayHintLabel, InlayHintsConfig, InlayKind}; use crate::{FileId, InlayHint, InlayHintLabel, InlayHintPosition, InlayHintsConfig, InlayKind};
pub(super) fn hints( pub(super) fn hints(
acc: &mut Vec<InlayHint>, acc: &mut Vec<InlayHint>,
@ -113,6 +113,9 @@ pub(super) fn hints(
kind: InlayKind::ClosingBrace, kind: InlayKind::ClosingBrace,
label: InlayHintLabel::simple(label, None, linked_location), label: InlayHintLabel::simple(label, None, linked_location),
text_edit: None, text_edit: None,
position: InlayHintPosition::After,
pad_left: true,
pad_right: false,
}); });
None None

View file

@ -5,7 +5,7 @@ use ide_db::{base_db::FileId, famous_defs::FamousDefs};
use syntax::ast::{self, AstNode}; use syntax::ast::{self, AstNode};
use text_edit::{TextRange, TextSize}; use text_edit::{TextRange, TextSize};
use crate::{InlayHint, InlayHintLabel, InlayHintsConfig, InlayKind}; use crate::{InlayHint, InlayHintLabel, InlayHintPosition, InlayHintsConfig, InlayKind};
pub(super) fn hints( pub(super) fn hints(
acc: &mut Vec<InlayHint>, acc: &mut Vec<InlayHint>,
@ -35,6 +35,9 @@ pub(super) fn hints(
kind: InlayKind::ClosureCapture, kind: InlayKind::ClosureCapture,
label: InlayHintLabel::simple("move", None, None), label: InlayHintLabel::simple("move", None, None),
text_edit: None, text_edit: None,
position: InlayHintPosition::After,
pad_left: false,
pad_right: false,
}); });
range range
} }
@ -44,6 +47,9 @@ pub(super) fn hints(
kind: InlayKind::ClosureCapture, kind: InlayKind::ClosureCapture,
label: InlayHintLabel::from("("), label: InlayHintLabel::from("("),
text_edit: None, text_edit: None,
position: InlayHintPosition::After,
pad_left: false,
pad_right: false,
}); });
let last = captures.len() - 1; let last = captures.len() - 1;
for (idx, capture) in captures.into_iter().enumerate() { for (idx, capture) in captures.into_iter().enumerate() {
@ -71,6 +77,9 @@ pub(super) fn hints(
source.name().and_then(|name| sema.original_range_opt(name.syntax())), source.name().and_then(|name| sema.original_range_opt(name.syntax())),
), ),
text_edit: None, text_edit: None,
position: InlayHintPosition::After,
pad_left: false,
pad_right: false,
}); });
if idx != last { if idx != last {
@ -79,6 +88,9 @@ pub(super) fn hints(
kind: InlayKind::ClosureCapture, kind: InlayKind::ClosureCapture,
label: InlayHintLabel::simple(", ", None, None), label: InlayHintLabel::simple(", ", None, None),
text_edit: None, text_edit: None,
position: InlayHintPosition::After,
pad_left: false,
pad_right: false,
}); });
} }
} }
@ -87,6 +99,9 @@ pub(super) fn hints(
kind: InlayKind::ClosureCapture, kind: InlayKind::ClosureCapture,
label: InlayHintLabel::from(")"), label: InlayHintLabel::from(")"),
text_edit: None, text_edit: None,
position: InlayHintPosition::After,
pad_left: false,
pad_right: true,
}); });
Some(()) Some(())

View file

@ -6,7 +6,7 @@ use syntax::ast::{self, AstNode};
use crate::{ use crate::{
inlay_hints::{closure_has_block_body, label_of_ty, ty_to_text_edit}, inlay_hints::{closure_has_block_body, label_of_ty, ty_to_text_edit},
ClosureReturnTypeHints, InlayHint, InlayHintsConfig, InlayKind, ClosureReturnTypeHints, InlayHint, InlayHintPosition, InlayHintsConfig, InlayKind,
}; };
pub(super) fn hints( pub(super) fn hints(
@ -20,9 +20,12 @@ pub(super) fn hints(
return None; return None;
} }
if closure.ret_type().is_some() { let ret_type = closure.ret_type().map(|rt| (rt.thin_arrow_token(), rt.ty().is_some()));
return None; let arrow = match ret_type {
} Some((_, true)) => return None,
Some((arrow, _)) => arrow,
None => None,
};
let has_block_body = closure_has_block_body(&closure); let has_block_body = closure_has_block_body(&closure);
if !has_block_body && config.closure_return_type_hints == ClosureReturnTypeHints::WithBlock { if !has_block_body && config.closure_return_type_hints == ClosureReturnTypeHints::WithBlock {
@ -35,18 +38,26 @@ pub(super) fn hints(
let ty = sema.type_of_expr(&ast::Expr::ClosureExpr(closure.clone()))?.adjusted(); let ty = sema.type_of_expr(&ast::Expr::ClosureExpr(closure.clone()))?.adjusted();
let callable = ty.as_callable(sema.db)?; let callable = ty.as_callable(sema.db)?;
let ty = callable.return_type(); let ty = callable.return_type();
if ty.is_unit() { if arrow.is_none() && ty.is_unit() {
return None; return None;
} }
let mut label = label_of_ty(famous_defs, config, &ty)?;
if arrow.is_none() {
label.prepend_str(" -> ");
}
// FIXME?: We could provide text edit to insert braces for closures with non-block body. // FIXME?: We could provide text edit to insert braces for closures with non-block body.
let text_edit = if has_block_body { let text_edit = if has_block_body {
ty_to_text_edit( ty_to_text_edit(
sema, sema,
closure.syntax(), closure.syntax(),
&ty, &ty,
param_list.syntax().text_range().end(), arrow
String::from(" -> "), .as_ref()
.map_or_else(|| param_list.syntax().text_range(), |t| t.text_range())
.end(),
if arrow.is_none() { String::from(" -> ") } else { String::new() },
) )
} else { } else {
None None
@ -54,9 +65,36 @@ pub(super) fn hints(
acc.push(InlayHint { acc.push(InlayHint {
range: param_list.syntax().text_range(), range: param_list.syntax().text_range(),
kind: InlayKind::ClosureReturnType, kind: InlayKind::Type,
label: label_of_ty(famous_defs, config, ty)?, label,
text_edit, text_edit,
position: InlayHintPosition::After,
pad_left: false,
pad_right: false,
}); });
Some(()) Some(())
} }
#[cfg(test)]
mod tests {
use crate::inlay_hints::tests::{check_with_config, DISABLED_CONFIG};
use super::*;
#[test]
fn return_type_hints_for_closure_without_block() {
check_with_config(
InlayHintsConfig {
closure_return_type_hints: ClosureReturnTypeHints::Always,
..DISABLED_CONFIG
},
r#"
fn main() {
let a = || { 0 };
//^^ -> i32
let b = || 0;
//^^ -> i32
}"#,
);
}
}

View file

@ -9,7 +9,8 @@ use ide_db::{base_db::FileId, famous_defs::FamousDefs, RootDatabase};
use syntax::ast::{self, AstNode, HasName}; use syntax::ast::{self, AstNode, HasName};
use crate::{ use crate::{
DiscriminantHints, InlayHint, InlayHintLabel, InlayHintsConfig, InlayKind, InlayTooltip, DiscriminantHints, InlayHint, InlayHintLabel, InlayHintPosition, InlayHintsConfig, InlayKind,
InlayTooltip,
}; };
pub(super) fn enum_hints( pub(super) fn enum_hints(
@ -41,10 +42,11 @@ fn variant_hints(
sema: &Semantics<'_, RootDatabase>, sema: &Semantics<'_, RootDatabase>,
variant: &ast::Variant, variant: &ast::Variant,
) -> Option<()> { ) -> Option<()> {
if variant.eq_token().is_some() { if variant.expr().is_some() {
return None; return None;
} }
let eq_token = variant.eq_token();
let name = variant.name()?; let name = variant.name()?;
let descended = sema.descend_node_into_attributes(variant.clone()).pop(); let descended = sema.descend_node_into_attributes(variant.clone()).pop();
@ -52,30 +54,39 @@ fn variant_hints(
let v = sema.to_def(desc_pat)?; let v = sema.to_def(desc_pat)?;
let d = v.eval(sema.db); let d = v.eval(sema.db);
let range = match variant.field_list() {
Some(field_list) => name.syntax().text_range().cover(field_list.syntax().text_range()),
None => name.syntax().text_range(),
};
let eq_ = if eq_token.is_none() { " =" } else { "" };
let label = InlayHintLabel::simple(
match d {
Ok(x) => {
if x >= 10 {
format!("{eq_} {x} ({x:#X})")
} else {
format!("{eq_} {x}")
}
}
Err(_) => format!("{eq_} ?"),
},
Some(InlayTooltip::String(match &d {
Ok(_) => "enum variant discriminant".into(),
Err(e) => format!("{e:?}").into(),
})),
None,
);
acc.push(InlayHint { acc.push(InlayHint {
range: match variant.field_list() { range: match eq_token {
Some(field_list) => name.syntax().text_range().cover(field_list.syntax().text_range()), Some(t) => range.cover(t.text_range()),
None => name.syntax().text_range(), _ => range,
}, },
kind: InlayKind::Discriminant, kind: InlayKind::Discriminant,
label: InlayHintLabel::simple( label,
match d {
Ok(x) => {
if x >= 10 {
format!("{x} ({x:#X})")
} else {
format!("{x}")
}
}
Err(_) => "?".into(),
},
Some(InlayTooltip::String(match &d {
Ok(_) => "enum variant discriminant".into(),
Err(e) => format!("{e:?}").into(),
})),
None,
),
text_edit: None, text_edit: None,
position: InlayHintPosition::After,
pad_left: false,
pad_right: false,
}); });
Some(()) Some(())
@ -113,14 +124,14 @@ mod tests {
r#" r#"
enum Enum { enum Enum {
Variant, Variant,
//^^^^^^^0 //^^^^^^^ = 0$
Variant1, Variant1,
//^^^^^^^^1 //^^^^^^^^ = 1$
Variant2, Variant2,
//^^^^^^^^2 //^^^^^^^^ = 2$
Variant5 = 5, Variant5 = 5,
Variant6, Variant6,
//^^^^^^^^6 //^^^^^^^^ = 6$
} }
"#, "#,
); );
@ -128,14 +139,14 @@ enum Enum {
r#" r#"
enum Enum { enum Enum {
Variant, Variant,
//^^^^^^^0 //^^^^^^^ = 0
Variant1, Variant1,
//^^^^^^^^1 //^^^^^^^^ = 1
Variant2, Variant2,
//^^^^^^^^2 //^^^^^^^^ = 2
Variant5 = 5, Variant5 = 5,
Variant6, Variant6,
//^^^^^^^^6 //^^^^^^^^ = 6
} }
"#, "#,
); );
@ -147,16 +158,16 @@ enum Enum {
r#" r#"
enum Enum { enum Enum {
Variant(), Variant(),
//^^^^^^^^^0 //^^^^^^^^^ = 0
Variant1, Variant1,
//^^^^^^^^1 //^^^^^^^^ = 1
Variant2 {}, Variant2 {},
//^^^^^^^^^^^2 //^^^^^^^^^^^ = 2
Variant3, Variant3,
//^^^^^^^^3 //^^^^^^^^ = 3
Variant5 = 5, Variant5 = 5,
Variant6, Variant6,
//^^^^^^^^6 //^^^^^^^^ = 6
} }
"#, "#,
); );
@ -180,16 +191,16 @@ enum Enum {
r#" r#"
enum Enum { enum Enum {
Variant(), Variant(),
//^^^^^^^^^0 //^^^^^^^^^ = 0
Variant1, Variant1,
//^^^^^^^^1 //^^^^^^^^ = 1
Variant2 {}, Variant2 {},
//^^^^^^^^^^^2 //^^^^^^^^^^^ = 2
Variant3, Variant3,
//^^^^^^^^3 //^^^^^^^^ = 3
Variant5 = 5, Variant5 = 5,
Variant6, Variant6,
//^^^^^^^^6 //^^^^^^^^ = 6
} }
"#, "#,
); );

View file

@ -10,7 +10,7 @@ use syntax::{
SyntaxToken, SyntaxToken,
}; };
use crate::{InlayHint, InlayHintsConfig, InlayKind, LifetimeElisionHints}; use crate::{InlayHint, InlayHintPosition, InlayHintsConfig, InlayKind, LifetimeElisionHints};
pub(super) fn hints( pub(super) fn hints(
acc: &mut Vec<InlayHint>, acc: &mut Vec<InlayHint>,
@ -26,6 +26,9 @@ pub(super) fn hints(
kind: InlayKind::Lifetime, kind: InlayKind::Lifetime,
label: label.into(), label: label.into(),
text_edit: None, text_edit: None,
position: InlayHintPosition::After,
pad_left: false,
pad_right: true,
}; };
let param_list = func.param_list()?; let param_list = func.param_list()?;
@ -191,6 +194,9 @@ pub(super) fn hints(
) )
.into(), .into(),
text_edit: None, text_edit: None,
position: InlayHintPosition::After,
pad_left: false,
pad_right: true,
}); });
} }
(None, allocated_lifetimes) => acc.push(InlayHint { (None, allocated_lifetimes) => acc.push(InlayHint {
@ -198,6 +204,9 @@ pub(super) fn hints(
kind: InlayKind::GenericParamList, kind: InlayKind::GenericParamList,
label: format!("<{}>", allocated_lifetimes.iter().format(", "),).into(), label: format!("<{}>", allocated_lifetimes.iter().format(", "),).into(),
text_edit: None, text_edit: None,
position: InlayHintPosition::After,
pad_left: false,
pad_right: false,
}), }),
} }
Some(()) Some(())

View file

@ -8,7 +8,7 @@ use syntax::{
SyntaxKind, SyntaxKind,
}; };
use crate::{InlayHint, InlayHintsConfig, InlayKind, LifetimeElisionHints}; use crate::{InlayHint, InlayHintPosition, InlayHintsConfig, InlayKind, LifetimeElisionHints};
pub(super) fn hints( pub(super) fn hints(
acc: &mut Vec<InlayHint>, acc: &mut Vec<InlayHint>,
@ -35,6 +35,9 @@ pub(super) fn hints(
kind: InlayKind::Lifetime, kind: InlayKind::Lifetime,
label: "'static".to_owned().into(), label: "'static".to_owned().into(),
text_edit: None, text_edit: None,
position: InlayHintPosition::After,
pad_left: false,
pad_right: true,
}); });
} }
} }

View file

@ -10,7 +10,7 @@ use ide_db::{base_db::FileRange, RootDatabase};
use stdx::to_lower_snake_case; use stdx::to_lower_snake_case;
use syntax::ast::{self, AstNode, HasArgList, HasName, UnaryOp}; use syntax::ast::{self, AstNode, HasArgList, HasName, UnaryOp};
use crate::{InlayHint, InlayHintLabel, InlayHintsConfig, InlayKind}; use crate::{InlayHint, InlayHintLabel, InlayHintPosition, InlayHintsConfig, InlayKind};
pub(super) fn hints( pub(super) fn hints(
acc: &mut Vec<InlayHint>, acc: &mut Vec<InlayHint>,
@ -31,16 +31,16 @@ pub(super) fn hints(
// Only annotate hints for expressions that exist in the original file // Only annotate hints for expressions that exist in the original file
let range = sema.original_range_opt(arg.syntax())?; let range = sema.original_range_opt(arg.syntax())?;
let (param_name, name_syntax) = match param.as_ref()? { let (param_name, name_syntax) = match param.as_ref()? {
Either::Left(pat) => ("self".to_string(), pat.name()), Either::Left(pat) => (pat.name()?, pat.name()),
Either::Right(pat) => match pat { Either::Right(pat) => match pat {
ast::Pat::IdentPat(it) => (it.name()?.to_string(), it.name()), ast::Pat::IdentPat(it) => (it.name()?, it.name()),
_ => return None, _ => return None,
}, },
}; };
Some((name_syntax, param_name, arg, range)) Some((name_syntax, param_name, arg, range))
}) })
.filter(|(_, param_name, arg, _)| { .filter(|(_, param_name, arg, _)| {
!should_hide_param_name_hint(sema, &callable, param_name, arg) !should_hide_param_name_hint(sema, &callable, &param_name.text(), arg)
}) })
.map(|(param, param_name, _, FileRange { range, .. })| { .map(|(param, param_name, _, FileRange { range, .. })| {
let mut linked_location = None; let mut linked_location = None;
@ -53,11 +53,17 @@ pub(super) fn hints(
} }
} }
let colon = if config.render_colons { ":" } else { "" };
let label =
InlayHintLabel::simple(format!("{param_name}{colon}"), None, linked_location);
InlayHint { InlayHint {
range, range,
kind: InlayKind::Parameter, kind: InlayKind::Parameter,
label: InlayHintLabel::simple(param_name, None, linked_location), label,
text_edit: None, text_edit: None,
position: InlayHintPosition::Before,
pad_left: false,
pad_right: true,
} }
}); });

View file

@ -87,8 +87,8 @@ pub use crate::{
hover::{HoverAction, HoverConfig, HoverDocFormat, HoverGotoTypeData, HoverResult}, hover::{HoverAction, HoverConfig, HoverDocFormat, HoverGotoTypeData, HoverResult},
inlay_hints::{ inlay_hints::{
AdjustmentHints, AdjustmentHintsMode, ClosureReturnTypeHints, DiscriminantHints, InlayHint, AdjustmentHints, AdjustmentHintsMode, ClosureReturnTypeHints, DiscriminantHints, InlayHint,
InlayHintLabel, InlayHintLabelPart, InlayHintsConfig, InlayKind, InlayTooltip, InlayHintLabel, InlayHintLabelPart, InlayHintPosition, InlayHintsConfig, InlayKind,
LifetimeElisionHints, InlayTooltip, LifetimeElisionHints,
}, },
join_lines::JoinLinesConfig, join_lines::JoinLinesConfig,
markup::Markup, markup::Markup,

View file

@ -1349,9 +1349,7 @@ pub(crate) fn handle_inlay_hints(
snap.analysis snap.analysis
.inlay_hints(&inlay_hints_config, file_id, Some(range))? .inlay_hints(&inlay_hints_config, file_id, Some(range))?
.into_iter() .into_iter()
.map(|it| { .map(|it| to_proto::inlay_hint(&snap, &line_index, it))
to_proto::inlay_hint(&snap, &line_index, inlay_hints_config.render_colons, it)
})
.collect::<Cancellable<Vec<_>>>()?, .collect::<Cancellable<Vec<_>>>()?,
)) ))
} }

View file

@ -434,87 +434,21 @@ pub(crate) fn signature_help(
pub(crate) fn inlay_hint( pub(crate) fn inlay_hint(
snap: &GlobalStateSnapshot, snap: &GlobalStateSnapshot,
line_index: &LineIndex, line_index: &LineIndex,
render_colons: bool, inlay_hint: InlayHint,
mut inlay_hint: InlayHint,
) -> Cancellable<lsp_types::InlayHint> { ) -> Cancellable<lsp_types::InlayHint> {
match inlay_hint.kind {
InlayKind::Parameter if render_colons => inlay_hint.label.append_str(":"),
InlayKind::Type if render_colons => inlay_hint.label.prepend_str(": "),
InlayKind::ClosureReturnType => inlay_hint.label.prepend_str(" -> "),
InlayKind::Discriminant => inlay_hint.label.prepend_str(" = "),
_ => {}
}
let (label, tooltip) = inlay_hint_label(snap, inlay_hint.label)?; let (label, tooltip) = inlay_hint_label(snap, inlay_hint.label)?;
Ok(lsp_types::InlayHint { Ok(lsp_types::InlayHint {
position: match inlay_hint.kind { position: match inlay_hint.position {
// before annotated thing ide::InlayHintPosition::Before => position(line_index, inlay_hint.range.start()),
InlayKind::OpeningParenthesis ide::InlayHintPosition::After => position(line_index, inlay_hint.range.end()),
| InlayKind::Parameter
| InlayKind::Adjustment
| InlayKind::BindingMode => position(line_index, inlay_hint.range.start()),
// after annotated thing
InlayKind::ClosureReturnType
| InlayKind::ClosureCapture
| InlayKind::Type
| InlayKind::Discriminant
| InlayKind::Chaining
| InlayKind::GenericParamList
| InlayKind::ClosingParenthesis
| InlayKind::AdjustmentPostfix
| InlayKind::Lifetime
| InlayKind::ClosingBrace => position(line_index, inlay_hint.range.end()),
}, },
padding_left: Some(match inlay_hint.kind { padding_left: Some(inlay_hint.pad_left),
InlayKind::Type => !render_colons, padding_right: Some(inlay_hint.pad_right),
InlayKind::Chaining | InlayKind::ClosingBrace => true,
InlayKind::ClosingParenthesis
| InlayKind::ClosureCapture
| InlayKind::Discriminant
| InlayKind::OpeningParenthesis
| InlayKind::BindingMode
| InlayKind::ClosureReturnType
| InlayKind::GenericParamList
| InlayKind::Adjustment
| InlayKind::AdjustmentPostfix
| InlayKind::Lifetime
| InlayKind::Parameter => false,
}),
padding_right: Some(match inlay_hint.kind {
InlayKind::ClosingParenthesis
| InlayKind::OpeningParenthesis
| InlayKind::Chaining
| InlayKind::ClosureReturnType
| InlayKind::GenericParamList
| InlayKind::Adjustment
| InlayKind::AdjustmentPostfix
| InlayKind::Type
| InlayKind::Discriminant
| InlayKind::ClosingBrace => false,
InlayKind::ClosureCapture => {
matches!(&label, lsp_types::InlayHintLabel::String(s) if s == ")")
}
InlayKind::BindingMode => {
matches!(&label, lsp_types::InlayHintLabel::String(s) if s != "&")
}
InlayKind::Parameter | InlayKind::Lifetime => true,
}),
kind: match inlay_hint.kind { kind: match inlay_hint.kind {
InlayKind::Parameter => Some(lsp_types::InlayHintKind::PARAMETER), InlayKind::Parameter => Some(lsp_types::InlayHintKind::PARAMETER),
InlayKind::ClosureReturnType | InlayKind::Type | InlayKind::Chaining => { InlayKind::Type | InlayKind::Chaining => Some(lsp_types::InlayHintKind::TYPE),
Some(lsp_types::InlayHintKind::TYPE) _ => None,
}
InlayKind::ClosingParenthesis
| InlayKind::ClosureCapture
| InlayKind::Discriminant
| InlayKind::OpeningParenthesis
| InlayKind::BindingMode
| InlayKind::GenericParamList
| InlayKind::Lifetime
| InlayKind::Adjustment
| InlayKind::AdjustmentPostfix
| InlayKind::ClosingBrace => None,
}, },
text_edits: inlay_hint.text_edit.map(|it| text_edit_vec(line_index, it)), text_edits: inlay_hint.text_edit.map(|it| text_edit_vec(line_index, it)),
data: None, data: None,