Auto merge of #138515 - petrochenkov:cfgtrace, r=nnethercote

expand: Leave traces when expanding `cfg_attr` attributes

Currently `cfg_trace` just disappears during expansion, but after this PR `#[cfg_attr(some tokens)]` will leave a `#[cfg_attr_trace(some tokens)]` attribute instead of itself in AST after expansion (the new attribute is built-in and inert, its inner tokens are the same as in the original attribute).
This trace attribute can then be used by lints or other diagnostics, #133823 has some examples.

Tokens in these trace attributes are set to an empty token stream, so the traces are non-existent for proc macros and cannot affect any user-observable behavior.
This is also a weakness, because if a proc macro processes some code with the trace attributes, they will be lost, so the traces are best effort rather than precise.

The next step is to do the same thing with `cfg` attributes (`#[cfg(TRUE)]` currently remains in both AST and tokens after expanding, it should be replaced with a trace instead).

The idea belongs to `@estebank.`
This commit is contained in:
bors 2025-03-20 19:24:48 +00:00
commit 78948ac259
10 changed files with 136 additions and 19 deletions

View file

@ -272,6 +272,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
| sym::forbid
| sym::cfg
| sym::cfg_attr
| sym::cfg_attr_trace
// need to be fixed
| sym::cfi_encoding // FIXME(cfi_encoding)
| sym::pointee // FIXME(derive_coerce_pointee)
@ -575,6 +576,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
// conditional compilation
sym::cfg,
sym::cfg_attr,
sym::cfg_attr_trace,
// testing (allowed here so better errors can be generated in `rustc_builtin_macros::test`)
sym::test,
sym::ignore,
@ -2641,7 +2643,7 @@ impl<'tcx> Visitor<'tcx> for CheckAttrVisitor<'tcx> {
// only `#[cfg]` and `#[cfg_attr]` are allowed, but it should be removed
// if we allow more attributes (e.g., tool attributes and `allow/deny/warn`)
// in where clauses. After that, only `self.check_attributes` should be enough.
const ATTRS_ALLOWED: &[Symbol] = &[sym::cfg, sym::cfg_attr];
const ATTRS_ALLOWED: &[Symbol] = &[sym::cfg, sym::cfg_attr, sym::cfg_attr_trace];
let spans = self
.tcx
.hir_attrs(where_predicate.hir_id)