Don't complete ; when in closure return expression

Completing it will break syntax.
This commit is contained in:
Chayim Refael Friedman 2024-09-17 23:46:37 +03:00
parent f4aca78c92
commit 7f023154f0

View file

@ -6,7 +6,7 @@ use hir::{db::HirDatabase, AsAssocItem, HirDisplay};
use ide_db::{SnippetCap, SymbolKind}; use ide_db::{SnippetCap, SymbolKind};
use itertools::Itertools; use itertools::Itertools;
use stdx::{format_to, to_lower_snake_case}; use stdx::{format_to, to_lower_snake_case};
use syntax::{ast, format_smolstr, AstNode, Edition, SmolStr, SyntaxKind, ToSmolStr, T}; use syntax::{ast, format_smolstr, match_ast, AstNode, Edition, SmolStr, SyntaxKind, ToSmolStr, T};
use crate::{ use crate::{
context::{CompletionContext, DotAccess, DotAccessKind, PathCompletionCtx, PathKind}, context::{CompletionContext, DotAccess, DotAccessKind, PathCompletionCtx, PathKind},
@ -278,13 +278,25 @@ pub(super) fn add_call_parens<'b>(
(snippet, "(…)") (snippet, "(…)")
}; };
if ret_type.is_unit() && ctx.config.add_semicolon_to_unit { if ret_type.is_unit() && ctx.config.add_semicolon_to_unit {
let inside_closure_ret = ctx.token.parent_ancestors().try_for_each(|ancestor| {
match_ast! {
match ancestor {
ast::BlockExpr(_) => ControlFlow::Break(false),
ast::ClosureExpr(_) => ControlFlow::Break(true),
_ => ControlFlow::Continue(())
}
}
});
if inside_closure_ret != ControlFlow::Break(true) {
let next_non_trivia_token = let next_non_trivia_token =
std::iter::successors(ctx.token.next_token(), |it| it.next_token()) std::iter::successors(ctx.token.next_token(), |it| it.next_token())
.find(|it| !it.kind().is_trivia()); .find(|it| !it.kind().is_trivia());
let in_match_arm = ctx.token.parent_ancestors().try_for_each(|ancestor| { let in_match_arm = ctx.token.parent_ancestors().try_for_each(|ancestor| {
if ast::MatchArm::can_cast(ancestor.kind()) { if ast::MatchArm::can_cast(ancestor.kind()) {
ControlFlow::Break(true) ControlFlow::Break(true)
} else if matches!(ancestor.kind(), SyntaxKind::EXPR_STMT | SyntaxKind::BLOCK_EXPR) { } else if matches!(ancestor.kind(), SyntaxKind::EXPR_STMT | SyntaxKind::BLOCK_EXPR)
{
ControlFlow::Break(false) ControlFlow::Break(false)
} else { } else {
ControlFlow::Continue(()) ControlFlow::Continue(())
@ -306,6 +318,7 @@ pub(super) fn add_call_parens<'b>(
} }
} }
} }
}
builder.label(SmolStr::from_iter([&name, label_suffix])).insert_snippet(cap, snippet) builder.label(SmolStr::from_iter([&name, label_suffix])).insert_snippet(cap, snippet)
} }
@ -886,6 +899,27 @@ fn bar() {
v => foo()$0, v => foo()$0,
} }
} }
"#,
);
}
#[test]
fn no_semicolon_in_closure_ret() {
check_edit(
r#"foo"#,
r#"
fn foo() {}
fn baz(_: impl FnOnce()) {}
fn bar() {
baz(|| fo$0);
}
"#,
r#"
fn foo() {}
fn baz(_: impl FnOnce()) {}
fn bar() {
baz(|| foo()$0);
}
"#, "#,
); );
} }