Skip to content

Make check-cfg diagnostics work in #[doc(cfg(..))] #140894

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

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
27 changes: 21 additions & 6 deletions compiler/rustc_attr_parsing/src/attributes/cfg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,29 @@ use rustc_attr_data_structures::RustcVersion;
use rustc_feature::{Features, GatedCfg, find_gated_cfg};
use rustc_session::Session;
use rustc_session::config::ExpectedValues;
use rustc_session::lint::BuiltinLintDiag;
use rustc_session::lint::builtin::UNEXPECTED_CFGS;
use rustc_session::lint::{BuiltinLintDiag, Lint};
use rustc_session::parse::feature_err;
use rustc_span::{Span, Symbol, sym};

use crate::session_diagnostics::{self, UnsupportedLiteralReason};
use crate::{fluent_generated, parse_version};

/// Emitter of a builtin lint from `cfg_matches`.
///
/// Used to support emiting a lint (currently on check-cfg), either:
/// - as an early buffered lint (in `rustc`)
/// - or has a "normal" lint from HIR (in `rustdoc`)
pub trait CfgMatchesLintEmitter {
fn emit_span_lint(&self, sess: &Session, lint: &'static Lint, sp: Span, diag: BuiltinLintDiag);
}

impl CfgMatchesLintEmitter for NodeId {
fn emit_span_lint(&self, sess: &Session, lint: &'static Lint, sp: Span, diag: BuiltinLintDiag) {
sess.psess.buffer_lint(lint, sp, *self, diag);
}
}

#[derive(Clone, Debug)]
pub struct Condition {
pub name: Symbol,
Expand All @@ -25,28 +40,28 @@ pub struct Condition {
pub fn cfg_matches(
cfg: &MetaItemInner,
sess: &Session,
lint_node_id: NodeId,
lint_emitter: impl CfgMatchesLintEmitter,
features: Option<&Features>,
) -> bool {
eval_condition(cfg, sess, features, &mut |cfg| {
try_gate_cfg(cfg.name, cfg.span, sess, features);
match sess.psess.check_config.expecteds.get(&cfg.name) {
Some(ExpectedValues::Some(values)) if !values.contains(&cfg.value) => {
sess.psess.buffer_lint(
lint_emitter.emit_span_lint(
sess,
UNEXPECTED_CFGS,
cfg.span,
lint_node_id,
BuiltinLintDiag::UnexpectedCfgValue(
(cfg.name, cfg.name_span),
cfg.value.map(|v| (v, cfg.value_span.unwrap())),
),
);
}
None if sess.psess.check_config.exhaustive_names => {
sess.psess.buffer_lint(
lint_emitter.emit_span_lint(
sess,
UNEXPECTED_CFGS,
cfg.span,
lint_node_id,
BuiltinLintDiag::UnexpectedCfgName(
(cfg.name, cfg.name_span),
cfg.value.map(|v| (v, cfg.value_span.unwrap())),
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_lint/src/early.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use tracing::debug;
use crate::context::{EarlyContext, LintContext, LintStore};
use crate::passes::{EarlyLintPass, EarlyLintPassObject};

mod diagnostics;
pub(super) mod diagnostics;

macro_rules! lint_callback { ($cx:expr, $f:ident, $($args:expr),*) => ({
$cx.pass.$f(&$cx.context, $($args),*);
Expand All @@ -40,7 +40,7 @@ impl<'ecx, 'tcx, T: EarlyLintPass> EarlyContextAndPass<'ecx, 'tcx, T> {
for early_lint in self.context.buffered.take(id) {
let BufferedEarlyLint { span, node_id: _, lint_id, diagnostic } = early_lint;
self.context.opt_span_lint(lint_id.lint, span, |diag| {
diagnostics::decorate_lint(self.context.sess(), self.tcx, diagnostic, diag);
diagnostics::decorate_builtin_lint(self.context.sess(), self.tcx, diagnostic, diag);
});
}
}
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_lint/src/early/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use crate::lints::{self, ElidedNamedLifetime};

mod check_cfg;

pub(super) fn decorate_lint(
pub fn decorate_builtin_lint(
sess: &Session,
tcx: Option<TyCtxt<'_>>,
diagnostic: BuiltinLintDiag,
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_lint/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@ use unused::*;
#[rustfmt::skip]
pub use builtin::{MissingDoc, SoftLints};
pub use context::{CheckLintNameResult, EarlyContext, LateContext, LintContext, LintStore};
pub use early::diagnostics::decorate_builtin_lint;
pub use early::{EarlyCheckNode, check_ast_node};
pub use late::{check_crate, late_lint_mod, unerased_lint_store};
pub use levels::LintLevelsBuilder;
Expand Down
4 changes: 2 additions & 2 deletions src/librustdoc/clean/inline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -409,12 +409,12 @@ pub(crate) fn merge_attrs(
} else {
Attributes::from_hir(&both)
},
extract_cfg_from_attrs(both.iter(), cx.tcx, &cx.cache.hidden_cfg),
extract_cfg_from_attrs(both.iter(), cx.tcx, None, &cx.cache.hidden_cfg),
)
} else {
(
Attributes::from_hir(old_attrs),
extract_cfg_from_attrs(old_attrs.iter(), cx.tcx, &cx.cache.hidden_cfg),
extract_cfg_from_attrs(old_attrs.iter(), cx.tcx, None, &cx.cache.hidden_cfg),
)
}
}
Expand Down
1 change: 1 addition & 0 deletions src/librustdoc/clean/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,7 @@ fn generate_item_with_correct_attrs(
Cow::Owned(attr) => attr,
}),
cx.tcx,
def_id.as_local().map(|did| cx.tcx.local_def_id_to_hir_id(did)),
&cx.cache.hidden_cfg,
);
let attrs = Attributes::from_hir_iter(attrs.iter().map(|(attr, did)| (&**attr, *did)), false);
Expand Down
39 changes: 36 additions & 3 deletions src/librustdoc/clean/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,9 @@ use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet};
use rustc_hir::def::{CtorKind, DefKind, Res};
use rustc_hir::def_id::{CrateNum, DefId, LOCAL_CRATE, LocalDefId};
use rustc_hir::lang_items::LangItem;
use rustc_hir::{BodyId, Mutability};
use rustc_hir::{BodyId, HirId, Mutability};
use rustc_index::IndexVec;
use rustc_lint_defs::{BuiltinLintDiag, Lint};
use rustc_metadata::rendered_const;
use rustc_middle::span_bug;
use rustc_middle::ty::fast_reject::SimplifiedType;
Expand Down Expand Up @@ -475,7 +476,12 @@ impl Item {
name,
kind,
Attributes::from_hir(hir_attrs),
extract_cfg_from_attrs(hir_attrs.iter(), cx.tcx, &cx.cache.hidden_cfg),
extract_cfg_from_attrs(
hir_attrs.iter(),
cx.tcx,
def_id.as_local().map(|did| cx.tcx.local_def_id_to_hir_id(did)),
&cx.cache.hidden_cfg,
),
)
}

Expand Down Expand Up @@ -1014,6 +1020,7 @@ pub(crate) fn hir_attr_lists<'a, I: IntoIterator<Item = &'a hir::Attribute>>(
pub(crate) fn extract_cfg_from_attrs<'a, I: Iterator<Item = &'a hir::Attribute> + Clone>(
attrs: I,
tcx: TyCtxt<'_>,
hir_id: Option<HirId>,
hidden_cfg: &FxHashSet<Cfg>,
) -> Option<Arc<Cfg>> {
let doc_cfg_active = tcx.features().doc_cfg();
Expand All @@ -1037,6 +1044,32 @@ pub(crate) fn extract_cfg_from_attrs<'a, I: Iterator<Item = &'a hir::Attribute>
.peekable();
if doc_cfg.peek().is_some() && doc_cfg_active {
let sess = tcx.sess;

struct RustdocCfgMatchesLintEmitter<'a>(TyCtxt<'a>, Option<HirId>);

impl<'a> rustc_attr_parsing::CfgMatchesLintEmitter for RustdocCfgMatchesLintEmitter<'a> {
fn emit_span_lint(
&self,
sess: &Session,
lint: &'static Lint,
sp: rustc_span::Span,
builtin_diag: BuiltinLintDiag,
) {
if let Some(hir_id) = self.1 {
self.0.node_span_lint(lint, hir_id, sp, |diag| {
rustc_lint::decorate_builtin_lint(
sess,
Some(self.0),
builtin_diag,
diag,
)
});
} else {
// no HIR id, probably in another crate don't lint
}
}
}

doc_cfg.fold(Cfg::True, |mut cfg, item| {
if let Some(cfg_mi) =
item.meta_item().and_then(|item| rustc_expand::config::parse_cfg(item, sess))
Expand All @@ -1045,7 +1078,7 @@ pub(crate) fn extract_cfg_from_attrs<'a, I: Iterator<Item = &'a hir::Attribute>
rustc_attr_parsing::cfg_matches(
cfg_mi,
tcx.sess,
rustc_ast::CRATE_NODE_ID,
RustdocCfgMatchesLintEmitter(tcx, hir_id),
Some(tcx.features()),
);
match Cfg::parse(cfg_mi) {
Expand Down
9 changes: 6 additions & 3 deletions src/librustdoc/doctest/rust.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,9 +95,12 @@ impl HirCollector<'_> {
nested: F,
) {
let ast_attrs = self.tcx.hir_attrs(self.tcx.local_def_id_to_hir_id(def_id));
if let Some(ref cfg) =
extract_cfg_from_attrs(ast_attrs.iter(), self.tcx, &FxHashSet::default())
&& !cfg.matches(&self.tcx.sess.psess)
if let Some(ref cfg) = extract_cfg_from_attrs(
ast_attrs.iter(),
self.tcx,
Some(self.tcx.local_def_id_to_hir_id(def_id)),
&FxHashSet::default(),
) && !cfg.matches(&self.tcx.sess.psess)
{
return;
}
Expand Down
12 changes: 12 additions & 0 deletions tests/rustdoc-ui/doc-cfg-check-cfg.cfg_empty.stderr
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
warning: unexpected `cfg` condition name: `foo`
--> $DIR/doc-cfg-check-cfg.rs:13:11
|
LL | #[doc(cfg(foo))]
| ^^^
|
= help: to expect this configuration use `--check-cfg=cfg(foo)`
= note: see <https://doc.rust-lang.org/nightly/rustc/check-cfg.html> for more information about checking conditional configuration
= note: `#[warn(unexpected_cfgs)]` on by default

warning: 1 warning emitted

19 changes: 12 additions & 7 deletions tests/rustdoc-ui/doc-cfg-check-cfg.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,21 @@
// Ensure that `doc(cfg())` respects `check-cfg`
// Currently not properly working
#![feature(doc_cfg)]
#![deny(unexpected_cfgs)]

//@revisions: no_check cfg_empty cfg_foo
//@ check-pass
//@ no-auto-check-cfg

//@ revisions: no_check cfg_empty cfg_foo
//@[cfg_empty] compile-flags: --check-cfg cfg()
//@[cfg_foo] compile-flags: --check-cfg cfg(foo)

//@[no_check] check-pass
//@[cfg_empty] check-pass
//@[cfg_empty] known-bug: #138358
//@[cfg_foo] check-pass
#![feature(doc_cfg)]

#[doc(cfg(foo))]
//[cfg_empty]~^ WARN unexpected `cfg` condition name: `foo`
pub fn foo() {}

pub mod module {
#[allow(unexpected_cfgs)]
#[doc(cfg(bar))]
pub fn bar() {}
}
4 changes: 3 additions & 1 deletion tests/rustdoc-ui/doc-cfg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
#[doc(cfg(), cfg(foo, bar))]
//~^ ERROR
//~^^ ERROR
#[doc(cfg(foo), cfg(bar))] // ok!
#[doc(cfg(foo), cfg(bar))]
//~^ WARN unexpected `cfg` condition name: `foo`
//~^^ WARN unexpected `cfg` condition name: `bar`
#[doc(cfg())] //~ ERROR
#[doc(cfg(foo, bar))] //~ ERROR
pub fn foo() {}
26 changes: 23 additions & 3 deletions tests/rustdoc-ui/doc-cfg.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,37 @@ error: multiple `cfg` predicates are specified
LL | #[doc(cfg(), cfg(foo, bar))]
| ^^^

warning: unexpected `cfg` condition name: `foo`
--> $DIR/doc-cfg.rs:6:11
|
LL | #[doc(cfg(foo), cfg(bar))]
| ^^^
|
= help: expected names are: `FALSE` and `test` and 31 more
= help: to expect this configuration use `--check-cfg=cfg(foo)`
= note: see <https://doc.rust-lang.org/nightly/rustc/check-cfg.html> for more information about checking conditional configuration
= note: `#[warn(unexpected_cfgs)]` on by default

warning: unexpected `cfg` condition name: `bar`
--> $DIR/doc-cfg.rs:6:21
|
LL | #[doc(cfg(foo), cfg(bar))]
| ^^^
|
= help: to expect this configuration use `--check-cfg=cfg(bar)`
= note: see <https://doc.rust-lang.org/nightly/rustc/check-cfg.html> for more information about checking conditional configuration

error: `cfg` predicate is not specified
--> $DIR/doc-cfg.rs:7:7
--> $DIR/doc-cfg.rs:9:7
|
LL | #[doc(cfg())]
| ^^^^^ help: expected syntax is: `cfg(/* predicate */)`

error: multiple `cfg` predicates are specified
--> $DIR/doc-cfg.rs:8:16
--> $DIR/doc-cfg.rs:10:16
|
LL | #[doc(cfg(foo, bar))]
| ^^^

error: aborting due to 4 previous errors
error: aborting due to 4 previous errors; 2 warnings emitted

Loading