From fc37e2f953a0d200e875c4711c1b0bf79a75a2a2 Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Thu, 27 May 2021 23:28:14 +0200 Subject: Attribute completion is context aware --- crates/ide_completion/Cargo.toml | 1 + crates/ide_completion/src/completions/attribute.rs | 169 +++++++++++++++++---- crates/syntax/src/ast/node_ext.rs | 7 + 3 files changed, 149 insertions(+), 28 deletions(-) (limited to 'crates') diff --git a/crates/ide_completion/Cargo.toml b/crates/ide_completion/Cargo.toml index 6bd8a5500..ba81c9e04 100644 --- a/crates/ide_completion/Cargo.toml +++ b/crates/ide_completion/Cargo.toml @@ -15,6 +15,7 @@ itertools = "0.10.0" log = "0.4.8" rustc-hash = "1.1.0" either = "1.6.1" +once_cell = "1.7" stdx = { path = "../stdx", version = "0.0.0" } syntax = { path = "../syntax", version = "0.0.0" } diff --git a/crates/ide_completion/src/completions/attribute.rs b/crates/ide_completion/src/completions/attribute.rs index b1505c74b..0997302a6 100644 --- a/crates/ide_completion/src/completions/attribute.rs +++ b/crates/ide_completion/src/completions/attribute.rs @@ -4,8 +4,9 @@ //! for built-in attributes. use itertools::Itertools; -use rustc_hash::FxHashSet; -use syntax::{ast, AstNode, T}; +use once_cell::sync::Lazy; +use rustc_hash::{FxHashMap, FxHashSet}; +use syntax::{ast, AstNode, SyntaxKind, T}; use crate::{ context::CompletionContext, @@ -20,27 +21,34 @@ pub(crate) fn complete_attribute(acc: &mut Completions, ctx: &CompletionContext) } let attribute = ctx.attribute_under_caret.as_ref()?; - match (attribute.path(), attribute.token_tree()) { - (Some(path), Some(token_tree)) => { - let path = path.syntax().text(); - if path == "derive" { - complete_derive(acc, ctx, token_tree) - } else if path == "feature" { - complete_lint(acc, ctx, token_tree, FEATURES) - } else if path == "allow" || path == "warn" || path == "deny" || path == "forbid" { + match (attribute.path().and_then(|p| p.as_single_name_ref()), attribute.token_tree()) { + (Some(path), Some(token_tree)) => match path.text().as_str() { + "derive" => complete_derive(acc, ctx, token_tree), + "feature" => complete_lint(acc, ctx, token_tree, FEATURES), + "allow" | "warn" | "deny" | "forbid" => { complete_lint(acc, ctx, token_tree.clone(), DEFAULT_LINT_COMPLETIONS); complete_lint(acc, ctx, token_tree, CLIPPY_LINTS); } - } - (_, Some(_token_tree)) => {} - _ => complete_attribute_start(acc, ctx, attribute), + _ => (), + }, + (None, Some(_)) => (), + _ => complete_new_attribute(acc, ctx, attribute), } Some(()) } -fn complete_attribute_start(acc: &mut Completions, ctx: &CompletionContext, attribute: &ast::Attr) { +fn complete_new_attribute(acc: &mut Completions, ctx: &CompletionContext, attribute: &ast::Attr) { + let attribute_annotated_item_kind = attribute.syntax().parent().map(|it| it.kind()); + let attributes = attribute_annotated_item_kind.and_then(|kind| { + if ast::Expr::can_cast(kind) { + Some(EXPR_ATTRIBUTES) + } else { + KIND_TO_ATTRIBUTES.get(&kind).copied() + } + }); let is_inner = attribute.kind() == ast::AttrKind::Inner; - for attr_completion in ATTRIBUTES.iter().filter(|compl| is_inner || !compl.prefer_inner) { + + let add_completion = |attr_completion: &AttrCompletion| { let mut item = CompletionItem::new( CompletionKind::Attribute, ctx.source_range(), @@ -56,9 +64,19 @@ fn complete_attribute_start(acc: &mut Completions, ctx: &CompletionContext, attr item.insert_snippet(cap, snippet); } - if attribute.kind() == ast::AttrKind::Inner || !attr_completion.prefer_inner { + if is_inner || !attr_completion.prefer_inner { acc.add(item.build()); } + }; + + match attributes { + Some(applicable) => applicable + .iter() + .flat_map(|name| ATTRIBUTES.binary_search_by(|attr| attr.key().cmp(name)).ok()) + .flat_map(|idx| ATTRIBUTES.get(idx)) + .for_each(add_completion), + None if is_inner => ATTRIBUTES.iter().for_each(add_completion), + None => ATTRIBUTES.iter().filter(|compl| !compl.prefer_inner).for_each(add_completion), } } @@ -70,6 +88,10 @@ struct AttrCompletion { } impl AttrCompletion { + fn key(&self) -> &'static str { + self.lookup.unwrap_or(self.label) + } + const fn prefer_inner(self) -> AttrCompletion { AttrCompletion { prefer_inner: true, ..self } } @@ -83,26 +105,81 @@ const fn attr( AttrCompletion { label, lookup, snippet, prefer_inner: false } } +macro_rules! attrs { + [$($($mac:ident!),+;)? $($key:literal),*] => { + &["allow", "cfg", "cfg_attr", "deny", "forbid", "warn", $($($mac!()),+,)? $($key),*] as _ + } +} +macro_rules! item_attrs { + () => { + "deprecated" + }; +} + +static KIND_TO_ATTRIBUTES: Lazy> = Lazy::new(|| { + std::array::IntoIter::new([ + (SyntaxKind::SOURCE_FILE, attrs!(item_attrs!;"crate_name")), + (SyntaxKind::MODULE, attrs!(item_attrs!;)), + (SyntaxKind::ITEM_LIST, attrs!(item_attrs!;)), + (SyntaxKind::MACRO_RULES, attrs!(item_attrs!;)), + (SyntaxKind::MACRO_DEF, attrs!(item_attrs!;)), + (SyntaxKind::EXTERN_CRATE, attrs!(item_attrs!;)), + (SyntaxKind::USE, attrs!(item_attrs!;)), + (SyntaxKind::FN, attrs!(item_attrs!;"cold", "must_use")), + (SyntaxKind::TYPE_ALIAS, attrs!(item_attrs!;)), + (SyntaxKind::STRUCT, attrs!(item_attrs!;"must_use")), + (SyntaxKind::ENUM, attrs!(item_attrs!;"must_use")), + (SyntaxKind::UNION, attrs!(item_attrs!;"must_use")), + (SyntaxKind::CONST, attrs!(item_attrs!;)), + (SyntaxKind::STATIC, attrs!(item_attrs!;)), + (SyntaxKind::TRAIT, attrs!(item_attrs!; "must_use")), + (SyntaxKind::IMPL, attrs!(item_attrs!;"automatically_derived")), + (SyntaxKind::ASSOC_ITEM_LIST, attrs!(item_attrs!;)), + (SyntaxKind::EXTERN_BLOCK, attrs!(item_attrs!;)), + (SyntaxKind::EXTERN_ITEM_LIST, attrs!(item_attrs!;)), + (SyntaxKind::MACRO_CALL, attrs!()), + (SyntaxKind::SELF_PARAM, attrs!()), + (SyntaxKind::PARAM, attrs!()), + (SyntaxKind::RECORD_FIELD, attrs!()), + (SyntaxKind::VARIANT, attrs!()), + (SyntaxKind::TYPE_PARAM, attrs!()), + (SyntaxKind::CONST_PARAM, attrs!()), + (SyntaxKind::LIFETIME_PARAM, attrs!()), + (SyntaxKind::LET_STMT, attrs!()), + (SyntaxKind::EXPR_STMT, attrs!()), + (SyntaxKind::LITERAL, attrs!()), + (SyntaxKind::RECORD_EXPR_FIELD_LIST, attrs!()), + (SyntaxKind::RECORD_EXPR_FIELD, attrs!()), + (SyntaxKind::MATCH_ARM_LIST, attrs!()), + (SyntaxKind::MATCH_ARM, attrs!()), + (SyntaxKind::IDENT_PAT, attrs!()), + (SyntaxKind::RECORD_PAT_FIELD, attrs!()), + ]) + .collect() +}); +const EXPR_ATTRIBUTES: &[&str] = attrs!(); + /// https://doc.rust-lang.org/reference/attributes.html#built-in-attributes-index +// Keep these sorted for the binary search! const ATTRIBUTES: &[AttrCompletion] = &[ attr("allow(…)", Some("allow"), Some("allow(${0:lint})")), attr("automatically_derived", None, None), - attr("cfg_attr(…)", Some("cfg_attr"), Some("cfg_attr(${1:predicate}, ${0:attr})")), attr("cfg(…)", Some("cfg"), Some("cfg(${0:predicate})")), + attr("cfg_attr(…)", Some("cfg_attr"), Some("cfg_attr(${1:predicate}, ${0:attr})")), attr("cold", None, None), attr(r#"crate_name = """#, Some("crate_name"), Some(r#"crate_name = "${0:crate_name}""#)) .prefer_inner(), attr("deny(…)", Some("deny"), Some("deny(${0:lint})")), attr(r#"deprecated"#, Some("deprecated"), Some(r#"deprecated"#)), attr("derive(…)", Some("derive"), Some(r#"derive(${0:Debug})"#)), + attr(r#"doc = "…""#, Some("doc"), Some(r#"doc = "${0:docs}""#)), + attr(r#"doc(alias = "…")"#, Some("docalias"), Some(r#"doc(alias = "${0:docs}")"#)), + attr(r#"doc(hidden)"#, Some("dochidden"), Some(r#"doc(hidden)"#)), attr( r#"export_name = "…""#, Some("export_name"), Some(r#"export_name = "${0:exported_symbol_name}""#), ), - attr(r#"doc(alias = "…")"#, Some("docalias"), Some(r#"doc(alias = "${0:docs}")"#)), - attr(r#"doc = "…""#, Some("doc"), Some(r#"doc = "${0:docs}""#)), - attr(r#"doc(hidden)"#, Some("dochidden"), Some(r#"doc(hidden)"#)), attr("feature(…)", Some("feature"), Some("feature(${0:flag})")).prefer_inner(), attr("forbid(…)", Some("forbid"), Some("forbid(${0:lint})")), // FIXME: resolve through macro resolution? @@ -119,8 +196,8 @@ const ATTRIBUTES: &[AttrCompletion] = &[ attr("macro_export", None, None), attr("macro_use", None, None), attr(r#"must_use"#, Some("must_use"), Some(r#"must_use"#)), - attr("no_link", None, None).prefer_inner(), attr("no_implicit_prelude", None, None).prefer_inner(), + attr("no_link", None, None).prefer_inner(), attr("no_main", None, None).prefer_inner(), attr("no_mangle", None, None), attr("no_std", None, None).prefer_inner(), @@ -153,6 +230,22 @@ const ATTRIBUTES: &[AttrCompletion] = &[ .prefer_inner(), ]; +#[test] +fn attributes_are_sorted() { + let mut attrs = ATTRIBUTES.iter().map(|attr| attr.key()); + let mut prev = attrs.next().unwrap(); + + attrs.for_each(|next| { + assert!( + prev < next, + r#"Attributes are not sorted, "{}" should come after "{}""#, + prev, + next + ); + prev = next; + }); +} + fn complete_derive(acc: &mut Completions, ctx: &CompletionContext, derive_input: ast::TokenTree) { if let Ok(existing_derives) = parse_comma_sep_input(derive_input) { for derive_completion in DEFAULT_DERIVE_COMPLETIONS @@ -409,6 +502,26 @@ mod tests { expect.assert_eq(&actual); } + #[test] + fn complete_attribute_on_struct() { + check( + r#" +#[$0] +struct Test {} + "#, + expect![[r#" + at allow(…) + at cfg(…) + at cfg_attr(…) + at deny(…) + at forbid(…) + at warn(…) + at deprecated + at must_use + "#]], + ); + } + #[test] fn empty_derive_completion() { check( @@ -468,16 +581,16 @@ struct Test {} expect![[r#" at allow(…) at automatically_derived - at cfg_attr(…) at cfg(…) + at cfg_attr(…) at cold at deny(…) at deprecated at derive(…) - at export_name = "…" - at doc(alias = "…") at doc = "…" + at doc(alias = "…") at doc(hidden) + at export_name = "…" at forbid(…) at ignore = "…" at inline @@ -516,17 +629,17 @@ struct Test {} expect![[r#" at allow(…) at automatically_derived - at cfg_attr(…) at cfg(…) + at cfg_attr(…) at cold at crate_name = "" at deny(…) at deprecated at derive(…) - at export_name = "…" - at doc(alias = "…") at doc = "…" + at doc(alias = "…") at doc(hidden) + at export_name = "…" at feature(…) at forbid(…) at global_allocator @@ -538,8 +651,8 @@ struct Test {} at macro_export at macro_use at must_use - at no_link at no_implicit_prelude + at no_link at no_main at no_mangle at no_std diff --git a/crates/syntax/src/ast/node_ext.rs b/crates/syntax/src/ast/node_ext.rs index df8f98b5b..884fe0739 100644 --- a/crates/syntax/src/ast/node_ext.rs +++ b/crates/syntax/src/ast/node_ext.rs @@ -243,6 +243,13 @@ impl ast::Path { } } + pub fn as_single_name_ref(&self) -> Option { + match self.qualifier() { + Some(_) => None, + None => self.segment()?.name_ref(), + } + } + pub fn first_qualifier_or_self(&self) -> ast::Path { successors(Some(self.clone()), ast::Path::qualifier).last().unwrap() } -- cgit v1.2.3 From ab9c6ea4dd2c1a3b71fe50469627b0b518350896 Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Thu, 27 May 2021 23:40:33 +0200 Subject: Split attribute completion module into attribute, derive and lint modules --- crates/ide_completion/src/completions/attribute.rs | 374 +-------------------- .../src/completions/attribute/derive.rs | 141 ++++++++ .../src/completions/attribute/lint.rs | 153 +++++++++ 3 files changed, 302 insertions(+), 366 deletions(-) create mode 100644 crates/ide_completion/src/completions/attribute/derive.rs create mode 100644 crates/ide_completion/src/completions/attribute/lint.rs (limited to 'crates') diff --git a/crates/ide_completion/src/completions/attribute.rs b/crates/ide_completion/src/completions/attribute.rs index 0997302a6..e128e307c 100644 --- a/crates/ide_completion/src/completions/attribute.rs +++ b/crates/ide_completion/src/completions/attribute.rs @@ -3,7 +3,6 @@ //! This module uses a bit of static metadata to provide completions //! for built-in attributes. -use itertools::Itertools; use once_cell::sync::Lazy; use rustc_hash::{FxHashMap, FxHashSet}; use syntax::{ast, AstNode, SyntaxKind, T}; @@ -15,6 +14,10 @@ use crate::{ Completions, }; +mod derive; +mod lint; +pub(crate) use self::lint::LintCompletion; + pub(crate) fn complete_attribute(acc: &mut Completions, ctx: &CompletionContext) -> Option<()> { if ctx.mod_declaration_under_caret.is_some() { return None; @@ -23,11 +26,11 @@ pub(crate) fn complete_attribute(acc: &mut Completions, ctx: &CompletionContext) let attribute = ctx.attribute_under_caret.as_ref()?; match (attribute.path().and_then(|p| p.as_single_name_ref()), attribute.token_tree()) { (Some(path), Some(token_tree)) => match path.text().as_str() { - "derive" => complete_derive(acc, ctx, token_tree), - "feature" => complete_lint(acc, ctx, token_tree, FEATURES), + "derive" => derive::complete_derive(acc, ctx, token_tree), + "feature" => lint::complete_lint(acc, ctx, token_tree, FEATURES), "allow" | "warn" | "deny" | "forbid" => { - complete_lint(acc, ctx, token_tree.clone(), DEFAULT_LINT_COMPLETIONS); - complete_lint(acc, ctx, token_tree, CLIPPY_LINTS); + lint::complete_lint(acc, ctx, token_tree.clone(), lint::DEFAULT_LINT_COMPLETIONS); + lint::complete_lint(acc, ctx, token_tree, CLIPPY_LINTS); } _ => (), }, @@ -246,61 +249,6 @@ fn attributes_are_sorted() { }); } -fn complete_derive(acc: &mut Completions, ctx: &CompletionContext, derive_input: ast::TokenTree) { - if let Ok(existing_derives) = parse_comma_sep_input(derive_input) { - for derive_completion in DEFAULT_DERIVE_COMPLETIONS - .iter() - .filter(|completion| !existing_derives.contains(completion.label)) - { - let mut components = vec![derive_completion.label]; - components.extend( - derive_completion - .dependencies - .iter() - .filter(|&&dependency| !existing_derives.contains(dependency)), - ); - let lookup = components.join(", "); - let label = components.iter().rev().join(", "); - let mut item = - CompletionItem::new(CompletionKind::Attribute, ctx.source_range(), label); - item.lookup_by(lookup).kind(CompletionItemKind::Attribute); - item.add_to(acc); - } - - for custom_derive_name in get_derive_names_in_scope(ctx).difference(&existing_derives) { - let mut item = CompletionItem::new( - CompletionKind::Attribute, - ctx.source_range(), - custom_derive_name, - ); - item.kind(CompletionItemKind::Attribute); - item.add_to(acc); - } - } -} - -fn complete_lint( - acc: &mut Completions, - ctx: &CompletionContext, - derive_input: ast::TokenTree, - lints_completions: &[LintCompletion], -) { - if let Ok(existing_lints) = parse_comma_sep_input(derive_input) { - for lint_completion in lints_completions - .into_iter() - .filter(|completion| !existing_lints.contains(completion.label)) - { - let mut item = CompletionItem::new( - CompletionKind::Attribute, - ctx.source_range(), - lint_completion.label, - ); - item.kind(CompletionItemKind::Attribute).detail(lint_completion.description); - item.add_to(acc) - } - } -} - fn parse_comma_sep_input(derive_input: ast::TokenTree) -> Result, ()> { match (derive_input.left_delimiter_token(), derive_input.right_delimiter_token()) { (Some(left_paren), Some(right_paren)) @@ -335,162 +283,6 @@ fn parse_comma_sep_input(derive_input: ast::TokenTree) -> Result FxHashSet { - let mut result = FxHashSet::default(); - ctx.scope.process_all_names(&mut |name, scope_def| { - if let hir::ScopeDef::MacroDef(mac) = scope_def { - // FIXME kind() doesn't check whether proc-macro is a derive - if mac.kind() == hir::MacroKind::Derive || mac.kind() == hir::MacroKind::ProcMacro { - result.insert(name.to_string()); - } - } - }); - result -} - -struct DeriveCompletion { - label: &'static str, - dependencies: &'static [&'static str], -} - -/// Standard Rust derives and the information about their dependencies -/// (the dependencies are needed so that the main derive don't break the compilation when added) -const DEFAULT_DERIVE_COMPLETIONS: &[DeriveCompletion] = &[ - DeriveCompletion { label: "Clone", dependencies: &[] }, - DeriveCompletion { label: "Copy", dependencies: &["Clone"] }, - DeriveCompletion { label: "Debug", dependencies: &[] }, - DeriveCompletion { label: "Default", dependencies: &[] }, - DeriveCompletion { label: "Hash", dependencies: &[] }, - DeriveCompletion { label: "PartialEq", dependencies: &[] }, - DeriveCompletion { label: "Eq", dependencies: &["PartialEq"] }, - DeriveCompletion { label: "PartialOrd", dependencies: &["PartialEq"] }, - DeriveCompletion { label: "Ord", dependencies: &["PartialOrd", "Eq", "PartialEq"] }, -]; - -pub(crate) struct LintCompletion { - pub(crate) label: &'static str, - pub(crate) description: &'static str, -} - -#[rustfmt::skip] -const DEFAULT_LINT_COMPLETIONS: &[LintCompletion] = &[ - LintCompletion { label: "absolute_paths_not_starting_with_crate", description: r#"fully qualified paths that start with a module name instead of `crate`, `self`, or an extern crate name"# }, - LintCompletion { label: "anonymous_parameters", description: r#"detects anonymous parameters"# }, - LintCompletion { label: "box_pointers", description: r#"use of owned (Box type) heap memory"# }, - LintCompletion { label: "deprecated_in_future", description: r#"detects use of items that will be deprecated in a future version"# }, - LintCompletion { label: "elided_lifetimes_in_paths", description: r#"hidden lifetime parameters in types are deprecated"# }, - LintCompletion { label: "explicit_outlives_requirements", description: r#"outlives requirements can be inferred"# }, - LintCompletion { label: "indirect_structural_match", description: r#"pattern with const indirectly referencing non-structural-match type"# }, - LintCompletion { label: "keyword_idents", description: r#"detects edition keywords being used as an identifier"# }, - LintCompletion { label: "macro_use_extern_crate", description: r#"the `#[macro_use]` attribute is now deprecated in favor of using macros via the module system"# }, - LintCompletion { label: "meta_variable_misuse", description: r#"possible meta-variable misuse at macro definition"# }, - LintCompletion { label: "missing_copy_implementations", description: r#"detects potentially-forgotten implementations of `Copy`"# }, - LintCompletion { label: "missing_crate_level_docs", description: r#"detects crates with no crate-level documentation"# }, - LintCompletion { label: "missing_debug_implementations", description: r#"detects missing implementations of Debug"# }, - LintCompletion { label: "missing_docs", description: r#"detects missing documentation for public members"# }, - LintCompletion { label: "missing_doc_code_examples", description: r#"detects publicly-exported items without code samples in their documentation"# }, - LintCompletion { label: "non_ascii_idents", description: r#"detects non-ASCII identifiers"# }, - LintCompletion { label: "private_doc_tests", description: r#"detects code samples in docs of private items not documented by rustdoc"# }, - LintCompletion { label: "single_use_lifetimes", description: r#"detects lifetime parameters that are only used once"# }, - LintCompletion { label: "trivial_casts", description: r#"detects trivial casts which could be removed"# }, - LintCompletion { label: "trivial_numeric_casts", description: r#"detects trivial casts of numeric types which could be removed"# }, - LintCompletion { label: "unaligned_references", description: r#"detects unaligned references to fields of packed structs"# }, - LintCompletion { label: "unreachable_pub", description: r#"`pub` items not reachable from crate root"# }, - LintCompletion { label: "unsafe_code", description: r#"usage of `unsafe` code"# }, - LintCompletion { label: "unsafe_op_in_unsafe_fn", description: r#"unsafe operations in unsafe functions without an explicit unsafe block are deprecated"# }, - LintCompletion { label: "unstable_features", description: r#"enabling unstable features (deprecated. do not use)"# }, - LintCompletion { label: "unused_crate_dependencies", description: r#"crate dependencies that are never used"# }, - LintCompletion { label: "unused_extern_crates", description: r#"extern crates that are never used"# }, - LintCompletion { label: "unused_import_braces", description: r#"unnecessary braces around an imported item"# }, - LintCompletion { label: "unused_lifetimes", description: r#"detects lifetime parameters that are never used"# }, - LintCompletion { label: "unused_qualifications", description: r#"detects unnecessarily qualified names"# }, - LintCompletion { label: "unused_results", description: r#"unused result of an expression in a statement"# }, - LintCompletion { label: "variant_size_differences", description: r#"detects enums with widely varying variant sizes"# }, - LintCompletion { label: "array_into_iter", description: r#"detects calling `into_iter` on arrays"# }, - LintCompletion { label: "asm_sub_register", description: r#"using only a subset of a register for inline asm inputs"# }, - LintCompletion { label: "bare_trait_objects", description: r#"suggest using `dyn Trait` for trait objects"# }, - LintCompletion { label: "bindings_with_variant_name", description: r#"detects pattern bindings with the same name as one of the matched variants"# }, - LintCompletion { label: "cenum_impl_drop_cast", description: r#"a C-like enum implementing Drop is cast"# }, - LintCompletion { label: "clashing_extern_declarations", description: r#"detects when an extern fn has been declared with the same name but different types"# }, - LintCompletion { label: "coherence_leak_check", description: r#"distinct impls distinguished only by the leak-check code"# }, - LintCompletion { label: "confusable_idents", description: r#"detects visually confusable pairs between identifiers"# }, - LintCompletion { label: "dead_code", description: r#"detect unused, unexported items"# }, - LintCompletion { label: "deprecated", description: r#"detects use of deprecated items"# }, - LintCompletion { label: "ellipsis_inclusive_range_patterns", description: r#"`...` range patterns are deprecated"# }, - LintCompletion { label: "exported_private_dependencies", description: r#"public interface leaks type from a private dependency"# }, - LintCompletion { label: "illegal_floating_point_literal_pattern", description: r#"floating-point literals cannot be used in patterns"# }, - LintCompletion { label: "improper_ctypes", description: r#"proper use of libc types in foreign modules"# }, - LintCompletion { label: "improper_ctypes_definitions", description: r#"proper use of libc types in foreign item definitions"# }, - LintCompletion { label: "incomplete_features", description: r#"incomplete features that may function improperly in some or all cases"# }, - LintCompletion { label: "inline_no_sanitize", description: r#"detects incompatible use of `#[inline(always)]` and `#[no_sanitize(...)]`"# }, - LintCompletion { label: "intra_doc_link_resolution_failure", description: r#"failures in resolving intra-doc link targets"# }, - LintCompletion { label: "invalid_codeblock_attributes", description: r#"codeblock attribute looks a lot like a known one"# }, - LintCompletion { label: "invalid_value", description: r#"an invalid value is being created (such as a NULL reference)"# }, - LintCompletion { label: "irrefutable_let_patterns", description: r#"detects irrefutable patterns in if-let and while-let statements"# }, - LintCompletion { label: "late_bound_lifetime_arguments", description: r#"detects generic lifetime arguments in path segments with late bound lifetime parameters"# }, - LintCompletion { label: "mixed_script_confusables", description: r#"detects Unicode scripts whose mixed script confusables codepoints are solely used"# }, - LintCompletion { label: "mutable_borrow_reservation_conflict", description: r#"reservation of a two-phased borrow conflicts with other shared borrows"# }, - LintCompletion { label: "non_camel_case_types", description: r#"types, variants, traits and type parameters should have camel case names"# }, - LintCompletion { label: "non_shorthand_field_patterns", description: r#"using `Struct { x: x }` instead of `Struct { x }` in a pattern"# }, - LintCompletion { label: "non_snake_case", description: r#"variables, methods, functions, lifetime parameters and modules should have snake case names"# }, - LintCompletion { label: "non_upper_case_globals", description: r#"static constants should have uppercase identifiers"# }, - LintCompletion { label: "no_mangle_generic_items", description: r#"generic items must be mangled"# }, - LintCompletion { label: "overlapping_patterns", description: r#"detects overlapping patterns"# }, - LintCompletion { label: "path_statements", description: r#"path statements with no effect"# }, - LintCompletion { label: "private_in_public", description: r#"detect private items in public interfaces not caught by the old implementation"# }, - LintCompletion { label: "proc_macro_derive_resolution_fallback", description: r#"detects proc macro derives using inaccessible names from parent modules"# }, - LintCompletion { label: "redundant_semicolons", description: r#"detects unnecessary trailing semicolons"# }, - LintCompletion { label: "renamed_and_removed_lints", description: r#"lints that have been renamed or removed"# }, - LintCompletion { label: "safe_packed_borrows", description: r#"safe borrows of fields of packed structs were erroneously allowed"# }, - LintCompletion { label: "stable_features", description: r#"stable features found in `#[feature]` directive"# }, - LintCompletion { label: "trivial_bounds", description: r#"these bounds don't depend on an type parameters"# }, - LintCompletion { label: "type_alias_bounds", description: r#"bounds in type aliases are not enforced"# }, - LintCompletion { label: "tyvar_behind_raw_pointer", description: r#"raw pointer to an inference variable"# }, - LintCompletion { label: "uncommon_codepoints", description: r#"detects uncommon Unicode codepoints in identifiers"# }, - LintCompletion { label: "unconditional_recursion", description: r#"functions that cannot return without calling themselves"# }, - LintCompletion { label: "unknown_lints", description: r#"unrecognized lint attribute"# }, - LintCompletion { label: "unnameable_test_items", description: r#"detects an item that cannot be named being marked as `#[test_case]`"# }, - LintCompletion { label: "unreachable_code", description: r#"detects unreachable code paths"# }, - LintCompletion { label: "unreachable_patterns", description: r#"detects unreachable patterns"# }, - LintCompletion { label: "unstable_name_collisions", description: r#"detects name collision with an existing but unstable method"# }, - LintCompletion { label: "unused_allocation", description: r#"detects unnecessary allocations that can be eliminated"# }, - LintCompletion { label: "unused_assignments", description: r#"detect assignments that will never be read"# }, - LintCompletion { label: "unused_attributes", description: r#"detects attributes that were not used by the compiler"# }, - LintCompletion { label: "unused_braces", description: r#"unnecessary braces around an expression"# }, - LintCompletion { label: "unused_comparisons", description: r#"comparisons made useless by limits of the types involved"# }, - LintCompletion { label: "unused_doc_comments", description: r#"detects doc comments that aren't used by rustdoc"# }, - LintCompletion { label: "unused_features", description: r#"unused features found in crate-level `#[feature]` directives"# }, - LintCompletion { label: "unused_imports", description: r#"imports that are never used"# }, - LintCompletion { label: "unused_labels", description: r#"detects labels that are never used"# }, - LintCompletion { label: "unused_macros", description: r#"detects macros that were not used"# }, - LintCompletion { label: "unused_must_use", description: r#"unused result of a type flagged as `#[must_use]`"# }, - LintCompletion { label: "unused_mut", description: r#"detect mut variables which don't need to be mutable"# }, - LintCompletion { label: "unused_parens", description: r#"`if`, `match`, `while` and `return` do not need parentheses"# }, - LintCompletion { label: "unused_unsafe", description: r#"unnecessary use of an `unsafe` block"# }, - LintCompletion { label: "unused_variables", description: r#"detect variables which are not used in any way"# }, - LintCompletion { label: "warnings", description: r#"mass-change the level for lints which produce warnings"# }, - LintCompletion { label: "where_clauses_object_safety", description: r#"checks the object safety of where clauses"# }, - LintCompletion { label: "while_true", description: r#"suggest using `loop { }` instead of `while true { }`"# }, - LintCompletion { label: "ambiguous_associated_items", description: r#"ambiguous associated items"# }, - LintCompletion { label: "arithmetic_overflow", description: r#"arithmetic operation overflows"# }, - LintCompletion { label: "conflicting_repr_hints", description: r#"conflicts between `#[repr(..)]` hints that were previously accepted and used in practice"# }, - LintCompletion { label: "const_err", description: r#"constant evaluation detected erroneous expression"# }, - LintCompletion { label: "ill_formed_attribute_input", description: r#"ill-formed attribute inputs that were previously accepted and used in practice"# }, - LintCompletion { label: "incomplete_include", description: r#"trailing content in included file"# }, - LintCompletion { label: "invalid_type_param_default", description: r#"type parameter default erroneously allowed in invalid location"# }, - LintCompletion { label: "macro_expanded_macro_exports_accessed_by_absolute_paths", description: r#"macro-expanded `macro_export` macros from the current crate cannot be referred to by absolute paths"# }, - LintCompletion { label: "missing_fragment_specifier", description: r#"detects missing fragment specifiers in unused `macro_rules!` patterns"# }, - LintCompletion { label: "mutable_transmutes", description: r#"mutating transmuted &mut T from &T may cause undefined behavior"# }, - LintCompletion { label: "no_mangle_const_items", description: r#"const items will not have their symbols exported"# }, - LintCompletion { label: "order_dependent_trait_objects", description: r#"trait-object types were treated as different depending on marker-trait order"# }, - LintCompletion { label: "overflowing_literals", description: r#"literal out of range for its type"# }, - LintCompletion { label: "patterns_in_fns_without_body", description: r#"patterns in functions without body were erroneously allowed"# }, - LintCompletion { label: "pub_use_of_private_extern_crate", description: r#"detect public re-exports of private extern crates"# }, - LintCompletion { label: "soft_unstable", description: r#"a feature gate that doesn't break dependent crates"# }, - LintCompletion { label: "unconditional_panic", description: r#"operation will cause a panic at runtime"# }, - LintCompletion { label: "unknown_crate_types", description: r#"unknown crate type found in `#[crate_type]` directive"# }, -]; - #[cfg(test)] mod tests { use expect_test::{expect, Expect}; @@ -521,158 +313,8 @@ struct Test {} "#]], ); } - - #[test] - fn empty_derive_completion() { - check( - r#" -#[derive($0)] -struct Test {} - "#, - expect![[r#" - at Clone - at Clone, Copy - at Debug - at Default - at Hash - at PartialEq - at PartialEq, Eq - at PartialEq, PartialOrd - at PartialEq, Eq, PartialOrd, Ord - "#]], - ); - } - - #[test] - fn no_completion_for_incorrect_derive() { - check( - r#" -#[derive{$0)] -struct Test {} -"#, - expect![[r#""#]], - ) - } - - #[test] - fn derive_with_input_completion() { - check( - r#" -#[derive(serde::Serialize, PartialEq, $0)] -struct Test {} -"#, - expect![[r#" - at Clone - at Clone, Copy - at Debug - at Default - at Hash - at Eq - at PartialOrd - at Eq, PartialOrd, Ord - "#]], - ) - } - - #[test] - fn test_attribute_completion() { - check( - r#"#[$0]"#, - expect![[r#" - at allow(…) - at automatically_derived - at cfg(…) - at cfg_attr(…) - at cold - at deny(…) - at deprecated - at derive(…) - at doc = "…" - at doc(alias = "…") - at doc(hidden) - at export_name = "…" - at forbid(…) - at ignore = "…" - at inline - at link - at link_name = "…" - at link_section = "…" - at macro_export - at macro_use - at must_use - at no_mangle - at non_exhaustive - at path = "…" - at proc_macro - at proc_macro_attribute - at proc_macro_derive(…) - at repr(…) - at should_panic - at target_feature = "…" - at test - at track_caller - at used - at warn(…) - "#]], - ) - } - #[test] fn test_attribute_completion_inside_nested_attr() { check(r#"#[cfg($0)]"#, expect![[]]) } - - #[test] - fn test_inner_attribute_completion() { - check( - r"#![$0]", - expect![[r#" - at allow(…) - at automatically_derived - at cfg(…) - at cfg_attr(…) - at cold - at crate_name = "" - at deny(…) - at deprecated - at derive(…) - at doc = "…" - at doc(alias = "…") - at doc(hidden) - at export_name = "…" - at feature(…) - at forbid(…) - at global_allocator - at ignore = "…" - at inline - at link - at link_name = "…" - at link_section = "…" - at macro_export - at macro_use - at must_use - at no_implicit_prelude - at no_link - at no_main - at no_mangle - at no_std - at non_exhaustive - at panic_handler - at path = "…" - at proc_macro - at proc_macro_attribute - at proc_macro_derive(…) - at recursion_limit = … - at repr(…) - at should_panic - at target_feature = "…" - at test - at track_caller - at type_length_limit = … - at used - at warn(…) - at windows_subsystem = "…" - "#]], - ); - } } diff --git a/crates/ide_completion/src/completions/attribute/derive.rs b/crates/ide_completion/src/completions/attribute/derive.rs new file mode 100644 index 000000000..c14b03ea4 --- /dev/null +++ b/crates/ide_completion/src/completions/attribute/derive.rs @@ -0,0 +1,141 @@ +use itertools::Itertools; +use rustc_hash::FxHashSet; +use syntax::ast; + +use crate::{ + context::CompletionContext, + item::{CompletionItem, CompletionItemKind, CompletionKind}, + Completions, +}; + +pub(super) fn complete_derive( + acc: &mut Completions, + ctx: &CompletionContext, + derive_input: ast::TokenTree, +) { + if let Ok(existing_derives) = super::parse_comma_sep_input(derive_input) { + for derive_completion in DEFAULT_DERIVE_COMPLETIONS + .iter() + .filter(|completion| !existing_derives.contains(completion.label)) + { + let mut components = vec![derive_completion.label]; + components.extend( + derive_completion + .dependencies + .iter() + .filter(|&&dependency| !existing_derives.contains(dependency)), + ); + let lookup = components.join(", "); + let label = components.iter().rev().join(", "); + let mut item = + CompletionItem::new(CompletionKind::Attribute, ctx.source_range(), label); + item.lookup_by(lookup).kind(CompletionItemKind::Attribute); + item.add_to(acc); + } + + for custom_derive_name in get_derive_names_in_scope(ctx).difference(&existing_derives) { + let mut item = CompletionItem::new( + CompletionKind::Attribute, + ctx.source_range(), + custom_derive_name, + ); + item.kind(CompletionItemKind::Attribute); + item.add_to(acc); + } + } +} +fn get_derive_names_in_scope(ctx: &CompletionContext) -> FxHashSet { + let mut result = FxHashSet::default(); + ctx.scope.process_all_names(&mut |name, scope_def| { + if let hir::ScopeDef::MacroDef(mac) = scope_def { + // FIXME kind() doesn't check whether proc-macro is a derive + if mac.kind() == hir::MacroKind::Derive || mac.kind() == hir::MacroKind::ProcMacro { + result.insert(name.to_string()); + } + } + }); + result +} + +struct DeriveCompletion { + label: &'static str, + dependencies: &'static [&'static str], +} + +/// Standard Rust derives and the information about their dependencies +/// (the dependencies are needed so that the main derive don't break the compilation when added) +const DEFAULT_DERIVE_COMPLETIONS: &[DeriveCompletion] = &[ + DeriveCompletion { label: "Clone", dependencies: &[] }, + DeriveCompletion { label: "Copy", dependencies: &["Clone"] }, + DeriveCompletion { label: "Debug", dependencies: &[] }, + DeriveCompletion { label: "Default", dependencies: &[] }, + DeriveCompletion { label: "Hash", dependencies: &[] }, + DeriveCompletion { label: "PartialEq", dependencies: &[] }, + DeriveCompletion { label: "Eq", dependencies: &["PartialEq"] }, + DeriveCompletion { label: "PartialOrd", dependencies: &["PartialEq"] }, + DeriveCompletion { label: "Ord", dependencies: &["PartialOrd", "Eq", "PartialEq"] }, +]; + +#[cfg(test)] +mod tests { + use expect_test::{expect, Expect}; + + use crate::{test_utils::completion_list, CompletionKind}; + + fn check(ra_fixture: &str, expect: Expect) { + let actual = completion_list(ra_fixture, CompletionKind::Attribute); + expect.assert_eq(&actual); + } + + #[test] + fn empty_derive_completion() { + check( + r#" +#[derive($0)] +struct Test {} + "#, + expect![[r#" + at Clone + at Clone, Copy + at Debug + at Default + at Hash + at PartialEq + at PartialEq, Eq + at PartialEq, PartialOrd + at PartialEq, Eq, PartialOrd, Ord + "#]], + ); + } + + #[test] + fn no_completion_for_incorrect_derive() { + check( + r#" +#[derive{$0)] +struct Test {} +"#, + expect![[r#""#]], + ) + } + + #[test] + fn derive_with_input_completion() { + check( + r#" +#[derive(serde::Serialize, PartialEq, $0)] +struct Test {} +"#, + expect![[r#" + at Clone + at Clone, Copy + at Debug + at Default + at Hash + at Eq + at PartialOrd + at Eq, PartialOrd, Ord + "#]], + ) + } +} diff --git a/crates/ide_completion/src/completions/attribute/lint.rs b/crates/ide_completion/src/completions/attribute/lint.rs new file mode 100644 index 000000000..1f9873d3c --- /dev/null +++ b/crates/ide_completion/src/completions/attribute/lint.rs @@ -0,0 +1,153 @@ +use syntax::ast; + +use crate::{ + context::CompletionContext, + item::{CompletionItem, CompletionItemKind, CompletionKind}, + Completions, +}; + +pub(super) fn complete_lint( + acc: &mut Completions, + ctx: &CompletionContext, + derive_input: ast::TokenTree, + lints_completions: &[LintCompletion], +) { + if let Ok(existing_lints) = super::parse_comma_sep_input(derive_input) { + for lint_completion in lints_completions + .into_iter() + .filter(|completion| !existing_lints.contains(completion.label)) + { + let mut item = CompletionItem::new( + CompletionKind::Attribute, + ctx.source_range(), + lint_completion.label, + ); + item.kind(CompletionItemKind::Attribute).detail(lint_completion.description); + item.add_to(acc) + } + } +} + +pub(crate) struct LintCompletion { + pub(crate) label: &'static str, + pub(crate) description: &'static str, +} + +#[rustfmt::skip] +pub(super) const DEFAULT_LINT_COMPLETIONS: &[LintCompletion] = &[ + LintCompletion { label: "absolute_paths_not_starting_with_crate", description: r#"fully qualified paths that start with a module name instead of `crate`, `self`, or an extern crate name"# }, + LintCompletion { label: "anonymous_parameters", description: r#"detects anonymous parameters"# }, + LintCompletion { label: "box_pointers", description: r#"use of owned (Box type) heap memory"# }, + LintCompletion { label: "deprecated_in_future", description: r#"detects use of items that will be deprecated in a future version"# }, + LintCompletion { label: "elided_lifetimes_in_paths", description: r#"hidden lifetime parameters in types are deprecated"# }, + LintCompletion { label: "explicit_outlives_requirements", description: r#"outlives requirements can be inferred"# }, + LintCompletion { label: "indirect_structural_match", description: r#"pattern with const indirectly referencing non-structural-match type"# }, + LintCompletion { label: "keyword_idents", description: r#"detects edition keywords being used as an identifier"# }, + LintCompletion { label: "macro_use_extern_crate", description: r#"the `#[macro_use]` attribute is now deprecated in favor of using macros via the module system"# }, + LintCompletion { label: "meta_variable_misuse", description: r#"possible meta-variable misuse at macro definition"# }, + LintCompletion { label: "missing_copy_implementations", description: r#"detects potentially-forgotten implementations of `Copy`"# }, + LintCompletion { label: "missing_crate_level_docs", description: r#"detects crates with no crate-level documentation"# }, + LintCompletion { label: "missing_debug_implementations", description: r#"detects missing implementations of Debug"# }, + LintCompletion { label: "missing_docs", description: r#"detects missing documentation for public members"# }, + LintCompletion { label: "missing_doc_code_examples", description: r#"detects publicly-exported items without code samples in their documentation"# }, + LintCompletion { label: "non_ascii_idents", description: r#"detects non-ASCII identifiers"# }, + LintCompletion { label: "private_doc_tests", description: r#"detects code samples in docs of private items not documented by rustdoc"# }, + LintCompletion { label: "single_use_lifetimes", description: r#"detects lifetime parameters that are only used once"# }, + LintCompletion { label: "trivial_casts", description: r#"detects trivial casts which could be removed"# }, + LintCompletion { label: "trivial_numeric_casts", description: r#"detects trivial casts of numeric types which could be removed"# }, + LintCompletion { label: "unaligned_references", description: r#"detects unaligned references to fields of packed structs"# }, + LintCompletion { label: "unreachable_pub", description: r#"`pub` items not reachable from crate root"# }, + LintCompletion { label: "unsafe_code", description: r#"usage of `unsafe` code"# }, + LintCompletion { label: "unsafe_op_in_unsafe_fn", description: r#"unsafe operations in unsafe functions without an explicit unsafe block are deprecated"# }, + LintCompletion { label: "unstable_features", description: r#"enabling unstable features (deprecated. do not use)"# }, + LintCompletion { label: "unused_crate_dependencies", description: r#"crate dependencies that are never used"# }, + LintCompletion { label: "unused_extern_crates", description: r#"extern crates that are never used"# }, + LintCompletion { label: "unused_import_braces", description: r#"unnecessary braces around an imported item"# }, + LintCompletion { label: "unused_lifetimes", description: r#"detects lifetime parameters that are never used"# }, + LintCompletion { label: "unused_qualifications", description: r#"detects unnecessarily qualified names"# }, + LintCompletion { label: "unused_results", description: r#"unused result of an expression in a statement"# }, + LintCompletion { label: "variant_size_differences", description: r#"detects enums with widely varying variant sizes"# }, + LintCompletion { label: "array_into_iter", description: r#"detects calling `into_iter` on arrays"# }, + LintCompletion { label: "asm_sub_register", description: r#"using only a subset of a register for inline asm inputs"# }, + LintCompletion { label: "bare_trait_objects", description: r#"suggest using `dyn Trait` for trait objects"# }, + LintCompletion { label: "bindings_with_variant_name", description: r#"detects pattern bindings with the same name as one of the matched variants"# }, + LintCompletion { label: "cenum_impl_drop_cast", description: r#"a C-like enum implementing Drop is cast"# }, + LintCompletion { label: "clashing_extern_declarations", description: r#"detects when an extern fn has been declared with the same name but different types"# }, + LintCompletion { label: "coherence_leak_check", description: r#"distinct impls distinguished only by the leak-check code"# }, + LintCompletion { label: "confusable_idents", description: r#"detects visually confusable pairs between identifiers"# }, + LintCompletion { label: "dead_code", description: r#"detect unused, unexported items"# }, + LintCompletion { label: "deprecated", description: r#"detects use of deprecated items"# }, + LintCompletion { label: "ellipsis_inclusive_range_patterns", description: r#"`...` range patterns are deprecated"# }, + LintCompletion { label: "exported_private_dependencies", description: r#"public interface leaks type from a private dependency"# }, + LintCompletion { label: "illegal_floating_point_literal_pattern", description: r#"floating-point literals cannot be used in patterns"# }, + LintCompletion { label: "improper_ctypes", description: r#"proper use of libc types in foreign modules"# }, + LintCompletion { label: "improper_ctypes_definitions", description: r#"proper use of libc types in foreign item definitions"# }, + LintCompletion { label: "incomplete_features", description: r#"incomplete features that may function improperly in some or all cases"# }, + LintCompletion { label: "inline_no_sanitize", description: r#"detects incompatible use of `#[inline(always)]` and `#[no_sanitize(...)]`"# }, + LintCompletion { label: "intra_doc_link_resolution_failure", description: r#"failures in resolving intra-doc link targets"# }, + LintCompletion { label: "invalid_codeblock_attributes", description: r#"codeblock attribute looks a lot like a known one"# }, + LintCompletion { label: "invalid_value", description: r#"an invalid value is being created (such as a NULL reference)"# }, + LintCompletion { label: "irrefutable_let_patterns", description: r#"detects irrefutable patterns in if-let and while-let statements"# }, + LintCompletion { label: "late_bound_lifetime_arguments", description: r#"detects generic lifetime arguments in path segments with late bound lifetime parameters"# }, + LintCompletion { label: "mixed_script_confusables", description: r#"detects Unicode scripts whose mixed script confusables codepoints are solely used"# }, + LintCompletion { label: "mutable_borrow_reservation_conflict", description: r#"reservation of a two-phased borrow conflicts with other shared borrows"# }, + LintCompletion { label: "non_camel_case_types", description: r#"types, variants, traits and type parameters should have camel case names"# }, + LintCompletion { label: "non_shorthand_field_patterns", description: r#"using `Struct { x: x }` instead of `Struct { x }` in a pattern"# }, + LintCompletion { label: "non_snake_case", description: r#"variables, methods, functions, lifetime parameters and modules should have snake case names"# }, + LintCompletion { label: "non_upper_case_globals", description: r#"static constants should have uppercase identifiers"# }, + LintCompletion { label: "no_mangle_generic_items", description: r#"generic items must be mangled"# }, + LintCompletion { label: "overlapping_patterns", description: r#"detects overlapping patterns"# }, + LintCompletion { label: "path_statements", description: r#"path statements with no effect"# }, + LintCompletion { label: "private_in_public", description: r#"detect private items in public interfaces not caught by the old implementation"# }, + LintCompletion { label: "proc_macro_derive_resolution_fallback", description: r#"detects proc macro derives using inaccessible names from parent modules"# }, + LintCompletion { label: "redundant_semicolons", description: r#"detects unnecessary trailing semicolons"# }, + LintCompletion { label: "renamed_and_removed_lints", description: r#"lints that have been renamed or removed"# }, + LintCompletion { label: "safe_packed_borrows", description: r#"safe borrows of fields of packed structs were erroneously allowed"# }, + LintCompletion { label: "stable_features", description: r#"stable features found in `#[feature]` directive"# }, + LintCompletion { label: "trivial_bounds", description: r#"these bounds don't depend on an type parameters"# }, + LintCompletion { label: "type_alias_bounds", description: r#"bounds in type aliases are not enforced"# }, + LintCompletion { label: "tyvar_behind_raw_pointer", description: r#"raw pointer to an inference variable"# }, + LintCompletion { label: "uncommon_codepoints", description: r#"detects uncommon Unicode codepoints in identifiers"# }, + LintCompletion { label: "unconditional_recursion", description: r#"functions that cannot return without calling themselves"# }, + LintCompletion { label: "unknown_lints", description: r#"unrecognized lint attribute"# }, + LintCompletion { label: "unnameable_test_items", description: r#"detects an item that cannot be named being marked as `#[test_case]`"# }, + LintCompletion { label: "unreachable_code", description: r#"detects unreachable code paths"# }, + LintCompletion { label: "unreachable_patterns", description: r#"detects unreachable patterns"# }, + LintCompletion { label: "unstable_name_collisions", description: r#"detects name collision with an existing but unstable method"# }, + LintCompletion { label: "unused_allocation", description: r#"detects unnecessary allocations that can be eliminated"# }, + LintCompletion { label: "unused_assignments", description: r#"detect assignments that will never be read"# }, + LintCompletion { label: "unused_attributes", description: r#"detects attributes that were not used by the compiler"# }, + LintCompletion { label: "unused_braces", description: r#"unnecessary braces around an expression"# }, + LintCompletion { label: "unused_comparisons", description: r#"comparisons made useless by limits of the types involved"# }, + LintCompletion { label: "unused_doc_comments", description: r#"detects doc comments that aren't used by rustdoc"# }, + LintCompletion { label: "unused_features", description: r#"unused features found in crate-level `#[feature]` directives"# }, + LintCompletion { label: "unused_imports", description: r#"imports that are never used"# }, + LintCompletion { label: "unused_labels", description: r#"detects labels that are never used"# }, + LintCompletion { label: "unused_macros", description: r#"detects macros that were not used"# }, + LintCompletion { label: "unused_must_use", description: r#"unused result of a type flagged as `#[must_use]`"# }, + LintCompletion { label: "unused_mut", description: r#"detect mut variables which don't need to be mutable"# }, + LintCompletion { label: "unused_parens", description: r#"`if`, `match`, `while` and `return` do not need parentheses"# }, + LintCompletion { label: "unused_unsafe", description: r#"unnecessary use of an `unsafe` block"# }, + LintCompletion { label: "unused_variables", description: r#"detect variables which are not used in any way"# }, + LintCompletion { label: "warnings", description: r#"mass-change the level for lints which produce warnings"# }, + LintCompletion { label: "where_clauses_object_safety", description: r#"checks the object safety of where clauses"# }, + LintCompletion { label: "while_true", description: r#"suggest using `loop { }` instead of `while true { }`"# }, + LintCompletion { label: "ambiguous_associated_items", description: r#"ambiguous associated items"# }, + LintCompletion { label: "arithmetic_overflow", description: r#"arithmetic operation overflows"# }, + LintCompletion { label: "conflicting_repr_hints", description: r#"conflicts between `#[repr(..)]` hints that were previously accepted and used in practice"# }, + LintCompletion { label: "const_err", description: r#"constant evaluation detected erroneous expression"# }, + LintCompletion { label: "ill_formed_attribute_input", description: r#"ill-formed attribute inputs that were previously accepted and used in practice"# }, + LintCompletion { label: "incomplete_include", description: r#"trailing content in included file"# }, + LintCompletion { label: "invalid_type_param_default", description: r#"type parameter default erroneously allowed in invalid location"# }, + LintCompletion { label: "macro_expanded_macro_exports_accessed_by_absolute_paths", description: r#"macro-expanded `macro_export` macros from the current crate cannot be referred to by absolute paths"# }, + LintCompletion { label: "missing_fragment_specifier", description: r#"detects missing fragment specifiers in unused `macro_rules!` patterns"# }, + LintCompletion { label: "mutable_transmutes", description: r#"mutating transmuted &mut T from &T may cause undefined behavior"# }, + LintCompletion { label: "no_mangle_const_items", description: r#"const items will not have their symbols exported"# }, + LintCompletion { label: "order_dependent_trait_objects", description: r#"trait-object types were treated as different depending on marker-trait order"# }, + LintCompletion { label: "overflowing_literals", description: r#"literal out of range for its type"# }, + LintCompletion { label: "patterns_in_fns_without_body", description: r#"patterns in functions without body were erroneously allowed"# }, + LintCompletion { label: "pub_use_of_private_extern_crate", description: r#"detect public re-exports of private extern crates"# }, + LintCompletion { label: "soft_unstable", description: r#"a feature gate that doesn't break dependent crates"# }, + LintCompletion { label: "unconditional_panic", description: r#"operation will cause a panic at runtime"# }, + LintCompletion { label: "unknown_crate_types", description: r#"unknown crate type found in `#[crate_type]` directive"# }, +]; -- cgit v1.2.3 From 594270be49fbd6e7aee9a36afab02920fd771706 Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Fri, 28 May 2021 00:35:21 +0200 Subject: tt muncher time --- crates/ide_completion/src/completions/attribute.rs | 82 +++++++++++++++------- .../src/completions/attribute/derive.rs | 1 + .../src/completions/attribute/lint.rs | 1 + 3 files changed, 57 insertions(+), 27 deletions(-) (limited to 'crates') diff --git a/crates/ide_completion/src/completions/attribute.rs b/crates/ide_completion/src/completions/attribute.rs index e128e307c..246a3270a 100644 --- a/crates/ide_completion/src/completions/attribute.rs +++ b/crates/ide_completion/src/completions/attribute.rs @@ -109,42 +109,70 @@ const fn attr( } macro_rules! attrs { - [$($($mac:ident!),+;)? $($key:literal),*] => { - &["allow", "cfg", "cfg_attr", "deny", "forbid", "warn", $($($mac!()),+,)? $($key),*] as _ - } -} -macro_rules! item_attrs { - () => { - "deprecated" + [@ { item $($tt:tt)* } {$($acc:tt)*}] => { + attrs!(@ { $($tt)* } { $($acc)*, "deprecated", "doc", "dochidden", "docalias", "must_use", "no_mangle" }) + }; + [@ { adt $($tt:tt)* } {$($acc:tt)*}] => { + attrs!(@ { $($tt)* } { $($acc)*, "derive", "repr" }) + }; + [@ { linkable $($tt:tt)* } {$($acc:tt)*}] => { + attrs!(@ { $($tt)* } { $($acc)*, "export_name", "link_name", "link_section" }) }; + [@ { $ty:ident $($tt:tt)* } {$($acc:tt)*}] => { compile_error!(concat!("unknown attr subtype ", stringify!($ty))) + }; + [@ { $lit:literal $($tt:tt)*} {$($acc:tt)*}] => { + attrs!(@ { $($tt)* } { $($acc)*, $lit }) + }; + [@ {$($tt:tt)+} {$($tt2:tt)*}] => { + compile_error!(concat!("Unexpected input ", stringify!($($tt)+))) + }; + [@ {} {$($tt:tt)*}] => { &[$($tt)*] as _ }; + [$($tt:tt),*] => { + attrs!(@ { $($tt)* } { "allow", "cfg", "cfg_attr", "deny", "forbid", "warn" }) }; } +#[rustfmt::skip] static KIND_TO_ATTRIBUTES: Lazy> = Lazy::new(|| { std::array::IntoIter::new([ - (SyntaxKind::SOURCE_FILE, attrs!(item_attrs!;"crate_name")), - (SyntaxKind::MODULE, attrs!(item_attrs!;)), - (SyntaxKind::ITEM_LIST, attrs!(item_attrs!;)), - (SyntaxKind::MACRO_RULES, attrs!(item_attrs!;)), - (SyntaxKind::MACRO_DEF, attrs!(item_attrs!;)), - (SyntaxKind::EXTERN_CRATE, attrs!(item_attrs!;)), - (SyntaxKind::USE, attrs!(item_attrs!;)), - (SyntaxKind::FN, attrs!(item_attrs!;"cold", "must_use")), - (SyntaxKind::TYPE_ALIAS, attrs!(item_attrs!;)), - (SyntaxKind::STRUCT, attrs!(item_attrs!;"must_use")), - (SyntaxKind::ENUM, attrs!(item_attrs!;"must_use")), - (SyntaxKind::UNION, attrs!(item_attrs!;"must_use")), - (SyntaxKind::CONST, attrs!(item_attrs!;)), - (SyntaxKind::STATIC, attrs!(item_attrs!;)), - (SyntaxKind::TRAIT, attrs!(item_attrs!; "must_use")), - (SyntaxKind::IMPL, attrs!(item_attrs!;"automatically_derived")), - (SyntaxKind::ASSOC_ITEM_LIST, attrs!(item_attrs!;)), - (SyntaxKind::EXTERN_BLOCK, attrs!(item_attrs!;)), - (SyntaxKind::EXTERN_ITEM_LIST, attrs!(item_attrs!;)), + ( + SyntaxKind::SOURCE_FILE, + attrs!( + item, + "crate_name", "feature", "no_implicit_prelude", "no_main", "no_std", + "recursion_limit", "type_length_limit", "windows_subsystem" + ), + ), + (SyntaxKind::MODULE, attrs!(item, "no_implicit_prelude", "path")), + (SyntaxKind::ITEM_LIST, attrs!(item, "no_implicit_prelude")), + (SyntaxKind::MACRO_RULES, attrs!(item, "macro_export", "macro_use")), + (SyntaxKind::MACRO_DEF, attrs!(item)), + (SyntaxKind::EXTERN_CRATE, attrs!(item, "macro_use", "no_link")), + (SyntaxKind::USE, attrs!(item)), + (SyntaxKind::TYPE_ALIAS, attrs!(item)), + (SyntaxKind::STRUCT, attrs!(item, adt, "non_exhaustive")), + (SyntaxKind::ENUM, attrs!(item, adt, "non_exhaustive")), + (SyntaxKind::UNION, attrs!(item, adt)), + (SyntaxKind::CONST, attrs!(item)), + ( + SyntaxKind::FN, + attrs!( + item, linkable, + "cold", "ignore", "inline", "must_use", "panic_handler", "proc_macro", + "proc_macro_derive", "proc_macro_attribute", "should_panic", "target_feature", + "test", "track_caller" + ), + ), + (SyntaxKind::STATIC, attrs!(item, linkable, "global_allocator", "used")), + (SyntaxKind::TRAIT, attrs!(item, "must_use")), + (SyntaxKind::IMPL, attrs!(item, "automatically_derived")), + (SyntaxKind::ASSOC_ITEM_LIST, attrs!(item)), + (SyntaxKind::EXTERN_BLOCK, attrs!(item, "link")), + (SyntaxKind::EXTERN_ITEM_LIST, attrs!(item, "link")), (SyntaxKind::MACRO_CALL, attrs!()), (SyntaxKind::SELF_PARAM, attrs!()), (SyntaxKind::PARAM, attrs!()), (SyntaxKind::RECORD_FIELD, attrs!()), - (SyntaxKind::VARIANT, attrs!()), + (SyntaxKind::VARIANT, attrs!("non_exhaustive")), (SyntaxKind::TYPE_PARAM, attrs!()), (SyntaxKind::CONST_PARAM, attrs!()), (SyntaxKind::LIFETIME_PARAM, attrs!()), diff --git a/crates/ide_completion/src/completions/attribute/derive.rs b/crates/ide_completion/src/completions/attribute/derive.rs index c14b03ea4..c213e4792 100644 --- a/crates/ide_completion/src/completions/attribute/derive.rs +++ b/crates/ide_completion/src/completions/attribute/derive.rs @@ -1,3 +1,4 @@ +//! Completion for derives use itertools::Itertools; use rustc_hash::FxHashSet; use syntax::ast; diff --git a/crates/ide_completion/src/completions/attribute/lint.rs b/crates/ide_completion/src/completions/attribute/lint.rs index 1f9873d3c..8815e5867 100644 --- a/crates/ide_completion/src/completions/attribute/lint.rs +++ b/crates/ide_completion/src/completions/attribute/lint.rs @@ -1,3 +1,4 @@ +//! Completion for lints use syntax::ast; use crate::{ -- cgit v1.2.3 From 0724bd0f21e5f7294ee656a89597de9e6df65d29 Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Fri, 28 May 2021 00:54:52 +0200 Subject: Add attribute completion tests --- crates/ide_completion/src/completions/attribute.rs | 407 ++++++++++++++++++++- 1 file changed, 399 insertions(+), 8 deletions(-) (limited to 'crates') diff --git a/crates/ide_completion/src/completions/attribute.rs b/crates/ide_completion/src/completions/attribute.rs index 246a3270a..79a9c6d87 100644 --- a/crates/ide_completion/src/completions/attribute.rs +++ b/crates/ide_completion/src/completions/attribute.rs @@ -19,10 +19,6 @@ mod lint; pub(crate) use self::lint::LintCompletion; pub(crate) fn complete_attribute(acc: &mut Completions, ctx: &CompletionContext) -> Option<()> { - if ctx.mod_declaration_under_caret.is_some() { - return None; - } - let attribute = ctx.attribute_under_caret.as_ref()?; match (attribute.path().and_then(|p| p.as_single_name_ref()), attribute.token_tree()) { (Some(path), Some(token_tree)) => match path.text().as_str() { @@ -322,13 +318,281 @@ mod tests { expect.assert_eq(&actual); } + #[test] + fn complete_attribute_on_source_file() { + check( + r#"#![$0]"#, + expect![[r#" + at allow(…) + at cfg(…) + at cfg_attr(…) + at deny(…) + at forbid(…) + at warn(…) + at deprecated + at doc = "…" + at doc(hidden) + at doc(alias = "…") + at must_use + at no_mangle + at crate_name = "" + at feature(…) + at no_implicit_prelude + at no_main + at no_std + at recursion_limit = … + at type_length_limit = … + at windows_subsystem = "…" + "#]], + ); + } + + #[test] + fn complete_attribute_on_module() { + check( + r#"#[$0] mod foo;"#, + expect![[r#" + at allow(…) + at cfg(…) + at cfg_attr(…) + at deny(…) + at forbid(…) + at warn(…) + at deprecated + at doc = "…" + at doc(hidden) + at doc(alias = "…") + at must_use + at no_mangle + at path = "…" + "#]], + ); + check( + r#"mod foo {#![$0]}"#, + expect![[r#" + at allow(…) + at cfg(…) + at cfg_attr(…) + at deny(…) + at forbid(…) + at warn(…) + at deprecated + at doc = "…" + at doc(hidden) + at doc(alias = "…") + at must_use + at no_mangle + at no_implicit_prelude + "#]], + ); + } + + #[test] + fn complete_attribute_on_macro_rules() { + check( + r#"#[$0] macro_rules! foo {}"#, + expect![[r#" + at allow(…) + at cfg(…) + at cfg_attr(…) + at deny(…) + at forbid(…) + at warn(…) + at deprecated + at doc = "…" + at doc(hidden) + at doc(alias = "…") + at must_use + at no_mangle + at macro_export + at macro_use + "#]], + ); + } + + #[test] + fn complete_attribute_on_macro_def() { + check( + r#"#[$0] macro foo {}"#, + expect![[r#" + at allow(…) + at cfg(…) + at cfg_attr(…) + at deny(…) + at forbid(…) + at warn(…) + at deprecated + at doc = "…" + at doc(hidden) + at doc(alias = "…") + at must_use + at no_mangle + "#]], + ); + } + + #[test] + fn complete_attribute_on_extern_crate() { + check( + r#"#[$0] extern crate foo;"#, + expect![[r#" + at allow(…) + at cfg(…) + at cfg_attr(…) + at deny(…) + at forbid(…) + at warn(…) + at deprecated + at doc = "…" + at doc(hidden) + at doc(alias = "…") + at must_use + at no_mangle + at macro_use + "#]], + ); + } + + #[test] + fn complete_attribute_on_use() { + check( + r#"#[$0] use foo;"#, + expect![[r#" + at allow(…) + at cfg(…) + at cfg_attr(…) + at deny(…) + at forbid(…) + at warn(…) + at deprecated + at doc = "…" + at doc(hidden) + at doc(alias = "…") + at must_use + at no_mangle + "#]], + ); + } + + #[test] + fn complete_attribute_on_type_alias() { + check( + r#"#[$0] type foo = ();"#, + expect![[r#" + at allow(…) + at cfg(…) + at cfg_attr(…) + at deny(…) + at forbid(…) + at warn(…) + at deprecated + at doc = "…" + at doc(hidden) + at doc(alias = "…") + at must_use + at no_mangle + "#]], + ); + } + #[test] fn complete_attribute_on_struct() { check( - r#" -#[$0] -struct Test {} - "#, + r#"#[$0] struct Foo;"#, + expect![[r#" + at allow(…) + at cfg(…) + at cfg_attr(…) + at deny(…) + at forbid(…) + at warn(…) + at deprecated + at doc = "…" + at doc(hidden) + at doc(alias = "…") + at must_use + at no_mangle + at derive(…) + at repr(…) + at non_exhaustive + "#]], + ); + } + + #[test] + fn complete_attribute_on_enum() { + check( + r#"#[$0] enum Foo {}"#, + expect![[r#" + at allow(…) + at cfg(…) + at cfg_attr(…) + at deny(…) + at forbid(…) + at warn(…) + at deprecated + at doc = "…" + at doc(hidden) + at doc(alias = "…") + at must_use + at no_mangle + at derive(…) + at repr(…) + at non_exhaustive + "#]], + ); + } + + #[test] + fn complete_attribute_on_const() { + check( + r#"#[$0] const FOO: () = ();"#, + expect![[r#" + at allow(…) + at cfg(…) + at cfg_attr(…) + at deny(…) + at forbid(…) + at warn(…) + at deprecated + at doc = "…" + at doc(hidden) + at doc(alias = "…") + at must_use + at no_mangle + "#]], + ); + } + + #[test] + fn complete_attribute_on_static() { + check( + r#"#[$0] static FOO: () = ()"#, + expect![[r#" + at allow(…) + at cfg(…) + at cfg_attr(…) + at deny(…) + at forbid(…) + at warn(…) + at deprecated + at doc = "…" + at doc(hidden) + at doc(alias = "…") + at must_use + at no_mangle + at export_name = "…" + at link_name = "…" + at link_section = "…" + at used + "#]], + ); + } + + #[test] + fn complete_attribute_on_trait() { + check( + r#"#[$0] trait Foo {}"#, expect![[r#" at allow(…) at cfg(…) @@ -337,10 +601,137 @@ struct Test {} at forbid(…) at warn(…) at deprecated + at doc = "…" + at doc(hidden) + at doc(alias = "…") + at must_use + at no_mangle at must_use "#]], ); } + + #[test] + fn complete_attribute_on_impl() { + check( + r#"#[$0] impl () {}"#, + expect![[r#" + at allow(…) + at cfg(…) + at cfg_attr(…) + at deny(…) + at forbid(…) + at warn(…) + at deprecated + at doc = "…" + at doc(hidden) + at doc(alias = "…") + at must_use + at no_mangle + at automatically_derived + "#]], + ); + check( + r#"impl () {#![$0]}"#, + expect![[r#" + at allow(…) + at cfg(…) + at cfg_attr(…) + at deny(…) + at forbid(…) + at warn(…) + at deprecated + at doc = "…" + at doc(hidden) + at doc(alias = "…") + at must_use + at no_mangle + "#]], + ); + } + + #[test] + fn complete_attribute_on_extern_block() { + check( + r#"#[$0] extern {}"#, + expect![[r#" + at allow(…) + at cfg(…) + at cfg_attr(…) + at deny(…) + at forbid(…) + at warn(…) + at deprecated + at doc = "…" + at doc(hidden) + at doc(alias = "…") + at must_use + at no_mangle + at link + "#]], + ); + check( + r#"extern {#![$0]}"#, + expect![[r#" + at allow(…) + at cfg(…) + at cfg_attr(…) + at deny(…) + at forbid(…) + at warn(…) + at deprecated + at doc = "…" + at doc(hidden) + at doc(alias = "…") + at must_use + at no_mangle + at link + "#]], + ); + } + + #[test] + fn complete_attribute_on_variant() { + check( + r#"enum Foo { #[$0] Bar }"#, + expect![[r#" + at allow(…) + at cfg(…) + at cfg_attr(…) + at deny(…) + at forbid(…) + at warn(…) + at non_exhaustive + "#]], + ); + } + + #[test] + fn complete_attribute_on_expr() { + check( + r#"fn main() { #[$0] foo() }"#, + expect![[r#" + at allow(…) + at cfg(…) + at cfg_attr(…) + at deny(…) + at forbid(…) + at warn(…) + "#]], + ); + check( + r#"fn main() { #[$0] foo(); }"#, + expect![[r#" + at allow(…) + at cfg(…) + at cfg_attr(…) + at deny(…) + at forbid(…) + at warn(…) + "#]], + ); + } + #[test] fn test_attribute_completion_inside_nested_attr() { check(r#"#[cfg($0)]"#, expect![[]]) -- cgit v1.2.3 From 411eee76147b0730e1eb5afe84d13558de2ee082 Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Fri, 28 May 2021 01:09:22 +0200 Subject: Add another attribute completion test --- crates/ide_completion/src/completions/attribute.rs | 25 +++++++++++++++++----- 1 file changed, 20 insertions(+), 5 deletions(-) (limited to 'crates') diff --git a/crates/ide_completion/src/completions/attribute.rs b/crates/ide_completion/src/completions/attribute.rs index 79a9c6d87..8b018c32f 100644 --- a/crates/ide_completion/src/completions/attribute.rs +++ b/crates/ide_completion/src/completions/attribute.rs @@ -318,6 +318,26 @@ mod tests { expect.assert_eq(&actual); } + #[test] + fn test_attribute_completion_inside_nested_attr() { + check(r#"#[cfg($0)]"#, expect![[]]) + } + + #[test] + fn test_attribute_completion_with_existing_attr() { + check( + r#"#[no_mangle] #[$0] mcall!();"#, + expect![[r#" + at allow(…) + at cfg(…) + at cfg_attr(…) + at deny(…) + at forbid(…) + at warn(…) + "#]], + ) + } + #[test] fn complete_attribute_on_source_file() { check( @@ -731,9 +751,4 @@ mod tests { "#]], ); } - - #[test] - fn test_attribute_completion_inside_nested_attr() { - check(r#"#[cfg($0)]"#, expect![[]]) - } } -- cgit v1.2.3 From c9f0f47bbba3d02a6389af14aaf1c3d1d088d191 Mon Sep 17 00:00:00 2001 From: Lukas Wirth Date: Sat, 29 May 2021 14:02:06 +0200 Subject: simplify --- crates/ide_completion/src/completions/attribute.rs | 173 +++++++++++---------- .../src/completions/attribute/derive.rs | 2 +- .../src/completions/attribute/lint.rs | 2 +- 3 files changed, 92 insertions(+), 85 deletions(-) (limited to 'crates') diff --git a/crates/ide_completion/src/completions/attribute.rs b/crates/ide_completion/src/completions/attribute.rs index 8b018c32f..610fec65a 100644 --- a/crates/ide_completion/src/completions/attribute.rs +++ b/crates/ide_completion/src/completions/attribute.rs @@ -3,9 +3,11 @@ //! This module uses a bit of static metadata to provide completions //! for built-in attributes. +use std::mem; + use once_cell::sync::Lazy; use rustc_hash::{FxHashMap, FxHashSet}; -use syntax::{ast, AstNode, SyntaxKind, T}; +use syntax::{ast, AstNode, NodeOrToken, SyntaxKind, T}; use crate::{ context::CompletionContext, @@ -105,23 +107,32 @@ const fn attr( } macro_rules! attrs { + // attributes applicable to all items [@ { item $($tt:tt)* } {$($acc:tt)*}] => { attrs!(@ { $($tt)* } { $($acc)*, "deprecated", "doc", "dochidden", "docalias", "must_use", "no_mangle" }) }; + // attributes applicable to all adts [@ { adt $($tt:tt)* } {$($acc:tt)*}] => { attrs!(@ { $($tt)* } { $($acc)*, "derive", "repr" }) }; + // attributes applicable to all linkable things aka functions/statics [@ { linkable $($tt:tt)* } {$($acc:tt)*}] => { - attrs!(@ { $($tt)* } { $($acc)*, "export_name", "link_name", "link_section" }) }; - [@ { $ty:ident $($tt:tt)* } {$($acc:tt)*}] => { compile_error!(concat!("unknown attr subtype ", stringify!($ty))) + attrs!(@ { $($tt)* } { $($acc)*, "export_name", "link_name", "link_section" }) + }; + // error fallback for nicer error message + [@ { $ty:ident $($tt:tt)* } {$($acc:tt)*}] => { + compile_error!(concat!("unknown attr subtype ", stringify!($ty))) }; + // general push down accumulation [@ { $lit:literal $($tt:tt)*} {$($acc:tt)*}] => { attrs!(@ { $($tt)* } { $($acc)*, $lit }) }; [@ {$($tt:tt)+} {$($tt2:tt)*}] => { compile_error!(concat!("Unexpected input ", stringify!($($tt)+))) }; + // final output construction [@ {} {$($tt:tt)*}] => { &[$($tt)*] as _ }; + // starting matcher [$($tt:tt),*] => { attrs!(@ { $($tt)* } { "allow", "cfg", "cfg_attr", "deny", "forbid", "warn" }) }; @@ -129,28 +140,29 @@ macro_rules! attrs { #[rustfmt::skip] static KIND_TO_ATTRIBUTES: Lazy> = Lazy::new(|| { + use SyntaxKind::*; std::array::IntoIter::new([ ( - SyntaxKind::SOURCE_FILE, + SOURCE_FILE, attrs!( item, "crate_name", "feature", "no_implicit_prelude", "no_main", "no_std", "recursion_limit", "type_length_limit", "windows_subsystem" ), ), - (SyntaxKind::MODULE, attrs!(item, "no_implicit_prelude", "path")), - (SyntaxKind::ITEM_LIST, attrs!(item, "no_implicit_prelude")), - (SyntaxKind::MACRO_RULES, attrs!(item, "macro_export", "macro_use")), - (SyntaxKind::MACRO_DEF, attrs!(item)), - (SyntaxKind::EXTERN_CRATE, attrs!(item, "macro_use", "no_link")), - (SyntaxKind::USE, attrs!(item)), - (SyntaxKind::TYPE_ALIAS, attrs!(item)), - (SyntaxKind::STRUCT, attrs!(item, adt, "non_exhaustive")), - (SyntaxKind::ENUM, attrs!(item, adt, "non_exhaustive")), - (SyntaxKind::UNION, attrs!(item, adt)), - (SyntaxKind::CONST, attrs!(item)), + (MODULE, attrs!(item, "no_implicit_prelude", "path")), + (ITEM_LIST, attrs!(item, "no_implicit_prelude")), + (MACRO_RULES, attrs!(item, "macro_export", "macro_use")), + (MACRO_DEF, attrs!(item)), + (EXTERN_CRATE, attrs!(item, "macro_use", "no_link")), + (USE, attrs!(item)), + (TYPE_ALIAS, attrs!(item)), + (STRUCT, attrs!(item, adt, "non_exhaustive")), + (ENUM, attrs!(item, adt, "non_exhaustive")), + (UNION, attrs!(item, adt)), + (CONST, attrs!(item)), ( - SyntaxKind::FN, + FN, attrs!( item, linkable, "cold", "ignore", "inline", "must_use", "panic_handler", "proc_macro", @@ -158,29 +170,29 @@ static KIND_TO_ATTRIBUTES: Lazy> = Lazy::new(|| { "test", "track_caller" ), ), - (SyntaxKind::STATIC, attrs!(item, linkable, "global_allocator", "used")), - (SyntaxKind::TRAIT, attrs!(item, "must_use")), - (SyntaxKind::IMPL, attrs!(item, "automatically_derived")), - (SyntaxKind::ASSOC_ITEM_LIST, attrs!(item)), - (SyntaxKind::EXTERN_BLOCK, attrs!(item, "link")), - (SyntaxKind::EXTERN_ITEM_LIST, attrs!(item, "link")), - (SyntaxKind::MACRO_CALL, attrs!()), - (SyntaxKind::SELF_PARAM, attrs!()), - (SyntaxKind::PARAM, attrs!()), - (SyntaxKind::RECORD_FIELD, attrs!()), - (SyntaxKind::VARIANT, attrs!("non_exhaustive")), - (SyntaxKind::TYPE_PARAM, attrs!()), - (SyntaxKind::CONST_PARAM, attrs!()), - (SyntaxKind::LIFETIME_PARAM, attrs!()), - (SyntaxKind::LET_STMT, attrs!()), - (SyntaxKind::EXPR_STMT, attrs!()), - (SyntaxKind::LITERAL, attrs!()), - (SyntaxKind::RECORD_EXPR_FIELD_LIST, attrs!()), - (SyntaxKind::RECORD_EXPR_FIELD, attrs!()), - (SyntaxKind::MATCH_ARM_LIST, attrs!()), - (SyntaxKind::MATCH_ARM, attrs!()), - (SyntaxKind::IDENT_PAT, attrs!()), - (SyntaxKind::RECORD_PAT_FIELD, attrs!()), + (STATIC, attrs!(item, linkable, "global_allocator", "used")), + (TRAIT, attrs!(item, "must_use")), + (IMPL, attrs!(item, "automatically_derived")), + (ASSOC_ITEM_LIST, attrs!(item)), + (EXTERN_BLOCK, attrs!(item, "link")), + (EXTERN_ITEM_LIST, attrs!(item, "link")), + (MACRO_CALL, attrs!()), + (SELF_PARAM, attrs!()), + (PARAM, attrs!()), + (RECORD_FIELD, attrs!()), + (VARIANT, attrs!("non_exhaustive")), + (TYPE_PARAM, attrs!()), + (CONST_PARAM, attrs!()), + (LIFETIME_PARAM, attrs!()), + (LET_STMT, attrs!()), + (EXPR_STMT, attrs!()), + (LITERAL, attrs!()), + (RECORD_EXPR_FIELD_LIST, attrs!()), + (RECORD_EXPR_FIELD, attrs!()), + (MATCH_ARM_LIST, attrs!()), + (MATCH_ARM, attrs!()), + (IDENT_PAT, attrs!()), + (RECORD_PAT_FIELD, attrs!()), ]) .collect() }); @@ -257,62 +269,57 @@ const ATTRIBUTES: &[AttrCompletion] = &[ .prefer_inner(), ]; -#[test] -fn attributes_are_sorted() { - let mut attrs = ATTRIBUTES.iter().map(|attr| attr.key()); - let mut prev = attrs.next().unwrap(); - - attrs.for_each(|next| { - assert!( - prev < next, - r#"Attributes are not sorted, "{}" should come after "{}""#, - prev, - next - ); - prev = next; - }); -} - -fn parse_comma_sep_input(derive_input: ast::TokenTree) -> Result, ()> { - match (derive_input.left_delimiter_token(), derive_input.right_delimiter_token()) { - (Some(left_paren), Some(right_paren)) - if left_paren.kind() == T!['('] && right_paren.kind() == T![')'] => - { - let mut input_derives = FxHashSet::default(); - let mut current_derive = String::new(); - for token in derive_input - .syntax() - .children_with_tokens() - .filter_map(|token| token.into_token()) - .skip_while(|token| token != &left_paren) - .skip(1) - .take_while(|token| token != &right_paren) - { - if T![,] == token.kind() { - if !current_derive.is_empty() { - input_derives.insert(current_derive); - current_derive = String::new(); - } - } else { - current_derive.push_str(token.text().trim()); - } - } - +fn parse_comma_sep_input(derive_input: ast::TokenTree) -> Option> { + let (l_paren, r_paren) = derive_input.l_paren_token().zip(derive_input.r_paren_token())?; + let mut input_derives = FxHashSet::default(); + let mut current_derive = String::new(); + for token in derive_input + .syntax() + .children_with_tokens() + .filter_map(NodeOrToken::into_token) + .skip_while(|token| token != &l_paren) + .skip(1) + .take_while(|token| token != &r_paren) + { + if token.kind() == T![,] { if !current_derive.is_empty() { - input_derives.insert(current_derive); + input_derives.insert(mem::take(&mut current_derive)); } - Ok(input_derives) + } else { + current_derive.push_str(token.text().trim()); } - _ => Err(()), } + + if !current_derive.is_empty() { + input_derives.insert(current_derive); + } + Some(input_derives) } #[cfg(test)] mod tests { + use super::*; + use expect_test::{expect, Expect}; use crate::{test_utils::completion_list, CompletionKind}; + #[test] + fn attributes_are_sorted() { + let mut attrs = ATTRIBUTES.iter().map(|attr| attr.key()); + let mut prev = attrs.next().unwrap(); + + attrs.for_each(|next| { + assert!( + prev < next, + r#"ATTRIBUTES array is not sorted, "{}" should come after "{}""#, + prev, + next + ); + prev = next; + }); + } + fn check(ra_fixture: &str, expect: Expect) { let actual = completion_list(ra_fixture, CompletionKind::Attribute); expect.assert_eq(&actual); diff --git a/crates/ide_completion/src/completions/attribute/derive.rs b/crates/ide_completion/src/completions/attribute/derive.rs index c213e4792..7b0a778a2 100644 --- a/crates/ide_completion/src/completions/attribute/derive.rs +++ b/crates/ide_completion/src/completions/attribute/derive.rs @@ -14,7 +14,7 @@ pub(super) fn complete_derive( ctx: &CompletionContext, derive_input: ast::TokenTree, ) { - if let Ok(existing_derives) = super::parse_comma_sep_input(derive_input) { + if let Some(existing_derives) = super::parse_comma_sep_input(derive_input) { for derive_completion in DEFAULT_DERIVE_COMPLETIONS .iter() .filter(|completion| !existing_derives.contains(completion.label)) diff --git a/crates/ide_completion/src/completions/attribute/lint.rs b/crates/ide_completion/src/completions/attribute/lint.rs index 8815e5867..115c6cfe0 100644 --- a/crates/ide_completion/src/completions/attribute/lint.rs +++ b/crates/ide_completion/src/completions/attribute/lint.rs @@ -13,7 +13,7 @@ pub(super) fn complete_lint( derive_input: ast::TokenTree, lints_completions: &[LintCompletion], ) { - if let Ok(existing_lints) = super::parse_comma_sep_input(derive_input) { + if let Some(existing_lints) = super::parse_comma_sep_input(derive_input) { for lint_completion in lints_completions .into_iter() .filter(|completion| !existing_lints.contains(completion.label)) -- cgit v1.2.3