rust/compiler/rustc_lint/src/early.rs

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

460 lines
15 KiB
Rust
Raw Normal View History

//! Implementation of lint checking.
//!
//! The lint checking is mostly consolidated into one pass which runs
//! after all other analyses. Throughout compilation, lint warnings
//! can be added via the `add_lint` method on the Session structure. This
//! requires a span and an ID of the node that the lint is being added to. The
//! lint isn't actually emitted at that time because it is unknown what the
//! actual lint level at that location is.
//!
//! To actually emit lint warnings/errors, a separate pass is used.
//! A context keeps track of the current state of all lint levels.
//! Upon entering a node of the ast which can modify the lint settings, the
//! previous lint state is pushed onto a stack and the ast is then recursed
//! upon. As the ast is traversed, this keeps track of the current lint level
//! for all lint attributes.
use crate::context::{EarlyContext, LintContext, LintStore};
use crate::passes::{EarlyLintPass, EarlyLintPassObject};
use rustc_ast::ptr::P;
use rustc_ast::visit::{self as ast_visit, Visitor};
use rustc_ast::{self as ast, walk_list, HasAttrs};
use rustc_middle::ty::RegisteredTools;
2020-03-15 18:43:37 -05:00
use rustc_session::lint::{BufferedEarlyLint, LintBuffer, LintPass};
2020-01-05 02:40:16 -06:00
use rustc_session::Session;
2020-04-19 06:00:18 -05:00
use rustc_span::symbol::Ident;
use rustc_span::Span;
2020-01-05 02:40:16 -06:00
use std::slice;
macro_rules! run_early_pass { ($cx:expr, $f:ident, $($args:expr),*) => ({
$cx.pass.$f(&$cx.context, $($args),*);
}) }
pub struct EarlyContextAndPass<'a, T: EarlyLintPass> {
context: EarlyContext<'a>,
pass: T,
}
impl<'a, T: EarlyLintPass> EarlyContextAndPass<'a, T> {
fn check_id(&mut self, id: ast::NodeId) {
for early_lint in self.context.buffered.take(id) {
2020-03-15 18:43:37 -05:00
let BufferedEarlyLint { span, msg, node_id: _, lint_id, diagnostic } = early_lint;
self.context.lookup_with_diagnostics(
2020-02-05 09:28:23 -06:00
lint_id.lint,
Some(span),
2022-09-16 02:01:02 -05:00
msg,
|lint| lint,
diagnostic,
);
}
}
/// Merge the lints specified by any lint attributes into the
/// current lint context, call the provided function, then reset the
/// lints in effect to their previous state.
fn with_lint_attrs<F>(&mut self, id: ast::NodeId, attrs: &'a [ast::Attribute], f: F)
where
F: FnOnce(&mut Self),
{
let is_crate_node = id == ast::CRATE_NODE_ID;
2022-07-22 11:48:36 -05:00
debug!(?id);
let push = self.context.builder.push(attrs, is_crate_node, None);
self.check_id(id);
debug!("early context: enter_attrs({:?})", attrs);
run_early_pass!(self, enter_lint_attrs, attrs);
f(self);
debug!("early context: exit_attrs({:?})", attrs);
run_early_pass!(self, exit_lint_attrs, attrs);
self.context.builder.pop(push);
}
}
impl<'a, T: EarlyLintPass> ast_visit::Visitor<'a> for EarlyContextAndPass<'a, T> {
fn visit_param(&mut self, param: &'a ast::Param) {
self.with_lint_attrs(param.id, &param.attrs, |cx| {
run_early_pass!(cx, check_param, param);
ast_visit::walk_param(cx, param);
});
}
fn visit_item(&mut self, it: &'a ast::Item) {
self.with_lint_attrs(it.id, &it.attrs, |cx| {
run_early_pass!(cx, check_item, it);
ast_visit::walk_item(cx, it);
run_early_pass!(cx, check_item_post, it);
})
}
fn visit_foreign_item(&mut self, it: &'a ast::ForeignItem) {
self.with_lint_attrs(it.id, &it.attrs, |cx| {
ast_visit::walk_foreign_item(cx, it);
})
}
fn visit_pat(&mut self, p: &'a ast::Pat) {
run_early_pass!(self, check_pat, p);
self.check_id(p.id);
ast_visit::walk_pat(self, p);
run_early_pass!(self, check_pat_post, p);
}
fn visit_pat_field(&mut self, field: &'a ast::PatField) {
self.with_lint_attrs(field.id, &field.attrs, |cx| {
ast_visit::walk_pat_field(cx, field);
});
}
fn visit_anon_const(&mut self, c: &'a ast::AnonConst) {
self.check_id(c.id);
ast_visit::walk_anon_const(self, c);
}
fn visit_expr(&mut self, e: &'a ast::Expr) {
self.with_lint_attrs(e.id, &e.attrs, |cx| {
run_early_pass!(cx, check_expr, e);
ast_visit::walk_expr(cx, e);
})
}
2021-07-14 20:07:56 -05:00
fn visit_expr_field(&mut self, f: &'a ast::ExprField) {
self.with_lint_attrs(f.id, &f.attrs, |cx| {
ast_visit::walk_expr_field(cx, f);
})
}
fn visit_stmt(&mut self, s: &'a ast::Stmt) {
Fix inconsistencies in handling of inert attributes on statements When the 'early' and 'late' visitors visit an attribute target, they activate any lint attributes (e.g. `#[allow]`) that apply to it. This can affect warnings emitted on sibiling attributes. For example, the following code does not produce an `unused_attributes` for `#[inline]`, since the sibiling `#[allow(unused_attributes)]` suppressed the warning. ```rust trait Foo { #[allow(unused_attributes)] #[inline] fn first(); #[inline] #[allow(unused_attributes)] fn second(); } ``` However, we do not do this for statements - instead, the lint attributes only become active when we visit the struct nested inside `StmtKind` (e.g. `Item`). Currently, this is difficult to observe due to another issue - the `HasAttrs` impl for `StmtKind` ignores attributes for `StmtKind::Item`. As a result, the `unused_doc_comments` lint will never see attributes on item statements. This commit makes two interrelated fixes to the handling of inert (non-proc-macro) attributes on statements: * The `HasAttr` impl for `StmtKind` now returns attributes for `StmtKind::Item`, treating it just like every other `StmtKind` variant. The only place relying on the old behavior was macro which has been updated to explicitly ignore attributes on item statements. This allows the `unused_doc_comments` lint to fire for item statements. * The `early` and `late` lint visitors now activate lint attributes when invoking the callback for `Stmt`. This ensures that a lint attribute (e.g. `#[allow(unused_doc_comments)]`) can be applied to sibiling attributes on an item statement. For now, the `unused_doc_comments` lint is explicitly disabled on item statements, which preserves the current behavior. The exact locatiosn where this lint should fire are being discussed in PR #78306
2020-10-23 17:17:00 -05:00
// Add the statement's lint attributes to our
// current state when checking the statement itself.
// This allows us to handle attributes like
// `#[allow(unused_doc_comments)]`, which apply to
// sibling attributes on the same target
//
// Note that statements get their attributes from
// the AST struct that they wrap (e.g. an item)
self.with_lint_attrs(s.id, s.attrs(), |cx| {
run_early_pass!(cx, check_stmt, s);
cx.check_id(s.id);
});
// The visitor for the AST struct wrapped
// by the statement (e.g. `Item`) will call
// `with_lint_attrs`, so do this walk
// outside of the above `with_lint_attrs` call
ast_visit::walk_stmt(self, s);
}
fn visit_fn(&mut self, fk: ast_visit::FnKind<'a>, span: Span, id: ast::NodeId) {
run_early_pass!(self, check_fn, fk, span, id);
self.check_id(id);
ast_visit::walk_fn(self, fk);
// Explicitly check for lints associated with 'closure_id', since
// it does not have a corresponding AST node
2021-11-19 15:03:43 -06:00
if let ast_visit::FnKind::Fn(_, _, sig, _, _, _) = fk {
if let ast::Async::Yes { closure_id, .. } = sig.header.asyncness {
self.check_id(closure_id);
}
}
}
fn visit_variant_data(&mut self, s: &'a ast::VariantData) {
if let Some(ctor_node_id) = s.ctor_node_id() {
self.check_id(ctor_node_id);
}
ast_visit::walk_struct_def(self, s);
}
fn visit_field_def(&mut self, s: &'a ast::FieldDef) {
self.with_lint_attrs(s.id, &s.attrs, |cx| {
ast_visit::walk_field_def(cx, s);
})
}
fn visit_variant(&mut self, v: &'a ast::Variant) {
self.with_lint_attrs(v.id, &v.attrs, |cx| {
run_early_pass!(cx, check_variant, v);
ast_visit::walk_variant(cx, v);
})
}
fn visit_ty(&mut self, t: &'a ast::Ty) {
run_early_pass!(self, check_ty, t);
self.check_id(t.id);
ast_visit::walk_ty(self, t);
}
2020-04-19 06:00:18 -05:00
fn visit_ident(&mut self, ident: Ident) {
run_early_pass!(self, check_ident, ident);
}
fn visit_local(&mut self, l: &'a ast::Local) {
self.with_lint_attrs(l.id, &l.attrs, |cx| {
run_early_pass!(cx, check_local, l);
ast_visit::walk_local(cx, l);
})
}
fn visit_block(&mut self, b: &'a ast::Block) {
run_early_pass!(self, check_block, b);
self.check_id(b.id);
ast_visit::walk_block(self, b);
}
fn visit_arm(&mut self, a: &'a ast::Arm) {
self.with_lint_attrs(a.id, &a.attrs, |cx| {
run_early_pass!(cx, check_arm, a);
ast_visit::walk_arm(cx, a);
})
}
fn visit_expr_post(&mut self, e: &'a ast::Expr) {
// Explicitly check for lints associated with 'closure_id', since
// it does not have a corresponding AST node
match e.kind {
ast::ExprKind::Closure(box ast::Closure {
asyncness: ast::Async::Yes { closure_id, .. },
..
})
| ast::ExprKind::Async(_, closure_id, ..) => self.check_id(closure_id),
_ => {}
}
}
2020-10-09 17:20:06 -05:00
fn visit_generic_arg(&mut self, arg: &'a ast::GenericArg) {
run_early_pass!(self, check_generic_arg, arg);
ast_visit::walk_generic_arg(self, arg);
}
fn visit_generic_param(&mut self, param: &'a ast::GenericParam) {
self.with_lint_attrs(param.id, &param.attrs, |cx| {
run_early_pass!(cx, check_generic_param, param);
ast_visit::walk_generic_param(cx, param);
});
}
fn visit_generics(&mut self, g: &'a ast::Generics) {
run_early_pass!(self, check_generics, g);
ast_visit::walk_generics(self, g);
}
fn visit_where_predicate(&mut self, p: &'a ast::WherePredicate) {
ast_visit::walk_where_predicate(self, p);
}
fn visit_poly_trait_ref(&mut self, t: &'a ast::PolyTraitRef) {
run_early_pass!(self, check_poly_trait_ref, t);
ast_visit::walk_poly_trait_ref(self, t);
}
fn visit_assoc_item(&mut self, item: &'a ast::AssocItem, ctxt: ast_visit::AssocCtxt) {
self.with_lint_attrs(item.id, &item.attrs, |cx| match ctxt {
ast_visit::AssocCtxt::Trait => {
run_early_pass!(cx, check_trait_item, item);
ast_visit::walk_assoc_item(cx, item, ctxt);
}
ast_visit::AssocCtxt::Impl => {
run_early_pass!(cx, check_impl_item, item);
ast_visit::walk_assoc_item(cx, item, ctxt);
}
});
}
2022-05-10 12:56:46 -05:00
fn visit_lifetime(&mut self, lt: &'a ast::Lifetime, _: ast_visit::LifetimeCtxt) {
self.check_id(lt.id);
}
fn visit_path(&mut self, p: &'a ast::Path, id: ast::NodeId) {
self.check_id(id);
ast_visit::walk_path(self, p);
}
fn visit_path_segment(&mut self, s: &'a ast::PathSegment) {
self.check_id(s.id);
ast_visit::walk_path_segment(self, s);
}
fn visit_attribute(&mut self, attr: &'a ast::Attribute) {
run_early_pass!(self, check_attribute, attr);
}
fn visit_mac_def(&mut self, mac: &'a ast::MacroDef, id: ast::NodeId) {
run_early_pass!(self, check_mac_def, mac);
self.check_id(id);
}
fn visit_mac_call(&mut self, mac: &'a ast::MacCall) {
run_early_pass!(self, check_mac, mac);
ast_visit::walk_mac(self, mac);
}
}
struct EarlyLintPassObjects<'a> {
lints: &'a mut [EarlyLintPassObject],
}
#[allow(rustc::lint_pass_impl_without_macro)]
impl LintPass for EarlyLintPassObjects<'_> {
fn name(&self) -> &'static str {
panic!()
}
}
macro_rules! early_lint_pass_impl {
([], [$($(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*);)*]) => (
impl EarlyLintPass for EarlyLintPassObjects<'_> {
$(fn $name(&mut self, context: &EarlyContext<'_>, $($param: $arg),*) {
for obj in self.lints.iter_mut() {
obj.$name(context, $($param),*);
}
})*
}
)
}
crate::early_lint_methods!(early_lint_pass_impl, []);
/// Early lints work on different nodes - either on the crate root, or on freshly loaded modules.
/// This trait generalizes over those nodes.
pub trait EarlyCheckNode<'a>: Copy {
fn id(self) -> ast::NodeId;
fn attrs<'b>(self) -> &'b [ast::Attribute]
where
'a: 'b;
fn check<'b>(self, cx: &mut EarlyContextAndPass<'b, impl EarlyLintPass>)
where
'a: 'b;
}
impl<'a> EarlyCheckNode<'a> for &'a ast::Crate {
fn id(self) -> ast::NodeId {
ast::CRATE_NODE_ID
}
fn attrs<'b>(self) -> &'b [ast::Attribute]
where
'a: 'b,
{
&self.attrs
}
fn check<'b>(self, cx: &mut EarlyContextAndPass<'b, impl EarlyLintPass>)
where
'a: 'b,
{
run_early_pass!(cx, check_crate, self);
ast_visit::walk_crate(cx, self);
run_early_pass!(cx, check_crate_post, self);
}
}
impl<'a> EarlyCheckNode<'a> for (ast::NodeId, &'a [ast::Attribute], &'a [P<ast::Item>]) {
fn id(self) -> ast::NodeId {
self.0
}
fn attrs<'b>(self) -> &'b [ast::Attribute]
where
'a: 'b,
{
self.1
}
fn check<'b>(self, cx: &mut EarlyContextAndPass<'b, impl EarlyLintPass>)
where
'a: 'b,
{
walk_list!(cx, visit_attribute, self.1);
walk_list!(cx, visit_item, self.2);
}
}
fn early_lint_node<'a>(
sess: &Session,
warn_about_weird_lints: bool,
lint_store: &LintStore,
registered_tools: &RegisteredTools,
buffered: LintBuffer,
pass: impl EarlyLintPass,
check_node: impl EarlyCheckNode<'a>,
) -> LintBuffer {
let mut cx = EarlyContextAndPass {
context: EarlyContext::new(
sess,
warn_about_weird_lints,
lint_store,
registered_tools,
buffered,
),
pass,
};
cx.with_lint_attrs(check_node.id(), check_node.attrs(), |cx| check_node.check(cx));
cx.context.buffered
}
pub fn check_ast_node<'a>(
sess: &Session,
pre_expansion: bool,
lint_store: &LintStore,
registered_tools: &RegisteredTools,
lint_buffer: Option<LintBuffer>,
builtin_lints: impl EarlyLintPass,
check_node: impl EarlyCheckNode<'a>,
) {
2020-03-15 18:43:37 -05:00
let passes =
if pre_expansion { &lint_store.pre_expansion_passes } else { &lint_store.early_passes };
let mut passes: Vec<_> = passes.iter().map(|p| (p)()).collect();
let mut buffered = lint_buffer.unwrap_or_default();
if sess.opts.unstable_opts.no_interleave_lints {
for (i, pass) in passes.iter_mut().enumerate() {
buffered =
Remove `-Ztime` option. The compiler currently has `-Ztime` and `-Ztime-passes`. I've used `-Ztime-passes` for years but only recently learned about `-Ztime`. What's the difference? Let's look at the `-Zhelp` output: ``` -Z time=val -- measure time of rustc processes (default: no) -Z time-passes=val -- measure time of each rustc pass (default: no) ``` The `-Ztime-passes` description is clear, but the `-Ztime` one is less so. Sounds like it measures the time for the entire process? No. The real difference is that `-Ztime-passes` prints out info about passes, and `-Ztime` does the same, but only for a subset of those passes. More specifically, there is a distinction in the profiling code between a "verbose generic activity" and an "extra verbose generic activity". `-Ztime-passes` prints both kinds, while `-Ztime` only prints the first one. (It took me a close reading of the source code to determine this difference.) In practice this distinction has low value. Perhaps in the past the "extra verbose" output was more voluminous, but now that we only print stats for a pass if it exceeds 5ms or alters the RSS, `-Ztime-passes` is less spammy. Also, a lot of the "extra verbose" cases are for individual lint passes, and you need to also use `-Zno-interleave-lints` to see those anyway. Therefore, this commit removes `-Ztime` and the associated machinery. One thing to note is that the existing "extra verbose" activities all have an extra string argument, so the commit adds the ability to accept an extra argument to the "verbose" activities.
2022-10-05 22:51:45 -05:00
sess.prof.verbose_generic_activity_with_arg("run_lint", pass.name()).run(|| {
early_lint_node(
sess,
!pre_expansion && i == 0,
lint_store,
registered_tools,
buffered,
EarlyLintPassObjects { lints: slice::from_mut(pass) },
check_node,
)
});
}
} else {
buffered = early_lint_node(
sess,
!pre_expansion,
lint_store,
registered_tools,
buffered,
builtin_lints,
check_node,
);
if !passes.is_empty() {
buffered = early_lint_node(
sess,
false,
lint_store,
registered_tools,
buffered,
EarlyLintPassObjects { lints: &mut passes[..] },
check_node,
);
}
}
// All of the buffered lints should have been emitted at this point.
// If not, that means that we somehow buffered a lint for a node id
// that was not lint-checked (perhaps it doesn't exist?). This is a bug.
2021-07-14 20:07:56 -05:00
for (id, lints) in buffered.map {
for early_lint in lints {
2021-07-14 20:07:56 -05:00
sess.delay_span_bug(
early_lint.span,
&format!(
"failed to process buffered lint here (dummy = {})",
id == ast::DUMMY_NODE_ID
),
);
}
}
}