Skip to content

Commit f9b2e3c

Browse files
committed
Auto merge of rust-lang#96816 - GuillaumeGomez:rollup-oumn95i, r=GuillaumeGomez
Rollup of 7 pull requests Successful merges: - rust-lang#96581 (make Size and Align debug-printing a bit more compact) - rust-lang#96636 (Fix jump to def regression) - rust-lang#96760 (diagnostics: port more diagnostics to derive + add support for `Vec` fields) - rust-lang#96788 (Improve validator around field projections and checked bin ops) - rust-lang#96805 (Change eslint rules from configuration comments to configuration file) - rust-lang#96807 (update Miri) - rust-lang#96811 (Fix a minor typo in the description of Formatter) Failed merges: r? `@ghost` `@rustbot` modify labels: rollup
2 parents 6139205 + c6007d6 commit f9b2e3c

File tree

51 files changed

+538
-665
lines changed

Some content is hidden

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

51 files changed

+538
-665
lines changed

compiler/rustc_const_eval/src/transform/validate.rs

+96-4
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ use rustc_middle::ty::{self, InstanceDef, ParamEnv, Ty, TyCtxt, TypeFoldable};
1414
use rustc_mir_dataflow::impls::MaybeStorageLive;
1515
use rustc_mir_dataflow::storage::AlwaysLiveLocals;
1616
use rustc_mir_dataflow::{Analysis, ResultsCursor};
17-
use rustc_target::abi::Size;
17+
use rustc_target::abi::{Size, VariantIdx};
1818

1919
#[derive(Copy, Clone, Debug)]
2020
enum EdgeKind {
@@ -244,6 +244,60 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> {
244244
self.fail(location, format!("bad index ({:?} != usize)", index_ty))
245245
}
246246
}
247+
if let ProjectionElem::Field(f, ty) = elem {
248+
let parent = Place { local, projection: self.tcx.intern_place_elems(proj_base) };
249+
let parent_ty = parent.ty(&self.body.local_decls, self.tcx);
250+
let fail_out_of_bounds = |this: &Self, location| {
251+
this.fail(location, format!("Out of bounds field {:?} for {:?}", f, parent_ty));
252+
};
253+
let check_equal = |this: &Self, location, f_ty| {
254+
if !this.mir_assign_valid_types(ty, f_ty) {
255+
this.fail(
256+
location,
257+
format!(
258+
"Field projection `{:?}.{:?}` specified type `{:?}`, but actual type is {:?}",
259+
parent, f, ty, f_ty
260+
)
261+
)
262+
}
263+
};
264+
match parent_ty.ty.kind() {
265+
ty::Tuple(fields) => {
266+
let Some(f_ty) = fields.get(f.as_usize()) else {
267+
fail_out_of_bounds(self, location);
268+
return;
269+
};
270+
check_equal(self, location, *f_ty);
271+
}
272+
ty::Adt(adt_def, substs) => {
273+
let var = parent_ty.variant_index.unwrap_or(VariantIdx::from_u32(0));
274+
let Some(field) = adt_def.variant(var).fields.get(f.as_usize()) else {
275+
fail_out_of_bounds(self, location);
276+
return;
277+
};
278+
check_equal(self, location, field.ty(self.tcx, substs));
279+
}
280+
ty::Closure(_, substs) => {
281+
let substs = substs.as_closure();
282+
let Some(f_ty) = substs.upvar_tys().nth(f.as_usize()) else {
283+
fail_out_of_bounds(self, location);
284+
return;
285+
};
286+
check_equal(self, location, f_ty);
287+
}
288+
ty::Generator(_, substs, _) => {
289+
let substs = substs.as_generator();
290+
let Some(f_ty) = substs.upvar_tys().nth(f.as_usize()) else {
291+
fail_out_of_bounds(self, location);
292+
return;
293+
};
294+
check_equal(self, location, f_ty);
295+
}
296+
_ => {
297+
self.fail(location, format!("{:?} does not have fields", parent_ty.ty));
298+
}
299+
}
300+
}
247301
self.super_projection_elem(local, proj_base, elem, context, location);
248302
}
249303

