Commit 7c2c3c0

Browse files
committed
Auto merge of #149063 - matthiaskrgr:rollup-6z23izv, r=matthiaskrgr
Rollup of 5 pull requests Successful merges: - #147887 (Improve the documentation of atomic::fence) - #148281 (repr(transparent) check: do not compute check_unsuited more than once) - #148484 (Fix suggestion for the `cfg!` macro) - #149057 (`rust-analyzer` subtree update) - #149061 (debug-assert FixedSizeEncoding invariant) r? `@ghost` `@rustbot` modify labels: rollup
2 parents 3d461af + ceb33e9 commit 7c2c3c0

82 files changed

Lines changed: 6193 additions & 513 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎compiler/rustc_attr_parsing/src/attributes/cfg.rs‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use rustc_ast::token::Delimiter;
22
use rustc_ast::tokenstream::DelimSpan;
33
use rustc_ast::{AttrItem,Attribute,CRATE_NODE_ID,LitKind,NodeId, ast, token};
44
use rustc_errors::{Applicability,PResult};
5-
use rustc_feature::{AttributeTemplate,Features, template};
5+
use rustc_feature::{AttrSuggestionStyle,AttributeTemplate,Features, template};
66
use rustc_hir::attrs::CfgEntry;
77
use rustc_hir::{AttrPath,RustcVersion};
88
use rustc_parse::parser::{ForceCollect,Parser};
@@ -323,8 +323,8 @@ pub fn parse_cfg_attr(
323323
}){
324324
Ok(r) => returnSome(r),
325325
Err(e) => {
326-
let suggestions =
327-
CFG_ATTR_TEMPLATE.suggestions(Some(cfg_attr.style), sym::cfg_attr);
326+
let suggestions =CFG_ATTR_TEMPLATE
327+
.suggestions(AttrSuggestionStyle::Attribute(cfg_attr.style), sym::cfg_attr);
328328
e.with_span_suggestions(
329329
cfg_attr.span,
330330
"must be of the form",
@@ -355,7 +355,8 @@ pub fn parse_cfg_attr(
355355
path:AttrPath::from_ast(&cfg_attr.get_normal_item().path),
356356
description:ParsedDescription::Attribute,
357357
reason,
358-
suggestions:CFG_ATTR_TEMPLATE.suggestions(Some(cfg_attr.style), sym::cfg_attr),
358+
suggestions:CFG_ATTR_TEMPLATE
359+
.suggestions(AttrSuggestionStyle::Attribute(cfg_attr.style), sym::cfg_attr),
359360
});
360361
}
361362
}

‎compiler/rustc_attr_parsing/src/context.rs‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ use std::sync::LazyLock;
66
use private::Sealed;
77
use rustc_ast::{AttrStyle,CRATE_NODE_ID,MetaItemLit,NodeId};
88
use rustc_errors::{Diag,Diagnostic,Level};
9-
use rustc_feature::AttributeTemplate;
9+
use rustc_feature::{AttrSuggestionStyle,AttributeTemplate};
1010
use rustc_hir::attrs::AttributeKind;
1111
use rustc_hir::lints::{AttributeLint,AttributeLintKind};
1212
use rustc_hir::{AttrPath,CRATE_HIR_ID,HirId};
@@ -637,9 +637,15 @@ impl<'f, 'sess: 'f, S: Stage> AcceptContext<'f, 'sess, S> {
637637
}
638638

639639
pub(crate)fnsuggestions(&self) -> Vec<String>{
640-
// If the outer and inner spans are equal, we are parsing an attribute from `cfg_attr`,
641-
// So don't display an attribute style in the suggestions
642-
let style = (self.attr_span != self.inner_span).then_some(self.attr_style);
640+
let style = matchself.parsed_description{
641+
// If the outer and inner spans are equal, we are parsing an embedded attribute
642+
ParsedDescription::Attributeifself.attr_span == self.inner_span => {
643+
AttrSuggestionStyle::EmbeddedAttribute
644+
}
645+
ParsedDescription::Attribute => AttrSuggestionStyle::Attribute(self.attr_style),
646+
ParsedDescription::Macro => AttrSuggestionStyle::Macro,
647+
};
648+
643649
self.template.suggestions(style,&self.attr_path)
644650
}
645651
}

‎compiler/rustc_feature/src/builtin_attrs.rs‎

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -132,28 +132,45 @@ pub struct AttributeTemplate {
132132
pubdocs:Option<&'staticstr>,
133133
}
134134

135+
pubenumAttrSuggestionStyle{
136+
/// The suggestion is styled for a normal attribute.
137+
/// The `AttrStyle` determines whether this is an inner or outer attribute.
138+
Attribute(AttrStyle),
139+
/// The suggestion is styled for an attribute embedded into another attribute.
140+
/// For example, attributes inside `#[cfg_attr(true, attr(...)]`.
141+
EmbeddedAttribute,
142+
/// The suggestion is styled for macros that are parsed with attribute parsers.
143+
/// For example, the `cfg!(predicate)` macro.
144+
Macro,
145+
}
146+
135147
implAttributeTemplate{
136148
pubfnsuggestions(
137149
&self,
138-
style:Option<AttrStyle>,
150+
style:AttrSuggestionStyle,
139151
name:impl std::fmt::Display,
140152
) -> Vec<String>{
141-
letmut suggestions = vec![];
142-
let(start, end) =match style {
143-
Some(AttrStyle::Outer) => ("#[","]"),
144-
Some(AttrStyle::Inner) => ("#![","]"),
145-
None => ("",""),
153+
let(start, macro_call, end) = match style {
154+
AttrSuggestionStyle::Attribute(AttrStyle::Outer) => ("#[","","]"),
155+
AttrSuggestionStyle::Attribute(AttrStyle::Inner) => ("#![","","]"),
156+
AttrSuggestionStyle::Macro => ("","!",""),
157+
AttrSuggestionStyle::EmbeddedAttribute => ("","",""),
146158
};
159+
160+
letmut suggestions = vec![];
161+
147162
ifself.word{
163+
debug_assert!(macro_call.is_empty(),"Macro suggestions use list style");
148164
suggestions.push(format!("{start}{name}{end}"));
149165
}
150166
ifletSome(descr) = self.list{
151167
for descr in descr {
152-
suggestions.push(format!("{start}{name}({descr}){end}"));
168+
suggestions.push(format!("{start}{name}{macro_call}({descr}){end}"));
153169
}
154170
}
155171
suggestions.extend(self.one_of.iter().map(|&word| format!("{start}{name}({word}){end}")));
156172
ifletSome(descr) = self.name_value_str{
173+
debug_assert!(macro_call.is_empty(),"Macro suggestions use list style");
157174
for descr in descr {
158175
suggestions.push(format!("{start}{name} = \"{descr}\"{end}"));
159176
}

‎compiler/rustc_feature/src/lib.rs‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -129,9 +129,10 @@ pub fn find_feature_issue(feature: Symbol, issue: GateIssue) -> Option<NonZero<u
129129

130130
pubuse accepted::ACCEPTED_LANG_FEATURES;
131131
pubuse builtin_attrs::{
132-
AttributeDuplicates,AttributeGate,AttributeSafety,AttributeTemplate,AttributeType,
133-
BUILTIN_ATTRIBUTE_MAP,BUILTIN_ATTRIBUTES,BuiltinAttribute,GatedCfg, encode_cross_crate,
134-
find_gated_cfg, is_builtin_attr_name, is_stable_diagnostic_attribute, is_valid_for_get_attr,
132+
AttrSuggestionStyle,AttributeDuplicates,AttributeGate,AttributeSafety,AttributeTemplate,
133+
AttributeType,BUILTIN_ATTRIBUTE_MAP,BUILTIN_ATTRIBUTES,BuiltinAttribute,GatedCfg,
134+
encode_cross_crate, find_gated_cfg, is_builtin_attr_name, is_stable_diagnostic_attribute,
135+
is_valid_for_get_attr,
135136
};
136137
pubuse removed::REMOVED_LANG_FEATURES;
137138
pubuse unstable::{

‎compiler/rustc_hir_analysis/src/check/check.rs‎

Lines changed: 56 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -1542,22 +1542,10 @@ pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>)
15421542

15431543
let typing_env = ty::TypingEnv::non_body_analysis(tcx, adt.did());
15441544
// For each field, figure out if it has "trivial" layout (i.e., is a 1-ZST).
1545-
// Even some 1-ZST fields are not allowed though, if they have `non_exhaustive` or private
1546-
// fields or `repr(C)`. We call those fields "unsuited".
15471545
structFieldInfo<'tcx>{
15481546
span:Span,
15491547
trivial:bool,
1550-
unsuited:Option<UnsuitedInfo<'tcx>>,
1551-
}
1552-
structUnsuitedInfo<'tcx>{
1553-
/// The source of the problem, a type that is found somewhere within the field type.
15541548
ty:Ty<'tcx>,
1555-
reason:UnsuitedReason,
1556-
}
1557-
enumUnsuitedReason{
1558-
NonExhaustive,
1559-
PrivateField,
1560-
ReprC,
15611549
}
15621550

15631551
let field_infos = adt.all_fields().map(|field| {
@@ -1566,60 +1554,7 @@ pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>)
15661554
// We are currently checking the type this field came from, so it must be local
15671555
let span = tcx.hir_span_if_local(field.did).unwrap();
15681556
let trivial = layout.is_ok_and(|layout| layout.is_1zst());
1569-
if !trivial {
1570-
// No need to even compute `unsuited`.
1571-
returnFieldInfo{ span, trivial,unsuited:None};
1572-
}
1573-
1574-
fncheck_unsuited<'tcx>(
1575-
tcx:TyCtxt<'tcx>,
1576-
typing_env: ty::TypingEnv<'tcx>,
1577-
ty:Ty<'tcx>,
1578-
) -> ControlFlow<UnsuitedInfo<'tcx>>{
1579-
// We can encounter projections during traversal, so ensure the type is normalized.
1580-
let ty = tcx.try_normalize_erasing_regions(typing_env, ty).unwrap_or(ty);
1581-
match ty.kind(){
1582-
ty::Tuple(list) => list.iter().try_for_each(|t| check_unsuited(tcx, typing_env, t)),
1583-
ty::Array(ty, _) => check_unsuited(tcx, typing_env,*ty),
1584-
ty::Adt(def, args) => {
1585-
if !def.did().is_local()
1586-
&& !find_attr!(
1587-
tcx.get_all_attrs(def.did()),
1588-
AttributeKind::PubTransparent(_)
1589-
)
1590-
{
1591-
let non_exhaustive = def.is_variant_list_non_exhaustive()
1592-
|| def
1593-
.variants()
1594-
.iter()
1595-
.any(ty::VariantDef::is_field_list_non_exhaustive);
1596-
let has_priv = def.all_fields().any(|f| !f.vis.is_public());
1597-
if non_exhaustive || has_priv {
1598-
returnControlFlow::Break(UnsuitedInfo{
1599-
ty,
1600-
reason:if non_exhaustive {
1601-
UnsuitedReason::NonExhaustive
1602-
}else{
1603-
UnsuitedReason::PrivateField
1604-
},
1605-
});
1606-
}
1607-
}
1608-
if def.repr().c(){
1609-
returnControlFlow::Break(UnsuitedInfo{
1610-
ty,
1611-
reason:UnsuitedReason::ReprC,
1612-
});
1613-
}
1614-
def.all_fields()
1615-
.map(|field| field.ty(tcx, args))
1616-
.try_for_each(|t| check_unsuited(tcx, typing_env, t))
1617-
}
1618-
_ => ControlFlow::Continue(()),
1619-
}
1620-
}
1621-
1622-
FieldInfo{ span, trivial,unsuited:check_unsuited(tcx, typing_env, ty).break_value()}
1557+
FieldInfo{ span, trivial, ty }
16231558
});
16241559

16251560
let non_trivial_fields = field_infos
@@ -1637,10 +1572,63 @@ pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>)
16371572
return;
16381573
}
16391574

