Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rollup of 9 pull requests #112957

Merged
merged 33 commits into from
Jun 23, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
18b8646
slice::from_raw_parts: mention no-wrap-around condition
RalfJung Jun 16, 2023
9202caa
Fix indentation for where clause in rustdoc pages
GuillaumeGomez Jun 22, 2023
b858a47
Update existing snapshot and add more snapshots of where clause inden…
GuillaumeGomez Jun 22, 2023
c896062
avoid `&format` in error message code
TaKO8Ki Jun 22, 2023
9637d44
style-guide: Fix typo
joshtriplett Jun 22, 2023
3747d7f
style-guide: Move text about block vs visual indent to indentation se…
joshtriplett Jun 22, 2023
9280567
style-guide: Move and expand text about trailing commas
joshtriplett Jun 22, 2023
2c0dd90
style-guide: s/right-ward/rightward/
joshtriplett Jun 22, 2023
4c5bb06
style-guide: Consistently refer to rustfmt as `rustfmt`
joshtriplett Jun 22, 2023
d270af3
style-guide: Remove inaccurate statement about rustfmt
joshtriplett Jun 22, 2023
c5f8b2c
style-guide: Define (and capitalize) "ASCIIbetically"
joshtriplett Jun 22, 2023
20f2828
style-guide: Update cargo.md for authors being optional and not recom…
joshtriplett Jun 22, 2023
6f8f83f
style-guide: Avoid normative recommendations for formatting tool conf…
joshtriplett Jun 22, 2023
fec28b2
style-guide: Clarify advice on names matching keywords
joshtriplett Jun 22, 2023
2828c56
typo
tshepang Jun 22, 2023
c930b21
style-guide: Reword an awkwardly phrased recommendation (and fix a typo)
joshtriplett Jun 22, 2023
3e2449c
style-guide: Rephrase a confusingly ordered, ambiguous sentence (and …
joshtriplett Jun 22, 2023
a9d1db3
style-guide: Avoid hyphenating "semicolon"
joshtriplett Jun 22, 2023
5d63721
style-guide: Make link text in SUMMARY.md match the headings in the l…
joshtriplett Jun 22, 2023
f972e09
style-guide: Define what an item is
joshtriplett Jun 22, 2023
fcc23a3
style-guide: Avoid referring to the style team in the past tense
joshtriplett Jun 22, 2023
2748efa
style-guide: Add language disclaiming any effects on non-default Rust…
joshtriplett Jun 22, 2023
afe3650
Don't structurally resolve during method ambiguity in probe
compiler-errors May 19, 2023
48167bd
Avoid guessing unknown trait impl in suggestions
bkrl Jun 22, 2023
01cc9ca
Rollup merge of #111747 - compiler-errors:structural-probe-side-effec…
matthiaskrgr Jun 23, 2023
8168915
Rollup merge of #112704 - RalfJung:dont-wrap-slices, r=ChrisDenton
matthiaskrgr Jun 23, 2023
3feee9f
Rollup merge of #112927 - GuillaumeGomez:where-clause-indent, r=notri…
matthiaskrgr Jun 23, 2023
4e96aba
Rollup merge of #112933 - TaKO8Ki:avoid-&format-in-error-message-code…
matthiaskrgr Jun 23, 2023
61e881e
Rollup merge of #112935 - joshtriplett:style-guide-typo-fix, r=compil…
matthiaskrgr Jun 23, 2023
46aacf5
Rollup merge of #112941 - tshepang:patch-1, r=lqd
matthiaskrgr Jun 23, 2023
441e59a
Rollup merge of #112942 - joshtriplett:style-guide-tweaks, r=compiler…
matthiaskrgr Jun 23, 2023
8d6b02f
Rollup merge of #112944 - joshtriplett:style-guide-defaults-vs-config…
matthiaskrgr Jun 23, 2023
c5fd537
Rollup merge of #112948 - bkrl:trait-impl-suggestion, r=compiler-errors
matthiaskrgr Jun 23, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion compiler/rustc_borrowck/src/borrowck_errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -278,7 +278,7 @@ impl<'cx, 'tcx> crate::MirBorrowckCtxt<'cx, 'tcx> {
move_from_span: Span,
move_from_desc: &str,
) -> DiagnosticBuilder<'cx, ErrorGuaranteed> {
struct_span_err!(self, move_from_span, E0507, "cannot move out of {}", move_from_desc,)
struct_span_err!(self, move_from_span, E0507, "cannot move out of {}", move_from_desc)
}

