mirror of
https://github.com/rust-lang/rust-analyzer.git
synced 2025-09-26 11:59:49 +00:00
Auto merge of #14742 - Veykril:closure-capture-inlays, r=Veykril
feat: Closure capture inlay hints I opted for a fictional `move(foo, &bar, &mut qux)` syntax here, disabled by default as these are not correct rust syntax and hence could cause confusion. 
This commit is contained in:
commit
d3ce333ec8
11 changed files with 278 additions and 37 deletions
|
@ -3,7 +3,8 @@ use std::fmt::Display;
|
|||
|
||||
use either::Either;
|
||||
use hir::{
|
||||
Adt, AsAssocItem, AttributeTemplate, HasAttrs, HasSource, HirDisplay, Semantics, TypeInfo,
|
||||
Adt, AsAssocItem, AttributeTemplate, CaptureKind, HasAttrs, HasSource, HirDisplay, Semantics,
|
||||
TypeInfo,
|
||||
};
|
||||
use ide_db::{
|
||||
base_db::SourceDatabase,
|
||||
|
@ -58,8 +59,14 @@ pub(super) fn closure_expr(
|
|||
let mut captures = c
|
||||
.captured_items(sema.db)
|
||||
.into_iter()
|
||||
.map(|x| {
|
||||
format!("* `{}` by {}", x.display_place(c.clone().into(), sema.db), x.display_kind())
|
||||
.map(|it| {
|
||||
let borrow_kind= match it.kind() {
|
||||
CaptureKind::SharedRef => "immutable borrow",
|
||||
CaptureKind::UniqueSharedRef => "unique immutable borrow ([read more](https://doc.rust-lang.org/stable/reference/types/closure.html#unique-immutable-borrows-in-captures))",
|
||||
CaptureKind::MutableRef => "mutable borrow",
|
||||
CaptureKind::Move => "move",
|
||||
};
|
||||
format!("* `{}` by {}", it.display_place(sema.db), borrow_kind)
|
||||
})
|
||||
.join("\n");
|
||||
if captures.trim().is_empty() {
|
||||
|
|
|
@ -20,16 +20,17 @@ use text_edit::TextEdit;
|
|||
|
||||
use crate::{navigation_target::TryToNav, FileId};
|
||||
|
||||
mod closing_brace;
|
||||
mod implicit_static;
|
||||
mod fn_lifetime_fn;
|
||||
mod closure_ret;
|
||||
mod adjustment;
|
||||
mod chaining;
|
||||
mod param_name;
|
||||
mod binding_mode;
|
||||
mod bind_pat;
|
||||
mod binding_mode;
|
||||
mod chaining;
|
||||
mod closing_brace;
|
||||
mod closure_ret;
|
||||
mod closure_captures;
|
||||
mod discriminant;
|
||||
mod fn_lifetime_fn;
|
||||
mod implicit_static;
|
||||
mod param_name;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct InlayHintsConfig {
|
||||
|
@ -42,6 +43,7 @@ pub struct InlayHintsConfig {
|
|||
pub adjustment_hints_mode: AdjustmentHintsMode,
|
||||
pub adjustment_hints_hide_outside_unsafe: bool,
|
||||
pub closure_return_type_hints: ClosureReturnTypeHints,
|
||||
pub closure_capture_hints: bool,
|
||||
pub binding_mode_hints: bool,
|
||||
pub lifetime_elision_hints: LifetimeElisionHints,
|
||||
pub param_names_for_lifetime_elision_hints: bool,
|
||||
|
@ -88,6 +90,8 @@ pub enum AdjustmentHintsMode {
|
|||
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)]
|
||||
pub enum InlayKind {
|
||||
BindingMode,
|
||||
|
@ -98,6 +102,7 @@ pub enum InlayKind {
|
|||
Adjustment,
|
||||
AdjustmentPostfix,
|
||||
Lifetime,
|
||||
ClosureCapture,
|
||||
Parameter,
|
||||
Type,
|
||||
Discriminant,
|
||||
|
@ -444,10 +449,10 @@ fn hints(
|
|||
ast::Expr::MethodCallExpr(it) => {
|
||||
param_name::hints(hints, sema, config, ast::Expr::from(it))
|
||||
}
|
||||
ast::Expr::ClosureExpr(it) => closure_ret::hints(hints, famous_defs, config, file_id, it),
|
||||
// We could show reborrows for all expressions, but usually that is just noise to the user
|
||||
// and the main point here is to show why "moving" a mutable reference doesn't necessarily move it
|
||||
// ast::Expr::PathExpr(_) => reborrow_hints(hints, sema, config, &expr),
|
||||
ast::Expr::ClosureExpr(it) => {
|
||||
closure_captures::hints(hints, famous_defs, config, file_id, it.clone());
|
||||
closure_ret::hints(hints, famous_defs, config, file_id, it)
|
||||
},
|
||||
_ => None,
|
||||
}
|
||||
},
|
||||
|
@ -535,6 +540,7 @@ mod tests {
|
|||
chaining_hints: false,
|
||||
lifetime_elision_hints: LifetimeElisionHints::Never,
|
||||
closure_return_type_hints: ClosureReturnTypeHints::Never,
|
||||
closure_capture_hints: false,
|
||||
adjustment_hints: AdjustmentHints::Never,
|
||||
adjustment_hints_mode: AdjustmentHintsMode::Prefix,
|
||||
adjustment_hints_hide_outside_unsafe: false,
|
||||
|
|
192
crates/ide/src/inlay_hints/closure_captures.rs
Normal file
192
crates/ide/src/inlay_hints/closure_captures.rs
Normal file
|
@ -0,0 +1,192 @@
|
|||
//! Implementation of "closure return type" inlay hints.
|
||||
//!
|
||||
//! Tests live in [`bind_pat`][super::bind_pat] module.
|
||||
use ide_db::{base_db::FileId, famous_defs::FamousDefs};
|
||||
use syntax::ast::{self, AstNode};
|
||||
use text_edit::{TextRange, TextSize};
|
||||
|
||||
use crate::{InlayHint, InlayHintLabel, InlayHintsConfig, InlayKind};
|
||||
|
||||
pub(super) fn hints(
|
||||
acc: &mut Vec<InlayHint>,
|
||||
FamousDefs(sema, _): &FamousDefs<'_, '_>,
|
||||
config: &InlayHintsConfig,
|
||||
_file_id: FileId,
|
||||
closure: ast::ClosureExpr,
|
||||
) -> Option<()> {
|
||||
if !config.closure_capture_hints {
|
||||
return None;
|
||||
}
|
||||
let ty = &sema.type_of_expr(&closure.clone().into())?.original;
|
||||
let c = ty.as_closure()?;
|
||||
let captures = c.captured_items(sema.db);
|
||||
|
||||
if captures.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let move_kw_range = match closure.move_token() {
|
||||
Some(t) => t.text_range(),
|
||||
None => {
|
||||
let range = closure.syntax().first_token()?.prev_token()?.text_range();
|
||||
let range = TextRange::new(range.end() - TextSize::from(1), range.end());
|
||||
acc.push(InlayHint {
|
||||
range,
|
||||
kind: InlayKind::ClosureCapture,
|
||||
label: InlayHintLabel::simple("move", None, None),
|
||||
text_edit: None,
|
||||
});
|
||||
range
|
||||
}
|
||||
};
|
||||
acc.push(InlayHint {
|
||||
range: move_kw_range,
|
||||
kind: InlayKind::ClosureCapture,
|
||||
label: InlayHintLabel::from("("),
|
||||
text_edit: None,
|
||||
});
|
||||
let last = captures.len() - 1;
|
||||
for (idx, capture) in captures.into_iter().enumerate() {
|
||||
let local = capture.local();
|
||||
let source = local.primary_source(sema.db);
|
||||
|
||||
// force cache the source file, otherwise sema lookup will potentially panic
|
||||
_ = sema.parse_or_expand(source.file());
|
||||
|
||||
acc.push(InlayHint {
|
||||
range: move_kw_range,
|
||||
kind: InlayKind::ClosureCapture,
|
||||
label: InlayHintLabel::simple(
|
||||
format!(
|
||||
"{}{}",
|
||||
match capture.kind() {
|
||||
hir::CaptureKind::SharedRef => "&",
|
||||
hir::CaptureKind::UniqueSharedRef => "&unique ",
|
||||
hir::CaptureKind::MutableRef => "&mut ",
|
||||
hir::CaptureKind::Move => "",
|
||||
},
|
||||
capture.display_place(sema.db)
|
||||
),
|
||||
None,
|
||||
source.name().and_then(|name| sema.original_range_opt(name.syntax())),
|
||||
),
|
||||
text_edit: None,
|
||||
});
|
||||
|
||||
if idx != last {
|
||||
acc.push(InlayHint {
|
||||
range: move_kw_range,
|
||||
kind: InlayKind::ClosureCapture,
|
||||
label: InlayHintLabel::simple(", ", None, None),
|
||||
text_edit: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
acc.push(InlayHint {
|
||||
range: move_kw_range,
|
||||
kind: InlayKind::ClosureCapture,
|
||||
label: InlayHintLabel::from(")"),
|
||||
text_edit: None,
|
||||
});
|
||||
|
||||
Some(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::{
|
||||
inlay_hints::tests::{check_with_config, DISABLED_CONFIG},
|
||||
InlayHintsConfig,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn all_capture_kinds() {
|
||||
check_with_config(
|
||||
InlayHintsConfig { closure_capture_hints: true, ..DISABLED_CONFIG },
|
||||
r#"
|
||||
//- minicore: copy, derive
|
||||
|
||||
|
||||
#[derive(Copy, Clone)]
|
||||
struct Copy;
|
||||
|
||||
struct NonCopy;
|
||||
|
||||
fn main() {
|
||||
let foo = Copy;
|
||||
let bar = NonCopy;
|
||||
let mut baz = NonCopy;
|
||||
let qux = &mut NonCopy;
|
||||
|| {
|
||||
// ^ move
|
||||
// ^ (
|
||||
// ^ &foo
|
||||
// ^ , $
|
||||
// ^ bar
|
||||
// ^ , $
|
||||
// ^ baz
|
||||
// ^ , $
|
||||
// ^ qux
|
||||
// ^ )
|
||||
foo;
|
||||
bar;
|
||||
baz;
|
||||
qux;
|
||||
};
|
||||
|| {
|
||||
// ^ move
|
||||
// ^ (
|
||||
// ^ &foo
|
||||
// ^ , $
|
||||
// ^ &bar
|
||||
// ^ , $
|
||||
// ^ &baz
|
||||
// ^ , $
|
||||
// ^ &qux
|
||||
// ^ )
|
||||
&foo;
|
||||
&bar;
|
||||
&baz;
|
||||
&qux;
|
||||
};
|
||||
|| {
|
||||
// ^ move
|
||||
// ^ (
|
||||
// ^ &mut baz
|
||||
// ^ )
|
||||
&mut baz;
|
||||
};
|
||||
|| {
|
||||
// ^ move
|
||||
// ^ (
|
||||
// ^ &mut baz
|
||||
// ^ , $
|
||||
// ^ &mut *qux
|
||||
// ^ )
|
||||
baz = NonCopy;
|
||||
*qux = NonCopy;
|
||||
};
|
||||
}
|
||||
"#,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn move_token() {
|
||||
check_with_config(
|
||||
InlayHintsConfig { closure_capture_hints: true, ..DISABLED_CONFIG },
|
||||
r#"
|
||||
//- minicore: copy, derive
|
||||
fn main() {
|
||||
let foo = u32;
|
||||
move || {
|
||||
// ^^^^ (
|
||||
// ^^^^ foo
|
||||
// ^^^^ )
|
||||
foo;
|
||||
};
|
||||
}
|
||||
"#,
|
||||
);
|
||||
}
|
||||
}
|
|
@ -122,6 +122,7 @@ impl StaticIndex<'_> {
|
|||
param_names_for_lifetime_elision_hints: false,
|
||||
binding_mode_hints: false,
|
||||
max_length: Some(25),
|
||||
closure_capture_hints: false,
|
||||
closing_brace_hints_min_lines: Some(25),
|
||||
},
|
||||
file_id,
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue