|
| 1 | +use clippy_utils::diagnostics::span_lint_and_sugg; |
| 2 | +use clippy_utils::source::snippet_opt; |
| 3 | +use rustc_ast::{AttrArgs, AttrArgsEq, AttrKind, AttrStyle, Attribute}; |
| 4 | +use rustc_errors::Applicability; |
| 5 | +use rustc_lint::LateContext; |
| 6 | +use rustc_span::sym; |
| 7 | + |
| 8 | +use super::DOC_INCLUDE_WITHOUT_CFG; |
| 9 | + |
| 10 | +pub fn check(cx: &LateContext<'_>, attrs: &[Attribute]) { |
| 11 | + for attr in attrs { |
| 12 | + if let AttrKind::Normal(ref normal) = attr.kind |
| 13 | + && normal.item.path == sym::doc |
| 14 | + && let AttrArgs::Eq(_, AttrArgsEq::Hir(ref meta)) = normal.item.args |
| 15 | + && !attr.span.contains(meta.span) |
| 16 | + // Since the `include_str` is already expanded at this point, we can only take the |
| 17 | + // whole attribute snippet and then modify for our suggestion. |
| 18 | + && let Some(snippet) = snippet_opt(cx, attr.span) |
| 19 | + // We cannot remove this because a `#[doc = include_str!("...")]` attribute can occupy |
| 20 | + // several lines. |
| 21 | + && let Some(start) = snippet.find('[') |
| 22 | + && let Some(end) = snippet.rfind(']') |
| 23 | + { |
| 24 | + let snippet = &snippet[start + 1..end]; |
| 25 | + span_lint_and_sugg( |
| 26 | + cx, |
| 27 | + DOC_INCLUDE_WITHOUT_CFG, |
| 28 | + attr.span, |
| 29 | + "included a file in documentation unconditionally", |
| 30 | + "use `cfg_attr(doc, doc = \"...\")`", |
| 31 | + format!( |
| 32 | + "#{}[cfg_attr(doc, {snippet})]", |
| 33 | + if attr.style == AttrStyle::Inner { "!" } else { "" } |
| 34 | + ), |
| 35 | + Applicability::MachineApplicable, |
| 36 | + ); |
| 37 | + } |
| 38 | + } |
| 39 | +} |
0 commit comments