Skip to content

Commit c0da80f

Browse files
authored
Rollup merge of rust-lang#119828 - azhogin:azhogin/collapse_debuginfo_improved_attr, r=petrochenkov
Improved collapse_debuginfo attribute, added command-line flag Improved attribute collapse_debuginfo with variants: `#[collapse_debuginfo=(no|external|yes)]`. Added command-line flag for default behaviour. Work-in-progress: will add more tests. cc rust-lang#100758
2 parents 16489f7 + 8507f51 commit c0da80f

17 files changed

+281
-21
lines changed

compiler/rustc_expand/messages.ftl

+3
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,9 @@ expand_attributes_wrong_form =
1616
expand_cannot_be_name_of_macro =
1717
`{$trait_ident}` cannot be a name of {$macro_type} macro
1818
19+
expand_collapse_debuginfo_illegal =
20+
illegal value for attribute #[collapse_debuginfo(no|external|yes)]
21+
1922
expand_count_repetition_misplaced =
2023
`count` can not be placed inside the inner-most repetition
2124

compiler/rustc_expand/src/base.rs

+54-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
#![deny(rustc::untranslatable_diagnostic)]
22

3+
use crate::base::ast::NestedMetaItem;
34
use crate::errors;
45
use crate::expand::{self, AstFragment, Invocation};
56
use crate::module::DirOwnership;
@@ -19,6 +20,7 @@ use rustc_feature::Features;
1920
use rustc_lint_defs::builtin::PROC_MACRO_BACK_COMPAT;
2021
use rustc_lint_defs::{BufferedEarlyLint, BuiltinLintDiagnostics, RegisteredTools};
2122
use rustc_parse::{parser, MACRO_ARGUMENTS};
23+
use rustc_session::config::CollapseMacroDebuginfo;
2224
use rustc_session::errors::report_lit_error;
2325
use rustc_session::{parse::ParseSess, Limit, Session};
2426
use rustc_span::def_id::{CrateNum, DefId, LocalDefId};
@@ -761,6 +763,55 @@ impl SyntaxExtension {
761763
}
762764
}
763765

