Skip to content

Commit 150d59c

Browse files
committed
Improved collapse_debuginfo attribute, added command-line flag (no|external|yes)
1 parent bf2637f commit 150d59c

20 files changed

+312
-25
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

+74-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,75 @@ 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+
let item = l[0].meta_item();
776+
item.map_or(CollapseMacroDebuginfo::Unspecified, |mi| {
777+
if !mi.is_word() {
778+
sess.dcx().emit_err(CollapseMacroDebuginfoIllegal { span: mi.span });
779+
CollapseMacroDebuginfo::Unspecified
780+
} else {
781+
match mi.name_or_empty() {
782+
sym::no => CollapseMacroDebuginfo::No,
783+
sym::external => CollapseMacroDebuginfo::External,
784+
sym::yes => CollapseMacroDebuginfo::Yes,
785+
_ => {
786+
sess.dcx().emit_err(CollapseMacroDebuginfoIllegal { span: mi.span });
787+
CollapseMacroDebuginfo::Unspecified
788+
}
789+
}
790+
}
791+
})
792+
})
793+
}
794+
795+
/// if-ext - if macro from different crate (related to callsite code)
796+
/// | cmd \ attr | no | (unspecified) | external | yes |
797+
/// | no | no | no | no | no |
798+
/// | (unspecified) | no | no | if-ext | yes |
799+
/// | external | no | if-ext | if-ext | yes |
800+
/// | yes | yes | yes | yes | yes |
801+
pub fn should_collapse(
802+
flag: CollapseMacroDebuginfo,
803+
attr: CollapseMacroDebuginfo,
804+
ext: bool,
805+
) -> bool {
806+
#[rustfmt::skip]
807+
let collapse_table = [
808+
[false, false, false, false],
809+
[false, false, ext, true],
810+
[false, ext, ext, true],
811+
[true, true, true, true],
812+
];
813+
let rv = collapse_table[flag as usize][attr as usize];
814+
tracing::debug!(?flag, ?attr, ?ext, ?rv);
815+
rv
816+
}
817+
818+
fn get_collapse_debuginfo(
819+
sess: &Session,
820+
span: Span,
821+
attrs: &[ast::Attribute],
822+
is_local: bool,
823+
) -> bool {
824+
let collapse_debuginfo_attr = attr::find_by_name(attrs, sym::collapse_debuginfo)
825+
.map(|v| Self::collapse_debuginfo_by_name(sess, v))
826+
.unwrap_or(CollapseMacroDebuginfo::Unspecified);
827+
debug!("get_collapse_debuginfo span {:?} attrs: {:?}, is_ext: {}", span, attrs, !is_local);
828+
Self::should_collapse(
829+
sess.opts.unstable_opts.collapse_macro_debuginfo,
830+
collapse_debuginfo_attr,
831+
!is_local,
832+
)
833+
}
834+
764835
/// Constructs a syntax extension with the given properties
765836
/// and other properties converted from attributes.
766837
pub fn new(
@@ -772,6 +843,7 @@ impl SyntaxExtension {
772843
edition: Edition,
773844
name: Symbol,
774845
attrs: &[ast::Attribute],
846+
is_local: bool,
775847
) -> SyntaxExtension {
776848
let allow_internal_unstable =
777849
attr::allow_internal_unstable(sess, attrs).collect::<Vec<Symbol>>();
@@ -780,8 +852,8 @@ impl SyntaxExtension {
780852
let local_inner_macros = attr::find_by_name(attrs, sym::macro_export)
781853
.and_then(|macro_export| macro_export.meta_item_list())
782854
.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);
855+
let collapse_debuginfo = Self::get_collapse_debuginfo(sess, span, attrs, is_local);
856+
tracing::debug!(?name, ?local_inner_macros, ?collapse_debuginfo, ?allow_internal_unsafe);
785857

786858
let (builtin_name, helper_attrs) = attr::find_by_name(attrs, sym::rustc_builtin_macro)
787859
.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

+2
Original file line numberDiff line numberDiff line change
@@ -355,6 +355,7 @@ pub fn compile_declarative_macro(
355355
features: &Features,
356356
def: &ast::Item,
357357
edition: Edition,
358+
is_local: bool,
358359
) -> (SyntaxExtension, Vec<(usize, Span)>) {
359360
debug!("compile_declarative_macro: {:?}", def);
360361
let mk_syn_ext = |expander| {
@@ -367,6 +368,7 @@ pub fn compile_declarative_macro(
367368
edition,
368369
def.ident.name,
369370
&def.attrs,
371+
is_local,
370372
)
371373
};
372374
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_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_resolve/src/build_reduced_graph.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
171171

172172
let loaded_macro = self.cstore().load_macro_untracked(def_id, self.tcx);
173173
let macro_data = match loaded_macro {
174-
LoadedMacro::MacroDef(item, edition) => self.compile_macro(&item, edition),
174+
LoadedMacro::MacroDef(item, edition) => self.compile_macro(&item, edition, false),
175175
LoadedMacro::ProcMacro(ext) => MacroData::new(Lrc::new(ext)),
176176
};
177177

compiler/rustc_resolve/src/def_collector.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,8 @@ impl<'a, 'b, 'tcx> visit::Visitor<'a> for DefCollector<'a, 'b, 'tcx> {
113113
ItemKind::Const(..) => DefKind::Const,
114114
ItemKind::Fn(..) | ItemKind::Delegation(..) => DefKind::Fn,
115115
ItemKind::MacroDef(..) => {
116-
let macro_data = self.resolver.compile_macro(i, self.resolver.tcx.sess.edition());
116+
let macro_data =
117+
self.resolver.compile_macro(i, self.resolver.tcx.sess.edition(), true);
117118
let macro_kind = macro_data.ext.macro_kind();
118119
opt_macro_data = Some(macro_data);
119120
DefKind::Macro(macro_kind)

compiler/rustc_resolve/src/macros.rs

+7-2
Original file line numberDiff line numberDiff line change
@@ -926,9 +926,14 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
926926
/// Compile the macro into a `SyntaxExtension` and its rule spans.
927927
///
928928
/// Possibly replace its expander to a pre-defined one for built-in macros.
929-
pub(crate) fn compile_macro(&mut self, item: &ast::Item, edition: Edition) -> MacroData {
929+
pub(crate) fn compile_macro(
930+
&mut self,
931+
item: &ast::Item,
932+
edition: Edition,
933+
is_local: bool,
934+
) -> MacroData {
930935
let (mut ext, mut rule_spans) =
931-
compile_declarative_macro(self.tcx.sess, self.tcx.features(), item, edition);
936+
compile_declarative_macro(self.tcx.sess, self.tcx.features(), item, edition, is_local);
932937

933938
if let Some(builtin_name) = ext.builtin_name {
934939
// The macro was marked with `#[rustc_builtin_macro]`.

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 command line flag enables collapsing
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,

0 commit comments

Comments
 (0)