@@ -291,7 +345,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> {
291345
ty::Array(..) | ty::Slice(..)
292346
);
293347
}
294-
Rvalue::BinaryOp(op, vals) | Rvalue::CheckedBinaryOp(op, vals) => {
348+
Rvalue::BinaryOp(op, vals) => {
295349
use BinOp::*;
296350
let a = vals.0.ty(&self.body.local_decls, self.tcx);
297351
let b = vals.1.ty(&self.body.local_decls, self.tcx);
@@ -355,17 +409,55 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> {
355409
for x in [a, b] {
356410
check_kinds!(
357411
x,
358-
"Cannot perform op on type {:?}",
412+
"Cannot perform arithmetic on type {:?}",
359413
ty::Uint(..) | ty::Int(..) | ty::Float(..)
360414
)
361415
}
362416
if a != b {
363417
self.fail(
364418
location,
365-
format!("Cannot perform op on unequal types {:?} and {:?}", a, b),
419+
format!(
420+
"Cannot perform arithmetic on unequal types {:?} and {:?}",
421+
a, b
422+
),
423+
);
424+
}
425+
}
426+
}
427+
}
428+
Rvalue::CheckedBinaryOp(op, vals) => {
429+
use BinOp::*;
430+
let a = vals.0.ty(&self.body.local_decls, self.tcx);
431+
let b = vals.1.ty(&self.body.local_decls, self.tcx);
432+
match op {
433+
Add | Sub | Mul => {
434+
for x in [a, b] {
435+
check_kinds!(
436+
x,
437+
"Cannot perform checked arithmetic on type {:?}",
438+
ty::Uint(..) | ty::Int(..)
439+
)
440+
}
441+
if a != b {
442+
self.fail(
443+
location,
444+
format!(
445+
"Cannot perform checked arithmetic on unequal types {:?} and {:?}",
446+
a, b
447+
),
366448
);
367449
}
368450
}
451+
Shl | Shr => {
452+
for x in [a, b] {
453+
check_kinds!(
454+
x,
455+
"Cannot perform checked shift on non-integer type {:?}",
456+
ty::Uint(..) | ty::Int(..)
457+
)
458+
}
459+
}
460+
_ => self.fail(location, format!("There is no checked version of {:?}", op)),
369461
}
370462
}
371463
Rvalue::UnaryOp(op, operand) => {

compiler/rustc_error_messages/locales/en-US/typeck.ftl

+11
Original file line numberDiff line numberDiff line change
@@ -90,3 +90,14 @@ typeck-add-return-type-missing-here = a return type might be missing here
9090
typeck-expected-default-return-type = expected `()` because of default return type
9191
9292
typeck-expected-return-type = expected `{$expected}` because of return type
93+
94+
typeck-unconstrained-opaque-type = unconstrained opaque type
95+
.note = `{$name}` must be used in combination with a concrete type within the same module
96+
97+
typeck-explicit-generic-args-with-impl-trait =
98+
cannot provide explicit generic arguments when `impl Trait` is used in argument position
99+
.label = explicit generic argument not allowed
100+
.note = see issue #83701 <https://github.com/rust-lang/rust/issues/83701> for more information
101+
102+
typeck-explicit-generic-args-with-impl-trait-feature =
103+
add `#![feature(explicit_generic_args_with_impl_trait)]` to the crate attributes to enable

compiler/rustc_macros/src/diagnostics/diagnostic.rs

+25-20
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@ use crate::diagnostics::error::{
55
SessionDiagnosticDeriveError,
66
};
77
use crate::diagnostics::utils::{
8-
option_inner_ty, report_error_if_not_applied_to_span, type_matches_path, Applicability,
9-
FieldInfo, HasFieldMap, SetOnce,
8+
report_error_if_not_applied_to_span, type_matches_path, Applicability, FieldInfo, FieldInnerTy,
9+
HasFieldMap, SetOnce,
1010
};
1111
use proc_macro2::TokenStream;
1212
use quote::{format_ident, quote};
@@ -353,35 +353,40 @@ impl SessionDiagnosticDeriveBuilder {
353353
info: FieldInfo<'_>,
354354
) -> Result<TokenStream, SessionDiagnosticDeriveError> {
355355
let field_binding = &info.binding.binding;
356-
let option_ty = option_inner_ty(&info.ty);
357-
let generated_code = self.generate_non_option_field_code(
356+
357+
let inner_ty = FieldInnerTy::from_type(&info.ty);
358+
let name = attr.path.segments.last().unwrap().ident.to_string();
359+
let (binding, needs_destructure) = match (name.as_str(), &inner_ty) {
360+
// `primary_span` can accept a `Vec<Span>` so don't destructure that.
361+
("primary_span", FieldInnerTy::Vec(_)) => (quote! { #field_binding.clone() }, false),
362+
_ => (quote! { *#field_binding }, true),
363+
};
364+
365+
let generated_code = self.generate_inner_field_code(
358366
attr,
359367
FieldInfo {
360368
vis: info.vis,
361369
binding: info.binding,
362-
ty: option_ty.unwrap_or(&info.ty),
370+
ty: inner_ty.inner_type().unwrap_or(&info.ty),
363371
span: info.span,
364372
},
373+
binding,
365374
)?;
366375

367-
if option_ty.is_none() {
368-
Ok(quote! { #generated_code })
376+
if needs_destructure {
377+
Ok(inner_ty.with(field_binding, generated_code))
369378
} else {
370-
Ok(quote! {
371-
if let Some(#field_binding) = #field_binding {
372-
#generated_code
373-
}
374-
})
379+
Ok(generated_code)
375380
}
376381
}
377382

378-
fn generate_non_option_field_code(
383+
fn generate_inner_field_code(
379384
&mut self,
380385
attr: &Attribute,
381386
info: FieldInfo<'_>,
387+
binding: TokenStream,
382388
) -> Result<TokenStream, SessionDiagnosticDeriveError> {
383389
let diag = &self.diag;
384-
let field_binding = &info.binding.binding;
385390

386391
let name = attr.path.segments.last().unwrap().ident.to_string();
387392
let name = name.as_str();
@@ -397,14 +402,14 @@ impl SessionDiagnosticDeriveBuilder {
397402
"primary_span" => {
398403
report_error_if_not_applied_to_span(attr, &info)?;
399404
Ok(quote! {
400-
#diag.set_span(*#field_binding);
405+
#diag.set_span(#binding);
401406
})
402407
}
403408
"label" | "note" | "help" => {
404409
report_error_if_not_applied_to_span(attr, &info)?;
405-
Ok(self.add_subdiagnostic(field_binding, name, name))
410+
Ok(self.add_subdiagnostic(binding, name, name))
406411
}
407-
"subdiagnostic" => Ok(quote! { #diag.subdiagnostic(*#field_binding); }),
412+
"subdiagnostic" => Ok(quote! { #diag.subdiagnostic(#binding); }),
408413
_ => throw_invalid_attr!(attr, &meta, |diag| {
409414
diag
410415
.help("only `skip_arg`, `primary_span`, `label`, `note`, `help` and `subdiagnostic` are valid field attributes")
@@ -413,7 +418,7 @@ impl SessionDiagnosticDeriveBuilder {
413418
Meta::NameValue(MetaNameValue { lit: syn::Lit::Str(ref s), .. }) => match name {
414419
"label" | "note" | "help" => {
415420
report_error_if_not_applied_to_span(attr, &info)?;
416-
Ok(self.add_subdiagnostic(field_binding, name, &s.value()))
421+
Ok(self.add_subdiagnostic(binding, name, &s.value()))
417422
}
418423
_ => throw_invalid_attr!(attr, &meta, |diag| {
419424
diag.help("only `label`, `note` and `help` are valid field attributes")
@@ -509,7 +514,7 @@ impl SessionDiagnosticDeriveBuilder {
509514
/// `fluent_attr_identifier`.
510515
fn add_subdiagnostic(
511516
&self,
512-
field_binding: &proc_macro2::Ident,
517+
field_binding: TokenStream,
513518
kind: &str,
514519
fluent_attr_identifier: &str,
515520
) -> TokenStream {
@@ -520,7 +525,7 @@ impl SessionDiagnosticDeriveBuilder {
520525
let fn_name = format_ident!("span_{}", kind);
521526
quote! {
522527
#diag.#fn_name(
523-
*#field_binding,
528+
#field_binding,
524529
rustc_errors::DiagnosticMessage::fluent_attr(#slug, #fluent_attr_identifier)
525530
);
526531
}

compiler/rustc_macros/src/diagnostics/subdiagnostic.rs

+5-13
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@ use crate::diagnostics::error::{
55
SessionDiagnosticDeriveError,
66
};
77
use crate::diagnostics::utils::{
8-
option_inner_ty, report_error_if_not_applied_to_applicability,
9-
report_error_if_not_applied_to_span, Applicability, FieldInfo, HasFieldMap, SetOnce,
8+
report_error_if_not_applied_to_applicability, report_error_if_not_applied_to_span,
9+
Applicability, FieldInfo, FieldInnerTy, HasFieldMap, SetOnce,
1010
};
1111
use proc_macro2::TokenStream;
1212
use quote::{format_ident, quote};
@@ -301,11 +301,11 @@ impl<'a> SessionSubdiagnosticDeriveBuilder<'a> {
301301
) -> Result<TokenStream, SessionDiagnosticDeriveError> {
302302
let ast = binding.ast();
303303

304-
let option_ty = option_inner_ty(&ast.ty);
304+
let inner_ty = FieldInnerTy::from_type(&ast.ty);
305305
let info = FieldInfo {
306306
vis: &ast.vis,
307307
binding: binding,
308-
ty: option_ty.unwrap_or(&ast.ty),
308+
ty: inner_ty.inner_type().unwrap_or(&ast.ty),
309309
span: &ast.span(),
310310
};
311311

@@ -353,15 +353,7 @@ impl<'a> SessionSubdiagnosticDeriveBuilder<'a> {
353353
);
354354
};
355355

356-
if option_ty.is_none() {
357-
Ok(quote! { #generated })
358-
} else {
359-
Ok(quote! {
360-
if let Some(#binding) = #binding {
361-
#generated
362-
}
363-
})
364-
}
356+
Ok(inner_ty.with(binding, generated))
365357
}
366358

367359
fn into_tokens(&mut self) -> Result<TokenStream, SessionDiagnosticDeriveError> {

compiler/rustc_macros/src/diagnostics/utils.rs

+55-6
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use crate::diagnostics::error::{span_err, throw_span_err, SessionDiagnosticDeriveError};
22
use proc_macro::Span;
33
use proc_macro2::TokenStream;
4-
use quote::{format_ident, quote};
4+
use quote::{format_ident, quote, ToTokens};
55
use std::collections::BTreeSet;
66
use std::str::FromStr;
77
use syn::{spanned::Spanned, Attribute, Meta, Type, Visibility};
@@ -76,22 +76,71 @@ pub(crate) fn report_error_if_not_applied_to_span(
7676
report_error_if_not_applied_to_ty(attr, info, &["rustc_span", "Span"], "Span")
7777
}
7878

79-
/// If `ty` is an Option, returns `Some(inner type)`, otherwise returns `None`.
80-
pub(crate) fn option_inner_ty(ty: &Type) -> Option<&Type> {
81-
if type_matches_path(ty, &["std", "option", "Option"]) {
79+
/// Inner type of a field and type of wrapper.
80+
pub(crate) enum FieldInnerTy<'ty> {
81+
/// Field is wrapped in a `Option<$inner>`.
82+
Option(&'ty Type),
83+
/// Field is wrapped in a `Vec<$inner>`.
84+
Vec(&'ty Type),
85+
/// Field isn't wrapped in an outer type.
86+
None,
87+
}
88+
89+
impl<'ty> FieldInnerTy<'ty> {
90+
/// Returns inner type for a field, if there is one.
91+
///
92+
/// - If `ty` is an `Option`, returns `FieldInnerTy::Option { inner: (inner type) }`.
93+
/// - If `ty` is a `Vec`, returns `FieldInnerTy::Vec { inner: (inner type) }`.
94+
/// - Otherwise returns `None`.
95+
pub(crate) fn from_type(ty: &'ty Type) -> Self {
96+
let variant: &dyn Fn(&'ty Type) -> FieldInnerTy<'ty> =
97+
if type_matches_path(ty, &["std", "option", "Option"]) {
98+
&FieldInnerTy::Option
99+
} else if type_matches_path(ty, &["std", "vec", "Vec"]) {
100+
&FieldInnerTy::Vec
101+
} else {
102+
return FieldInnerTy::None;
103+
};
104+
82105
if let Type::Path(ty_path) = ty {
83106
let path = &ty_path.path;
84107
let ty = path.segments.iter().last().unwrap();
85108
if let syn::PathArguments::AngleBracketed(bracketed) = &ty.arguments {
86109
if bracketed.args.len() == 1 {
87110
if let syn::GenericArgument::Type(ty) = &bracketed.args[0] {
88-
return Some(ty);
111+
return variant(ty);
89112
}
90113
}
91114
}
92115
}
116+
117+
unreachable!();
118+
}
119+
120+
/// Returns `Option` containing inner type if there is one.
121+
pub(crate) fn inner_type(&self) -> Option<&'ty Type> {
122+
match self {
123+
FieldInnerTy::Option(inner) | FieldInnerTy::Vec(inner) => Some(inner),
124+
FieldInnerTy::None => None,
125+
}
126+
}
127+
128+
/// Surrounds `inner` with destructured wrapper type, exposing inner type as `binding`.
129+
pub(crate) fn with(&self, binding: impl ToTokens, inner: impl ToTokens) -> TokenStream {
130+
match self {
131+
FieldInnerTy::Option(..) => quote! {
132+
if let Some(#binding) = #binding {
133+
#inner
134+
}
135+
},
136+
FieldInnerTy::Vec(..) => quote! {
137+
for #binding in #binding {
138+
#inner
139+
}
140+
},
141+
FieldInnerTy::None => quote! { #inner },
142+
}
93143
}
94-
None
95144
}
96145

97146
/// Field information passed to the builder. Deliberately omits attrs to discourage the

0 commit comments

Comments
 (0)