766+
fn collapse_debuginfo_by_name(sess: &Session, attr: &Attribute) -> CollapseMacroDebuginfo {
767+
use crate::errors::CollapseMacroDebuginfoIllegal;
768+
// #[collapse_debuginfo] without enum value (#[collapse_debuginfo(no/external/yes)])
769+
// considered as `yes`
770+
attr.meta_item_list().map_or(CollapseMacroDebuginfo::Yes, |l| {
771+
let [NestedMetaItem::MetaItem(item)] = &l[..] else {
772+
sess.dcx().emit_err(CollapseMacroDebuginfoIllegal { span: attr.span });
773+
return CollapseMacroDebuginfo::Unspecified;
774+
};
775+
if !item.is_word() {
776+
sess.dcx().emit_err(CollapseMacroDebuginfoIllegal { span: item.span });
777+
CollapseMacroDebuginfo::Unspecified
778+
} else {
779+
match item.name_or_empty() {
780+
sym::no => CollapseMacroDebuginfo::No,
781+
sym::external => CollapseMacroDebuginfo::External,
782+
sym::yes => CollapseMacroDebuginfo::Yes,
783+
_ => {
784+
sess.dcx().emit_err(CollapseMacroDebuginfoIllegal { span: item.span });
785+
CollapseMacroDebuginfo::Unspecified
786+
}
787+
}
788+
}
789+
})
790+
}
791+
792+
/// if-ext - if macro from different crate (related to callsite code)
793+
/// | cmd \ attr | no | (unspecified) | external | yes |
794+
/// | no | no | no | no | no |
795+
/// | (unspecified) | no | no | if-ext | yes |
796+
/// | external | no | if-ext | if-ext | yes |
797+
/// | yes | yes | yes | yes | yes |
798+
fn get_collapse_debuginfo(sess: &Session, attrs: &[ast::Attribute], is_local: bool) -> bool {
799+
let collapse_debuginfo_attr = attr::find_by_name(attrs, sym::collapse_debuginfo)
800+
.map(|v| Self::collapse_debuginfo_by_name(sess, v))
801+
.unwrap_or(CollapseMacroDebuginfo::Unspecified);
802+
let flag = sess.opts.unstable_opts.collapse_macro_debuginfo;
803+
let attr = collapse_debuginfo_attr;
804+
let ext = !is_local;
805+
#[rustfmt::skip]
806+
let collapse_table = [
807+
[false, false, false, false],
808+
[false, false, ext, true],
809+
[false, ext, ext, true],
810+
[true, true, true, true],
811+
];
812+
collapse_table[flag as usize][attr as usize]
813+
}
814+
764815
/// Constructs a syntax extension with the given properties
765816
/// and other properties converted from attributes.
766817
pub fn new(
@@ -772,6 +823,7 @@ impl SyntaxExtension {
772823
edition: Edition,
773824
name: Symbol,
774825
attrs: &[ast::Attribute],
826+
is_local: bool,
775827
) -> SyntaxExtension {
776828
let allow_internal_unstable =
777829
attr::allow_internal_unstable(sess, attrs).collect::<Vec<Symbol>>();
@@ -780,8 +832,8 @@ impl SyntaxExtension {
780832
let local_inner_macros = attr::find_by_name(attrs, sym::macro_export)
781833
.and_then(|macro_export| macro_export.meta_item_list())
782834
.is_some_and(|l| attr::list_contains_name(&l, sym::local_inner_macros));
783-
let collapse_debuginfo = attr::contains_name(attrs, sym::collapse_debuginfo);
784-
tracing::debug!(?local_inner_macros, ?collapse_debuginfo, ?allow_internal_unsafe);
835+
let collapse_debuginfo = Self::get_collapse_debuginfo(sess, attrs, is_local);
836+
tracing::debug!(?name, ?local_inner_macros, ?collapse_debuginfo, ?allow_internal_unsafe);
785837

786838
let (builtin_name, helper_attrs) = attr::find_by_name(attrs, sym::rustc_builtin_macro)
787839
.map(|attr| {

compiler/rustc_expand/src/errors.rs

+7
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,13 @@ pub(crate) struct ResolveRelativePath {
5858
pub path: String,
5959
}
6060

61+
#[derive(Diagnostic)]
62+
#[diag(expand_collapse_debuginfo_illegal)]
63+
pub(crate) struct CollapseMacroDebuginfoIllegal {
64+
#[primary_span]
65+
pub span: Span,
66+
}
67+
6168
#[derive(Diagnostic)]
6269
#[diag(expand_macro_const_stability)]
6370
pub(crate) struct MacroConstStability {

compiler/rustc_expand/src/mbe/macro_rules.rs

+1
Original file line numberDiff line numberDiff line change
@@ -367,6 +367,7 @@ pub fn compile_declarative_macro(
367367
edition,
368368
def.ident.name,
369369
&def.attrs,
370+
def.id != DUMMY_NODE_ID,
370371
)
371372
};
372373
let dummy_syn_ext = || (mk_syn_ext(Box::new(macro_rules_dummy_expander)), Vec::new());

compiler/rustc_feature/src/builtin_attrs.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -469,7 +469,7 @@ pub const BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[
469469

470470
// `#[collapse_debuginfo]`
471471
gated!(
472-
collapse_debuginfo, Normal, template!(Word), WarnFollowing,
472+
collapse_debuginfo, Normal, template!(Word, List: "no|external|yes"), ErrorFollowing,
473473
experimental!(collapse_debuginfo)
474474
),
475475

compiler/rustc_interface/src/tests.rs

+5-4
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,10 @@ use rustc_data_structures::profiling::TimePassesFormat;
44
use rustc_errors::{emitter::HumanReadableErrorType, registry, ColorConfig};
55
use rustc_session::config::{
66
build_configuration, build_session_options, rustc_optgroups, BranchProtection, CFGuard, Cfg,
7-
DebugInfo, DumpMonoStatsFormat, ErrorOutputType, ExternEntry, ExternLocation, Externs,
8-
FunctionReturn, InliningThreshold, Input, InstrumentCoverage, InstrumentXRay,
9-
LinkSelfContained, LinkerPluginLto, LocationDetail, LtoCli, NextSolverConfig, OomStrategy,
10-
Options, OutFileName, OutputType, OutputTypes, PAuthKey, PacRet, Passes, Polonius,
7+
CollapseMacroDebuginfo, DebugInfo, DumpMonoStatsFormat, ErrorOutputType, ExternEntry,
8+
ExternLocation, Externs, FunctionReturn, InliningThreshold, Input, InstrumentCoverage,
9+
InstrumentXRay, LinkSelfContained, LinkerPluginLto, LocationDetail, LtoCli, NextSolverConfig,
10+
OomStrategy, Options, OutFileName, OutputType, OutputTypes, PAuthKey, PacRet, Passes, Polonius,
1111
ProcMacroExecutionStrategy, Strip, SwitchWithOptPath, SymbolManglingVersion, WasiExecModel,
1212
};
1313
use rustc_session::lint::Level;
@@ -742,6 +742,7 @@ fn test_unstable_options_tracking_hash() {
742742
})
743743
);
744744
tracked!(codegen_backend, Some("abc".to_string()));
745+
tracked!(collapse_macro_debuginfo, CollapseMacroDebuginfo::Yes);
745746
tracked!(crate_attr, vec!["abc".to_string()]);
746747
tracked!(cross_crate_inline_threshold, InliningThreshold::Always);
747748
tracked!(debug_info_for_profiling, true);

compiler/rustc_metadata/src/rmeta/decoder.rs

+1
Original file line numberDiff line numberDiff line change
@@ -1027,6 +1027,7 @@ impl<'a, 'tcx> CrateMetadataRef<'a> {
10271027
self.root.edition,
10281028
Symbol::intern(name),
10291029
&attrs,
1030+
false,
10301031
)
10311032
}
10321033

compiler/rustc_middle/src/ty/mod.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -2535,8 +2535,7 @@ impl<'tcx> TyCtxt<'tcx> {
25352535
if self.sess.opts.unstable_opts.debug_macros || !span.from_expansion() {
25362536
return span;
25372537
}
2538-
let collapse_debuginfo_enabled = self.features().collapse_debuginfo;
2539-
hygiene::walk_chain_collapsed(span, upto, collapse_debuginfo_enabled)
2538+
hygiene::walk_chain_collapsed(span, upto, self.features().collapse_debuginfo)
25402539
}
25412540

25422541
#[inline]

compiler/rustc_session/src/config.rs

+26-6
Original file line numberDiff line numberDiff line change
@@ -3190,12 +3190,12 @@ pub enum WasiExecModel {
31903190
/// how the hash should be calculated when adding a new command-line argument.
31913191
pub(crate) mod dep_tracking {
31923192
use super::{
3193-
BranchProtection, CFGuard, CFProtection, CrateType, DebugInfo, DebugInfoCompression,
3194-
ErrorOutputType, FunctionReturn, InliningThreshold, InstrumentCoverage, InstrumentXRay,
3195-
LinkerPluginLto, LocationDetail, LtoCli, NextSolverConfig, OomStrategy, OptLevel,
3196-
OutFileName, OutputType, OutputTypes, Polonius, RemapPathScopeComponents, ResolveDocLinks,
3197-
SourceFileHashAlgorithm, SplitDwarfKind, SwitchWithOptPath, SymbolManglingVersion,
3198-
WasiExecModel,
3193+
BranchProtection, CFGuard, CFProtection, CollapseMacroDebuginfo, CrateType, DebugInfo,
3194+
DebugInfoCompression, ErrorOutputType, FunctionReturn, InliningThreshold,
3195+
InstrumentCoverage, InstrumentXRay, LinkerPluginLto, LocationDetail, LtoCli,
3196+
NextSolverConfig, OomStrategy, OptLevel, OutFileName, OutputType, OutputTypes, Polonius,
3197+
RemapPathScopeComponents, ResolveDocLinks, SourceFileHashAlgorithm, SplitDwarfKind,
3198+
SwitchWithOptPath, SymbolManglingVersion, WasiExecModel,
31993199
};
32003200
use crate::lint;
32013201
use crate::utils::NativeLib;
@@ -3274,6 +3274,7 @@ pub(crate) mod dep_tracking {
32743274
LtoCli,
32753275
DebugInfo,
32763276
DebugInfoCompression,
3277+
CollapseMacroDebuginfo,
32773278
UnstableFeatures,
32783279
NativeLib,
32793280
SanitizerSet,
@@ -3437,6 +3438,25 @@ pub enum ProcMacroExecutionStrategy {
34373438
CrossThread,
34383439
}
34393440

3441+
/// How to perform collapse macros debug info
3442+
/// if-ext - if macro from different crate (related to callsite code)
3443+
/// | cmd \ attr | no | (unspecified) | external | yes |
3444+
/// | no | no | no | no | no |
3445+
/// | (unspecified) | no | no | if-ext | yes |
3446+
/// | external | no | if-ext | if-ext | yes |
3447+
/// | yes | yes | yes | yes | yes |
3448+
#[derive(Clone, Copy, PartialEq, Hash, Debug)]
3449+
pub enum CollapseMacroDebuginfo {
3450+
/// Don't collapse debuginfo for the macro
3451+
No = 0,
3452+
/// Unspecified value
3453+
Unspecified = 1,
3454+
/// Collapse debuginfo if the macro comes from a different crate
3455+
External = 2,
3456+
/// Collapse debuginfo for the macro
3457+
Yes = 3,
3458+
}
3459+
34403460
/// Which format to use for `-Z dump-mono-stats`
34413461
#[derive(Clone, Copy, PartialEq, Hash, Debug)]
34423462
pub enum DumpMonoStatsFormat {

compiler/rustc_session/src/options.rs

+17
Original file line numberDiff line numberDiff line change
@@ -388,6 +388,7 @@ mod desc {
388388
pub const parse_cfprotection: &str = "`none`|`no`|`n` (default), `branch`, `return`, or `full`|`yes`|`y` (equivalent to `branch` and `return`)";
389389
pub const parse_debuginfo: &str = "either an integer (0, 1, 2), `none`, `line-directives-only`, `line-tables-only`, `limited`, or `full`";
390390
pub const parse_debuginfo_compression: &str = "one of `none`, `zlib`, or `zstd`";
391+
pub const parse_collapse_macro_debuginfo: &str = "one of `no`, `external`, or `yes`";
391392
pub const parse_strip: &str = "either `none`, `debuginfo`, or `symbols`";
392393
pub const parse_linker_flavor: &str = ::rustc_target::spec::LinkerFlavorCli::one_of();
393394
pub const parse_optimization_fuel: &str = "crate=integer";
@@ -1302,6 +1303,19 @@ mod parse {
13021303
true
13031304
}
13041305

1306+
pub(crate) fn parse_collapse_macro_debuginfo(
1307+
slot: &mut CollapseMacroDebuginfo,
1308+
v: Option<&str>,
1309+
) -> bool {
1310+
*slot = match v {
1311+
Some("no") => CollapseMacroDebuginfo::No,
1312+
Some("external") => CollapseMacroDebuginfo::External,
1313+
Some("yes") => CollapseMacroDebuginfo::Yes,
1314+
_ => return false,
1315+
};
1316+
true
1317+
}
1318+
13051319
pub(crate) fn parse_proc_macro_execution_strategy(
13061320
slot: &mut ProcMacroExecutionStrategy,
13071321
v: Option<&str>,
@@ -1534,6 +1548,9 @@ options! {
15341548
"instrument control-flow architecture protection"),
15351549
codegen_backend: Option<String> = (None, parse_opt_string, [TRACKED],
15361550
"the backend to use"),
1551+
collapse_macro_debuginfo: CollapseMacroDebuginfo = (CollapseMacroDebuginfo::Unspecified,
1552+
parse_collapse_macro_debuginfo, [TRACKED],
1553+
"set option to collapse debuginfo for macros"),
15371554
combine_cgu: bool = (false, parse_bool, [TRACKED],
15381555
"combine CGUs into a single one"),
15391556
crate_attr: Vec<String> = (Vec::new(), parse_string_push, [TRACKED],

compiler/rustc_span/src/hygiene.rs

+14-5
Original file line numberDiff line numberDiff line change
@@ -464,20 +464,23 @@ impl HygieneData {
464464
&self,
465465
mut span: Span,
466466
to: Span,
467-
collapse_debuginfo_enabled: bool,
467+
collapse_debuginfo_feature_enabled: bool,
468468
) -> Span {
469469
let orig_span = span;
470470
let mut ret_span = span;
471471

472-
debug!("walk_chain_collapsed({:?}, {:?})", span, to);
472+
debug!(
473+
"walk_chain_collapsed({:?}, {:?}), feature_enable={}",
474+
span, to, collapse_debuginfo_feature_enabled,
475+
);
473476
debug!("walk_chain_collapsed: span ctxt = {:?}", span.ctxt());
474477
while !span.eq_ctxt(to) && span.from_expansion() {
475478
let outer_expn = self.outer_expn(span.ctxt());
476479
debug!("walk_chain_collapsed({:?}): outer_expn={:?}", span, outer_expn);
477480
let expn_data = self.expn_data(outer_expn);
478481
debug!("walk_chain_collapsed({:?}): expn_data={:?}", span, expn_data);
479482
span = expn_data.call_site;
480-
if !collapse_debuginfo_enabled || expn_data.collapse_debuginfo {
483+
if !collapse_debuginfo_feature_enabled || expn_data.collapse_debuginfo {
481484
ret_span = span;
482485
}
483486
}
@@ -601,8 +604,14 @@ pub fn walk_chain(span: Span, to: SyntaxContext) -> Span {
601604
HygieneData::with(|data| data.walk_chain(span, to))
602605
}
603606

604-
pub fn walk_chain_collapsed(span: Span, to: Span, collapse_debuginfo_enabled: bool) -> Span {
605-
HygieneData::with(|hdata| hdata.walk_chain_collapsed(span, to, collapse_debuginfo_enabled))
607+
pub fn walk_chain_collapsed(
608+
span: Span,
609+
to: Span,
610+
collapse_debuginfo_feature_enabled: bool,
611+
) -> Span {
612+
HygieneData::with(|hdata| {
613+
hdata.walk_chain_collapsed(span, to, collapse_debuginfo_feature_enabled)
614+
})
606615
}
607616

608617
pub fn update_dollar_crate_names(mut get_name: impl FnMut(SyntaxContext) -> Symbol) {

compiler/rustc_span/src/symbol.rs

+2
Original file line numberDiff line numberDiff line change
@@ -749,6 +749,7 @@ symbols! {
749749
extern_in_paths,
750750
extern_prelude,
751751
extern_types,
752+
external,
752753
external_doc,
753754
f,
754755
f16c_target_feature,
@@ -1811,6 +1812,7 @@ symbols! {
18111812
xmm_reg,
18121813
yeet_desugar_details,
18131814
yeet_expr,
1815+
yes,
18141816
yield_expr,
18151817
ymm_reg,
18161818
zmm_reg,
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
// ignore-lldb
2+
#![feature(collapse_debuginfo)]
3+
4+
// Test that local macro debug info is not collapsed with #[collapse_debuginfo(external)]
5+
6+
// compile-flags:-g
7+
8+
// === GDB TESTS ===================================================================================
9+
10+
// gdb-command:run
11+
// gdb-command:next
12+
// gdb-command:frame
13+
// gdb-check:[...]#one_callsite[...]
14+
// gdb-command:continue
15+
16+
fn one() {
17+
println!("one");
18+
}
19+
20+
#[collapse_debuginfo(external)]
21+
macro_rules! outer {
22+
() => {
23+
one(); // #one_callsite
24+
};
25+
}
26+
27+
fn main() {
28+
let ret = 0; // #break
29+
outer!();
30+
std::process::exit(ret);
31+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// ignore-lldb
2+
#![feature(collapse_debuginfo)]
3+
4+
// Test that macro attribute #[collapse_debuginfo(no)]
5+
// overrides "collapse_macro_debuginfo=external" flag
6+
7+
// compile-flags:-g -Z collapse_macro_debuginfo=external
8+
9+
// === GDB TESTS ===================================================================================
10+
11+
// gdb-command:run
12+
// gdb-command:next
13+
// gdb-command:frame
14+
// gdb-check:[...]#one_callsite[...]
15+
// gdb-command:next
16+
// gdb-command:frame
17+
// gdb-command:continue
18+
19+
fn one() {
20+
println!("one");
21+
}
22+
23+
#[collapse_debuginfo(no)]
24+
macro_rules! outer {
25+
() => {
26+
one(); // #one_callsite
27+
};
28+
}
29+
30+
fn main() {
31+
let ret = 0; // #break
32+
outer!();
33+
std::process::exit(ret);
34+
}

0 commit comments

Comments
 (0)