Skip to content

Rollup of 9 pull requests #143840

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

Closed
wants to merge 21 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
75cea03
de-duplicate condition scoping logic
dianne Jun 28, 2025
fc557bc
clippy: conditions are no longer wrapped in `DropTemps`
dianne Jun 30, 2025
68d860f
remove `DesugaringKind::CondTemporary`
dianne Jun 30, 2025
c39a187
Be a bit more careful around exotic cycles in in the inliner
compiler-errors Jul 9, 2025
889582e
Check assoc consts and tys later like assoc fns
mu001999 Jul 6, 2025
f8e7813
make `cfg_select` a builtin macro
folkertdev Jul 4, 2025
e681d1a
constify `From` and `Into`
oli-obk Jul 11, 2025
34426dc
Fix fallback for CI_JOB_NAME
nikic Jul 11, 2025
2f05fa6
Fix ICE for parsed attributes with longer path not handled by CheckAt…
JonathanBrouwer Jul 11, 2025
cdbe44d
Use short command method directly from fingerprint
Shourya742 Jul 11, 2025
d004abb
remove format short command and push format short command method insi…
Shourya742 Jul 11, 2025
3751e13
slice: Mark `rotate_left`, `rotate_right` unstably const
okaneco Jul 6, 2025
d324c42
Rollup merge of #143213 - dianne:lower-cond-tweaks, r=cjgillot
matthiaskrgr Jul 12, 2025
d75363e
Rollup merge of #143461 - folkertdev:cfg-select-builtin-macro, r=petr…
matthiaskrgr Jul 12, 2025
9d11879
Rollup merge of #143519 - mu001999-contrib:dead-code/impl-items, r=pe…
matthiaskrgr Jul 12, 2025
14951c6
Rollup merge of #143554 - okaneco:const_slice_rotate, r=Amanieu,tgross35
matthiaskrgr Jul 12, 2025
a006d84
Rollup merge of #143704 - compiler-errors:cycle-exotic, r=cjgillot
matthiaskrgr Jul 12, 2025
041a306
Rollup merge of #143774 - oli-obk:const_from, r=fee1-dead
matthiaskrgr Jul 12, 2025
25c73fb
Rollup merge of #143786 - nikic:ci-job-name-fallback, r=marcoieni
matthiaskrgr Jul 12, 2025
04bf6fb
Rollup merge of #143796 - JonathanBrouwer:fix-builtin-attribute-prefi…
matthiaskrgr Jul 12, 2025
76c1c6c
Rollup merge of #143798 - Shourya742:2025-07-11-remove-format-short-c…
matthiaskrgr Jul 12, 2025
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
1 change: 1 addition & 0 deletions Cargo.lock
Original file line number Diff line number Diff line change
Expand Up @@ -4349,6 +4349,7 @@ dependencies = [
"rustc_ast_lowering",
"rustc_ast_pretty",
"rustc_attr_data_structures",
"rustc_attr_parsing",
"rustc_data_structures",
"rustc_errors",
"rustc_expand",
Expand Down
45 changes: 4 additions & 41 deletions compiler/rustc_ast_lowering/src/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -528,7 +528,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
then: &Block,
else_opt: Option<&Expr>,
) -> hir::ExprKind<'hir> {
let lowered_cond = self.lower_cond(cond);
let lowered_cond = self.lower_expr(cond);
let then_expr = self.lower_block_expr(then);
if let Some(rslt) = else_opt {
hir::ExprKind::If(
Expand All @@ -541,44 +541,6 @@ impl<'hir> LoweringContext<'_, 'hir> {
}
}

// Lowers a condition (i.e. `cond` in `if cond` or `while cond`), wrapping it in a terminating scope
// so that temporaries created in the condition don't live beyond it.
fn lower_cond(&mut self, cond: &Expr) -> &'hir hir::Expr<'hir> {
fn has_let_expr(expr: &Expr) -> bool {
match &expr.kind {
ExprKind::Binary(_, lhs, rhs) => has_let_expr(lhs) || has_let_expr(rhs),
ExprKind::Let(..) => true,
_ => false,
}
}

// We have to take special care for `let` exprs in the condition, e.g. in
// `if let pat = val` or `if foo && let pat = val`, as we _do_ want `val` to live beyond the
// condition in this case.
//
// In order to maintain the drop behavior for the non `let` parts of the condition,
// we still wrap them in terminating scopes, e.g. `if foo && let pat = val` essentially
// gets transformed into `if { let _t = foo; _t } && let pat = val`
match &cond.kind {
ExprKind::Binary(op @ Spanned { node: ast::BinOpKind::And, .. }, lhs, rhs)
if has_let_expr(cond) =>
{
let op = self.lower_binop(*op);
let lhs = self.lower_cond(lhs);
let rhs = self.lower_cond(rhs);

self.arena.alloc(self.expr(cond.span, hir::ExprKind::Binary(op, lhs, rhs)))
}
ExprKind::Let(..) => self.lower_expr(cond),
_ => {
let cond = self.lower_expr(cond);
let reason = DesugaringKind::CondTemporary;
let span_block = self.mark_span_with_reason(reason, cond.span, None);
self.expr_drop_temps(span_block, cond)
}
}
}

