rust/crates/completion/src/completions/pattern.rs

118 lines
2.7 KiB
Rust
Raw Normal View History

//! Completes constats and paths in patterns.
use crate::{CompletionContext, Completions};
2019-02-24 14:49:47 -06:00
/// Completes constats and paths in patterns.
2020-10-25 02:59:15 -05:00
pub(crate) fn complete_pattern(acc: &mut Completions, ctx: &CompletionContext) {
2020-11-25 16:25:10 -06:00
if !(ctx.is_pat_binding_or_const || ctx.is_irrefutable_let_pat_binding) {
2019-02-24 14:49:47 -06:00
return;
}
if ctx.record_pat_syntax.is_some() {
return;
}
2019-03-23 02:53:48 -05:00
// FIXME: ideally, we should look at the type we are matching against and
2019-02-24 14:49:47 -06:00
// suggest variants + auto-imports
2020-07-10 18:26:24 -05:00
ctx.scope.process_all_names(&mut |name, res| {
2020-11-25 16:25:10 -06:00
let add_resolution = match &res {
hir::ScopeDef::ModuleDef(def) => {
if ctx.is_irrefutable_let_pat_binding {
matches!(def, hir::ModuleDef::Adt(hir::Adt::Struct(_)))
} else {
matches!(
def,
hir::ModuleDef::Adt(hir::Adt::Enum(..))
| hir::ModuleDef::Adt(hir::Adt::Struct(..))
2020-12-20 01:05:24 -06:00
| hir::ModuleDef::Variant(..)
2020-11-25 16:25:10 -06:00
| hir::ModuleDef::Const(..)
| hir::ModuleDef::Module(..)
)
}
}
hir::ScopeDef::MacroDef(_) => true,
_ => false,
2019-02-24 14:49:47 -06:00
};
2020-11-25 16:25:10 -06:00
if add_resolution {
acc.add_resolution(ctx, name.to_string(), &res);
}
});
2019-02-24 14:49:47 -06:00
}
#[cfg(test)]
mod tests {
2020-08-21 06:19:31 -05:00
use expect_test::{expect, Expect};
2019-02-24 14:49:47 -06:00
use crate::{test_utils::completion_list, CompletionKind};
2020-07-04 08:10:55 -05:00
fn check(ra_fixture: &str, expect: Expect) {
let actual = completion_list(ra_fixture, CompletionKind::Reference);
expect.assert_eq(&actual)
2019-02-24 14:49:47 -06:00
}
#[test]
fn completes_enum_variants_and_modules() {
2020-07-04 08:10:55 -05:00
check(
r#"
enum E { X }
use self::E::X;
const Z: E = E::X;
mod m {}
2019-02-24 14:49:47 -06:00
2020-07-04 08:10:55 -05:00
static FOO: E = E::X;
struct Bar { f: u32 }
2019-02-24 14:49:47 -06:00
2020-07-04 08:10:55 -05:00
fn foo() {
match E::X { <|> }
}
"#,
expect![[r#"
en E
ct Z
st Bar
ev X ()
2020-07-04 08:10:55 -05:00
md m
"#]],
2019-02-24 14:49:47 -06:00
);
}
2020-03-07 08:47:10 -06:00
#[test]
fn completes_in_simple_macro_call() {
2020-07-04 08:10:55 -05:00
check(
r#"
macro_rules! m { ($e:expr) => { $e } }
enum E { X }
2020-03-07 08:47:10 -06:00
2020-07-04 08:10:55 -05:00
fn foo() {
m!(match E::X { <|> })
}
"#,
expect![[r#"
en E
ma m!() macro_rules! m
"#]],
2020-03-07 08:47:10 -06:00
);
}
2020-11-25 16:25:10 -06:00
#[test]
fn completes_in_irrefutable_let() {
check(
r#"
enum E { X }
use self::E::X;
const Z: E = E::X;
mod m {}
static FOO: E = E::X;
struct Bar { f: u32 }
fn foo() {
let <|>
}
"#,
expect![[r#"
st Bar
"#]],
);
}
2019-02-24 14:49:47 -06:00
}