mirror of
https://github.com/rust-lang/rust-analyzer
synced 2024-12-27 05:23:24 +00:00
Merge #9138
9138: feat: Implement hover for lints r=Veykril a=Veykril fixes https://github.com/rust-analyzer/rust-analyzer/issues/8857, fixes https://github.com/rust-analyzer/rust-analyzer/issues/3941 ![URXBanNxYe](https://user-images.githubusercontent.com/3757771/120830905-4bd8da80-c55f-11eb-9f55-ff5a321726fa.gif) We also generate the default lints(and lint groups 🎉) instead now by invoking `rustc -W help` and parsing the output from that. Co-authored-by: Lukas Wirth <lukastw97@gmail.com>
This commit is contained in:
commit
98395f29a4
8 changed files with 4410 additions and 3819 deletions
|
@ -6,12 +6,18 @@ use hir::{
|
|||
use ide_db::{
|
||||
base_db::SourceDatabase,
|
||||
defs::{Definition, NameClass, NameRefClass},
|
||||
helpers::FamousDefs,
|
||||
helpers::{
|
||||
generated_lints::{CLIPPY_LINTS, DEFAULT_LINTS, FEATURES},
|
||||
FamousDefs,
|
||||
},
|
||||
RootDatabase,
|
||||
};
|
||||
use itertools::Itertools;
|
||||
use stdx::format_to;
|
||||
use syntax::{ast, match_ast, AstNode, AstToken, SyntaxKind::*, SyntaxToken, TokenAtOffset, T};
|
||||
use syntax::{
|
||||
algo, ast, match_ast, AstNode, AstToken, Direction, SyntaxKind::*, SyntaxToken, TokenAtOffset,
|
||||
T,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
display::{macro_label, TryToNav},
|
||||
|
@ -118,8 +124,9 @@ pub(crate) fn hover(
|
|||
|d| d.defined(db),
|
||||
),
|
||||
|
||||
_ => ast::Comment::cast(token.clone())
|
||||
.and_then(|_| {
|
||||
_ => {
|
||||
if ast::Comment::cast(token.clone()).is_some() {
|
||||
cov_mark::hit!(no_highlight_on_comment_hover);
|
||||
let (attributes, def) = doc_attributes(&sema, &node)?;
|
||||
let (docs, doc_mapping) = attributes.docs_with_rangemap(db)?;
|
||||
let (idl_range, link, ns) =
|
||||
|
@ -132,9 +139,13 @@ pub(crate) fn hover(
|
|||
}
|
||||
})?;
|
||||
range = Some(idl_range);
|
||||
resolve_doc_path_for_def(db, def, &link, ns)
|
||||
})
|
||||
.map(Definition::ModuleDef),
|
||||
resolve_doc_path_for_def(db, def, &link, ns).map(Definition::ModuleDef)
|
||||
} else if let res@Some(_) = try_hover_for_attribute(&token) {
|
||||
return res;
|
||||
} else {
|
||||
None
|
||||
}
|
||||
},
|
||||
}
|
||||
};
|
||||
|
||||
|
@ -168,11 +179,6 @@ pub(crate) fn hover(
|
|||
}
|
||||
}
|
||||
|
||||
if token.kind() == syntax::SyntaxKind::COMMENT {
|
||||
cov_mark::hit!(no_highlight_on_comment_hover);
|
||||
return None;
|
||||
}
|
||||
|
||||
if let res @ Some(_) = hover_for_keyword(&sema, links_in_hover, markdown, &token) {
|
||||
return res;
|
||||
}
|
||||
|
@ -201,6 +207,51 @@ pub(crate) fn hover(
|
|||
Some(RangeInfo::new(range, res))
|
||||
}
|
||||
|
||||
fn try_hover_for_attribute(token: &SyntaxToken) -> Option<RangeInfo<HoverResult>> {
|
||||
let attr = token.ancestors().nth(1).and_then(ast::Attr::cast)?;
|
||||
let (path, tt) = attr.as_simple_call()?;
|
||||
if !tt.syntax().text_range().contains(token.text_range().start()) {
|
||||
return None;
|
||||
}
|
||||
let (is_clippy, lints) = match &*path {
|
||||
"feature" => (false, FEATURES),
|
||||
"allow" | "deny" | "forbid" | "warn" => {
|
||||
let is_clippy = algo::non_trivia_sibling(token.clone().into(), Direction::Prev)
|
||||
.filter(|t| t.kind() == T![:])
|
||||
.and_then(|t| algo::non_trivia_sibling(t, Direction::Prev))
|
||||
.filter(|t| t.kind() == T![:])
|
||||
.and_then(|t| algo::non_trivia_sibling(t, Direction::Prev))
|
||||
.map_or(false, |t| {
|
||||
t.kind() == T![ident] && t.into_token().map_or(false, |t| t.text() == "clippy")
|
||||
});
|
||||
if is_clippy {
|
||||
(true, CLIPPY_LINTS)
|
||||
} else {
|
||||
(false, DEFAULT_LINTS)
|
||||
}
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
|
||||
let tmp;
|
||||
let needle = if is_clippy {
|
||||
tmp = format!("clippy::{}", token.text());
|
||||
&tmp
|
||||
} else {
|
||||
&*token.text()
|
||||
};
|
||||
|
||||
let lint =
|
||||
lints.binary_search_by_key(&needle, |lint| lint.label).ok().map(|idx| &lints[idx])?;
|
||||
Some(RangeInfo::new(
|
||||
token.text_range(),
|
||||
HoverResult {
|
||||
markup: Markup::from(format!("```\n{}\n```\n___\n\n{}", lint.label, lint.description)),
|
||||
..Default::default()
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
fn show_implementations_action(db: &RootDatabase, def: Definition) -> Option<HoverAction> {
|
||||
fn to_action(nav_target: NavigationTarget) -> HoverAction {
|
||||
HoverAction::Implementation(FilePosition {
|
||||
|
@ -4004,4 +4055,74 @@ pub fn foo() {}
|
|||
"#]],
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hover_feature() {
|
||||
check(
|
||||
r#"#![feature(box_syntax$0)]"#,
|
||||
expect![[r##"
|
||||
*box_syntax*
|
||||
```
|
||||
box_syntax
|
||||
```
|
||||
___
|
||||
|
||||
# `box_syntax`
|
||||
|
||||
The tracking issue for this feature is: [#49733]
|
||||
|
||||
[#49733]: https://github.com/rust-lang/rust/issues/49733
|
||||
|
||||
See also [`box_patterns`](box-patterns.md)
|
||||
|
||||
------------------------
|
||||
|
||||
Currently the only stable way to create a `Box` is via the `Box::new` method.
|
||||
Also it is not possible in stable Rust to destructure a `Box` in a match
|
||||
pattern. The unstable `box` keyword can be used to create a `Box`. An example
|
||||
usage would be:
|
||||
|
||||
```rust
|
||||
#![feature(box_syntax)]
|
||||
|
||||
fn main() {
|
||||
let b = box 5;
|
||||
}
|
||||
```
|
||||
|
||||
"##]],
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hover_lint() {
|
||||
check(
|
||||
r#"#![allow(arithmetic_overflow$0)]"#,
|
||||
expect![[r#"
|
||||
*arithmetic_overflow*
|
||||
```
|
||||
arithmetic_overflow
|
||||
```
|
||||
___
|
||||
|
||||
arithmetic operation overflows
|
||||
"#]],
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hover_clippy_lint() {
|
||||
check(
|
||||
r#"#![allow(clippy::almost_swapped$0)]"#,
|
||||
expect![[r#"
|
||||
*almost_swapped*
|
||||
```
|
||||
clippy::almost_swapped
|
||||
```
|
||||
___
|
||||
|
||||
Checks for `foo = bar; bar = foo` sequences.
|
||||
"#]],
|
||||
)
|
||||
}
|
||||
}
|
||||
|
|
|
@ -3,20 +3,19 @@
|
|||
//! This module uses a bit of static metadata to provide completions
|
||||
//! for built-in attributes.
|
||||
|
||||
use ide_db::helpers::generated_lints::{CLIPPY_LINTS, DEFAULT_LINTS, FEATURES};
|
||||
use once_cell::sync::Lazy;
|
||||
use rustc_hash::{FxHashMap, FxHashSet};
|
||||
use syntax::{algo::non_trivia_sibling, ast, AstNode, Direction, NodeOrToken, SyntaxKind, T};
|
||||
|
||||
use crate::{
|
||||
context::CompletionContext,
|
||||
generated_lint_completions::{CLIPPY_LINTS, FEATURES},
|
||||
item::{CompletionItem, CompletionItemKind, CompletionKind},
|
||||
Completions,
|
||||
};
|
||||
|
||||
mod derive;
|
||||
mod lint;
|
||||
pub(crate) use self::lint::LintCompletion;
|
||||
|
||||
pub(crate) fn complete_attribute(acc: &mut Completions, ctx: &CompletionContext) -> Option<()> {
|
||||
let attribute = ctx.attribute_under_caret.as_ref()?;
|
||||
|
@ -25,7 +24,7 @@ pub(crate) fn complete_attribute(acc: &mut Completions, ctx: &CompletionContext)
|
|||
"derive" => derive::complete_derive(acc, ctx, token_tree),
|
||||
"feature" => lint::complete_lint(acc, ctx, token_tree, FEATURES),
|
||||
"allow" | "warn" | "deny" | "forbid" => {
|
||||
lint::complete_lint(acc, ctx, token_tree.clone(), lint::DEFAULT_LINT_COMPLETIONS);
|
||||
lint::complete_lint(acc, ctx, token_tree.clone(), DEFAULT_LINTS);
|
||||
lint::complete_lint(acc, ctx, token_tree, CLIPPY_LINTS);
|
||||
}
|
||||
_ => (),
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
//! Completion for lints
|
||||
use ide_db::helpers::generated_lints::Lint;
|
||||
use syntax::ast;
|
||||
|
||||
use crate::{
|
||||
|
@ -11,7 +12,7 @@ pub(super) fn complete_lint(
|
|||
acc: &mut Completions,
|
||||
ctx: &CompletionContext,
|
||||
derive_input: ast::TokenTree,
|
||||
lints_completions: &[LintCompletion],
|
||||
lints_completions: &[Lint],
|
||||
) {
|
||||
if let Some(existing_lints) = super::parse_comma_sep_input(derive_input) {
|
||||
for lint_completion in lints_completions
|
||||
|
@ -29,130 +30,6 @@ pub(super) fn complete_lint(
|
|||
}
|
||||
}
|
||||
|
||||
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"# },
|
||||
];
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
|
||||
|
|
|
@ -4,7 +4,6 @@ mod config;
|
|||
mod item;
|
||||
mod context;
|
||||
mod patterns;
|
||||
mod generated_lint_completions;
|
||||
#[cfg(test)]
|
||||
mod test_utils;
|
||||
mod render;
|
||||
|
|
|
@ -3,6 +3,7 @@ pub mod import_assets;
|
|||
pub mod insert_use;
|
||||
pub mod merge_imports;
|
||||
pub mod rust_doc;
|
||||
pub mod generated_lints;
|
||||
|
||||
use std::collections::VecDeque;
|
||||
|
||||
|
|
File diff suppressed because it is too large
Load diff
|
@ -1,4 +1,5 @@
|
|||
//! Generates descriptors structure for unstable feature from Unstable Book
|
||||
use std::borrow::Cow;
|
||||
use std::fmt::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
|
@ -12,25 +13,75 @@ pub(crate) fn generate_lint_completions() -> Result<()> {
|
|||
cmd!("git clone --depth=1 https://github.com/rust-lang/rust ./target/rust").run()?;
|
||||
}
|
||||
|
||||
let mut contents = String::from("use crate::completions::attribute::LintCompletion;\n\n");
|
||||
generate_descriptor(&mut contents, "./target/rust/src/doc/unstable-book/src".into())?;
|
||||
let mut contents = String::from(
|
||||
r#"pub struct Lint {
|
||||
pub label: &'static str,
|
||||
pub description: &'static str,
|
||||
}
|
||||
|
||||
"#,
|
||||
);
|
||||
generate_lint_descriptor(&mut contents)?;
|
||||
contents.push('\n');
|
||||
|
||||
generate_feature_descriptor(&mut contents, "./target/rust/src/doc/unstable-book/src".into())?;
|
||||
contents.push('\n');
|
||||
|
||||
cmd!("curl http://rust-lang.github.io/rust-clippy/master/lints.json --output ./target/clippy_lints.json").run()?;
|
||||
generate_descriptor_clippy(&mut contents, &Path::new("./target/clippy_lints.json"))?;
|
||||
let contents = reformat(&contents)?;
|
||||
|
||||
let destination =
|
||||
project_root().join("crates/ide_completion/src/generated_lint_completions.rs");
|
||||
let destination = project_root().join("crates/ide_db/src/helpers/generated_lints.rs");
|
||||
ensure_file_contents(destination.as_path(), &contents)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn generate_descriptor(buf: &mut String, src_dir: PathBuf) -> Result<()> {
|
||||
buf.push_str(r#"pub(super) const FEATURES: &[LintCompletion] = &["#);
|
||||
fn generate_lint_descriptor(buf: &mut String) -> Result<()> {
|
||||
let stdout = cmd!("rustc -W help").read()?;
|
||||
let start_lints =
|
||||
stdout.find("---- ------- -------").ok_or_else(|| anyhow::format_err!(""))?;
|
||||
let start_lint_groups =
|
||||
stdout.find("---- ---------").ok_or_else(|| anyhow::format_err!(""))?;
|
||||
let end_lints =
|
||||
stdout.find("Lint groups provided by rustc:").ok_or_else(|| anyhow::format_err!(""))?;
|
||||
let end_lint_groups = stdout
|
||||
.find("Lint tools like Clippy can provide additional lints and lint groups.")
|
||||
.ok_or_else(|| anyhow::format_err!(""))?;
|
||||
buf.push_str(r#"pub const DEFAULT_LINTS: &[Lint] = &["#);
|
||||
buf.push('\n');
|
||||
["language-features", "library-features"]
|
||||
let mut lints = stdout[start_lints..end_lints]
|
||||
.lines()
|
||||
.skip(1)
|
||||
.filter(|l| !l.is_empty())
|
||||
.map(|line| {
|
||||
let (name, rest) = line.trim().split_once(char::is_whitespace).unwrap();
|
||||
let (_default_level, description) =
|
||||
rest.trim().split_once(char::is_whitespace).unwrap();
|
||||
(name.trim(), Cow::Borrowed(description.trim()))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
lints.extend(
|
||||
stdout[start_lint_groups..end_lint_groups].lines().skip(1).filter(|l| !l.is_empty()).map(
|
||||
|line| {
|
||||
let (name, lints) = line.trim().split_once(char::is_whitespace).unwrap();
|
||||
(name.trim(), format!("lint group for: {}", lints.trim()).into())
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
lints.sort_by(|(ident, _), (ident2, _)| ident.cmp(ident2));
|
||||
lints.into_iter().for_each(|(name, description)| {
|
||||
push_lint_completion(buf, &name.replace("-", "_"), &description)
|
||||
});
|
||||
buf.push_str("];\n");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn generate_feature_descriptor(buf: &mut String, src_dir: PathBuf) -> Result<()> {
|
||||
buf.push_str(r#"pub const FEATURES: &[Lint] = &["#);
|
||||
buf.push('\n');
|
||||
let mut vec = ["language-features", "library-features"]
|
||||
.iter()
|
||||
.flat_map(|it| WalkDir::new(src_dir.join(it)))
|
||||
.filter_map(|e| e.ok())
|
||||
|
@ -38,13 +89,16 @@ fn generate_descriptor(buf: &mut String, src_dir: PathBuf) -> Result<()> {
|
|||
// Get all `.md ` files
|
||||
entry.file_type().is_file() && entry.path().extension().unwrap_or_default() == "md"
|
||||
})
|
||||
.for_each(|entry| {
|
||||
.map(|entry| {
|
||||
let path = entry.path();
|
||||
let feature_ident = path.file_stem().unwrap().to_str().unwrap().replace("-", "_");
|
||||
let doc = read_file(path).unwrap();
|
||||
|
||||
push_lint_completion(buf, &feature_ident, &doc);
|
||||
});
|
||||
(feature_ident, doc)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
vec.sort_by(|(feature_ident, _), (feature_ident2, _)| feature_ident.cmp(feature_ident2));
|
||||
vec.into_iter()
|
||||
.for_each(|(feature_ident, doc)| push_lint_completion(buf, &feature_ident, &doc));
|
||||
buf.push_str("];\n");
|
||||
Ok(())
|
||||
}
|
||||
|
@ -85,8 +139,8 @@ fn generate_descriptor_clippy(buf: &mut String, path: &Path) -> Result<()> {
|
|||
.into();
|
||||
}
|
||||
}
|
||||
|
||||
buf.push_str(r#"pub(super) const CLIPPY_LINTS: &[LintCompletion] = &["#);
|
||||
clippy_lints.sort_by(|lint, lint2| lint.id.cmp(&lint2.id));
|
||||
buf.push_str(r#"pub const CLIPPY_LINTS: &[Lint] = &["#);
|
||||
buf.push('\n');
|
||||
clippy_lints.into_iter().for_each(|clippy_lint| {
|
||||
let lint_ident = format!("clippy::{}", clippy_lint.id);
|
||||
|
@ -102,7 +156,7 @@ fn generate_descriptor_clippy(buf: &mut String, path: &Path) -> Result<()> {
|
|||
fn push_lint_completion(buf: &mut String, label: &str, description: &str) {
|
||||
writeln!(
|
||||
buf,
|
||||
r###" LintCompletion {{
|
||||
r###" Lint {{
|
||||
label: "{}",
|
||||
description: r##"{}"##
|
||||
}},"###,
|
||||
|
|
|
@ -193,7 +193,9 @@ https://github.blog/2015-06-08-how-to-undo-almost-anything-with-git/#redo-after-
|
|||
fn deny_clippy(path: &Path, text: &str) {
|
||||
let ignore = &[
|
||||
// The documentation in string literals may contain anything for its own purposes
|
||||
"ide_completion/src/generated_lint_completions.rs",
|
||||
"ide_db/src/helpers/generated_lints.rs",
|
||||
// The tests test clippy lint hovers
|
||||
"ide/src/hover.rs",
|
||||
];
|
||||
if ignore.iter().any(|p| path.ends_with(p)) {
|
||||
return;
|
||||
|
@ -280,7 +282,7 @@ fn check_todo(path: &Path, text: &str) {
|
|||
// `ast::make`.
|
||||
"ast/make.rs",
|
||||
// The documentation in string literals may contain anything for its own purposes
|
||||
"ide_completion/src/generated_lint_completions.rs",
|
||||
"ide_db/src/helpers/generated_lints.rs",
|
||||
];
|
||||
if need_todo.iter().any(|p| path.ends_with(p)) {
|
||||
return;
|
||||
|
@ -310,7 +312,7 @@ fn check_dbg(path: &Path, text: &str) {
|
|||
"ide_completion/src/completions/postfix.rs",
|
||||
// The documentation in string literals may contain anything for its own purposes
|
||||
"ide_completion/src/lib.rs",
|
||||
"ide_completion/src/generated_lint_completions.rs",
|
||||
"ide_db/src/helpers/generated_lints.rs",
|
||||
// test for doc test for remove_dbg
|
||||
"src/tests/generated.rs",
|
||||
];
|
||||
|
|
Loading…
Reference in a new issue