Auto merge of #16723 - norskeld:constants-autocomplete, r=Veykril

fix: autocomplete constants inside format strings

Hi! This PR adds autocompletion for constants (including statics) inside format strings and closes #16608.

I'm not sure about adding the `constants` field to the `CompletionContext`. It kinda makes sense, since it's in line with the `locals` field, and this way everything looks a bit cleaner, but at the same time does it really need to be there?

Anyway, let me know if anything should/can be changed. :)
This commit is contained in:
bors 2024-03-04 08:36:39 +00:00
commit 518cfe8cb7

View File

@ -1,6 +1,7 @@
//! Completes identifiers in format string literals.
use ide_db::syntax_helpers::format_string::is_format_string;
use hir::{ModuleDef, ScopeDef};
use ide_db::{syntax_helpers::format_string::is_format_string, SymbolKind};
use itertools::Itertools;
use syntax::{ast, AstToken, TextRange, TextSize};
@ -33,7 +34,23 @@ pub(crate) fn format_string(
ctx.locals.iter().for_each(|(name, _)| {
CompletionItem::new(CompletionItemKind::Binding, source_range, name.to_smol_str())
.add_to(acc, ctx.db);
})
});
ctx.scope.process_all_names(&mut |name, scope| {
if let ScopeDef::ModuleDef(module_def) = scope {
let symbol_kind = match module_def {
ModuleDef::Const(..) => SymbolKind::Const,
ModuleDef::Static(..) => SymbolKind::Static,
_ => return,
};
CompletionItem::new(
CompletionItemKind::SymbolKind(symbol_kind),
source_range,
name.to_smol_str(),
)
.add_to(acc, ctx.db);
}
});
}
#[cfg(test)]
@ -110,6 +127,80 @@ fn main() {
let foobar = 1;
format_args!("{foobar");
}
"#,
);
}
#[test]
fn completes_constants() {
check_edit(
"FOOBAR",
r#"
//- minicore: fmt
fn main() {
const FOOBAR: usize = 42;
format_args!("{f$0");
}
"#,
r#"
fn main() {
const FOOBAR: usize = 42;
format_args!("{FOOBAR");
}
"#,
);
check_edit(
"FOOBAR",
r#"
//- minicore: fmt
fn main() {
const FOOBAR: usize = 42;
format_args!("{$0");
}
"#,
r#"
fn main() {
const FOOBAR: usize = 42;
format_args!("{FOOBAR");
}
"#,
);
}
#[test]
fn completes_static_constants() {
check_edit(
"FOOBAR",
r#"
//- minicore: fmt
fn main() {
static FOOBAR: usize = 42;
format_args!("{f$0");
}
"#,
r#"
fn main() {
static FOOBAR: usize = 42;
format_args!("{FOOBAR");
}
"#,
);
check_edit(
"FOOBAR",
r#"
//- minicore: fmt
fn main() {
static FOOBAR: usize = 42;
format_args!("{$0");
}
"#,
r#"
fn main() {
static FOOBAR: usize = 42;
format_args!("{FOOBAR");
}
"#,
);
}