// We desugar: `'label: while $cond $body` into:
//
// ```
Expand All @@ -602,7 +564,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
body: &Block,
opt_label: Option<Label>,
) -> hir::ExprKind<'hir> {
let lowered_cond = self.with_loop_condition_scope(|t| t.lower_cond(cond));
let lowered_cond = self.with_loop_condition_scope(|t| t.lower_expr(cond));
let then = self.lower_block_expr(body);
let expr_break = self.expr_break(span);
let stmt_break = self.stmt_expr(span, expr_break);
Expand Down Expand Up @@ -2091,7 +2053,8 @@ impl<'hir> LoweringContext<'_, 'hir> {
/// In terms of drop order, it has the same effect as wrapping `expr` in
/// `{ let _t = $expr; _t }` but should provide better compile-time performance.
///
/// The drop order can be important in e.g. `if expr { .. }`.
/// The drop order can be important, e.g. to drop temporaries from an `async fn`
/// body before its parameters.
pub(super) fn expr_drop_temps(
&mut self,
span: Span,
Expand Down
5 changes: 5 additions & 0 deletions compiler/rustc_attr_parsing/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -735,6 +735,11 @@ impl<'sess, S: Stage> AttributeParser<'sess, S> {
attributes
}

/// Returns whether there is a parser for an attribute with this name
pub fn is_parsed_attribute(path: &[Symbol]) -> bool {
Late::parsers().0.contains_key(path)
}

fn lower_attr_args(&self, args: &ast::AttrArgs, lower_span: impl Fn(Span) -> Span) -> AttrArgs {
match args {
ast::AttrArgs::Empty => AttrArgs::Empty,
Expand Down
6 changes: 6 additions & 0 deletions compiler/rustc_builtin_macros/messages.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,12 @@ builtin_macros_cfg_accessible_literal_path = `cfg_accessible` path cannot be a l
builtin_macros_cfg_accessible_multiple_paths = multiple `cfg_accessible` paths are specified
builtin_macros_cfg_accessible_unspecified_path = `cfg_accessible` path is not specified
builtin_macros_cfg_select_no_matches = none of the rules in this `cfg_select` evaluated to true
builtin_macros_cfg_select_unreachable = unreachable rule
.label = always matches
.label2 = this rules is never reached
builtin_macros_coerce_pointee_requires_maybe_sized = `derive(CoercePointee)` requires `{$name}` to be marked `?Sized`
builtin_macros_coerce_pointee_requires_one_field = `CoercePointee` can only be derived on `struct`s with at least one field
Expand Down
63 changes: 63 additions & 0 deletions compiler/rustc_builtin_macros/src/cfg_select.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
use rustc_ast::tokenstream::TokenStream;
use rustc_attr_parsing as attr;
use rustc_expand::base::{DummyResult, ExpandResult, ExtCtxt, MacroExpanderResult};
use rustc_parse::parser::cfg_select::{CfgSelectBranches, CfgSelectRule, parse_cfg_select};
use rustc_span::{Ident, Span, sym};

use crate::errors::{CfgSelectNoMatches, CfgSelectUnreachable};

/// Selects the first arm whose rule evaluates to true.
fn select_arm(ecx: &ExtCtxt<'_>, branches: CfgSelectBranches) -> Option<(TokenStream, Span)> {
for (cfg, tt, arm_span) in branches.reachable {
if attr::cfg_matches(
&cfg,
&ecx.sess,
ecx.current_expansion.lint_node_id,
Some(ecx.ecfg.features),
) {
return Some((tt, arm_span));
}
}

branches.wildcard.map(|(_, tt, span)| (tt, span))
}

pub(super) fn expand_cfg_select<'cx>(
ecx: &'cx mut ExtCtxt<'_>,
sp: Span,
tts: TokenStream,
) -> MacroExpanderResult<'cx> {
ExpandResult::Ready(match parse_cfg_select(&mut ecx.new_parser_from_tts(tts)) {
Ok(branches) => {
if let Some((underscore, _, _)) = branches.wildcard {
// Warn for every unreachable rule. We store the fully parsed branch for rustfmt.
for (rule, _, _) in &branches.unreachable {
let span = match rule {
CfgSelectRule::Wildcard(underscore) => underscore.span,
CfgSelectRule::Cfg(cfg) => cfg.span(),
};
let err = CfgSelectUnreachable { span, wildcard_span: underscore.span };
ecx.dcx().emit_warn(err);
}
}

if let Some((tts, arm_span)) = select_arm(ecx, branches) {
return ExpandResult::from_tts(
ecx,
tts,
sp,
arm_span,
Ident::with_dummy_span(sym::cfg_select),
);
} else {
// Emit a compiler error when none of the rules matched.
let guar = ecx.dcx().emit_err(CfgSelectNoMatches { span: sp });
DummyResult::any(sp, guar)
}
}
Err(err) => {
let guar = err.emit();
DummyResult::any(sp, guar)
}
})
}
18 changes: 18 additions & 0 deletions compiler/rustc_builtin_macros/src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -954,3 +954,21 @@ pub(crate) struct AsmExpectedOther {
pub(crate) span: Span,
pub(crate) is_inline_asm: bool,
}

#[derive(Diagnostic)]
#[diag(builtin_macros_cfg_select_no_matches)]
pub(crate) struct CfgSelectNoMatches {
#[primary_span]
pub span: Span,
}

#[derive(Diagnostic)]
#[diag(builtin_macros_cfg_select_unreachable)]
pub(crate) struct CfgSelectUnreachable {
#[primary_span]
#[label(builtin_macros_label2)]
pub span: Span,

#[label]
pub wildcard_span: Span,
}
2 changes: 2 additions & 0 deletions compiler/rustc_builtin_macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ mod autodiff;
mod cfg;
mod cfg_accessible;
mod cfg_eval;
mod cfg_select;
mod compile_error;
mod concat;
mod concat_bytes;
Expand Down Expand Up @@ -79,6 +80,7 @@ pub fn register_builtin_macros(resolver: &mut dyn ResolverExpand) {
asm: asm::expand_asm,
assert: assert::expand_assert,
cfg: cfg::expand_cfg,
cfg_select: cfg_select::expand_cfg_select,
column: source_util::expand_column,
compile_error: compile_error::expand_compile_error,
concat: concat::expand_concat,
Expand Down
20 changes: 20 additions & 0 deletions compiler/rustc_expand/src/base.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ use thin_vec::ThinVec;
use crate::base::ast::MetaItemInner;
use crate::errors;
use crate::expand::{self, AstFragment, Invocation};
use crate::mbe::macro_rules::ParserAnyMacro;
use crate::module::DirOwnership;
use crate::stats::MacroStat;

Expand Down Expand Up @@ -262,6 +263,25 @@ impl<T, U> ExpandResult<T, U> {
}
}

impl<'cx> MacroExpanderResult<'cx> {
/// Creates a [`MacroExpanderResult::Ready`] from a [`TokenStream`].
///
/// The `TokenStream` is forwarded without any expansion.
pub fn from_tts(
cx: &'cx mut ExtCtxt<'_>,
tts: TokenStream,
site_span: Span,
arm_span: Span,
macro_ident: Ident,
) -> Self {
// Emit the SEMICOLON_IN_EXPRESSIONS_FROM_MACROS deprecation lint.
let is_local = true;

let parser = ParserAnyMacro::from_tts(cx, tts, site_span, arm_span, is_local, macro_ident);
ExpandResult::Ready(Box::new(parser))
}
}

pub trait MultiItemModifier {
/// `meta_item` is the attribute, and `item` is the item being modified.
fn expand(
Expand Down
65 changes: 38 additions & 27 deletions compiler/rustc_expand/src/mbe/macro_rules.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,30 @@ impl<'a> ParserAnyMacro<'a> {
ensure_complete_parse(parser, &path, kind.name(), site_span);
fragment
}

#[instrument(skip(cx, tts))]
pub(crate) fn from_tts<'cx>(
cx: &'cx mut ExtCtxt<'a>,
tts: TokenStream,
site_span: Span,
arm_span: Span,
is_local: bool,
macro_ident: Ident,
) -> Self {
Self {
parser: Parser::new(&cx.sess.psess, tts, None),

// Pass along the original expansion site and the name of the macro
// so we can print a useful error message if the parse of the expanded
// macro leaves unparsed tokens.
site_span,
macro_ident,
lint_node_id: cx.current_expansion.lint_node_id,
is_trailing_mac: cx.current_expansion.is_trailing_mac,
arm_span,
is_local,
}
}
}

pub(super) struct MacroRule {
Expand Down Expand Up @@ -207,9 +231,6 @@ fn expand_macro<'cx>(
rules: &[MacroRule],
) -> Box<dyn MacResult + 'cx> {
let psess = &cx.sess.psess;
// Macros defined in the current crate have a real node id,
// whereas macros from an external crate have a dummy id.
let is_local = node_id != DUMMY_NODE_ID;

if cx.trace_macros() {
let msg = format!("expanding `{}! {{ {} }}`", name, pprust::tts_to_string(&arg));
Expand All @@ -220,7 +241,7 @@ fn expand_macro<'cx>(
let try_success_result = try_match_macro(psess, name, &arg, rules, &mut NoopTracker);

match try_success_result {
Ok((i, rule, named_matches)) => {
Ok((rule_index, rule, named_matches)) => {
let mbe::TokenTree::Delimited(rhs_span, _, ref rhs) = rule.rhs else {
cx.dcx().span_bug(sp, "malformed macro rhs");
};
Expand All @@ -241,27 +262,13 @@ fn expand_macro<'cx>(
trace_macros_note(&mut cx.expansions, sp, msg);
}

let p = Parser::new(psess, tts, None);

let is_local = is_defined_in_current_crate(node_id);
if is_local {
cx.resolver.record_macro_rule_usage(node_id, i);
cx.resolver.record_macro_rule_usage(node_id, rule_index);
}

// Let the context choose how to interpret the result.
// Weird, but useful for X-macros.
Box::new(ParserAnyMacro {
parser: p,

// Pass along the original expansion site and the name of the macro
// so we can print a useful error message if the parse of the expanded
// macro leaves unparsed tokens.
site_span: sp,
macro_ident: name,
lint_node_id: cx.current_expansion.lint_node_id,
is_trailing_mac: cx.current_expansion.is_trailing_mac,
arm_span,
is_local,
})
// Let the context choose how to interpret the result. Weird, but useful for X-macros.
Box::new(ParserAnyMacro::from_tts(cx, tts, sp, arm_span, is_local, name))
}
Err(CanRetry::No(guar)) => {
debug!("Will not retry matching as an error was emitted already");
Expand Down Expand Up @@ -373,9 +380,9 @@ pub fn compile_declarative_macro(
node_id: NodeId,
edition: Edition,
) -> (SyntaxExtension, usize) {
let is_local = node_id != DUMMY_NODE_ID;
let mk_syn_ext = |expander| {
let kind = SyntaxExtensionKind::LegacyBang(expander);
let is_local = is_defined_in_current_crate(node_id);
SyntaxExtension::new(sess, kind, span, Vec::new(), edition, ident.name, attrs, is_local)
};
let dummy_syn_ext = |guar| (mk_syn_ext(Arc::new(DummyExpander(guar))), 0);
Expand Down Expand Up @@ -439,7 +446,7 @@ pub fn compile_declarative_macro(
}

// Return the number of rules for unused rule linting, if this is a local macro.
let nrules = if is_local { rules.len() } else { 0 };
let nrules = if is_defined_in_current_crate(node_id) { rules.len() } else { 0 };

let expander =
Arc::new(MacroRulesMacroExpander { name: ident, span, node_id, transparency, rules });
Expand Down Expand Up @@ -1034,9 +1041,7 @@ fn check_matcher_core<'tt>(
// definition of this macro_rules, not while (re)parsing
// the macro when compiling another crate that is using the
// macro. (See #86567.)
// Macros defined in the current crate have a real node id,
// whereas macros from an external crate have a dummy id.
if node_id != DUMMY_NODE_ID
if is_defined_in_current_crate(node_id)
&& matches!(kind, NonterminalKind::Pat(PatParam { inferred: true }))
&& matches!(
next_token,
Expand Down Expand Up @@ -1296,6 +1301,12 @@ fn quoted_tt_to_string(tt: &mbe::TokenTree) -> String {
}
}

fn is_defined_in_current_crate(node_id: NodeId) -> bool {
// Macros defined in the current crate have a real node id,
// whereas macros from an external crate have a dummy id.
node_id != DUMMY_NODE_ID
}

pub(super) fn parser_from_cx(
psess: &ParseSess,
mut tts: TokenStream,
Expand Down
Loading
Loading