Skip to content

Commit 54d6738

Browse files
committed
Auto merge of rust-lang#112957 - matthiaskrgr:rollup-7ly0nv7, r=matthiaskrgr
Rollup of 9 pull requests Successful merges: - rust-lang#111747 (Don't structurally resolve during method ambiguity in probe) - rust-lang#112704 (slice::from_raw_parts: mention no-wrap-around condition) - rust-lang#112927 (Fix indentation for where clause in rustdoc pages) - rust-lang#112933 (Avoid `&format` in error message code) - rust-lang#112935 (style-guide: Fix typo) - rust-lang#112941 (typo) - rust-lang#112942 (style-guide: Organizational and editing tweaks (no semantic changes)) - rust-lang#112944 (style-guide: Add language disclaiming any effects on non-default Rust styles) - rust-lang#112948 (Avoid guessing unknown trait implementation in suggestions) r? `@ghost` `@rustbot` modify labels: rollup
2 parents fe37f37 + c5fd537 commit 54d6738

29 files changed

+242
-116
lines changed

compiler/rustc_borrowck/src/borrowck_errors.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -278,7 +278,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
278278
move_from_span: Span,
279279
move_from_desc: &str,
280280
) -> DiagnosticBuilder<'cx, ErrorGuaranteed> {
281-
struct_span_err!(self, move_from_span, E0507, "cannot move out of {}", move_from_desc,)
281+
struct_span_err!(self, move_from_span, E0507, "cannot move out of {}", move_from_desc)
282282
}
283283

284284
/// Signal an error due to an attempt to move out of the interior

compiler/rustc_hir_typeck/src/method/probe.rs