/// Signal an error due to an attempt to move out of the interior
Expand Down
19 changes: 14 additions & 5 deletions compiler/rustc_hir_typeck/src/method/probe.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ use rustc_hir::def::DefKind;
use rustc_hir_analysis::autoderef::{self, Autoderef};
use rustc_infer::infer::canonical::OriginalQueryValues;
use rustc_infer::infer::canonical::{Canonical, QueryResponse};
use rustc_infer::infer::error_reporting::TypeAnnotationNeeded::E0282;
use rustc_infer::infer::DefineOpaqueTypes;
use rustc_infer::infer::{self, InferOk, TyCtxtInferExt};
use rustc_middle::middle::stability;
Expand Down Expand Up @@ -448,15 +449,23 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
);
}
} else {
// Encountered a real ambiguity, so abort the lookup. If `ty` is not
// an `Err`, report the right "type annotations needed" error pointing
// to it.
// Ended up encountering a type variable when doing autoderef,
// but it may not be a type variable after processing obligations
// in our local `FnCtxt`, so don't call `structurally_resolved_type`.
let ty = &bad_ty.ty;
let ty = self
.probe_instantiate_query_response(span, &orig_values, ty)
.unwrap_or_else(|_| span_bug!(span, "instantiating {:?} failed?", ty));
let ty = self.structurally_resolved_type(span, ty.value);
assert!(matches!(ty.kind(), ty::Error(_)));
let ty = self.resolve_vars_if_possible(ty.value);
let guar = match *ty.kind() {
ty::Infer(ty::TyVar(_)) => self
.err_ctxt()
.emit_inference_failure_err(self.body_id, span, ty.into(), E0282, true)
.emit(),
ty::Error(guar) => guar,
_ => bug!("unexpected bad final type in method autoderef"),
};
self.demand_eqtype(span, ty, self.tcx.ty_error(guar));
return Err(MethodError::NoMatch(NoMatchData {
static_candidates: Vec::new(),
unsatisfied_predicates: Vec::new(),
Expand Down
10 changes: 4 additions & 6 deletions compiler/rustc_macros/src/diagnostics/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ fn path_to_string(path: &syn::Path) -> String {

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

Expand All @@ -77,11 +77,9 @@ pub(crate) fn invalid_attr(attr: &Attribute) -> Diagnostic {
let span = attr.span().unwrap();
let path = path_to_string(attr.path());
match attr.meta {
Meta::Path(_) => span_err(span, &format!("`#[{path}]` is not a valid attribute")),
Meta::NameValue(_) => {
span_err(span, &format!("`#[{path} = ...]` is not a valid attribute"))
}
Meta::List(_) => span_err(span, &format!("`#[{path}(...)]` is not a valid attribute")),
Meta::Path(_) => span_err(span, format!("`#[{path}]` is not a valid attribute")),
Meta::NameValue(_) => span_err(span, format!("`#[{path} = ...]` is not a valid attribute")),
Meta::List(_) => span_err(span, format!("`#[{path}(...)]` is not a valid attribute")),
}
}

Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_macros/src/diagnostics/subdiagnostic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ impl<'parent, 'a> SubdiagnosticDeriveVariantBuilder<'parent, 'a> {

throw_span_err!(
attr.span().unwrap(),
&format!(
format!(
"diagnostic slug must be first argument of a `#[{name}(...)]` attribute"
)
);
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_macros/src/diagnostics/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -347,7 +347,7 @@ pub(crate) trait HasFieldMap {
None => {
span_err(
span.unwrap(),
&format!("`{field}` doesn't refer to a field on this type"),
format!("`{field}` doesn't refer to a field on this type"),
)
.emit();
quote! {
Expand Down
16 changes: 10 additions & 6 deletions compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2382,17 +2382,21 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
&& let Some(impl_def_id) = trait_impls.non_blanket_impls().values().flatten().next()
{
let non_blanket_impl_count = trait_impls.non_blanket_impls().values().flatten().count();
let message = if non_blanket_impl_count == 1 {
"use the fully-qualified path to the only available implementation".to_string()
} else {
// If there is only one implementation of the trait, suggest using it.
// Otherwise, use a placeholder comment for the implementation.
let (message, impl_suggestion) = if non_blanket_impl_count == 1 {(
"use the fully-qualified path to the only available implementation".to_string(),
format!("<{} as ", self.tcx.type_of(impl_def_id).subst_identity())
)} else {(
format!(
"use a fully-qualified path to a specific available implementation ({} found)",
non_blanket_impl_count
)
};
),
"</* self type */ as ".to_string()
)};
let mut suggestions = vec![(
path.span.shrink_to_lo(),
format!("<{} as ", self.tcx.type_of(impl_def_id).subst_identity())
impl_suggestion
)];
if let Some(generic_arg) = trait_path_segment.args {
let between_span = trait_path_segment.ident.span.between(generic_arg.span_ext);
Expand Down
24 changes: 14 additions & 10 deletions library/core/src/slice/raw.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,8 @@ use crate::ptr;
/// * The memory referenced by the returned slice must not be mutated for the duration
/// of lifetime `'a`, except inside an `UnsafeCell`.
///
/// * The total size `len * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
/// * The total size `len * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`,
/// and adding that size to `data` must not "wrap around" the address space.
/// See the safety documentation of [`pointer::offset`].
///
/// # Caveat
Expand Down Expand Up @@ -125,7 +126,8 @@ pub const unsafe fn from_raw_parts<'a, T>(data: *const T, len: usize) -> &'a [T]
/// (not derived from the return value) for the duration of lifetime `'a`.
/// Both read and write accesses are forbidden.
///
/// * The total size `len * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`.
/// * The total size `len * mem::size_of::<T>()` of the slice must be no larger than `isize::MAX`,
/// and adding that size to `data` must not "wrap around" the address space.
/// See the safety documentation of [`pointer::offset`].
///
/// [valid]: ptr#safety
Expand Down Expand Up @@ -179,15 +181,16 @@ pub const fn from_mut<T>(s: &mut T) -> &mut [T] {
/// the last element, such that the offset from the end to the start pointer is
/// the length of the slice.
///
/// * The range must contain `N` consecutive properly initialized values of type `T`:
/// * The entire memory range of this slice must be contained within a single allocated object!
/// Slices can never span across multiple allocated objects.
///
/// * The entire memory range of this slice must be contained within a single allocated object!
/// Slices can never span across multiple allocated objects.
/// * The range must contain `N` consecutive properly initialized values of type `T`.
///
/// * The memory referenced by the returned slice must not be mutated for the duration
/// of lifetime `'a`, except inside an `UnsafeCell`.
///
/// * The total length of the range must be no larger than `isize::MAX`.
/// * The total length of the range must be no larger than `isize::MAX`,
/// and adding that size to `data` must not "wrap around" the address space.
/// See the safety documentation of [`pointer::offset`].
///
/// Note that a range created from [`slice::as_ptr_range`] fulfills these requirements.
Expand Down Expand Up @@ -247,16 +250,17 @@ pub const unsafe fn from_ptr_range<'a, T>(range: Range<*const T>) -> &'a [T] {
/// the last element, such that the offset from the end to the start pointer is
/// the length of the slice.
///
/// * The range must contain `N` consecutive properly initialized values of type `T`:
/// * The entire memory range of this slice must be contained within a single allocated object!
/// Slices can never span across multiple allocated objects.
///
/// * The entire memory range of this slice must be contained within a single allocated object!
/// Slices can never span across multiple allocated objects.
/// * The range must contain `N` consecutive properly initialized values of type `T`.
///
/// * The memory referenced by the returned slice must not be accessed through any other pointer
/// (not derived from the return value) for the duration of lifetime `'a`.
/// Both read and write accesses are forbidden.
///
/// * The total length of the range must be no larger than `isize::MAX`.
/// * The total length of the range must be no larger than `isize::MAX`,
/// and adding that size to `data` must not "wrap around" the address space.
/// See the safety documentation of [`pointer::offset`].
///
/// Note that a range created from [`slice::as_mut_ptr_range`] fulfills these requirements.
Expand Down
63 changes: 55 additions & 8 deletions src/doc/style-guide/src/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,21 @@ Rust code has similar formatting, less mental effort is required to comprehend a
new project, lowering the barrier to entry for new developers.

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

## The default Rust style

The Rust Style Guide defines the default Rust style, and *recommends* that
developers and tools follow the default Rust style. Tools such as `rustfmt` use
the style guide as a reference for the default style. Everything in this style
guide, whether or not it uses language such as "must" or the imperative mood
such as "insert a space ..." or "break the line after ...", refers to the
default style.

This should not be interpreted as forbidding developers from following a
non-default style, or forbidding tools from adding any particular configuration
options.

## Formatting conventions

Expand All @@ -28,8 +40,47 @@ typically by using a formatting tool's default settings.
* Each level of indentation must be four spaces (that is, all indentation
outside of string literals and comments must be a multiple of four).
* The maximum width for a line is 100 characters.
* A tool should be configurable for all three of these variables.
* A tool may choose to make some of these configurable.

#### Block indent

Prefer block indent over visual indent:

```rust
// Block indent
a_function_call(
foo,
bar,
);

// Visual indent
a_function_call(foo,
bar);
```

This makes for smaller diffs (e.g., if `a_function_call` is renamed in the above
example) and less rightward drift.

### Trailing commas

Lists should have a trailing comma when followed by a newline:

```rust
function_call(
argument,
another_argument,
);

let array = [
element,
another_element,
yet_another_element,
];
```

This makes moving code (e.g., by copy and paste) easier, and makes diffs
smaller, as appending or removing items does not require modifying another line
to add or remove a comma.

### Blank lines

Expand All @@ -48,11 +99,7 @@ fn bar() {}
fn baz() {}
```

Formatting tools should make the bounds on blank lines configurable: there
should be separate minimum and maximum numbers of newlines between both
statements and (top-level) items (i.e., four options). As described above, the
defaults for both statements and items should be minimum: 1, maximum: 2.

Formatting tools may wish to make the bounds on blank lines configurable.

### [Module-level items](items.md)
### [Statements](statements.md)
Expand Down
8 changes: 4 additions & 4 deletions src/doc/style-guide/src/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@

[Introduction](README.md)

- [Module-level items](items.md)
- [Items](items.md)
- [Statements](statements.md)
- [Expressions](expressions.md)
- [Types](types.md)
- [Non-formatting conventions](advice.md)
- [Types and Bounds](types.md)
- [Other style advice](advice.md)
- [`Cargo.toml` conventions](cargo.md)
- [Principles used for deciding these guidelines](principles.md)
- [Guiding principles and rationale](principles.md)
6 changes: 3 additions & 3 deletions src/doc/style-guide/src/advice.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,9 @@ if y {
* Local variables shall be `snake_case`,
* Macro names shall be `snake_case`,
* Constants (`const`s and immutable `static`s) shall be `SCREAMING_SNAKE_CASE`.
* When a name is forbidden because it is a reserved word (e.g., `crate`), use a
trailing underscore to make the name legal (e.g., `crate_`), or use raw
identifiers if possible.
* When a name is forbidden because it is a reserved word (such as `crate`),
either use a raw identifier (`r#crate`) or use a trailing underscore
(`crate_`). Don't misspell the word (`krate`).

### Modules

Expand Down
21 changes: 11 additions & 10 deletions src/doc/style-guide/src/cargo.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Cargo.toml conventions
# `Cargo.toml` conventions

## Formatting conventions

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

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

```rust
authors = [
"A Uthor <a.uthor@example.org>",
"Another Author <author@example.net>",
some_feature = [
"another_feature",
"yet_another_feature",
"some_dependency?/some_feature",
]
```

Expand All @@ -54,11 +55,11 @@ version = "4.5.6"

## Metadata conventions

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

The license field must contain a valid [SPDX
expression](https://spdx.org/spdx-specification-21-web-version#h.jxpfx0ykyb60),
Expand Down
2 changes: 1 addition & 1 deletion src/doc/style-guide/src/expressions.md
Original file line number Diff line number Diff line change
Expand Up @@ -690,7 +690,7 @@ Where it is possible to use a block form on the right-hand side and avoid
breaking the left-hand side, do that. E.g.

```rust
// Assuming the following line does done fit in the max width
// Assuming the following line does not fit in the max width
a_very_long_pattern | another_pattern => ALongStructName {
...
},
Expand Down
Loading