Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use syn in needless_doctest_main lint #4729

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 3 additions & 4 deletions clippy_lints/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,13 @@ matches = "0.1.7"
pulldown-cmark = "0.6.0"
quine-mc_cluskey = "0.2.2"
regex-syntax = "0.6"
semver = "0.9.0"
serde = { version = "1.0", features = ["derive"] }
smallvec = { version = "1", features = ["union"] }
syn = { version = "1.0", features = ["full"] }
toml = "0.5.3"
unicode-normalization = "0.1"
semver = "0.9.0"
# NOTE: cargo requires serde feat in its url dep
# see <https://github.com/rust-lang/rust/pull/63587#issuecomment-522343864>
url = { version = "2.1.0", features = ["serde"] }
url = "2.1.0"

[features]
deny-warnings = []
33 changes: 29 additions & 4 deletions clippy_lints/src/doc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -395,11 +395,36 @@ fn check_doc<'a, Events: Iterator<Item = (pulldown_cmark::Event<'a>, Range<usize
headers
}

static LEAVE_MAIN_PATTERNS: &[&str] = &["static", "fn main() {}", "extern crate"];
fn needs_main(item: &syn::Item) -> bool {
match item {
syn::Item::Const(..) | syn::Item::Static(..) | syn::Item::ExternCrate(..) | syn::Item::ForeignMod(..) => true,
_ => false,
}
}

fn check_code(cx: &LateContext<'_, '_>, text: &str, span: Span) {
if text.contains("fn main() {") && !LEAVE_MAIN_PATTERNS.iter().any(|p| text.contains(p)) {
span_lint(cx, NEEDLESS_DOCTEST_MAIN, span, "needless `fn main` in doctest");
// check a syn Item for non-empty `fn main() { .. }`
fn is_default_main_fn(item: &syn::Item) -> bool {
match item {
syn::Item::Fn(syn::ItemFn { ref sig, ref block, .. }) => {
!block.stmts.is_empty()
&& sig.ident == "main"
&& match sig.output {
syn::ReturnType::Default => true,
syn::ReturnType::Type(_, ref ty) => match **ty {
syn::Type::Tuple(syn::TypeTuple { ref elems, .. }) => elems.is_empty(),
_ => false,
},
}
},
_ => false,
}
}

fn check_code(cx: &LateContext<'_, '_>, code: &str, span: Span) {
if let Ok(file) = syn::parse_file(code) {
if file.items.iter().any(is_default_main_fn) && !file.items.iter().any(needs_main) {
span_lint(cx, NEEDLESS_DOCTEST_MAIN, span, "needless `fn main` in doctest");
}
}
}

Expand Down