+14-5
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ use rustc_hir::def::DefKind;
1212
use rustc_hir_analysis::autoderef::{self, Autoderef};
1313
use rustc_infer::infer::canonical::OriginalQueryValues;
1414
use rustc_infer::infer::canonical::{Canonical, QueryResponse};
15+
use rustc_infer::infer::error_reporting::TypeAnnotationNeeded::E0282;
1516
use rustc_infer::infer::DefineOpaqueTypes;
1617
use rustc_infer::infer::{self, InferOk, TyCtxtInferExt};
1718
use rustc_middle::middle::stability;
@@ -448,15 +449,23 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
448449
);
449450
}
450451
} else {
451-
// Encountered a real ambiguity, so abort the lookup. If `ty` is not
452-
// an `Err`, report the right "type annotations needed" error pointing
453-
// to it.
452+
// Ended up encountering a type variable when doing autoderef,
453+
// but it may not be a type variable after processing obligations
454+
// in our local `FnCtxt`, so don't call `structurally_resolved_type`.
454455
let ty = &bad_ty.ty;
455456
let ty = self
456457
.probe_instantiate_query_response(span, &orig_values, ty)
457458
.unwrap_or_else(|_| span_bug!(span, "instantiating {:?} failed?", ty));
458-
let ty = self.structurally_resolved_type(span, ty.value);
459-
assert!(matches!(ty.kind(), ty::Error(_)));
459+
let ty = self.resolve_vars_if_possible(ty.value);
460+
let guar = match *ty.kind() {
461+
ty::Infer(ty::TyVar(_)) => self
462+
.err_ctxt()
463+
.emit_inference_failure_err(self.body_id, span, ty.into(), E0282, true)
464+
.emit(),
465+
ty::Error(guar) => guar,
466+
_ => bug!("unexpected bad final type in method autoderef"),
467+
};
468+
self.demand_eqtype(span, ty, self.tcx.ty_error(guar));
460469
return Err(MethodError::NoMatch(NoMatchData {
461470
static_candidates: Vec::new(),
462471
unsatisfied_predicates: Vec::new(),

compiler/rustc_macros/src/diagnostics/error.rs

+4-6
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ fn path_to_string(path: &syn::Path) -> String {
5454

5555
/// Returns an error diagnostic on span `span` with msg `msg`.
5656
#[must_use]
57-
pub(crate) fn span_err(span: impl MultiSpan, msg: &str) -> Diagnostic {
57+
pub(crate) fn span_err<T: Into<String>>(span: impl MultiSpan, msg: T) -> Diagnostic {
5858
Diagnostic::spanned(span, Level::Error, msg)
5959
}
6060

@@ -77,11 +77,9 @@ pub(crate) fn invalid_attr(attr: &Attribute) -> Diagnostic {
7777
let span = attr.span().unwrap();
7878
let path = path_to_string(attr.path());
7979
match attr.meta {
80-
Meta::Path(_) => span_err(span, &format!("`#[{path}]` is not a valid attribute")),
81-
Meta::NameValue(_) => {
82-
span_err(span, &format!("`#[{path} = ...]` is not a valid attribute"))
83-
}
84-
Meta::List(_) => span_err(span, &format!("`#[{path}(...)]` is not a valid attribute")),
80+
Meta::Path(_) => span_err(span, format!("`#[{path}]` is not a valid attribute")),
81+
Meta::NameValue(_) => span_err(span, format!("`#[{path} = ...]` is not a valid attribute")),
82+
Meta::List(_) => span_err(span, format!("`#[{path}(...)]` is not a valid attribute")),
8583
}
8684
}
8785

compiler/rustc_macros/src/diagnostics/subdiagnostic.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -200,7 +200,7 @@ impl<'parent, 'a> SubdiagnosticDeriveVariantBuilder<'parent, 'a> {
200200

201201
throw_span_err!(
202202
attr.span().unwrap(),
203-
&format!(
203+
format!(
204204
"diagnostic slug must be first argument of a `#[{name}(...)]` attribute"
205205
)
206206
);

compiler/rustc_macros/src/diagnostics/utils.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -347,7 +347,7 @@ pub(crate) trait HasFieldMap {
347347
None => {
348348
span_err(
349349
span.unwrap(),
350-
&format!("`{field}` doesn't refer to a field on this type"),
350+
format!("`{field}` doesn't refer to a field on this type"),
351351
)
352352
.emit();
353353
quote! {

compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs

+10-6
Original file line numberDiff line numberDiff line change
@@ -2382,17 +2382,21 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
23822382
&& let Some(impl_def_id) = trait_impls.non_blanket_impls().values().flatten().next()
23832383
{
23842384
let non_blanket_impl_count = trait_impls.non_blanket_impls().values().flatten().count();
2385-
let message = if non_blanket_impl_count == 1 {
2386-
"use the fully-qualified path to the only available implementation".to_string()
2387-
} else {
2385+
// If there is only one implementation of the trait, suggest using it.
2386+
// Otherwise, use a placeholder comment for the implementation.
2387+
let (message, impl_suggestion) = if non_blanket_impl_count == 1 {(
2388+
"use the fully-qualified path to the only available implementation".to_string(),
2389+
format!("<{} as ", self.tcx.type_of(impl_def_id).subst_identity())
2390+
)} else {(
23882391
format!(
23892392
"use a fully-qualified path to a specific available implementation ({} found)",
23902393
non_blanket_impl_count
2391-
)
2392-
};
2394+
),
2395+
"</* self type */ as ".to_string()
2396+
)};
23932397
let mut suggestions = vec![(
23942398
path.span.shrink_to_lo(),
2395-
format!("<{} as ", self.tcx.type_of(impl_def_id).subst_identity())
2399+
impl_suggestion
23962400
)];
23972401
if let Some(generic_arg) = trait_path_segment.args {
23982402
let between_span = trait_path_segment.ident.span.between(generic_arg.span_ext);

library/core/src/slice/raw.rs

+14-10
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,8 @@ use crate::ptr;
3232
/// * The memory referenced by the returned slice must not be mutated for the duration
3333
/// of lifetime `'a`, except inside an `UnsafeCell`.
3434
///
35-
/// * The total size `len * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
35+
/// * The total size `len * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`,
36+
/// and adding that size to `data` must not "wrap around" the address space.
3637
/// See the safety documentation of [`pointer::offset`].
3738
///
3839
/// # Caveat
@@ -125,7 +126,8 @@ pub const unsafe fn from_raw_parts<'a, T>(data: *const T, len: usize) -> &'a [T]
125126
/// (not derived from the return value) for the duration of lifetime `'a`.
126127
/// Both read and write accesses are forbidden.
127128
///
128-
/// * The total size `len * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
129+
/// * The total size `len * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`,
130+
/// and adding that size to `data` must not "wrap around" the address space.
129131
/// See the safety documentation of [`pointer::offset`].
130132
///
131133
/// [valid]: ptr#safety
@@ -179,15 +181,16 @@ pub const fn from_mut<T>(s: &mut T) -> &mut [T] {
179181
/// the last element, such that the offset from the end to the start pointer is
180182
/// the length of the slice.
181183
///
182-
/// * The range must contain `N` consecutive properly initialized values of type `T`:
184+
/// * The entire memory range of this slice must be contained within a single allocated object!
185+
/// Slices can never span across multiple allocated objects.
183186
///
184-
/// * The entire memory range of this slice must be contained within a single allocated object!
185-
/// Slices can never span across multiple allocated objects.
187+
/// * The range must contain `N` consecutive properly initialized values of type `T`.
186188
///
187189
/// * The memory referenced by the returned slice must not be mutated for the duration
188190
/// of lifetime `'a`, except inside an `UnsafeCell`.
189191
///
190-
/// * The total length of the range must be no larger than `isize::MAX`.
192+
/// * The total length of the range must be no larger than `isize::MAX`,
193+
/// and adding that size to `data` must not "wrap around" the address space.
191194
/// See the safety documentation of [`pointer::offset`].
192195
///
193196
/// Note that a range created from [`slice::as_ptr_range`] fulfills these requirements.
@@ -247,16 +250,17 @@ pub const unsafe fn from_ptr_range<'a, T>(range: Range<*const T>) -> &'a [T] {
247250
/// the last element, such that the offset from the end to the start pointer is
248251
/// the length of the slice.
249252
///
250-
/// * The range must contain `N` consecutive properly initialized values of type `T`:
253+
/// * The entire memory range of this slice must be contained within a single allocated object!
254+
/// Slices can never span across multiple allocated objects.
251255
///
252-
/// * The entire memory range of this slice must be contained within a single allocated object!
253-
/// Slices can never span across multiple allocated objects.
256+
/// * The range must contain `N` consecutive properly initialized values of type `T`.
254257
///
255258
/// * The memory referenced by the returned slice must not be accessed through any other pointer
256259
/// (not derived from the return value) for the duration of lifetime `'a`.
257260
/// Both read and write accesses are forbidden.
258261
///
259-
/// * The total length of the range must be no larger than `isize::MAX`.
262+
/// * The total length of the range must be no larger than `isize::MAX`,
263+
/// and adding that size to `data` must not "wrap around" the address space.
260264
/// See the safety documentation of [`pointer::offset`].
261265
///
262266
/// Note that a range created from [`slice::as_mut_ptr_range`] fulfills these requirements.

src/doc/style-guide/src/README.md

+55-8
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,21 @@ Rust code has similar formatting, less mental effort is required to comprehend a
1616
new project, lowering the barrier to entry for new developers.
1717

1818
Thus, there are productivity benefits to using a formatting tool (such as
19-
rustfmt), and even larger benefits by using a community-consistent formatting,
20-
typically by using a formatting tool's default settings.
19+
`rustfmt`), and even larger benefits by using a community-consistent
20+
formatting, typically by using a formatting tool's default settings.
2121

22+
## The default Rust style
23+
24+
The Rust Style Guide defines the default Rust style, and *recommends* that
25+
developers and tools follow the default Rust style. Tools such as `rustfmt` use
26+
the style guide as a reference for the default style. Everything in this style
27+
guide, whether or not it uses language such as "must" or the imperative mood
28+
such as "insert a space ..." or "break the line after ...", refers to the
29+
default style.
30+
31+
This should not be interpreted as forbidding developers from following a
32+
non-default style, or forbidding tools from adding any particular configuration
33+
options.
2234

2335
## Formatting conventions
2436

@@ -28,8 +40,47 @@ typically by using a formatting tool's default settings.
2840
* Each level of indentation must be four spaces (that is, all indentation
2941
outside of string literals and comments must be a multiple of four).
3042
* The maximum width for a line is 100 characters.
31-
* A tool should be configurable for all three of these variables.
43+
* A tool may choose to make some of these configurable.
44+
45+
#### Block indent
46+
47+
Prefer block indent over visual indent:
48+
49+
```rust
50+
// Block indent
51+
a_function_call(
52+
foo,
53+
bar,
54+
);
55+
56+
// Visual indent
57+
a_function_call(foo,
58+
bar);
59+
```
3260

61+
This makes for smaller diffs (e.g., if `a_function_call` is renamed in the above
62+
example) and less rightward drift.
63+
64+
### Trailing commas
65+
66+
Lists should have a trailing comma when followed by a newline:
67+
68+
```rust
69+
function_call(
70+
argument,
71+
another_argument,
72+
);
73+
74+
let array = [
75+
element,
76+
another_element,
77+
yet_another_element,
78+
];
79+
```
80+
81+
This makes moving code (e.g., by copy and paste) easier, and makes diffs
82+
smaller, as appending or removing items does not require modifying another line
83+
to add or remove a comma.
3384

3485
### Blank lines
3586

@@ -48,11 +99,7 @@ fn bar() {}
4899
fn baz() {}
49100
```
50101

51-
Formatting tools should make the bounds on blank lines configurable: there
52-
should be separate minimum and maximum numbers of newlines between both
53-
statements and (top-level) items (i.e., four options). As described above, the
54-
defaults for both statements and items should be minimum: 1, maximum: 2.
55-
102+
Formatting tools may wish to make the bounds on blank lines configurable.
56103

57104
### [Module-level items](items.md)
58105
### [Statements](statements.md)

src/doc/style-guide/src/SUMMARY.md

+4-4
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,10 @@
22

33
[Introduction](README.md)
44

5-
- [Module-level items](items.md)
5+
- [Items](items.md)
66
- [Statements](statements.md)
77
- [Expressions](expressions.md)
8-
- [Types](types.md)
9-
- [Non-formatting conventions](advice.md)
8+
- [Types and Bounds](types.md)
9+
- [Other style advice](advice.md)
1010
- [`Cargo.toml` conventions](cargo.md)
11-
- [Principles used for deciding these guidelines](principles.md)
11+
- [Guiding principles and rationale](principles.md)

src/doc/style-guide/src/advice.md

+3-3
Original file line numberDiff line numberDiff line change
@@ -25,9 +25,9 @@ if y {
2525
* Local variables shall be `snake_case`,
2626
* Macro names shall be `snake_case`,
2727
* Constants (`const`s and immutable `static`s) shall be `SCREAMING_SNAKE_CASE`.
28-
* When a name is forbidden because it is a reserved word (e.g., `crate`), use a
29-
trailing underscore to make the name legal (e.g., `crate_`), or use raw
30-
identifiers if possible.
28+
* When a name is forbidden because it is a reserved word (such as `crate`),
29+
either use a raw identifier (`r#crate`) or use a trailing underscore
30+
(`crate_`). Don't misspell the word (`krate`).
3131

3232
### Modules
3333

src/doc/style-guide/src/cargo.md

+11-10
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# Cargo.toml conventions
1+
# `Cargo.toml` conventions
22

33
## Formatting conventions
44

@@ -25,16 +25,17 @@ not indent any key names; start all key names at the start of a line.
2525
Use multi-line strings (rather than newline escape sequences) for any string
2626
values that include multiple lines, such as the crate description.
2727

28-
For array values, such as a list of authors, put the entire list on the same
28+
For array values, such as a list of features, put the entire list on the same
2929
line as the key, if it fits. Otherwise, use block indentation: put a newline
3030
after the opening square bracket, indent each item by one indentation level,
3131
put a comma after each item (including the last), and put the closing square
3232
bracket at the start of a line by itself after the last item.
3333

3434
```rust
35-
authors = [
36-
"A Uthor <a.uthor@example.org>",
37-
"Another Author <author@example.net>",
35+
some_feature = [
36+
"another_feature",
37+
"yet_another_feature",
38+
"some_dependency?/some_feature",
3839
]
3940
```
4041

@@ -54,11 +55,11 @@ version = "4.5.6"
5455

5556
## Metadata conventions
5657

57-
The authors list should consist of strings that each contain an author name
58-
followed by an email address in angle brackets: `Full Name <email@address>`.
59-
It should not contain bare email addresses, or names without email addresses.
60-
(The authors list may also include a mailing list address without an associated
61-
name.)
58+
The authors list, if present, should consist of strings that each contain an
59+
author name followed by an email address in angle brackets: `Full Name
60+
<email@address>`. It should not contain bare email addresses, or names without
61+
email addresses. (The authors list may also include a mailing list address
62+
without an associated name.)
6263

6364
The license field must contain a valid [SPDX
6465
expression](https://spdx.org/spdx-specification-21-web-version#h.jxpfx0ykyb60),

src/doc/style-guide/src/expressions.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -690,7 +690,7 @@ Where it is possible to use a block form on the right-hand side and avoid
690690
breaking the left-hand side, do that. E.g.
691691

692692
```rust
693-
// Assuming the following line does done fit in the max width
693+
// Assuming the following line does not fit in the max width
694694
a_very_long_pattern | another_pattern => ALongStructName {
695695
...
696696
},

0 commit comments

Comments
 (0)