1575+
// Even some 1-ZST fields are not allowed though, if they have `non_exhaustive` or private
1576+
// fields or `repr(C)`. We call those fields "unsuited".
1577+
structUnsuitedInfo<'tcx>{
1578+
/// The source of the problem, a type that is found somewhere within the field type.
1579+
ty:Ty<'tcx>,
1580+
reason:UnsuitedReason,
1581+
}
1582+
enumUnsuitedReason{
1583+
NonExhaustive,
1584+
PrivateField,
1585+
ReprC,
1586+
}
1587+
1588+
fncheck_unsuited<'tcx>(
1589+
tcx:TyCtxt<'tcx>,
1590+
typing_env: ty::TypingEnv<'tcx>,
1591+
ty:Ty<'tcx>,
1592+
) -> ControlFlow<UnsuitedInfo<'tcx>>{
1593+
// We can encounter projections during traversal, so ensure the type is normalized.
1594+
let ty = tcx.try_normalize_erasing_regions(typing_env, ty).unwrap_or(ty);
1595+
match ty.kind(){
1596+
ty::Tuple(list) => list.iter().try_for_each(|t| check_unsuited(tcx, typing_env, t)),
1597+
ty::Array(ty, _) => check_unsuited(tcx, typing_env,*ty),
1598+
ty::Adt(def, args) => {
1599+
if !def.did().is_local()
1600+
&& !find_attr!(tcx.get_all_attrs(def.did()),AttributeKind::PubTransparent(_))
1601+
{
1602+
let non_exhaustive = def.is_variant_list_non_exhaustive()
1603+
|| def.variants().iter().any(ty::VariantDef::is_field_list_non_exhaustive);
1604+
let has_priv = def.all_fields().any(|f| !f.vis.is_public());
1605+
if non_exhaustive || has_priv {
1606+
returnControlFlow::Break(UnsuitedInfo{
1607+
ty,
1608+
reason:if non_exhaustive {
1609+
UnsuitedReason::NonExhaustive
1610+
}else{
1611+
UnsuitedReason::PrivateField
1612+
},
1613+
});
1614+
}
1615+
}
1616+
if def.repr().c(){
1617+
returnControlFlow::Break(UnsuitedInfo{ ty,reason:UnsuitedReason::ReprC});
1618+
}
1619+
def.all_fields()
1620+
.map(|field| field.ty(tcx, args))
1621+
.try_for_each(|t| check_unsuited(tcx, typing_env, t))
1622+
}
1623+
_ => ControlFlow::Continue(()),
1624+
}
1625+
}
1626+
16401627
letmut prev_unsuited_1zst = false;
16411628
for field in field_infos {
1642-
ifletSome(unsuited) = field.unsuited{
1643-
assert!(field.trivial);
1629+
if field.trivial
1630+
&& letSome(unsuited) = check_unsuited(tcx, typing_env, field.ty).break_value()
1631+
{
16441632
// If there are any non-trivial fields, then there can be no non-exhaustive 1-zsts.
16451633
// Otherwise, it's only an issue if there's >1 non-exhaustive 1-zst.
16461634
if non_trivial_count > 0 || prev_unsuited_1zst {

‎compiler/rustc_metadata/src/rmeta/table.rs‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,8 +55,10 @@ impl IsDefault for UnusedGenericParams {
5555

5656
/// Helper trait, for encoding to, and decoding from, a fixed number of bytes.
5757
/// Used mainly for Lazy positions and lengths.
58-
/// Unchecked invariant: `Self::default()` should encode as `[0; BYTE_LEN]`,
58+
///
59+
/// Invariant: `Self::default()` should encode as `[0; BYTE_LEN]`,
5960
/// but this has no impact on safety.
61+
/// In debug builds, this invariant is checked in `[TableBuilder::set]`
6062
pub(super)traitFixedSizeEncoding:IsDefault{
6163
/// This should be `[u8; BYTE_LEN]`;
6264
/// Cannot use an associated `const BYTE_LEN: usize` instead due to const eval limitations.
@@ -432,6 +434,13 @@ impl<I: Idx, const N: usize, T: FixedSizeEncoding<ByteArray = [u8; N]>> TableBui
432434
/// arises in the future then a new method (e.g. `clear` or `reset`) will need to be introduced
433435
/// for doing that explicitly.
434436
pub(crate)fnset(&mutself,i:I,value:T){
437+
#[cfg(debug_assertions)]
438+
{
439+
debug_assert!(
440+
T::from_bytes(&[0;N]).is_default(),
441+
"expected all-zeroes to decode to the default value, as per the invariant of FixedSizeEncoding"
442+
);
443+
}
435444
if !value.is_default(){
436445
// FIXME(eddyb) investigate more compact encodings for sparse tables.
437446
// On the PR @michaelwoerister mentioned:

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Commit 7c2c3c0

Browse files
committed
Auto merge of #149063 - matthiaskrgr:rollup-6z23izv, r=matthiaskrgr
Rollup of 5 pull requests Successful merges: - #147887 (Improve the documentation of atomic::fence) - #148281 (repr(transparent) check: do not compute check_unsuited more than once) - #148484 (Fix suggestion for the `cfg!` macro) - #149057 (`rust-analyzer` subtree update) - #149061 (debug-assert FixedSizeEncoding invariant) r? `@ghost` `@rustbot` modify labels: rollup
2 parents 3d461af + ceb33e9 commit 7c2c3c0

82 files changed

Lines changed: 6193 additions & 513 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎compiler/rustc_attr_parsing/src/attributes/cfg.rs‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use rustc_ast::token::Delimiter;
22
use rustc_ast::tokenstream::DelimSpan;
33
use rustc_ast::{AttrItem,Attribute,CRATE_NODE_ID,LitKind,NodeId, ast, token};
44
use rustc_errors::{Applicability,PResult};
5-
use rustc_feature::{AttributeTemplate,Features, template};
5+
use rustc_feature::{AttrSuggestionStyle,AttributeTemplate,Features, template};
66
use rustc_hir::attrs::CfgEntry;
77
use rustc_hir::{AttrPath,RustcVersion};
88
use rustc_parse::parser::{ForceCollect,Parser};
@@ -323,8 +323,8 @@ pub fn parse_cfg_attr(
323323
}){
324324
Ok(r) => returnSome(r),
325325
Err(e) => {
326-
let suggestions =
327-
CFG_ATTR_TEMPLATE.suggestions(Some(cfg_attr.style), sym::cfg_attr);
326+
let suggestions =CFG_ATTR_TEMPLATE
327+
.suggestions(AttrSuggestionStyle::Attribute(cfg_attr.style), sym::cfg_attr);
328328
e.with_span_suggestions(
329329
cfg_attr.span,
330330
"must be of the form",
@@ -355,7 +355,8 @@ pub fn parse_cfg_attr(
355355
path:AttrPath::from_ast(&cfg_attr.get_normal_item().path),
356356
description:ParsedDescription::Attribute,
357357
reason,
358-
suggestions:CFG_ATTR_TEMPLATE.suggestions(Some(cfg_attr.style), sym::cfg_attr),
358+
suggestions:CFG_ATTR_TEMPLATE
359+
.suggestions(AttrSuggestionStyle::Attribute(cfg_attr.style), sym::cfg_attr),
359360
});
360361
}
361362
}

‎compiler/rustc_attr_parsing/src/context.rs‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ use std::sync::LazyLock;
66
use private::Sealed;
77
use rustc_ast::{AttrStyle,CRATE_NODE_ID,MetaItemLit,NodeId};
88
use rustc_errors::{Diag,Diagnostic,Level};
9-
use rustc_feature::AttributeTemplate;
9+
use rustc_feature::{AttrSuggestionStyle,AttributeTemplate};
1010
use rustc_hir::attrs::AttributeKind;
1111
use rustc_hir::lints::{AttributeLint,AttributeLintKind};
1212
use rustc_hir::{AttrPath,CRATE_HIR_ID,HirId};
@@ -637,9 +637,15 @@ impl<'f, 'sess: 'f, S: Stage> AcceptContext<'f, 'sess, S> {
637637
}
638638

639639
pub(crate)fnsuggestions(&self) -> Vec<String>{
640-
// If the outer and inner spans are equal, we are parsing an attribute from `cfg_attr`,
641-
// So don't display an attribute style in the suggestions
642-
let style = (self.attr_span != self.inner_span).then_some(self.attr_style);
640+
let style = matchself.parsed_description{
641+
// If the outer and inner spans are equal, we are parsing an embedded attribute
642+
ParsedDescription::Attributeifself.attr_span == self.inner_span => {
643+
AttrSuggestionStyle::EmbeddedAttribute
644+
}
645+
ParsedDescription::Attribute => AttrSuggestionStyle::Attribute(self.attr_style),
646+
ParsedDescription::Macro => AttrSuggestionStyle::Macro,
647+
};
648+
643649
self.template.suggestions(style,&self.attr_path)
644650
}
645651
}

‎compiler/rustc_feature/src/builtin_attrs.rs‎

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -132,28 +132,45 @@ pub struct AttributeTemplate {
132132
pubdocs:Option<&'staticstr>,
133133
}
134134

135+
pubenumAttrSuggestionStyle{
136+
/// The suggestion is styled for a normal attribute.
137+
/// The `AttrStyle` determines whether this is an inner or outer attribute.
138+
Attribute(AttrStyle),
139+
/// The suggestion is styled for an attribute embedded into another attribute.
140+
/// For example, attributes inside `#[cfg_attr(true, attr(...)]`.
141+
EmbeddedAttribute,
142+
/// The suggestion is styled for macros that are parsed with attribute parsers.
143+
/// For example, the `cfg!(predicate)` macro.
144+
Macro,
145+
}
146+
135147
implAttributeTemplate{
136148
pubfnsuggestions(
137149
&self,
138-
style:Option<AttrStyle>,
150+
style:AttrSuggestionStyle,
139151
name:impl std::fmt::Display,
140152
) -> Vec<String>{
141-
letmut suggestions = vec![];
142-
let(start, end) =match style {
143-
Some(AttrStyle::Outer) => ("#[","]"),
144-
Some(AttrStyle::Inner) => ("#![","]"),
145-
None => ("",""),
153+
let(start, macro_call, end) = match style {
154+
AttrSuggestionStyle::Attribute(AttrStyle::Outer) => ("#[","","]"),
155+
AttrSuggestionStyle::Attribute(AttrStyle::Inner) => ("#![","","]"),
156+
AttrSuggestionStyle::Macro => ("","!",""),
157+
AttrSuggestionStyle::EmbeddedAttribute => ("","",""),
146158
};
159+
160+
letmut suggestions = vec![];
161+
147162
ifself.word{
163+
debug_assert!(macro_call.is_empty(),"Macro suggestions use list style");
148164
suggestions.push(format!("{start}{name}{end}"));
149165
}
150166
ifletSome(descr) = self.list{
151167
for descr in descr {
152-
suggestions.push(format!("{start}{name}({descr}){end}"));
168+
suggestions.push(format!("{start}{name}{macro_call}({descr}){end}"));
153169
}
154170
}
155171
suggestions.extend(self.one_of.iter().map(|&word| format!("{start}{name}({word}){end}")));
156172
ifletSome(descr) = self.name_value_str{
173+
debug_assert!(macro_call.is_empty(),"Macro suggestions use list style");
157174
for descr in descr {
158175
suggestions.push(format!("{start}{name} = \"{descr}\"{end}"));
159176
}

‎compiler/rustc_feature/src/lib.rs‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -129,9 +129,10 @@ pub fn find_feature_issue(feature: Symbol, issue: GateIssue) -> Option<NonZero<u
129129

130130
pubuse accepted::ACCEPTED_LANG_FEATURES;
131131
pubuse builtin_attrs::{
132-
AttributeDuplicates,AttributeGate,AttributeSafety,AttributeTemplate,AttributeType,
133-
BUILTIN_ATTRIBUTE_MAP,BUILTIN_ATTRIBUTES,BuiltinAttribute,GatedCfg, encode_cross_crate,
134-
find_gated_cfg, is_builtin_attr_name, is_stable_diagnostic_attribute, is_valid_for_get_attr,
132+
AttrSuggestionStyle,AttributeDuplicates,AttributeGate,AttributeSafety,AttributeTemplate,
133+
AttributeType,BUILTIN_ATTRIBUTE_MAP,BUILTIN_ATTRIBUTES,BuiltinAttribute,GatedCfg,
134+
encode_cross_crate, find_gated_cfg, is_builtin_attr_name, is_stable_diagnostic_attribute,
135+
is_valid_for_get_attr,
135136
};
136137
pubuse removed::REMOVED_LANG_FEATURES;
137138
pubuse unstable::{

‎compiler/rustc_hir_analysis/src/check/check.rs‎

Lines changed: 56 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -1542,22 +1542,10 @@ pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>)
15421542

15431543
let typing_env = ty::TypingEnv::non_body_analysis(tcx, adt.did());
15441544
// For each field, figure out if it has "trivial" layout (i.e., is a 1-ZST).
1545-
// Even some 1-ZST fields are not allowed though, if they have `non_exhaustive` or private
1546-
// fields or `repr(C)`. We call those fields "unsuited".
15471545
structFieldInfo<'tcx>{
15481546
span:Span,
15491547
trivial:bool,
1550-
unsuited:Option<UnsuitedInfo<'tcx>>,
1551-
}
1552-
structUnsuitedInfo<'tcx>{
1553-
/// The source of the problem, a type that is found somewhere within the field type.
15541548
ty:Ty<'tcx>,
1555-
reason:UnsuitedReason,
1556-
}
1557-
enumUnsuitedReason{
1558-
NonExhaustive,
1559-
PrivateField,
1560-
ReprC,
15611549
}
15621550

15631551
let field_infos = adt.all_fields().map(|field| {
@@ -1566,60 +1554,7 @@ pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>)
15661554
// We are currently checking the type this field came from, so it must be local
15671555
let span = tcx.hir_span_if_local(field.did).unwrap();
15681556
let trivial = layout.is_ok_and(|layout| layout.is_1zst());
1569-
if !trivial {
1570-
// No need to even compute `unsuited`.
1571-
returnFieldInfo{ span, trivial,unsuited:None};
1572-
}
1573-
1574-
fncheck_unsuited<'tcx>(
1575-
tcx:TyCtxt<'tcx>,
1576-
typing_env: ty::TypingEnv<'tcx>,
1577-
ty:Ty<'tcx>,
1578-
) -> ControlFlow<UnsuitedInfo<'tcx>>{
1579-
// We can encounter projections during traversal, so ensure the type is normalized.
1580-
let ty = tcx.try_normalize_erasing_regions(typing_env, ty).unwrap_or(ty);
1581-
match ty.kind(){
1582-
ty::Tuple(list) => list.iter().try_for_each(|t| check_unsuited(tcx, typing_env, t)),
1583-
ty::Array(ty, _) => check_unsuited(tcx, typing_env,*ty),
1584-
ty::Adt(def, args) => {
1585-
if !def.did().is_local()
1586-
&& !find_attr!(
1587-
tcx.get_all_attrs(def.did()),
1588-
AttributeKind::PubTransparent(_)
1589-
)
1590-
{
1591-
let non_exhaustive = def.is_variant_list_non_exhaustive()
1592-
|| def
1593-
.variants()
1594-
.iter()
1595-
.any(ty::VariantDef::is_field_list_non_exhaustive);
1596-
let has_priv = def.all_fields().any(|f| !f.vis.is_public());
1597-
if non_exhaustive || has_priv {
1598-
returnControlFlow::Break(UnsuitedInfo{
1599-
ty,
1600-
reason:if non_exhaustive {
1601-
UnsuitedReason::NonExhaustive
1602-
}else{
1603-
UnsuitedReason::PrivateField
1604-
},
1605-
});
1606-
}
1607-
}
1608-
if def.repr().c(){
1609-
returnControlFlow::Break(UnsuitedInfo{
1610-
ty,
1611-
reason:UnsuitedReason::ReprC,
1612-
});
1613-
}
1614-
def.all_fields()
1615-
.map(|field| field.ty(tcx, args))
1616-
.try_for_each(|t| check_unsuited(tcx, typing_env, t))
1617-
}
1618-
_ => ControlFlow::Continue(()),
1619-
}
1620-
}
1621-
1622-
FieldInfo{ span, trivial,unsuited:check_unsuited(tcx, typing_env, ty).break_value()}
1557+
FieldInfo{ span, trivial, ty }
16231558
});
16241559

16251560
let non_trivial_fields = field_infos
@@ -1637,10 +1572,63 @@ pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>)
16371572
return;
16381573
}
16391574

1575+
// Even some 1-ZST fields are not allowed though, if they have `non_exhaustive` or private
1576+
// fields or `repr(C)`. We call those fields "unsuited".
1577+
structUnsuitedInfo<'tcx>{
1578+
/// The source of the problem, a type that is found somewhere within the field type.
1579+
ty:Ty<'tcx>,
1580+
reason:UnsuitedReason,
1581+
}
1582+
enumUnsuitedReason{
1583+
NonExhaustive,
1584+
PrivateField,
1585+
ReprC,
1586+
}
1587+
1588+
fncheck_unsuited<'tcx>(
1589+
tcx:TyCtxt<'tcx>,
1590+
typing_env: ty::TypingEnv<'tcx>,
1591+
ty:Ty<'tcx>,
1592+
) -> ControlFlow<UnsuitedInfo<'tcx>>{
1593+
// We can encounter projections during traversal, so ensure the type is normalized.
1594+
let ty = tcx.try_normalize_erasing_regions(typing_env, ty).unwrap_or(ty);
1595+
match ty.kind(){
1596+
ty::Tuple(list) => list.iter().try_for_each(|t| check_unsuited(tcx, typing_env, t)),
1597+
ty::Array(ty, _) => check_unsuited(tcx, typing_env,*ty),
1598+
ty::Adt(def, args) => {
1599+
if !def.did().is_local()
1600+
&& !find_attr!(tcx.get_all_attrs(def.did()),AttributeKind::PubTransparent(_))
1601+
{
1602+
let non_exhaustive = def.is_variant_list_non_exhaustive()
1603+
|| def.variants().iter().any(ty::VariantDef::is_field_list_non_exhaustive);
1604+
let has_priv = def.all_fields().any(|f| !f.vis.is_public());
1605+
if non_exhaustive || has_priv {
1606+
returnControlFlow::Break(UnsuitedInfo{
1607+
ty,
1608+
reason:if non_exhaustive {
1609+
UnsuitedReason::NonExhaustive
1610+
}else{
1611+
UnsuitedReason::PrivateField
1612+
},
1613+
});
1614+
}
1615+
}
1616+
if def.repr().c(){
1617+
returnControlFlow::Break(UnsuitedInfo{ ty,reason:UnsuitedReason::ReprC});
1618+
}
1619+
def.all_fields()
1620+
.map(|field| field.ty(tcx, args))
1621+
.try_for_each(|t| check_unsuited(tcx, typing_env, t))
1622+
}
1623+
_ => ControlFlow::Continue(()),
1624+
}
1625+
}
1626+
16401627
letmut prev_unsuited_1zst = false;
16411628
for field in field_infos {
1642-
ifletSome(unsuited) = field.unsuited{
1643-
assert!(field.trivial);
1629+
if field.trivial
1630+
&& letSome(unsuited) = check_unsuited(tcx, typing_env, field.ty).break_value()
1631+
{
16441632
// If there are any non-trivial fields, then there can be no non-exhaustive 1-zsts.
16451633
// Otherwise, it's only an issue if there's >1 non-exhaustive 1-zst.
16461634
if non_trivial_count > 0 || prev_unsuited_1zst {

‎compiler/rustc_metadata/src/rmeta/table.rs‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,8 +55,10 @@ impl IsDefault for UnusedGenericParams {
5555

5656
/// Helper trait, for encoding to, and decoding from, a fixed number of bytes.
5757
/// Used mainly for Lazy positions and lengths.
58-
/// Unchecked invariant: `Self::default()` should encode as `[0; BYTE_LEN]`,
58+
///
59+
/// Invariant: `Self::default()` should encode as `[0; BYTE_LEN]`,
5960
/// but this has no impact on safety.
61+
/// In debug builds, this invariant is checked in `[TableBuilder::set]`
6062
pub(super)traitFixedSizeEncoding:IsDefault{
6163
/// This should be `[u8; BYTE_LEN]`;
6264
/// Cannot use an associated `const BYTE_LEN: usize` instead due to const eval limitations.
@@ -432,6 +434,13 @@ impl<I: Idx, const N: usize, T: FixedSizeEncoding<ByteArray = [u8; N]>> TableBui
432434
/// arises in the future then a new method (e.g. `clear` or `reset`) will need to be introduced
433435
/// for doing that explicitly.
434436
pub(crate)fnset(&mutself,i:I,value:T){
437+
#[cfg(debug_assertions)]
438+
{
439+
debug_assert!(
440+
T::from_bytes(&[0;N]).is_default(),
441+
"expected all-zeroes to decode to the default value, as per the invariant of FixedSizeEncoding"
442+
);
443+
}
435444
if !value.is_default(){
436445
// FIXME(eddyb) investigate more compact encodings for sparse tables.
437446
// On the PR @michaelwoerister mentioned:

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit 7c2c3c0

Browse files
committed
Auto merge of #149063 - matthiaskrgr:rollup-6z23izv, r=matthiaskrgr
Rollup of 5 pull requests Successful merges: - #147887 (Improve the documentation of atomic::fence) - #148281 (repr(transparent) check: do not compute check_unsuited more than once) - #148484 (Fix suggestion for the `cfg!` macro) - #149057 (`rust-analyzer` subtree update) - #149061 (debug-assert FixedSizeEncoding invariant) r? `@ghost` `@rustbot` modify labels: rollup
2 parents 3d461af + ceb33e9 commit 7c2c3c0

82 files changed

Lines changed: 6193 additions & 513 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎compiler/rustc_attr_parsing/src/attributes/cfg.rs‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use rustc_ast::token::Delimiter;
22
use rustc_ast::tokenstream::DelimSpan;
33
use rustc_ast::{AttrItem,Attribute,CRATE_NODE_ID,LitKind,NodeId, ast, token};
44
use rustc_errors::{Applicability,PResult};
5-
use rustc_feature::{AttributeTemplate,Features, template};
5+
use rustc_feature::{AttrSuggestionStyle,AttributeTemplate,Features, template};
66
use rustc_hir::attrs::CfgEntry;
77
use rustc_hir::{AttrPath,RustcVersion};
88
use rustc_parse::parser::{ForceCollect,Parser};
@@ -323,8 +323,8 @@ pub fn parse_cfg_attr(
323323
}){
324324
Ok(r) => returnSome(r),
325325
Err(e) => {
326-
let suggestions =
327-
CFG_ATTR_TEMPLATE.suggestions(Some(cfg_attr.style), sym::cfg_attr);
326+
let suggestions =CFG_ATTR_TEMPLATE
327+
.suggestions(AttrSuggestionStyle::Attribute(cfg_attr.style), sym::cfg_attr);
328328
e.with_span_suggestions(
329329
cfg_attr.span,
330330
"must be of the form",
@@ -355,7 +355,8 @@ pub fn parse_cfg_attr(
355355
path:AttrPath::from_ast(&cfg_attr.get_normal_item().path),
356356
description:ParsedDescription::Attribute,
357357
reason,
358-
suggestions:CFG_ATTR_TEMPLATE.suggestions(Some(cfg_attr.style), sym::cfg_attr),
358+
suggestions:CFG_ATTR_TEMPLATE
359+
.suggestions(AttrSuggestionStyle::Attribute(cfg_attr.style), sym::cfg_attr),
359360
});
360361
}
361362
}

‎compiler/rustc_attr_parsing/src/context.rs‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ use std::sync::LazyLock;
66
use private::Sealed;
77
use rustc_ast::{AttrStyle,CRATE_NODE_ID,MetaItemLit,NodeId};
88
use rustc_errors::{Diag,Diagnostic,Level};
9-
use rustc_feature::AttributeTemplate;
9+
use rustc_feature::{AttrSuggestionStyle,AttributeTemplate};
1010
use rustc_hir::attrs::AttributeKind;
1111
use rustc_hir::lints::{AttributeLint,AttributeLintKind};
1212
use rustc_hir::{AttrPath,CRATE_HIR_ID,HirId};
@@ -637,9 +637,15 @@ impl<'f, 'sess: 'f, S: Stage> AcceptContext<'f, 'sess, S> {
637637
}
638638

639639
pub(crate)fnsuggestions(&self) -> Vec<String>{
640-
// If the outer and inner spans are equal, we are parsing an attribute from `cfg_attr`,
641-
// So don't display an attribute style in the suggestions
642-
let style = (self.attr_span != self.inner_span).then_some(self.attr_style);
640+
let style = matchself.parsed_description{
641+
// If the outer and inner spans are equal, we are parsing an embedded attribute
642+
ParsedDescription::Attributeifself.attr_span == self.inner_span => {
643+
AttrSuggestionStyle::EmbeddedAttribute
644+
}
645+
ParsedDescription::Attribute => AttrSuggestionStyle::Attribute(self.attr_style),
646+
ParsedDescription::Macro => AttrSuggestionStyle::Macro,
647+
};
648+
643649
self.template.suggestions(style,&self.attr_path)
644650
}
645651
}

‎compiler/rustc_feature/src/builtin_attrs.rs‎

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -132,28 +132,45 @@ pub struct AttributeTemplate {
132132
pubdocs:Option<&'staticstr>,
133133
}
134134

135+
pubenumAttrSuggestionStyle{
136+
/// The suggestion is styled for a normal attribute.
137+
/// The `AttrStyle` determines whether this is an inner or outer attribute.
138+
Attribute(AttrStyle),
139+
/// The suggestion is styled for an attribute embedded into another attribute.
140+
/// For example, attributes inside `#[cfg_attr(true, attr(...)]`.
141+
EmbeddedAttribute,
142+
/// The suggestion is styled for macros that are parsed with attribute parsers.
143+
/// For example, the `cfg!(predicate)` macro.
144+
Macro,
145+
}
146+
135147
implAttributeTemplate{
136148
pubfnsuggestions(
137149
&self,
138-
style:Option<AttrStyle>,
150+
style:AttrSuggestionStyle,
139151
name:impl std::fmt::Display,
140152
) -> Vec<String>{
141-
letmut suggestions = vec![];
142-
let(start, end) =match style {
143-
Some(AttrStyle::Outer) => ("#[","]"),
144-
Some(AttrStyle::Inner) => ("#![","]"),
145-
None => ("",""),
153+
let(start, macro_call, end) = match style {
154+
AttrSuggestionStyle::Attribute(AttrStyle::Outer) => ("#[","","]"),
155+
AttrSuggestionStyle::Attribute(AttrStyle::Inner) => ("#![","","]"),
156+
AttrSuggestionStyle::Macro => ("","!",""),
157+
AttrSuggestionStyle::EmbeddedAttribute => ("","",""),
146158
};
159+
160+
letmut suggestions = vec![];
161+
147162
ifself.word{
163+
debug_assert!(macro_call.is_empty(),"Macro suggestions use list style");
148164
suggestions.push(format!("{start}{name}{end}"));
149165
}
150166
ifletSome(descr) = self.list{
151167
for descr in descr {
152-
suggestions.push(format!("{start}{name}({descr}){end}"));
168+
suggestions.push(format!("{start}{name}{macro_call}({descr}){end}"));
153169
}
154170
}
155171
suggestions.extend(self.one_of.iter().map(|&word| format!("{start}{name}({word}){end}")));
156172
ifletSome(descr) = self.name_value_str{
173+
debug_assert!(macro_call.is_empty(),"Macro suggestions use list style");
157174
for descr in descr {
158175
suggestions.push(format!("{start}{name} = \"{descr}\"{end}"));
159176
}

‎compiler/rustc_feature/src/lib.rs‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -129,9 +129,10 @@ pub fn find_feature_issue(feature: Symbol, issue: GateIssue) -> Option<NonZero<u
129129

130130
pubuse accepted::ACCEPTED_LANG_FEATURES;
131131
pubuse builtin_attrs::{
132-
AttributeDuplicates,AttributeGate,AttributeSafety,AttributeTemplate,AttributeType,
133-
BUILTIN_ATTRIBUTE_MAP,BUILTIN_ATTRIBUTES,BuiltinAttribute,GatedCfg, encode_cross_crate,
134-
find_gated_cfg, is_builtin_attr_name, is_stable_diagnostic_attribute, is_valid_for_get_attr,
132+
AttrSuggestionStyle,AttributeDuplicates,AttributeGate,AttributeSafety,AttributeTemplate,
133+
AttributeType,BUILTIN_ATTRIBUTE_MAP,BUILTIN_ATTRIBUTES,BuiltinAttribute,GatedCfg,
134+
encode_cross_crate, find_gated_cfg, is_builtin_attr_name, is_stable_diagnostic_attribute,
135+
is_valid_for_get_attr,
135136
};
136137
pubuse removed::REMOVED_LANG_FEATURES;
137138
pubuse unstable::{

‎compiler/rustc_hir_analysis/src/check/check.rs‎

Lines changed: 56 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -1542,22 +1542,10 @@ pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>)
15421542

15431543
let typing_env = ty::TypingEnv::non_body_analysis(tcx, adt.did());
15441544
// For each field, figure out if it has "trivial" layout (i.e., is a 1-ZST).
1545-
// Even some 1-ZST fields are not allowed though, if they have `non_exhaustive` or private
1546-
// fields or `repr(C)`. We call those fields "unsuited".
15471545
structFieldInfo<'tcx>{
15481546
span:Span,
15491547
trivial:bool,
1550-
unsuited:Option<UnsuitedInfo<'tcx>>,
1551-
}
1552-
structUnsuitedInfo<'tcx>{
1553-
/// The source of the problem, a type that is found somewhere within the field type.
15541548
ty:Ty<'tcx>,
1555-
reason:UnsuitedReason,
1556-
}
1557-
enumUnsuitedReason{
1558-
NonExhaustive,
1559-
PrivateField,
1560-
ReprC,
15611549
}
15621550

15631551
let field_infos = adt.all_fields().map(|field| {
@@ -1566,60 +1554,7 @@ pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>)
15661554
// We are currently checking the type this field came from, so it must be local
15671555
let span = tcx.hir_span_if_local(field.did).unwrap();
15681556
let trivial = layout.is_ok_and(|layout| layout.is_1zst());
1569-
if !trivial {
1570-
// No need to even compute `unsuited`.
1571-
returnFieldInfo{ span, trivial,unsuited:None};
1572-
}
1573-
1574-
fncheck_unsuited<'tcx>(
1575-
tcx:TyCtxt<'tcx>,
1576-
typing_env: ty::TypingEnv<'tcx>,
1577-
ty:Ty<'tcx>,
1578-
) -> ControlFlow<UnsuitedInfo<'tcx>>{
1579-
// We can encounter projections during traversal, so ensure the type is normalized.
1580-
let ty = tcx.try_normalize_erasing_regions(typing_env, ty).unwrap_or(ty);
1581-
match ty.kind(){
1582-
ty::Tuple(list) => list.iter().try_for_each(|t| check_unsuited(tcx, typing_env, t)),
1583-
ty::Array(ty, _) => check_unsuited(tcx, typing_env,*ty),
1584-
ty::Adt(def, args) => {
1585-
if !def.did().is_local()
1586-
&& !find_attr!(
1587-
tcx.get_all_attrs(def.did()),
1588-
AttributeKind::PubTransparent(_)
1589-
)
1590-
{
1591-
let non_exhaustive = def.is_variant_list_non_exhaustive()
1592-
|| def
1593-
.variants()
1594-
.iter()
1595-
.any(ty::VariantDef::is_field_list_non_exhaustive);
1596-
let has_priv = def.all_fields().any(|f| !f.vis.is_public());
1597-
if non_exhaustive || has_priv {
1598-
returnControlFlow::Break(UnsuitedInfo{
1599-
ty,
1600-
reason:if non_exhaustive {
1601-
UnsuitedReason::NonExhaustive
1602-
}else{
1603-
UnsuitedReason::PrivateField
1604-
},
1605-
});
1606-
}
1607-
}
1608-
if def.repr().c(){
1609-
returnControlFlow::Break(UnsuitedInfo{
1610-
ty,
1611-
reason:UnsuitedReason::ReprC,
1612-
});
1613-
}
1614-
def.all_fields()
1615-
.map(|field| field.ty(tcx, args))
1616-
.try_for_each(|t| check_unsuited(tcx, typing_env, t))
1617-
}
1618-
_ => ControlFlow::Continue(()),
1619-
}
1620-
}
1621-
1622-
FieldInfo{ span, trivial,unsuited:check_unsuited(tcx, typing_env, ty).break_value()}
1557+
FieldInfo{ span, trivial, ty }
16231558
});
16241559

16251560
let non_trivial_fields = field_infos
@@ -1637,10 +1572,63 @@ pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>)
16371572
return;
16381573
}
16391574

1575+
// Even some 1-ZST fields are not allowed though, if they have `non_exhaustive` or private
1576+
// fields or `repr(C)`. We call those fields "unsuited".
1577+
structUnsuitedInfo<'tcx>{
1578+
/// The source of the problem, a type that is found somewhere within the field type.
1579+
ty:Ty<'tcx>,
1580+
reason:UnsuitedReason,
1581+
}
1582+
enumUnsuitedReason{
1583+
NonExhaustive,
1584+
PrivateField,
1585+
ReprC,
1586+
}
1587+
1588+
fncheck_unsuited<'tcx>(
1589+
tcx:TyCtxt<'tcx>,
1590+
typing_env: ty::TypingEnv<'tcx>,
1591+
ty:Ty<'tcx>,
1592+
) -> ControlFlow<UnsuitedInfo<'tcx>>{
1593+
// We can encounter projections during traversal, so ensure the type is normalized.
1594+
let ty = tcx.try_normalize_erasing_regions(typing_env, ty).unwrap_or(ty);
1595+
match ty.kind(){
1596+
ty::Tuple(list) => list.iter().try_for_each(|t| check_unsuited(tcx, typing_env, t)),
1597+
ty::Array(ty, _) => check_unsuited(tcx, typing_env,*ty),
1598+
ty::Adt(def, args) => {
1599+
if !def.did().is_local()
1600+
&& !find_attr!(tcx.get_all_attrs(def.did()),AttributeKind::PubTransparent(_))
1601+
{
1602+
let non_exhaustive = def.is_variant_list_non_exhaustive()
1603+
|| def.variants().iter().any(ty::VariantDef::is_field_list_non_exhaustive);
1604+
let has_priv = def.all_fields().any(|f| !f.vis.is_public());
1605+
if non_exhaustive || has_priv {
1606+
returnControlFlow::Break(UnsuitedInfo{
1607+
ty,
1608+
reason:if non_exhaustive {
1609+
UnsuitedReason::NonExhaustive
1610+
}else{
1611+
UnsuitedReason::PrivateField
1612+
},
1613+
});
1614+
}
1615+
}
1616+
if def.repr().c(){
1617+
returnControlFlow::Break(UnsuitedInfo{ ty,reason:UnsuitedReason::ReprC});
1618+
}
1619+
def.all_fields()
1620+
.map(|field| field.ty(tcx, args))
1621+
.try_for_each(|t| check_unsuited(tcx, typing_env, t))
1622+
}
1623+
_ => ControlFlow::Continue(()),
1624+
}
1625+
}
1626+
16401627
letmut prev_unsuited_1zst = false;
16411628
for field in field_infos {
1642-
ifletSome(unsuited) = field.unsuited{
1643-
assert!(field.trivial);
1629+
if field.trivial
1630+
&& letSome(unsuited) = check_unsuited(tcx, typing_env, field.ty).break_value()
1631+
{
16441632
// If there are any non-trivial fields, then there can be no non-exhaustive 1-zsts.
16451633
// Otherwise, it's only an issue if there's >1 non-exhaustive 1-zst.
16461634
if non_trivial_count > 0 || prev_unsuited_1zst {

‎compiler/rustc_metadata/src/rmeta/table.rs‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,8 +55,10 @@ impl IsDefault for UnusedGenericParams {
5555

5656
/// Helper trait, for encoding to, and decoding from, a fixed number of bytes.
5757
/// Used mainly for Lazy positions and lengths.
58-
/// Unchecked invariant: `Self::default()` should encode as `[0; BYTE_LEN]`,
58+
///
59+
/// Invariant: `Self::default()` should encode as `[0; BYTE_LEN]`,
5960
/// but this has no impact on safety.
61+
/// In debug builds, this invariant is checked in `[TableBuilder::set]`
6062
pub(super)traitFixedSizeEncoding:IsDefault{
6163
/// This should be `[u8; BYTE_LEN]`;
6264
/// Cannot use an associated `const BYTE_LEN: usize` instead due to const eval limitations.
@@ -432,6 +434,13 @@ impl<I: Idx, const N: usize, T: FixedSizeEncoding<ByteArray = [u8; N]>> TableBui
432434
/// arises in the future then a new method (e.g. `clear` or `reset`) will need to be introduced
433435
/// for doing that explicitly.
434436
pub(crate)fnset(&mutself,i:I,value:T){
437+
#[cfg(debug_assertions)]
438+
{
439+
debug_assert!(
440+
T::from_bytes(&[0;N]).is_default(),
441+
"expected all-zeroes to decode to the default value, as per the invariant of FixedSizeEncoding"
442+
);
443+
}
435444
if !value.is_default(){
436445
// FIXME(eddyb) investigate more compact encodings for sparse tables.
437446
// On the PR @michaelwoerister mentioned:

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit 7c2c3c0

Browse files
committed
Auto merge of #149063 - matthiaskrgr:rollup-6z23izv, r=matthiaskrgr
Rollup of 5 pull requests Successful merges: - #147887 (Improve the documentation of atomic::fence) - #148281 (repr(transparent) check: do not compute check_unsuited more than once) - #148484 (Fix suggestion for the `cfg!` macro) - #149057 (`rust-analyzer` subtree update) - #149061 (debug-assert FixedSizeEncoding invariant) r? `@ghost` `@rustbot` modify labels: rollup
2 parents 3d461af + ceb33e9 commit 7c2c3c0

82 files changed

Lines changed: 6193 additions & 513 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎compiler/rustc_attr_parsing/src/attributes/cfg.rs‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use rustc_ast::token::Delimiter;
22
use rustc_ast::tokenstream::DelimSpan;
33
use rustc_ast::{AttrItem,Attribute,CRATE_NODE_ID,LitKind,NodeId, ast, token};
44
use rustc_errors::{Applicability,PResult};
5-
use rustc_feature::{AttributeTemplate,Features, template};
5+
use rustc_feature::{AttrSuggestionStyle,AttributeTemplate,Features, template};
66
use rustc_hir::attrs::CfgEntry;
77
use rustc_hir::{AttrPath,RustcVersion};
88
use rustc_parse::parser::{ForceCollect,Parser};
@@ -323,8 +323,8 @@ pub fn parse_cfg_attr(
323323
}){
324324
Ok(r) => returnSome(r),
325325
Err(e) => {
326-
let suggestions =
327-
CFG_ATTR_TEMPLATE.suggestions(Some(cfg_attr.style), sym::cfg_attr);
326+
let suggestions =CFG_ATTR_TEMPLATE
327+
.suggestions(AttrSuggestionStyle::Attribute(cfg_attr.style), sym::cfg_attr);
328328
e.with_span_suggestions(
329329
cfg_attr.span,
330330
"must be of the form",
@@ -355,7 +355,8 @@ pub fn parse_cfg_attr(
355355
path:AttrPath::from_ast(&cfg_attr.get_normal_item().path),
356356
description:ParsedDescription::Attribute,
357357
reason,
358-
suggestions:CFG_ATTR_TEMPLATE.suggestions(Some(cfg_attr.style), sym::cfg_attr),
358+
suggestions:CFG_ATTR_TEMPLATE
359+
.suggestions(AttrSuggestionStyle::Attribute(cfg_attr.style), sym::cfg_attr),
359360
});
360361
}
361362
}

‎compiler/rustc_attr_parsing/src/context.rs‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ use std::sync::LazyLock;
66
use private::Sealed;
77
use rustc_ast::{AttrStyle,CRATE_NODE_ID,MetaItemLit,NodeId};
88
use rustc_errors::{Diag,Diagnostic,Level};
9-
use rustc_feature::AttributeTemplate;
9+
use rustc_feature::{AttrSuggestionStyle,AttributeTemplate};
1010
use rustc_hir::attrs::AttributeKind;
1111
use rustc_hir::lints::{AttributeLint,AttributeLintKind};
1212
use rustc_hir::{AttrPath,CRATE_HIR_ID,HirId};
@@ -637,9 +637,15 @@ impl<'f, 'sess: 'f, S: Stage> AcceptContext<'f, 'sess, S> {
637637
}
638638

639639
pub(crate)fnsuggestions(&self) -> Vec<String>{
640-
// If the outer and inner spans are equal, we are parsing an attribute from `cfg_attr`,
641-
// So don't display an attribute style in the suggestions
642-
let style = (self.attr_span != self.inner_span).then_some(self.attr_style);
640+
let style = matchself.parsed_description{
641+
// If the outer and inner spans are equal, we are parsing an embedded attribute
642+
ParsedDescription::Attributeifself.attr_span == self.inner_span => {
643+
AttrSuggestionStyle::EmbeddedAttribute
644+
}
645+
ParsedDescription::Attribute => AttrSuggestionStyle::Attribute(self.attr_style),
646+
ParsedDescription::Macro => AttrSuggestionStyle::Macro,
647+
};
648+
643649
self.template.suggestions(style,&self.attr_path)
644650
}
645651
}

‎compiler/rustc_feature/src/builtin_attrs.rs‎

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -132,28 +132,45 @@ pub struct AttributeTemplate {
132132
pubdocs:Option<&'staticstr>,
133133
}
134134

135+
pubenumAttrSuggestionStyle{
136+
/// The suggestion is styled for a normal attribute.
137+
/// The `AttrStyle` determines whether this is an inner or outer attribute.
138+
Attribute(AttrStyle),
139+
/// The suggestion is styled for an attribute embedded into another attribute.
140+
/// For example, attributes inside `#[cfg_attr(true, attr(...)]`.
141+
EmbeddedAttribute,
142+
/// The suggestion is styled for macros that are parsed with attribute parsers.
143+
/// For example, the `cfg!(predicate)` macro.
144+
Macro,
145+
}
146+
135147
implAttributeTemplate{
136148
pubfnsuggestions(
137149
&self,
138-
style:Option<AttrStyle>,
150+
style:AttrSuggestionStyle,
139151
name:impl std::fmt::Display,
140152
) -> Vec<String>{
141-
letmut suggestions = vec![];
142-
let(start, end) =match style {
143-
Some(AttrStyle::Outer) => ("#[","]"),
144-
Some(AttrStyle::Inner) => ("#![","]"),
145-
None => ("",""),
153+
let(start, macro_call, end) = match style {
154+
AttrSuggestionStyle::Attribute(AttrStyle::Outer) => ("#[","","]"),
155+
AttrSuggestionStyle::Attribute(AttrStyle::Inner) => ("#![","","]"),
156+
AttrSuggestionStyle::Macro => ("","!",""),
157+
AttrSuggestionStyle::EmbeddedAttribute => ("","",""),
146158
};
159+
160+
letmut suggestions = vec![];
161+
147162
ifself.word{
163+
debug_assert!(macro_call.is_empty(),"Macro suggestions use list style");
148164
suggestions.push(format!("{start}{name}{end}"));
149165
}
150166
ifletSome(descr) = self.list{
151167
for descr in descr {
152-
suggestions.push(format!("{start}{name}({descr}){end}"));
168+
suggestions.push(format!("{start}{name}{macro_call}({descr}){end}"));
153169
}
154170
}
155171
suggestions.extend(self.one_of.iter().map(|&word| format!("{start}{name}({word}){end}")));
156172
ifletSome(descr) = self.name_value_str{
173+
debug_assert!(macro_call.is_empty(),"Macro suggestions use list style");
157174
for descr in descr {
158175
suggestions.push(format!("{start}{name} = \"{descr}\"{end}"));
159176
}

‎compiler/rustc_feature/src/lib.rs‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -129,9 +129,10 @@ pub fn find_feature_issue(feature: Symbol, issue: GateIssue) -> Option<NonZero<u
129129

130130
pubuse accepted::ACCEPTED_LANG_FEATURES;
131131
pubuse builtin_attrs::{
132-
AttributeDuplicates,AttributeGate,AttributeSafety,AttributeTemplate,AttributeType,
133-
BUILTIN_ATTRIBUTE_MAP,BUILTIN_ATTRIBUTES,BuiltinAttribute,GatedCfg, encode_cross_crate,
134-
find_gated_cfg, is_builtin_attr_name, is_stable_diagnostic_attribute, is_valid_for_get_attr,
132+
AttrSuggestionStyle,AttributeDuplicates,AttributeGate,AttributeSafety,AttributeTemplate,
133+
AttributeType,BUILTIN_ATTRIBUTE_MAP,BUILTIN_ATTRIBUTES,BuiltinAttribute,GatedCfg,
134+
encode_cross_crate, find_gated_cfg, is_builtin_attr_name, is_stable_diagnostic_attribute,
135+
is_valid_for_get_attr,
135136
};
136137
pubuse removed::REMOVED_LANG_FEATURES;
137138
pubuse unstable::{

‎compiler/rustc_hir_analysis/src/check/check.rs‎

Lines changed: 56 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -1542,22 +1542,10 @@ pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>)
15421542

15431543
let typing_env = ty::TypingEnv::non_body_analysis(tcx, adt.did());
15441544
// For each field, figure out if it has "trivial" layout (i.e., is a 1-ZST).
1545-
// Even some 1-ZST fields are not allowed though, if they have `non_exhaustive` or private
1546-
// fields or `repr(C)`. We call those fields "unsuited".
15471545
structFieldInfo<'tcx>{
15481546
span:Span,
15491547
trivial:bool,
1550-
unsuited:Option<UnsuitedInfo<'tcx>>,
1551-
}
1552-
structUnsuitedInfo<'tcx>{
1553-
/// The source of the problem, a type that is found somewhere within the field type.
15541548
ty:Ty<'tcx>,
1555-
reason:UnsuitedReason,
1556-
}
1557-
enumUnsuitedReason{
1558-
NonExhaustive,
1559-
PrivateField,
1560-
ReprC,
15611549
}
15621550

15631551
let field_infos = adt.all_fields().map(|field| {
@@ -1566,60 +1554,7 @@ pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>)
15661554
// We are currently checking the type this field came from, so it must be local
15671555
let span = tcx.hir_span_if_local(field.did).unwrap();
15681556
let trivial = layout.is_ok_and(|layout| layout.is_1zst());
1569-
if !trivial {
1570-
// No need to even compute `unsuited`.
1571-
returnFieldInfo{ span, trivial,unsuited:None};
1572-
}
1573-
1574-
fncheck_unsuited<'tcx>(
1575-
tcx:TyCtxt<'tcx>,
1576-
typing_env: ty::TypingEnv<'tcx>,
1577-
ty:Ty<'tcx>,
1578-
) -> ControlFlow<UnsuitedInfo<'tcx>>{
1579-
// We can encounter projections during traversal, so ensure the type is normalized.
1580-
let ty = tcx.try_normalize_erasing_regions(typing_env, ty).unwrap_or(ty);
1581-
match ty.kind(){
1582-
ty::Tuple(list) => list.iter().try_for_each(|t| check_unsuited(tcx, typing_env, t)),
1583-
ty::Array(ty, _) => check_unsuited(tcx, typing_env,*ty),
1584-
ty::Adt(def, args) => {
1585-
if !def.did().is_local()
1586-
&& !find_attr!(
1587-
tcx.get_all_attrs(def.did()),
1588-
AttributeKind::PubTransparent(_)
1589-
)
1590-
{
1591-
let non_exhaustive = def.is_variant_list_non_exhaustive()
1592-
|| def
1593-
.variants()
1594-
.iter()
1595-
.any(ty::VariantDef::is_field_list_non_exhaustive);
1596-
let has_priv = def.all_fields().any(|f| !f.vis.is_public());
1597-
if non_exhaustive || has_priv {
1598-
returnControlFlow::Break(UnsuitedInfo{
1599-
ty,
1600-
reason:if non_exhaustive {
1601-
UnsuitedReason::NonExhaustive
1602-
}else{
1603-
UnsuitedReason::PrivateField
1604-
},
1605-
});
1606-
}
1607-
}
1608-
if def.repr().c(){
1609-
returnControlFlow::Break(UnsuitedInfo{
1610-
ty,
1611-
reason:UnsuitedReason::ReprC,
1612-
});
1613-
}
1614-
def.all_fields()
1615-
.map(|field| field.ty(tcx, args))
1616-
.try_for_each(|t| check_unsuited(tcx, typing_env, t))
1617-
}
1618-
_ => ControlFlow::Continue(()),
1619-
}
1620-
}
1621-
1622-
FieldInfo{ span, trivial,unsuited:check_unsuited(tcx, typing_env, ty).break_value()}
1557+
FieldInfo{ span, trivial, ty }
16231558
});
16241559

16251560
let non_trivial_fields = field_infos
@@ -1637,10 +1572,63 @@ pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>)
16371572
return;
16381573
}
16391574

1575+
// Even some 1-ZST fields are not allowed though, if they have `non_exhaustive` or private
1576+
// fields or `repr(C)`. We call those fields "unsuited".
1577+
structUnsuitedInfo<'tcx>{
1578+
/// The source of the problem, a type that is found somewhere within the field type.
1579+
ty:Ty<'tcx>,
1580+
reason:UnsuitedReason,
1581+
}
1582+
enumUnsuitedReason{
1583+
NonExhaustive,
1584+
PrivateField,
1585+
ReprC,
1586+
}
1587+
1588+
fncheck_unsuited<'tcx>(
1589+
tcx:TyCtxt<'tcx>,
1590+
typing_env: ty::TypingEnv<'tcx>,
1591+
ty:Ty<'tcx>,
1592+
) -> ControlFlow<UnsuitedInfo<'tcx>>{
1593+
// We can encounter projections during traversal, so ensure the type is normalized.
1594+
let ty = tcx.try_normalize_erasing_regions(typing_env, ty).unwrap_or(ty);
1595+
match ty.kind(){
1596+
ty::Tuple(list) => list.iter().try_for_each(|t| check_unsuited(tcx, typing_env, t)),
1597+
ty::Array(ty, _) => check_unsuited(tcx, typing_env,*ty),
1598+
ty::Adt(def, args) => {
1599+
if !def.did().is_local()
1600+
&& !find_attr!(tcx.get_all_attrs(def.did()),AttributeKind::PubTransparent(_))
1601+
{
1602+
let non_exhaustive = def.is_variant_list_non_exhaustive()
1603+
|| def.variants().iter().any(ty::VariantDef::is_field_list_non_exhaustive);
1604+
let has_priv = def.all_fields().any(|f| !f.vis.is_public());
1605+
if non_exhaustive || has_priv {
1606+
returnControlFlow::Break(UnsuitedInfo{
1607+
ty,
1608+
reason:if non_exhaustive {
1609+
UnsuitedReason::NonExhaustive
1610+
}else{
1611+
UnsuitedReason::PrivateField
1612+
},
1613+
});
1614+
}
1615+
}
1616+
if def.repr().c(){
1617+
returnControlFlow::Break(UnsuitedInfo{ ty,reason:UnsuitedReason::ReprC});
1618+
}
1619+
def.all_fields()
1620+
.map(|field| field.ty(tcx, args))
1621+
.try_for_each(|t| check_unsuited(tcx, typing_env, t))
1622+
}
1623+
_ => ControlFlow::Continue(()),
1624+
}
1625+
}
1626+
16401627
letmut prev_unsuited_1zst = false;
16411628
for field in field_infos {
1642-
ifletSome(unsuited) = field.unsuited{
1643-
assert!(field.trivial);
1629+
if field.trivial
1630+
&& letSome(unsuited) = check_unsuited(tcx, typing_env, field.ty).break_value()
1631+
{
16441632
// If there are any non-trivial fields, then there can be no non-exhaustive 1-zsts.
16451633
// Otherwise, it's only an issue if there's >1 non-exhaustive 1-zst.
16461634
if non_trivial_count > 0 || prev_unsuited_1zst {

‎compiler/rustc_metadata/src/rmeta/table.rs‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,8 +55,10 @@ impl IsDefault for UnusedGenericParams {
5555

5656
/// Helper trait, for encoding to, and decoding from, a fixed number of bytes.
5757
/// Used mainly for Lazy positions and lengths.
58-
/// Unchecked invariant: `Self::default()` should encode as `[0; BYTE_LEN]`,
58+
///
59+
/// Invariant: `Self::default()` should encode as `[0; BYTE_LEN]`,
5960
/// but this has no impact on safety.
61+
/// In debug builds, this invariant is checked in `[TableBuilder::set]`
6062
pub(super)traitFixedSizeEncoding:IsDefault{
6163
/// This should be `[u8; BYTE_LEN]`;
6264
/// Cannot use an associated `const BYTE_LEN: usize` instead due to const eval limitations.
@@ -432,6 +434,13 @@ impl<I: Idx, const N: usize, T: FixedSizeEncoding<ByteArray = [u8; N]>> TableBui
432434
/// arises in the future then a new method (e.g. `clear` or `reset`) will need to be introduced
433435
/// for doing that explicitly.
434436
pub(crate)fnset(&mutself,i:I,value:T){
437+
#[cfg(debug_assertions)]
438+
{
439+
debug_assert!(
440+
T::from_bytes(&[0;N]).is_default(),
441+
"expected all-zeroes to decode to the default value, as per the invariant of FixedSizeEncoding"
442+
);
443+
}
435444
if !value.is_default(){
436445
// FIXME(eddyb) investigate more compact encodings for sparse tables.
437446
// On the PR @michaelwoerister mentioned:

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Commit 7c2c3c0

Browse files
committed
Auto merge of #149063 - matthiaskrgr:rollup-6z23izv, r=matthiaskrgr
Rollup of 5 pull requests Successful merges: - #147887 (Improve the documentation of atomic::fence) - #148281 (repr(transparent) check: do not compute check_unsuited more than once) - #148484 (Fix suggestion for the `cfg!` macro) - #149057 (`rust-analyzer` subtree update) - #149061 (debug-assert FixedSizeEncoding invariant) r? `@ghost` `@rustbot` modify labels: rollup
2 parents 3d461af + ceb33e9 commit 7c2c3c0

82 files changed

Lines changed: 6193 additions & 513 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎compiler/rustc_attr_parsing/src/attributes/cfg.rs‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use rustc_ast::token::Delimiter;
22
use rustc_ast::tokenstream::DelimSpan;
33
use rustc_ast::{AttrItem,Attribute,CRATE_NODE_ID,LitKind,NodeId, ast, token};
44
use rustc_errors::{Applicability,PResult};
5-
use rustc_feature::{AttributeTemplate,Features, template};
5+
use rustc_feature::{AttrSuggestionStyle,AttributeTemplate,Features, template};
66
use rustc_hir::attrs::CfgEntry;
77
use rustc_hir::{AttrPath,RustcVersion};
88
use rustc_parse::parser::{ForceCollect,Parser};
@@ -323,8 +323,8 @@ pub fn parse_cfg_attr(
323323
}){
324324
Ok(r) => returnSome(r),
325325
Err(e) => {
326-
let suggestions =
327-
CFG_ATTR_TEMPLATE.suggestions(Some(cfg_attr.style), sym::cfg_attr);
326+
let suggestions =CFG_ATTR_TEMPLATE
327+
.suggestions(AttrSuggestionStyle::Attribute(cfg_attr.style), sym::cfg_attr);
328328
e.with_span_suggestions(
329329
cfg_attr.span,
330330
"must be of the form",
@@ -355,7 +355,8 @@ pub fn parse_cfg_attr(
355355
path:AttrPath::from_ast(&cfg_attr.get_normal_item().path),
356356
description:ParsedDescription::Attribute,
357357
reason,
358-
suggestions:CFG_ATTR_TEMPLATE.suggestions(Some(cfg_attr.style), sym::cfg_attr),
358+
suggestions:CFG_ATTR_TEMPLATE
359+
.suggestions(AttrSuggestionStyle::Attribute(cfg_attr.style), sym::cfg_attr),
359360
});
360361
}
361362
}

‎compiler/rustc_attr_parsing/src/context.rs‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ use std::sync::LazyLock;
66
use private::Sealed;
77
use rustc_ast::{AttrStyle,CRATE_NODE_ID,MetaItemLit,NodeId};
88
use rustc_errors::{Diag,Diagnostic,Level};
9-
use rustc_feature::AttributeTemplate;
9+
use rustc_feature::{AttrSuggestionStyle,AttributeTemplate};
1010
use rustc_hir::attrs::AttributeKind;
1111
use rustc_hir::lints::{AttributeLint,AttributeLintKind};
1212
use rustc_hir::{AttrPath,CRATE_HIR_ID,HirId};
@@ -637,9 +637,15 @@ impl<'f, 'sess: 'f, S: Stage> AcceptContext<'f, 'sess, S> {
637637
}
638638

639639
pub(crate)fnsuggestions(&self) -> Vec<String>{
640-
// If the outer and inner spans are equal, we are parsing an attribute from `cfg_attr`,
641-
// So don't display an attribute style in the suggestions
642-
let style = (self.attr_span != self.inner_span).then_some(self.attr_style);
640+
let style = matchself.parsed_description{
641+
// If the outer and inner spans are equal, we are parsing an embedded attribute
642+
ParsedDescription::Attributeifself.attr_span == self.inner_span => {
643+
AttrSuggestionStyle::EmbeddedAttribute
644+
}
645+
ParsedDescription::Attribute => AttrSuggestionStyle::Attribute(self.attr_style),
646+
ParsedDescription::Macro => AttrSuggestionStyle::Macro,
647+
};
648+
643649
self.template.suggestions(style,&self.attr_path)
644650
}
645651
}

‎compiler/rustc_feature/src/builtin_attrs.rs‎

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -132,28 +132,45 @@ pub struct AttributeTemplate {
132132
pubdocs:Option<&'staticstr>,
133133
}
134134

135+
pubenumAttrSuggestionStyle{
136+
/// The suggestion is styled for a normal attribute.
137+
/// The `AttrStyle` determines whether this is an inner or outer attribute.
138+
Attribute(AttrStyle),
139+
/// The suggestion is styled for an attribute embedded into another attribute.
140+
/// For example, attributes inside `#[cfg_attr(true, attr(...)]`.
141+
EmbeddedAttribute,
142+
/// The suggestion is styled for macros that are parsed with attribute parsers.
143+
/// For example, the `cfg!(predicate)` macro.
144+
Macro,
145+
}
146+
135147
implAttributeTemplate{
136148
pubfnsuggestions(
137149
&self,
138-
style:Option<AttrStyle>,
150+
style:AttrSuggestionStyle,
139151
name:impl std::fmt::Display,
140152
) -> Vec<String>{
141-
letmut suggestions = vec![];
142-
let(start, end) =match style {
143-
Some(AttrStyle::Outer) => ("#[","]"),
144-
Some(AttrStyle::Inner) => ("#![","]"),
145-
None => ("",""),
153+
let(start, macro_call, end) = match style {
154+
AttrSuggestionStyle::Attribute(AttrStyle::Outer) => ("#[","","]"),
155+
AttrSuggestionStyle::Attribute(AttrStyle::Inner) => ("#![","","]"),
156+
AttrSuggestionStyle::Macro => ("","!",""),
157+
AttrSuggestionStyle::EmbeddedAttribute => ("","",""),
146158
};
159+
160+
letmut suggestions = vec![];
161+
147162
ifself.word{
163+
debug_assert!(macro_call.is_empty(),"Macro suggestions use list style");
148164
suggestions.push(format!("{start}{name}{end}"));
149165
}
150166
ifletSome(descr) = self.list{
151167
for descr in descr {
152-
suggestions.push(format!("{start}{name}({descr}){end}"));
168+
suggestions.push(format!("{start}{name}{macro_call}({descr}){end}"));
153169
}
154170
}
155171
suggestions.extend(self.one_of.iter().map(|&word| format!("{start}{name}({word}){end}")));
156172
ifletSome(descr) = self.name_value_str{
173+
debug_assert!(macro_call.is_empty(),"Macro suggestions use list style");
157174
for descr in descr {
158175
suggestions.push(format!("{start}{name} = \"{descr}\"{end}"));
159176
}

‎compiler/rustc_feature/src/lib.rs‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -129,9 +129,10 @@ pub fn find_feature_issue(feature: Symbol, issue: GateIssue) -> Option<NonZero<u
129129

130130
pubuse accepted::ACCEPTED_LANG_FEATURES;
131131
pubuse builtin_attrs::{
132-
AttributeDuplicates,AttributeGate,AttributeSafety,AttributeTemplate,AttributeType,
133-
BUILTIN_ATTRIBUTE_MAP,BUILTIN_ATTRIBUTES,BuiltinAttribute,GatedCfg, encode_cross_crate,
134-
find_gated_cfg, is_builtin_attr_name, is_stable_diagnostic_attribute, is_valid_for_get_attr,
132+
AttrSuggestionStyle,AttributeDuplicates,AttributeGate,AttributeSafety,AttributeTemplate,
133+
AttributeType,BUILTIN_ATTRIBUTE_MAP,BUILTIN_ATTRIBUTES,BuiltinAttribute,GatedCfg,
134+
encode_cross_crate, find_gated_cfg, is_builtin_attr_name, is_stable_diagnostic_attribute,
135+
is_valid_for_get_attr,
135136
};
136137
pubuse removed::REMOVED_LANG_FEATURES;
137138
pubuse unstable::{

‎compiler/rustc_hir_analysis/src/check/check.rs‎

Lines changed: 56 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -1542,22 +1542,10 @@ pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>)
15421542

15431543
let typing_env = ty::TypingEnv::non_body_analysis(tcx, adt.did());
15441544
// For each field, figure out if it has "trivial" layout (i.e., is a 1-ZST).
1545-
// Even some 1-ZST fields are not allowed though, if they have `non_exhaustive` or private
1546-
// fields or `repr(C)`. We call those fields "unsuited".
15471545
structFieldInfo<'tcx>{
15481546
span:Span,
15491547
trivial:bool,
1550-
unsuited:Option<UnsuitedInfo<'tcx>>,
1551-
}
1552-
structUnsuitedInfo<'tcx>{
1553-
/// The source of the problem, a type that is found somewhere within the field type.
15541548
ty:Ty<'tcx>,
1555-
reason:UnsuitedReason,
1556-
}
1557-
enumUnsuitedReason{
1558-
NonExhaustive,
1559-
PrivateField,
1560-
ReprC,
15611549
}
15621550

15631551
let field_infos = adt.all_fields().map(|field| {
@@ -1566,60 +1554,7 @@ pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>)
15661554
// We are currently checking the type this field came from, so it must be local
15671555
let span = tcx.hir_span_if_local(field.did).unwrap();
15681556
let trivial = layout.is_ok_and(|layout| layout.is_1zst());
1569-
if !trivial {
1570-
// No need to even compute `unsuited`.
1571-
returnFieldInfo{ span, trivial,unsuited:None};
1572-
}
1573-
1574-
fncheck_unsuited<'tcx>(
1575-
tcx:TyCtxt<'tcx>,
1576-
typing_env: ty::TypingEnv<'tcx>,
1577-
ty:Ty<'tcx>,
1578-
) -> ControlFlow<UnsuitedInfo<'tcx>>{
1579-
// We can encounter projections during traversal, so ensure the type is normalized.
1580-
let ty = tcx.try_normalize_erasing_regions(typing_env, ty).unwrap_or(ty);
1581-
match ty.kind(){
1582-
ty::Tuple(list) => list.iter().try_for_each(|t| check_unsuited(tcx, typing_env, t)),
1583-
ty::Array(ty, _) => check_unsuited(tcx, typing_env,*ty),
1584-
ty::Adt(def, args) => {
1585-
if !def.did().is_local()
1586-
&& !find_attr!(
1587-
tcx.get_all_attrs(def.did()),
1588-
AttributeKind::PubTransparent(_)
1589-
)
1590-
{
1591-
let non_exhaustive = def.is_variant_list_non_exhaustive()
1592-
|| def
1593-
.variants()
1594-
.iter()
1595-
.any(ty::VariantDef::is_field_list_non_exhaustive);
1596-
let has_priv = def.all_fields().any(|f| !f.vis.is_public());
1597-
if non_exhaustive || has_priv {
1598-
returnControlFlow::Break(UnsuitedInfo{
1599-
ty,
1600-
reason:if non_exhaustive {
1601-
UnsuitedReason::NonExhaustive
1602-
}else{
1603-
UnsuitedReason::PrivateField
1604-
},
1605-
});
1606-
}
1607-
}
1608-
if def.repr().c(){
1609-
returnControlFlow::Break(UnsuitedInfo{
1610-
ty,
1611-
reason:UnsuitedReason::ReprC,
1612-
});
1613-
}
1614-
def.all_fields()
1615-
.map(|field| field.ty(tcx, args))
1616-
.try_for_each(|t| check_unsuited(tcx, typing_env, t))
1617-
}
1618-
_ => ControlFlow::Continue(()),
1619-
}
1620-
}
1621-
1622-
FieldInfo{ span, trivial,unsuited:check_unsuited(tcx, typing_env, ty).break_value()}
1557+
FieldInfo{ span, trivial, ty }
16231558
});
16241559

16251560
let non_trivial_fields = field_infos
@@ -1637,10 +1572,63 @@ pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>)
16371572
return;
16381573
}
16391574

1575+
// Even some 1-ZST fields are not allowed though, if they have `non_exhaustive` or private
1576+
// fields or `repr(C)`. We call those fields "unsuited".
1577+
structUnsuitedInfo<'tcx>{
1578+
/// The source of the problem, a type that is found somewhere within the field type.
1579+
ty:Ty<'tcx>,
1580+
reason:UnsuitedReason,
1581+
}
1582+
enumUnsuitedReason{
1583+
NonExhaustive,
1584+
PrivateField,
1585+
ReprC,
1586+
}
1587+
1588+
fncheck_unsuited<'tcx>(
1589+
tcx:TyCtxt<'tcx>,
1590+
typing_env: ty::TypingEnv<'tcx>,
1591+
ty:Ty<'tcx>,
1592+
) -> ControlFlow<UnsuitedInfo<'tcx>>{
1593+
// We can encounter projections during traversal, so ensure the type is normalized.
1594+
let ty = tcx.try_normalize_erasing_regions(typing_env, ty).unwrap_or(ty);
1595+
match ty.kind(){
1596+
ty::Tuple(list) => list.iter().try_for_each(|t| check_unsuited(tcx, typing_env, t)),
1597+
ty::Array(ty, _) => check_unsuited(tcx, typing_env,*ty),
1598+
ty::Adt(def, args) => {
1599+
if !def.did().is_local()
1600+
&& !find_attr!(tcx.get_all_attrs(def.did()),AttributeKind::PubTransparent(_))
1601+
{
1602+
let non_exhaustive = def.is_variant_list_non_exhaustive()
1603+
|| def.variants().iter().any(ty::VariantDef::is_field_list_non_exhaustive);
1604+
let has_priv = def.all_fields().any(|f| !f.vis.is_public());
1605+
if non_exhaustive || has_priv {
1606+
returnControlFlow::Break(UnsuitedInfo{
1607+
ty,
1608+
reason:if non_exhaustive {
1609+
UnsuitedReason::NonExhaustive
1610+
}else{
1611+
UnsuitedReason::PrivateField
1612+
},
1613+
});
1614+
}
1615+
}
1616+
if def.repr().c(){
1617+
returnControlFlow::Break(UnsuitedInfo{ ty,reason:UnsuitedReason::ReprC});
1618+
}
1619+
def.all_fields()
1620+
.map(|field| field.ty(tcx, args))
1621+
.try_for_each(|t| check_unsuited(tcx, typing_env, t))
1622+
}
1623+
_ => ControlFlow::Continue(()),
1624+
}
1625+
}
1626+
16401627
letmut prev_unsuited_1zst = false;
16411628
for field in field_infos {
1642-
ifletSome(unsuited) = field.unsuited{
1643-
assert!(field.trivial);
1629+
if field.trivial
1630+
&& letSome(unsuited) = check_unsuited(tcx, typing_env, field.ty).break_value()
1631+
{
16441632
// If there are any non-trivial fields, then there can be no non-exhaustive 1-zsts.
16451633
// Otherwise, it's only an issue if there's >1 non-exhaustive 1-zst.
16461634
if non_trivial_count > 0 || prev_unsuited_1zst {

‎compiler/rustc_metadata/src/rmeta/table.rs‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,8 +55,10 @@ impl IsDefault for UnusedGenericParams {
5555

5656
/// Helper trait, for encoding to, and decoding from, a fixed number of bytes.
5757
/// Used mainly for Lazy positions and lengths.
58-
/// Unchecked invariant: `Self::default()` should encode as `[0; BYTE_LEN]`,
58+
///
59+
/// Invariant: `Self::default()` should encode as `[0; BYTE_LEN]`,
5960
/// but this has no impact on safety.
61+
/// In debug builds, this invariant is checked in `[TableBuilder::set]`
6062
pub(super)traitFixedSizeEncoding:IsDefault{
6163
/// This should be `[u8; BYTE_LEN]`;
6264
/// Cannot use an associated `const BYTE_LEN: usize` instead due to const eval limitations.
@@ -432,6 +434,13 @@ impl<I: Idx, const N: usize, T: FixedSizeEncoding<ByteArray = [u8; N]>> TableBui
432434
/// arises in the future then a new method (e.g. `clear` or `reset`) will need to be introduced
433435
/// for doing that explicitly.
434436
pub(crate)fnset(&mutself,i:I,value:T){
437+
#[cfg(debug_assertions)]
438+
{
439+
debug_assert!(
440+
T::from_bytes(&[0;N]).is_default(),
441+
"expected all-zeroes to decode to the default value, as per the invariant of FixedSizeEncoding"
442+
);
443+
}
435444
if !value.is_default(){
436445
// FIXME(eddyb) investigate more compact encodings for sparse tables.
437446
// On the PR @michaelwoerister mentioned:

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit 7c2c3c0

Browse files
committed
Auto merge of #149063 - matthiaskrgr:rollup-6z23izv, r=matthiaskrgr
Rollup of 5 pull requests Successful merges: - #147887 (Improve the documentation of atomic::fence) - #148281 (repr(transparent) check: do not compute check_unsuited more than once) - #148484 (Fix suggestion for the `cfg!` macro) - #149057 (`rust-analyzer` subtree update) - #149061 (debug-assert FixedSizeEncoding invariant) r? `@ghost` `@rustbot` modify labels: rollup
2 parents 3d461af + ceb33e9 commit 7c2c3c0

82 files changed

Lines changed: 6193 additions & 513 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎compiler/rustc_attr_parsing/src/attributes/cfg.rs‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use rustc_ast::token::Delimiter;
22
use rustc_ast::tokenstream::DelimSpan;
33
use rustc_ast::{AttrItem,Attribute,CRATE_NODE_ID,LitKind,NodeId, ast, token};
44
use rustc_errors::{Applicability,PResult};
5-
use rustc_feature::{AttributeTemplate,Features, template};
5+
use rustc_feature::{AttrSuggestionStyle,AttributeTemplate,Features, template};
66
use rustc_hir::attrs::CfgEntry;
77
use rustc_hir::{AttrPath,RustcVersion};
88
use rustc_parse::parser::{ForceCollect,Parser};
@@ -323,8 +323,8 @@ pub fn parse_cfg_attr(
323323
}){
324324
Ok(r) => returnSome(r),
325325
Err(e) => {
326-
let suggestions =
327-
CFG_ATTR_TEMPLATE.suggestions(Some(cfg_attr.style), sym::cfg_attr);
326+
let suggestions =CFG_ATTR_TEMPLATE
327+
.suggestions(AttrSuggestionStyle::Attribute(cfg_attr.style), sym::cfg_attr);
328328
e.with_span_suggestions(
329329
cfg_attr.span,
330330
"must be of the form",
@@ -355,7 +355,8 @@ pub fn parse_cfg_attr(
355355
path:AttrPath::from_ast(&cfg_attr.get_normal_item().path),
356356
description:ParsedDescription::Attribute,
357357
reason,
358-
suggestions:CFG_ATTR_TEMPLATE.suggestions(Some(cfg_attr.style), sym::cfg_attr),
358+
suggestions:CFG_ATTR_TEMPLATE
359+
.suggestions(AttrSuggestionStyle::Attribute(cfg_attr.style), sym::cfg_attr),
359360
});
360361
}
361362
}

‎compiler/rustc_attr_parsing/src/context.rs‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ use std::sync::LazyLock;
66
use private::Sealed;
77
use rustc_ast::{AttrStyle,CRATE_NODE_ID,MetaItemLit,NodeId};
88
use rustc_errors::{Diag,Diagnostic,Level};
9-
use rustc_feature::AttributeTemplate;
9+
use rustc_feature::{AttrSuggestionStyle,AttributeTemplate};
1010
use rustc_hir::attrs::AttributeKind;
1111
use rustc_hir::lints::{AttributeLint,AttributeLintKind};
1212
use rustc_hir::{AttrPath,CRATE_HIR_ID,HirId};
@@ -637,9 +637,15 @@ impl<'f, 'sess: 'f, S: Stage> AcceptContext<'f, 'sess, S> {
637637
}
638638

639639
pub(crate)fnsuggestions(&self) -> Vec<String>{
640-
// If the outer and inner spans are equal, we are parsing an attribute from `cfg_attr`,
641-
// So don't display an attribute style in the suggestions
642-
let style = (self.attr_span != self.inner_span).then_some(self.attr_style);
640+
let style = matchself.parsed_description{
641+
// If the outer and inner spans are equal, we are parsing an embedded attribute
642+
ParsedDescription::Attributeifself.attr_span == self.inner_span => {
643+
AttrSuggestionStyle::EmbeddedAttribute
644+
}
645+
ParsedDescription::Attribute => AttrSuggestionStyle::Attribute(self.attr_style),
646+
ParsedDescription::Macro => AttrSuggestionStyle::Macro,
647+
};
648+
643649
self.template.suggestions(style,&self.attr_path)
644650
}
645651
}

‎compiler/rustc_feature/src/builtin_attrs.rs‎

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -132,28 +132,45 @@ pub struct AttributeTemplate {
132132
pubdocs:Option<&'staticstr>,
133133
}
134134

135+
pubenumAttrSuggestionStyle{
136+
/// The suggestion is styled for a normal attribute.
137+
/// The `AttrStyle` determines whether this is an inner or outer attribute.
138+
Attribute(AttrStyle),
139+
/// The suggestion is styled for an attribute embedded into another attribute.
140+
/// For example, attributes inside `#[cfg_attr(true, attr(...)]`.
141+
EmbeddedAttribute,
142+
/// The suggestion is styled for macros that are parsed with attribute parsers.
143+
/// For example, the `cfg!(predicate)` macro.
144+
Macro,
145+
}
146+
135147
implAttributeTemplate{
136148
pubfnsuggestions(
137149
&self,
138-
style:Option<AttrStyle>,
150+
style:AttrSuggestionStyle,
139151
name:impl std::fmt::Display,
140152
) -> Vec<String>{
141-
letmut suggestions = vec![];
142-
let(start, end) =match style {
143-
Some(AttrStyle::Outer) => ("#[","]"),
144-
Some(AttrStyle::Inner) => ("#![","]"),
145-
None => ("",""),
153+
let(start, macro_call, end) = match style {
154+
AttrSuggestionStyle::Attribute(AttrStyle::Outer) => ("#[","","]"),
155+
AttrSuggestionStyle::Attribute(AttrStyle::Inner) => ("#![","","]"),
156+
AttrSuggestionStyle::Macro => ("","!",""),
157+
AttrSuggestionStyle::EmbeddedAttribute => ("","",""),
146158
};
159+
160+
letmut suggestions = vec![];
161+
147162
ifself.word{
163+
debug_assert!(macro_call.is_empty(),"Macro suggestions use list style");
148164
suggestions.push(format!("{start}{name}{end}"));
149165
}
150166
ifletSome(descr) = self.list{
151167
for descr in descr {
152-
suggestions.push(format!("{start}{name}({descr}){end}"));
168+
suggestions.push(format!("{start}{name}{macro_call}({descr}){end}"));
153169
}
154170
}
155171
suggestions.extend(self.one_of.iter().map(|&word| format!("{start}{name}({word}){end}")));
156172
ifletSome(descr) = self.name_value_str{
173+
debug_assert!(macro_call.is_empty(),"Macro suggestions use list style");
157174
for descr in descr {
158175
suggestions.push(format!("{start}{name} = \"{descr}\"{end}"));
159176
}

‎compiler/rustc_feature/src/lib.rs‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -129,9 +129,10 @@ pub fn find_feature_issue(feature: Symbol, issue: GateIssue) -> Option<NonZero<u
129129

130130
pubuse accepted::ACCEPTED_LANG_FEATURES;
131131
pubuse builtin_attrs::{
132-
AttributeDuplicates,AttributeGate,AttributeSafety,AttributeTemplate,AttributeType,
133-
BUILTIN_ATTRIBUTE_MAP,BUILTIN_ATTRIBUTES,BuiltinAttribute,GatedCfg, encode_cross_crate,
134-
find_gated_cfg, is_builtin_attr_name, is_stable_diagnostic_attribute, is_valid_for_get_attr,
132+
AttrSuggestionStyle,AttributeDuplicates,AttributeGate,AttributeSafety,AttributeTemplate,
133+
AttributeType,BUILTIN_ATTRIBUTE_MAP,BUILTIN_ATTRIBUTES,BuiltinAttribute,GatedCfg,
134+
encode_cross_crate, find_gated_cfg, is_builtin_attr_name, is_stable_diagnostic_attribute,
135+
is_valid_for_get_attr,
135136
};
136137
pubuse removed::REMOVED_LANG_FEATURES;
137138
pubuse unstable::{

‎compiler/rustc_hir_analysis/src/check/check.rs‎

Lines changed: 56 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -1542,22 +1542,10 @@ pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>)
15421542

15431543
let typing_env = ty::TypingEnv::non_body_analysis(tcx, adt.did());
15441544
// For each field, figure out if it has "trivial" layout (i.e., is a 1-ZST).
1545-
// Even some 1-ZST fields are not allowed though, if they have `non_exhaustive` or private
1546-
// fields or `repr(C)`. We call those fields "unsuited".
15471545
structFieldInfo<'tcx>{
15481546
span:Span,
15491547
trivial:bool,
1550-
unsuited:Option<UnsuitedInfo<'tcx>>,
1551-
}
1552-
structUnsuitedInfo<'tcx>{
1553-
/// The source of the problem, a type that is found somewhere within the field type.
15541548
ty:Ty<'tcx>,
1555-
reason:UnsuitedReason,
1556-
}
1557-
enumUnsuitedReason{
1558-
NonExhaustive,
1559-
PrivateField,
1560-
ReprC,
15611549
}
15621550

15631551
let field_infos = adt.all_fields().map(|field| {
@@ -1566,60 +1554,7 @@ pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>)
15661554
// We are currently checking the type this field came from, so it must be local
15671555
let span = tcx.hir_span_if_local(field.did).unwrap();
15681556
let trivial = layout.is_ok_and(|layout| layout.is_1zst());
1569-
if !trivial {
1570-
// No need to even compute `unsuited`.
1571-
returnFieldInfo{ span, trivial,unsuited:None};
1572-
}
1573-
1574-
fncheck_unsuited<'tcx>(
1575-
tcx:TyCtxt<'tcx>,
1576-
typing_env: ty::TypingEnv<'tcx>,
1577-
ty:Ty<'tcx>,
1578-
) -> ControlFlow<UnsuitedInfo<'tcx>>{
1579-
// We can encounter projections during traversal, so ensure the type is normalized.
1580-
let ty = tcx.try_normalize_erasing_regions(typing_env, ty).unwrap_or(ty);
1581-
match ty.kind(){
1582-
ty::Tuple(list) => list.iter().try_for_each(|t| check_unsuited(tcx, typing_env, t)),
1583-
ty::Array(ty, _) => check_unsuited(tcx, typing_env,*ty),
1584-
ty::Adt(def, args) => {
1585-
if !def.did().is_local()
1586-
&& !find_attr!(
1587-
tcx.get_all_attrs(def.did()),
1588-
AttributeKind::PubTransparent(_)
1589-
)
1590-
{
1591-
let non_exhaustive = def.is_variant_list_non_exhaustive()
1592-
|| def
1593-
.variants()
1594-
.iter()
1595-
.any(ty::VariantDef::is_field_list_non_exhaustive);
1596-
let has_priv = def.all_fields().any(|f| !f.vis.is_public());
1597-
if non_exhaustive || has_priv {
1598-
returnControlFlow::Break(UnsuitedInfo{
1599-
ty,
1600-
reason:if non_exhaustive {
1601-
UnsuitedReason::NonExhaustive
1602-
}else{
1603-
UnsuitedReason::PrivateField
1604-
},
1605-
});
1606-
}
1607-
}
1608-
if def.repr().c(){
1609-
returnControlFlow::Break(UnsuitedInfo{
1610-
ty,
1611-
reason:UnsuitedReason::ReprC,
1612-
});
1613-
}
1614-
def.all_fields()
1615-
.map(|field| field.ty(tcx, args))
1616-
.try_for_each(|t| check_unsuited(tcx, typing_env, t))
1617-
}
1618-
_ => ControlFlow::Continue(()),
1619-
}
1620-
}
1621-
1622-
FieldInfo{ span, trivial,unsuited:check_unsuited(tcx, typing_env, ty).break_value()}
1557+
FieldInfo{ span, trivial, ty }
16231558
});
16241559

16251560
let non_trivial_fields = field_infos
@@ -1637,10 +1572,63 @@ pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>)
16371572
return;
16381573
}
16391574

1575+
// Even some 1-ZST fields are not allowed though, if they have `non_exhaustive` or private
1576+
// fields or `repr(C)`. We call those fields "unsuited".
1577+
structUnsuitedInfo<'tcx>{
1578+
/// The source of the problem, a type that is found somewhere within the field type.
1579+
ty:Ty<'tcx>,
1580+
reason:UnsuitedReason,
1581+
}
1582+
enumUnsuitedReason{
1583+
NonExhaustive,
1584+
PrivateField,
1585+
ReprC,
1586+
}
1587+
1588+
fncheck_unsuited<'tcx>(
1589+
tcx:TyCtxt<'tcx>,
1590+
typing_env: ty::TypingEnv<'tcx>,
1591+
ty:Ty<'tcx>,
1592+
) -> ControlFlow<UnsuitedInfo<'tcx>>{
1593+
// We can encounter projections during traversal, so ensure the type is normalized.
1594+
let ty = tcx.try_normalize_erasing_regions(typing_env, ty).unwrap_or(ty);
1595+
match ty.kind(){
1596+
ty::Tuple(list) => list.iter().try_for_each(|t| check_unsuited(tcx, typing_env, t)),
1597+
ty::Array(ty, _) => check_unsuited(tcx, typing_env,*ty),
1598+
ty::Adt(def, args) => {
1599+
if !def.did().is_local()
1600+
&& !find_attr!(tcx.get_all_attrs(def.did()),AttributeKind::PubTransparent(_))
1601+
{
1602+
let non_exhaustive = def.is_variant_list_non_exhaustive()
1603+
|| def.variants().iter().any(ty::VariantDef::is_field_list_non_exhaustive);
1604+
let has_priv = def.all_fields().any(|f| !f.vis.is_public());
1605+
if non_exhaustive || has_priv {
1606+
returnControlFlow::Break(UnsuitedInfo{
1607+
ty,
1608+
reason:if non_exhaustive {
1609+
UnsuitedReason::NonExhaustive
1610+
}else{
1611+
UnsuitedReason::PrivateField
1612+
},
1613+
});
1614+
}
1615+
}
1616+
if def.repr().c(){
1617+
returnControlFlow::Break(UnsuitedInfo{ ty,reason:UnsuitedReason::ReprC});
1618+
}
1619+
def.all_fields()
1620+
.map(|field| field.ty(tcx, args))
1621+
.try_for_each(|t| check_unsuited(tcx, typing_env, t))
1622+
}
1623+
_ => ControlFlow::Continue(()),
1624+
}
1625+
}
1626+
16401627
letmut prev_unsuited_1zst = false;
16411628
for field in field_infos {
1642-
ifletSome(unsuited) = field.unsuited{
1643-
assert!(field.trivial);
1629+
if field.trivial
1630+
&& letSome(unsuited) = check_unsuited(tcx, typing_env, field.ty).break_value()
1631+
{
16441632
// If there are any non-trivial fields, then there can be no non-exhaustive 1-zsts.
16451633
// Otherwise, it's only an issue if there's >1 non-exhaustive 1-zst.
16461634
if non_trivial_count > 0 || prev_unsuited_1zst {

‎compiler/rustc_metadata/src/rmeta/table.rs‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,8 +55,10 @@ impl IsDefault for UnusedGenericParams {
5555

5656
/// Helper trait, for encoding to, and decoding from, a fixed number of bytes.
5757
/// Used mainly for Lazy positions and lengths.
58-
/// Unchecked invariant: `Self::default()` should encode as `[0; BYTE_LEN]`,
58+
///
59+
/// Invariant: `Self::default()` should encode as `[0; BYTE_LEN]`,
5960
/// but this has no impact on safety.
61+
/// In debug builds, this invariant is checked in `[TableBuilder::set]`
6062
pub(super)traitFixedSizeEncoding:IsDefault{
6163
/// This should be `[u8; BYTE_LEN]`;
6264
/// Cannot use an associated `const BYTE_LEN: usize` instead due to const eval limitations.
@@ -432,6 +434,13 @@ impl<I: Idx, const N: usize, T: FixedSizeEncoding<ByteArray = [u8; N]>> TableBui
432434
/// arises in the future then a new method (e.g. `clear` or `reset`) will need to be introduced
433435
/// for doing that explicitly.
434436
pub(crate)fnset(&mutself,i:I,value:T){
437+
#[cfg(debug_assertions)]
438+
{
439+
debug_assert!(
440+
T::from_bytes(&[0;N]).is_default(),
441+
"expected all-zeroes to decode to the default value, as per the invariant of FixedSizeEncoding"
442+
);
443+
}
435444
if !value.is_default(){
436445
// FIXME(eddyb) investigate more compact encodings for sparse tables.
437446
// On the PR @michaelwoerister mentioned:

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit 7c2c3c0

Browse files
committed
Auto merge of #149063 - matthiaskrgr:rollup-6z23izv, r=matthiaskrgr
Rollup of 5 pull requests Successful merges: - #147887 (Improve the documentation of atomic::fence) - #148281 (repr(transparent) check: do not compute check_unsuited more than once) - #148484 (Fix suggestion for the `cfg!` macro) - #149057 (`rust-analyzer` subtree update) - #149061 (debug-assert FixedSizeEncoding invariant) r? `@ghost` `@rustbot` modify labels: rollup
2 parents 3d461af + ceb33e9 commit 7c2c3c0

82 files changed

Lines changed: 6193 additions & 513 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎compiler/rustc_attr_parsing/src/attributes/cfg.rs‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use rustc_ast::token::Delimiter;
22
use rustc_ast::tokenstream::DelimSpan;
33
use rustc_ast::{AttrItem,Attribute,CRATE_NODE_ID,LitKind,NodeId, ast, token};
44
use rustc_errors::{Applicability,PResult};
5-
use rustc_feature::{AttributeTemplate,Features, template};
5+
use rustc_feature::{AttrSuggestionStyle,AttributeTemplate,Features, template};
66
use rustc_hir::attrs::CfgEntry;
77
use rustc_hir::{AttrPath,RustcVersion};
88
use rustc_parse::parser::{ForceCollect,Parser};
@@ -323,8 +323,8 @@ pub fn parse_cfg_attr(
323323
}){
324324
Ok(r) => returnSome(r),
325325
Err(e) => {
326-
let suggestions =
327-
CFG_ATTR_TEMPLATE.suggestions(Some(cfg_attr.style), sym::cfg_attr);
326+
let suggestions =CFG_ATTR_TEMPLATE
327+
.suggestions(AttrSuggestionStyle::Attribute(cfg_attr.style), sym::cfg_attr);
328328
e.with_span_suggestions(
329329
cfg_attr.span,
330330
"must be of the form",
@@ -355,7 +355,8 @@ pub fn parse_cfg_attr(
355355
path:AttrPath::from_ast(&cfg_attr.get_normal_item().path),
356356
description:ParsedDescription::Attribute,
357357
reason,
358-
suggestions:CFG_ATTR_TEMPLATE.suggestions(Some(cfg_attr.style), sym::cfg_attr),
358+
suggestions:CFG_ATTR_TEMPLATE
359+
.suggestions(AttrSuggestionStyle::Attribute(cfg_attr.style), sym::cfg_attr),
359360
});
360361
}
361362
}

‎compiler/rustc_attr_parsing/src/context.rs‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ use std::sync::LazyLock;
66
use private::Sealed;
77
use rustc_ast::{AttrStyle,CRATE_NODE_ID,MetaItemLit,NodeId};
88
use rustc_errors::{Diag,Diagnostic,Level};
9-
use rustc_feature::AttributeTemplate;
9+
use rustc_feature::{AttrSuggestionStyle,AttributeTemplate};
1010
use rustc_hir::attrs::AttributeKind;
1111
use rustc_hir::lints::{AttributeLint,AttributeLintKind};
1212
use rustc_hir::{AttrPath,CRATE_HIR_ID,HirId};
@@ -637,9 +637,15 @@ impl<'f, 'sess: 'f, S: Stage> AcceptContext<'f, 'sess, S> {
637637
}
638638

639639
pub(crate)fnsuggestions(&self) -> Vec<String>{
640-
// If the outer and inner spans are equal, we are parsing an attribute from `cfg_attr`,
641-
// So don't display an attribute style in the suggestions
642-
let style = (self.attr_span != self.inner_span).then_some(self.attr_style);
640+
let style = matchself.parsed_description{
641+
// If the outer and inner spans are equal, we are parsing an embedded attribute
642+
ParsedDescription::Attributeifself.attr_span == self.inner_span => {
643+
AttrSuggestionStyle::EmbeddedAttribute
644+
}
645+
ParsedDescription::Attribute => AttrSuggestionStyle::Attribute(self.attr_style),
646+
ParsedDescription::Macro => AttrSuggestionStyle::Macro,
647+
};
648+
643649
self.template.suggestions(style,&self.attr_path)
644650
}
645651
}

‎compiler/rustc_feature/src/builtin_attrs.rs‎

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -132,28 +132,45 @@ pub struct AttributeTemplate {
132132
pubdocs:Option<&'staticstr>,
133133
}
134134

135+
pubenumAttrSuggestionStyle{
136+
/// The suggestion is styled for a normal attribute.
137+
/// The `AttrStyle` determines whether this is an inner or outer attribute.
138+
Attribute(AttrStyle),
139+
/// The suggestion is styled for an attribute embedded into another attribute.
140+
/// For example, attributes inside `#[cfg_attr(true, attr(...)]`.
141+
EmbeddedAttribute,
142+
/// The suggestion is styled for macros that are parsed with attribute parsers.
143+
/// For example, the `cfg!(predicate)` macro.
144+
Macro,
145+
}
146+
135147
implAttributeTemplate{
136148
pubfnsuggestions(
137149
&self,
138-
style:Option<AttrStyle>,
150+
style:AttrSuggestionStyle,
139151
name:impl std::fmt::Display,
140152
) -> Vec<String>{
141-
letmut suggestions = vec![];
142-
let(start, end) =match style {
143-
Some(AttrStyle::Outer) => ("#[","]"),
144-
Some(AttrStyle::Inner) => ("#![","]"),
145-
None => ("",""),
153+
let(start, macro_call, end) = match style {
154+
AttrSuggestionStyle::Attribute(AttrStyle::Outer) => ("#[","","]"),
155+
AttrSuggestionStyle::Attribute(AttrStyle::Inner) => ("#![","","]"),
156+
AttrSuggestionStyle::Macro => ("","!",""),
157+
AttrSuggestionStyle::EmbeddedAttribute => ("","",""),
146158
};
159+
160+
letmut suggestions = vec![];
161+
147162
ifself.word{
163+
debug_assert!(macro_call.is_empty(),"Macro suggestions use list style");
148164
suggestions.push(format!("{start}{name}{end}"));
149165
}
150166
ifletSome(descr) = self.list{
151167
for descr in descr {
152-
suggestions.push(format!("{start}{name}({descr}){end}"));
168+
suggestions.push(format!("{start}{name}{macro_call}({descr}){end}"));
153169
}
154170
}
155171
suggestions.extend(self.one_of.iter().map(|&word| format!("{start}{name}({word}){end}")));
156172
ifletSome(descr) = self.name_value_str{
173+
debug_assert!(macro_call.is_empty(),"Macro suggestions use list style");
157174
for descr in descr {
158175
suggestions.push(format!("{start}{name} = \"{descr}\"{end}"));
159176
}

‎compiler/rustc_feature/src/lib.rs‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -129,9 +129,10 @@ pub fn find_feature_issue(feature: Symbol, issue: GateIssue) -> Option<NonZero<u
129129

130130
pubuse accepted::ACCEPTED_LANG_FEATURES;
131131
pubuse builtin_attrs::{
132-
AttributeDuplicates,AttributeGate,AttributeSafety,AttributeTemplate,AttributeType,
133-
BUILTIN_ATTRIBUTE_MAP,BUILTIN_ATTRIBUTES,BuiltinAttribute,GatedCfg, encode_cross_crate,
134-
find_gated_cfg, is_builtin_attr_name, is_stable_diagnostic_attribute, is_valid_for_get_attr,
132+
AttrSuggestionStyle,AttributeDuplicates,AttributeGate,AttributeSafety,AttributeTemplate,
133+
AttributeType,BUILTIN_ATTRIBUTE_MAP,BUILTIN_ATTRIBUTES,BuiltinAttribute,GatedCfg,
134+
encode_cross_crate, find_gated_cfg, is_builtin_attr_name, is_stable_diagnostic_attribute,
135+
is_valid_for_get_attr,
135136
};
136137
pubuse removed::REMOVED_LANG_FEATURES;
137138
pubuse unstable::{

‎compiler/rustc_hir_analysis/src/check/check.rs‎

Lines changed: 56 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -1542,22 +1542,10 @@ pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>)
15421542

15431543
let typing_env = ty::TypingEnv::non_body_analysis(tcx, adt.did());
15441544
// For each field, figure out if it has "trivial" layout (i.e., is a 1-ZST).
1545-
// Even some 1-ZST fields are not allowed though, if they have `non_exhaustive` or private
1546-
// fields or `repr(C)`. We call those fields "unsuited".
15471545
structFieldInfo<'tcx>{
15481546
span:Span,
15491547
trivial:bool,
1550-
unsuited:Option<UnsuitedInfo<'tcx>>,
1551-
}
1552-
structUnsuitedInfo<'tcx>{
1553-
/// The source of the problem, a type that is found somewhere within the field type.
15541548
ty:Ty<'tcx>,
1555-
reason:UnsuitedReason,
1556-
}
1557-
enumUnsuitedReason{
1558-
NonExhaustive,
1559-
PrivateField,
1560-
ReprC,
15611549
}
15621550

15631551
let field_infos = adt.all_fields().map(|field| {
@@ -1566,60 +1554,7 @@ pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>)
15661554
// We are currently checking the type this field came from, so it must be local
15671555
let span = tcx.hir_span_if_local(field.did).unwrap();
15681556
let trivial = layout.is_ok_and(|layout| layout.is_1zst());
1569-
if !trivial {
1570-
// No need to even compute `unsuited`.
1571-
returnFieldInfo{ span, trivial,unsuited:None};
1572-
}
1573-
1574-
fncheck_unsuited<'tcx>(
1575-
tcx:TyCtxt<'tcx>,
1576-
typing_env: ty::TypingEnv<'tcx>,
1577-
ty:Ty<'tcx>,
1578-
) -> ControlFlow<UnsuitedInfo<'tcx>>{
1579-
// We can encounter projections during traversal, so ensure the type is normalized.
1580-
let ty = tcx.try_normalize_erasing_regions(typing_env, ty).unwrap_or(ty);
1581-
match ty.kind(){
1582-
ty::Tuple(list) => list.iter().try_for_each(|t| check_unsuited(tcx, typing_env, t)),
1583-
ty::Array(ty, _) => check_unsuited(tcx, typing_env,*ty),
1584-
ty::Adt(def, args) => {
1585-
if !def.did().is_local()
1586-
&& !find_attr!(
1587-
tcx.get_all_attrs(def.did()),
1588-
AttributeKind::PubTransparent(_)
1589-
)
1590-
{
1591-
let non_exhaustive = def.is_variant_list_non_exhaustive()
1592-
|| def
1593-
.variants()
1594-
.iter()
1595-
.any(ty::VariantDef::is_field_list_non_exhaustive);
1596-
let has_priv = def.all_fields().any(|f| !f.vis.is_public());
1597-
if non_exhaustive || has_priv {
1598-
returnControlFlow::Break(UnsuitedInfo{
1599-
ty,
1600-
reason:if non_exhaustive {
1601-
UnsuitedReason::NonExhaustive
1602-
}else{
1603-
UnsuitedReason::PrivateField
1604-
},
1605-
});
1606-
}
1607-
}
1608-
if def.repr().c(){
1609-
returnControlFlow::Break(UnsuitedInfo{
1610-
ty,
1611-
reason:UnsuitedReason::ReprC,
1612-
});
1613-
}
1614-
def.all_fields()
1615-
.map(|field| field.ty(tcx, args))
1616-
.try_for_each(|t| check_unsuited(tcx, typing_env, t))
1617-
}
1618-
_ => ControlFlow::Continue(()),
1619-
}
1620-
}
1621-
1622-
FieldInfo{ span, trivial,unsuited:check_unsuited(tcx, typing_env, ty).break_value()}
1557+
FieldInfo{ span, trivial, ty }
16231558
});
16241559

16251560
let non_trivial_fields = field_infos
@@ -1637,10 +1572,63 @@ pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>)
16371572
return;
16381573
}
16391574

1575+
// Even some 1-ZST fields are not allowed though, if they have `non_exhaustive` or private
1576+
// fields or `repr(C)`. We call those fields "unsuited".
1577+
structUnsuitedInfo<'tcx>{
1578+
/// The source of the problem, a type that is found somewhere within the field type.
1579+
ty:Ty<'tcx>,
1580+
reason:UnsuitedReason,
1581+
}
1582+
enumUnsuitedReason{
1583+
NonExhaustive,
1584+
PrivateField,
1585+
ReprC,
1586+
}
1587+
1588+
fncheck_unsuited<'tcx>(
1589+
tcx:TyCtxt<'tcx>,
1590+
typing_env: ty::TypingEnv<'tcx>,
1591+
ty:Ty<'tcx>,
1592+
) -> ControlFlow<UnsuitedInfo<'tcx>>{
1593+
// We can encounter projections during traversal, so ensure the type is normalized.
1594+
let ty = tcx.try_normalize_erasing_regions(typing_env, ty).unwrap_or(ty);
1595+
match ty.kind(){
1596+
ty::Tuple(list) => list.iter().try_for_each(|t| check_unsuited(tcx, typing_env, t)),
1597+
ty::Array(ty, _) => check_unsuited(tcx, typing_env,*ty),
1598+
ty::Adt(def, args) => {
1599+
if !def.did().is_local()
1600+
&& !find_attr!(tcx.get_all_attrs(def.did()),AttributeKind::PubTransparent(_))
1601+
{
1602+
let non_exhaustive = def.is_variant_list_non_exhaustive()
1603+
|| def.variants().iter().any(ty::VariantDef::is_field_list_non_exhaustive);
1604+
let has_priv = def.all_fields().any(|f| !f.vis.is_public());
1605+
if non_exhaustive || has_priv {
1606+
returnControlFlow::Break(UnsuitedInfo{
1607+
ty,
1608+
reason:if non_exhaustive {
1609+
UnsuitedReason::NonExhaustive
1610+
}else{
1611+
UnsuitedReason::PrivateField
1612+
},
1613+
});
1614+
}
1615+
}
1616+
if def.repr().c(){
1617+
returnControlFlow::Break(UnsuitedInfo{ ty,reason:UnsuitedReason::ReprC});
1618+
}
1619+
def.all_fields()
1620+
.map(|field| field.ty(tcx, args))
1621+
.try_for_each(|t| check_unsuited(tcx, typing_env, t))
1622+
}
1623+
_ => ControlFlow::Continue(()),
1624+
}
1625+
}
1626+
16401627
letmut prev_unsuited_1zst = false;
16411628
for field in field_infos {
1642-
ifletSome(unsuited) = field.unsuited{
1643-
assert!(field.trivial);
1629+
if field.trivial
1630+
&& letSome(unsuited) = check_unsuited(tcx, typing_env, field.ty).break_value()
1631+
{
16441632
// If there are any non-trivial fields, then there can be no non-exhaustive 1-zsts.
16451633
// Otherwise, it's only an issue if there's >1 non-exhaustive 1-zst.
16461634
if non_trivial_count > 0 || prev_unsuited_1zst {

‎compiler/rustc_metadata/src/rmeta/table.rs‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,8 +55,10 @@ impl IsDefault for UnusedGenericParams {
5555

5656
/// Helper trait, for encoding to, and decoding from, a fixed number of bytes.
5757
/// Used mainly for Lazy positions and lengths.
58-
/// Unchecked invariant: `Self::default()` should encode as `[0; BYTE_LEN]`,
58+
///
59+
/// Invariant: `Self::default()` should encode as `[0; BYTE_LEN]`,
5960
/// but this has no impact on safety.
61+
/// In debug builds, this invariant is checked in `[TableBuilder::set]`
6062
pub(super)traitFixedSizeEncoding:IsDefault{
6163
/// This should be `[u8; BYTE_LEN]`;
6264
/// Cannot use an associated `const BYTE_LEN: usize` instead due to const eval limitations.
@@ -432,6 +434,13 @@ impl<I: Idx, const N: usize, T: FixedSizeEncoding<ByteArray = [u8; N]>> TableBui
432434
/// arises in the future then a new method (e.g. `clear` or `reset`) will need to be introduced
433435
/// for doing that explicitly.
434436
pub(crate)fnset(&mutself,i:I,value:T){
437+
#[cfg(debug_assertions)]
438+
{
439+
debug_assert!(
440+
T::from_bytes(&[0;N]).is_default(),
441+
"expected all-zeroes to decode to the default value, as per the invariant of FixedSizeEncoding"
442+
);
443+
}
435444
if !value.is_default(){
436445
// FIXME(eddyb) investigate more compact encodings for sparse tables.
437446
// On the PR @michaelwoerister mentioned:

0 commit comments

Comments
 (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Commit 7c2c3c0

Browse files
committed
Auto merge of #149063 - matthiaskrgr:rollup-6z23izv, r=matthiaskrgr
Rollup of 5 pull requests Successful merges: - #147887 (Improve the documentation of atomic::fence) - #148281 (repr(transparent) check: do not compute check_unsuited more than once) - #148484 (Fix suggestion for the `cfg!` macro) - #149057 (`rust-analyzer` subtree update) - #149061 (debug-assert FixedSizeEncoding invariant) r? `@ghost` `@rustbot` modify labels: rollup
2 parents 3d461af + ceb33e9 commit 7c2c3c0

82 files changed

Lines changed: 6193 additions & 513 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎compiler/rustc_attr_parsing/src/attributes/cfg.rs‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use rustc_ast::token::Delimiter;
22
use rustc_ast::tokenstream::DelimSpan;
33
use rustc_ast::{AttrItem,Attribute,CRATE_NODE_ID,LitKind,NodeId, ast, token};
44
use rustc_errors::{Applicability,PResult};
5-
use rustc_feature::{AttributeTemplate,Features, template};
5+
use rustc_feature::{AttrSuggestionStyle,AttributeTemplate,Features, template};
66
use rustc_hir::attrs::CfgEntry;
77
use rustc_hir::{AttrPath,RustcVersion};
88
use rustc_parse::parser::{ForceCollect,Parser};
@@ -323,8 +323,8 @@ pub fn parse_cfg_attr(
323323
}){
324324
Ok(r) => returnSome(r),
325325
Err(e) => {
326-
let suggestions =
327-
CFG_ATTR_TEMPLATE.suggestions(Some(cfg_attr.style), sym::cfg_attr);
326+
let suggestions =CFG_ATTR_TEMPLATE
327+
.suggestions(AttrSuggestionStyle::Attribute(cfg_attr.style), sym::cfg_attr);
328328
e.with_span_suggestions(
329329
cfg_attr.span,
330330
"must be of the form",
@@ -355,7 +355,8 @@ pub fn parse_cfg_attr(
355355
path:AttrPath::from_ast(&cfg_attr.get_normal_item().path),
356356
description:ParsedDescription::Attribute,
357357
reason,
358-
suggestions:CFG_ATTR_TEMPLATE.suggestions(Some(cfg_attr.style), sym::cfg_attr),
358+
suggestions:CFG_ATTR_TEMPLATE
359+
.suggestions(AttrSuggestionStyle::Attribute(cfg_attr.style), sym::cfg_attr),
359360
});
360361
}
361362
}

‎compiler/rustc_attr_parsing/src/context.rs‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ use std::sync::LazyLock;
66
use private::Sealed;
77
use rustc_ast::{AttrStyle,CRATE_NODE_ID,MetaItemLit,NodeId};
88
use rustc_errors::{Diag,Diagnostic,Level};
9-
use rustc_feature::AttributeTemplate;
9+
use rustc_feature::{AttrSuggestionStyle,AttributeTemplate};
1010
use rustc_hir::attrs::AttributeKind;
1111
use rustc_hir::lints::{AttributeLint,AttributeLintKind};
1212
use rustc_hir::{AttrPath,CRATE_HIR_ID,HirId};
@@ -637,9 +637,15 @@ impl<'f, 'sess: 'f, S: Stage> AcceptContext<'f, 'sess, S> {
637637
}
638638

639639
pub(crate)fnsuggestions(&self) -> Vec<String>{
640-
// If the outer and inner spans are equal, we are parsing an attribute from `cfg_attr`,
641-
// So don't display an attribute style in the suggestions
642-
let style = (self.attr_span != self.inner_span).then_some(self.attr_style);
640+
let style = matchself.parsed_description{
641+
// If the outer and inner spans are equal, we are parsing an embedded attribute
642+
ParsedDescription::Attributeifself.attr_span == self.inner_span => {
643+
AttrSuggestionStyle::EmbeddedAttribute
644+
}
645+
ParsedDescription::Attribute => AttrSuggestionStyle::Attribute(self.attr_style),
646+
ParsedDescription::Macro => AttrSuggestionStyle::Macro,
647+
};
648+
643649
self.template.suggestions(style,&self.attr_path)
644650
}
645651
}

‎compiler/rustc_feature/src/builtin_attrs.rs‎

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -132,28 +132,45 @@ pub struct AttributeTemplate {
132132
pubdocs:Option<&'staticstr>,
133133
}
134134

135+
pubenumAttrSuggestionStyle{
136+
/// The suggestion is styled for a normal attribute.
137+
/// The `AttrStyle` determines whether this is an inner or outer attribute.
138+
Attribute(AttrStyle),
139+
/// The suggestion is styled for an attribute embedded into another attribute.
140+
/// For example, attributes inside `#[cfg_attr(true, attr(...)]`.
141+
EmbeddedAttribute,
142+
/// The suggestion is styled for macros that are parsed with attribute parsers.
143+
/// For example, the `cfg!(predicate)` macro.
144+
Macro,
145+
}
146+
135147
implAttributeTemplate{
136148
pubfnsuggestions(
137149
&self,
138-
style:Option<AttrStyle>,
150+
style:AttrSuggestionStyle,
139151
name:impl std::fmt::Display,
140152
) -> Vec<String>{
141-
letmut suggestions = vec![];
142-
let(start, end) =match style {
143-
Some(AttrStyle::Outer) => ("#[","]"),
144-
Some(AttrStyle::Inner) => ("#![","]"),
145-
None => ("",""),
153+
let(start, macro_call, end) = match style {
154+
AttrSuggestionStyle::Attribute(AttrStyle::Outer) => ("#[","","]"),
155+
AttrSuggestionStyle::Attribute(AttrStyle::Inner) => ("#![","","]"),
156+
AttrSuggestionStyle::Macro => ("","!",""),
157+
AttrSuggestionStyle::EmbeddedAttribute => ("","",""),
146158
};
159+
160+
letmut suggestions = vec![];
161+
147162
ifself.word{
163+
debug_assert!(macro_call.is_empty(),"Macro suggestions use list style");
148164
suggestions.push(format!("{start}{name}{end}"));
149165
}
150166
ifletSome(descr) = self.list{
151167
for descr in descr {
152-
suggestions.push(format!("{start}{name}({descr}){end}"));
168+
suggestions.push(format!("{start}{name}{macro_call}({descr}){end}"));
153169
}
154170
}
155171
suggestions.extend(self.one_of.iter().map(|&word| format!("{start}{name}({word}){end}")));
156172
ifletSome(descr) = self.name_value_str{
173+
debug_assert!(macro_call.is_empty(),"Macro suggestions use list style");
157174
for descr in descr {
158175
suggestions.push(format!("{start}{name} = \"{descr}\"{end}"));
159176
}

‎compiler/rustc_feature/src/lib.rs‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -129,9 +129,10 @@ pub fn find_feature_issue(feature: Symbol, issue: GateIssue) -> Option<NonZero<u
129129

130130
pubuse accepted::ACCEPTED_LANG_FEATURES;
131131
pubuse builtin_attrs::{
132-
AttributeDuplicates,AttributeGate,AttributeSafety,AttributeTemplate,AttributeType,
133-
BUILTIN_ATTRIBUTE_MAP,BUILTIN_ATTRIBUTES,BuiltinAttribute,GatedCfg, encode_cross_crate,
134-
find_gated_cfg, is_builtin_attr_name, is_stable_diagnostic_attribute, is_valid_for_get_attr,
132+
AttrSuggestionStyle,AttributeDuplicates,AttributeGate,AttributeSafety,AttributeTemplate,
133+
AttributeType,BUILTIN_ATTRIBUTE_MAP,BUILTIN_ATTRIBUTES,BuiltinAttribute,GatedCfg,
134+
encode_cross_crate, find_gated_cfg, is_builtin_attr_name, is_stable_diagnostic_attribute,
135+
is_valid_for_get_attr,
135136
};
136137
pubuse removed::REMOVED_LANG_FEATURES;
137138
pubuse unstable::{

‎compiler/rustc_hir_analysis/src/check/check.rs‎

Lines changed: 56 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -1542,22 +1542,10 @@ pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>)
15421542

15431543
let typing_env = ty::TypingEnv::non_body_analysis(tcx, adt.did());
15441544
// For each field, figure out if it has "trivial" layout (i.e., is a 1-ZST).
1545-
// Even some 1-ZST fields are not allowed though, if they have `non_exhaustive` or private
1546-
// fields or `repr(C)`. We call those fields "unsuited".
15471545
structFieldInfo<'tcx>{
15481546
span:Span,
15491547
trivial:bool,
1550-
unsuited:Option<UnsuitedInfo<'tcx>>,
1551-
}
1552-
structUnsuitedInfo<'tcx>{
1553-
/// The source of the problem, a type that is found somewhere within the field type.
15541548
ty:Ty<'tcx>,
1555-
reason:UnsuitedReason,
1556-
}
1557-
enumUnsuitedReason{
1558-
NonExhaustive,
1559-
PrivateField,
1560-
ReprC,
15611549
}
15621550

15631551
let field_infos = adt.all_fields().map(|field| {
@@ -1566,60 +1554,7 @@ pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>)
15661554
// We are currently checking the type this field came from, so it must be local
15671555
let span = tcx.hir_span_if_local(field.did).unwrap();
15681556
let trivial = layout.is_ok_and(|layout| layout.is_1zst());
1569-
if !trivial {
1570-
// No need to even compute `unsuited`.
1571-
returnFieldInfo{ span, trivial,unsuited:None};
1572-
}
1573-
1574-
fncheck_unsuited<'tcx>(
1575-
tcx:TyCtxt<'tcx>,
1576-
typing_env: ty::TypingEnv<'tcx>,
1577-
ty:Ty<'tcx>,
1578-
) -> ControlFlow<UnsuitedInfo<'tcx>>{
1579-
// We can encounter projections during traversal, so ensure the type is normalized.
1580-
let ty = tcx.try_normalize_erasing_regions(typing_env, ty).unwrap_or(ty);
1581-
match ty.kind(){
1582-
ty::Tuple(list) => list.iter().try_for_each(|t| check_unsuited(tcx, typing_env, t)),
1583-
ty::Array(ty, _) => check_unsuited(tcx, typing_env,*ty),
1584-
ty::Adt(def, args) => {
1585-
if !def.did().is_local()
1586-
&& !find_attr!(
1587-
tcx.get_all_attrs(def.did()),
1588-
AttributeKind::PubTransparent(_)
1589-
)
1590-
{
1591-
let non_exhaustive = def.is_variant_list_non_exhaustive()
1592-
|| def
1593-
.variants()
1594-
.iter()
1595-
.any(ty::VariantDef::is_field_list_non_exhaustive);
1596-
let has_priv = def.all_fields().any(|f| !f.vis.is_public());
1597-
if non_exhaustive || has_priv {
1598-
returnControlFlow::Break(UnsuitedInfo{
1599-
ty,
1600-
reason:if non_exhaustive {
1601-
UnsuitedReason::NonExhaustive
1602-
}else{
1603-
UnsuitedReason::PrivateField
1604-
},
1605-
});
1606-
}
1607-
}
1608-
if def.repr().c(){
1609-
returnControlFlow::Break(UnsuitedInfo{
1610-
ty,
1611-
reason:UnsuitedReason::ReprC,
1612-
});
1613-
}
1614-
def.all_fields()
1615-
.map(|field| field.ty(tcx, args))
1616-
.try_for_each(|t| check_unsuited(tcx, typing_env, t))
1617-
}
1618-
_ => ControlFlow::Continue(()),
1619-
}
1620-
}
1621-
1622-
FieldInfo{ span, trivial,unsuited:check_unsuited(tcx, typing_env, ty).break_value()}
1557+
FieldInfo{ span, trivial, ty }
16231558
});
16241559

16251560
let non_trivial_fields = field_infos
@@ -1637,10 +1572,63 @@ pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>)
16371572
return;
16381573
}
16391574

1575+
// Even some 1-ZST fields are not allowed though, if they have `non_exhaustive` or private
1576+
// fields or `repr(C)`. We call those fields "unsuited".
1577+
structUnsuitedInfo<'tcx>{
1578+
/// The source of the problem, a type that is found somewhere within the field type.
1579+
ty:Ty<'tcx>,
1580+
reason:UnsuitedReason,
1581+
}
1582+
enumUnsuitedReason{
1583+
NonExhaustive,
1584+
PrivateField,
1585+
ReprC,
1586+
}
1587+
1588+
fncheck_unsuited<'tcx>(
1589+
tcx:TyCtxt<'tcx>,
1590+
typing_env: ty::TypingEnv<'tcx>,
1591+
ty:Ty<'tcx>,
1592+
) -> ControlFlow<UnsuitedInfo<'tcx>>{
1593+
// We can encounter projections during traversal, so ensure the type is normalized.
1594+
let ty = tcx.try_normalize_erasing_regions(typing_env, ty).unwrap_or(ty);
1595+
match ty.kind(){
1596+
ty::Tuple(list) => list.iter().try_for_each(|t| check_unsuited(tcx, typing_env, t)),
1597+
ty::Array(ty, _) => check_unsuited(tcx, typing_env,*ty),
1598+
ty::Adt(def, args) => {
1599+
if !def.did().is_local()
1600+
&& !find_attr!(tcx.get_all_attrs(def.did()),AttributeKind::PubTransparent(_))
1601+
{
1602+
let non_exhaustive = def.is_variant_list_non_exhaustive()
1603+
|| def.variants().iter().any(ty::VariantDef::is_field_list_non_exhaustive);
1604+
let has_priv = def.all_fields().any(|f| !f.vis.is_public());
1605+
if non_exhaustive || has_priv {
1606+
returnControlFlow::Break(UnsuitedInfo{
1607+
ty,
1608+
reason:if non_exhaustive {
1609+
UnsuitedReason::NonExhaustive
1610+
}else{
1611+
UnsuitedReason::PrivateField
1612+
},
1613+
});
1614+
}
1615+
}
1616+
if def.repr().c(){
1617+
returnControlFlow::Break(UnsuitedInfo{ ty,reason:UnsuitedReason::ReprC});
1618+
}
1619+
def.all_fields()
1620+
.map(|field| field.ty(tcx, args))
1621+
.try_for_each(|t| check_unsuited(tcx, typing_env, t))
1622+
}
1623+
_ => ControlFlow::Continue(()),
1624+
}
1625+
}
1626+
16401627
letmut prev_unsuited_1zst = false;
16411628
for field in field_infos {
1642-
ifletSome(unsuited) = field.unsuited{
1643-
assert!(field.trivial);
1629+
if field.trivial
1630+
&& letSome(unsuited) = check_unsuited(tcx, typing_env, field.ty).break_value()
1631+
{
16441632
// If there are any non-trivial fields, then there can be no non-exhaustive 1-zsts.
16451633
// Otherwise, it's only an issue if there's >1 non-exhaustive 1-zst.
16461634
if non_trivial_count > 0 || prev_unsuited_1zst {

‎compiler/rustc_metadata/src/rmeta/table.rs‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,8 +55,10 @@ impl IsDefault for UnusedGenericParams {
5555

5656
/// Helper trait, for encoding to, and decoding from, a fixed number of bytes.
5757
/// Used mainly for Lazy positions and lengths.
58-
/// Unchecked invariant: `Self::default()` should encode as `[0; BYTE_LEN]`,
58+
///
59+
/// Invariant: `Self::default()` should encode as `[0; BYTE_LEN]`,
5960
/// but this has no impact on safety.
61+
/// In debug builds, this invariant is checked in `[TableBuilder::set]`
6062
pub(super)traitFixedSizeEncoding:IsDefault{
6163
/// This should be `[u8; BYTE_LEN]`;
6264
/// Cannot use an associated `const BYTE_LEN: usize` instead due to const eval limitations.
@@ -432,6 +434,13 @@ impl<I: Idx, const N: usize, T: FixedSizeEncoding<ByteArray = [u8; N]>> TableBui
432434
/// arises in the future then a new method (e.g. `clear` or `reset`) will need to be introduced
433435
/// for doing that explicitly.
434436
pub(crate)fnset(&mutself,i:I,value:T){
437+
#[cfg(debug_assertions)]
438+
{
439+
debug_assert!(
440+
T::from_bytes(&[0;N]).is_default(),
441+
"expected all-zeroes to decode to the default value, as per the invariant of FixedSizeEncoding"
442+
);
443+
}
435444
if !value.is_default(){
436445
// FIXME(eddyb) investigate more compact encodings for sparse tables.
437446
// On the PR @michaelwoerister mentioned:

0 commit comments

Comments
 (0)