Skip to content

Rollup of 8 pull requests #106588

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

Merged
merged 18 commits into from
Jan 8, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
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
27 changes: 16 additions & 11 deletions compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -344,20 +344,25 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
} else {
err.span_help(source_info.span, "try removing `&mut` here");
}
} else if decl.mutability == Mutability::Not
&& !matches!(
} else if decl.mutability == Mutability::Not {
if matches!(
decl.local_info,
Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::ImplicitSelf(
hir::ImplicitSelfKind::MutRef
))))
)
{
err.span_suggestion_verbose(
decl.source_info.span.shrink_to_lo(),
"consider making the binding mutable",
"mut ",
Applicability::MachineApplicable,
);
),)))
) {
err.note(
"as `Self` may be unsized, this call attempts to take `&mut &mut self`",
);
err.note("however, `&mut self` expands to `self: &mut Self`, therefore `self` cannot be borrowed mutably");
} else {
err.span_suggestion_verbose(
decl.source_info.span.shrink_to_lo(),
"consider making the binding mutable",
"mut ",
Applicability::MachineApplicable,
);
};
}
}

Expand Down
3 changes: 1 addition & 2 deletions compiler/rustc_error_codes/src/error_codes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -579,8 +579,7 @@ E0791: include_str!("./error_codes/E0791.md"),
// E0300, // unexpanded macro
// E0304, // expected signed integer constant
// E0305, // expected constant
E0313, // lifetime of borrowed pointer outlives lifetime of captured
// variable
// E0313, // removed: found unreachable
// E0314, // closure outlives stack frame
// E0315, // cannot invoke closure outside of its lifetime
// E0319, // trait impls for defaulted traits allowed just for structs/enums
Expand Down
23 changes: 8 additions & 15 deletions compiler/rustc_error_codes/src/error_codes/E0015.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
A constant item was initialized with something that is not a constant
expression.
A non-`const` function was called in a `const` context.

Erroneous code example:

Expand All @@ -8,26 +7,20 @@ fn create_some() -> Option<u8> {
Some(1)
}

const FOO: Option<u8> = create_some(); // error!
// error: cannot call non-const fn `create_some` in constants
const FOO: Option<u8> = create_some();
```

The only functions that can be called in static or constant expressions are
`const` functions, and struct/enum constructors.
All functions used in a `const` context (constant or static expression) must
be marked `const`.

To fix this error, you can declare `create_some` as a constant function:

```
const fn create_some() -> Option<u8> { // declared as a const function
// declared as a `const` function:
const fn create_some() -> Option<u8> {
Some(1)
}

const FOO: Option<u8> = create_some(); // ok!

// These are also working:
struct Bar {
x: u8,
}

const OTHER_FOO: Option<u8> = Some(1);
const BAR: Bar = Bar {x: 1};
const FOO: Option<u8> = create_some(); // no error!
```
5 changes: 4 additions & 1 deletion compiler/rustc_hir_typeck/src/demand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1379,7 +1379,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
}
}
// If we've reached our target type with just removing `&`, then just print now.
if steps == 0 {
if steps == 0 && !remove.trim().is_empty() {
return Some((
prefix_span,
format!("consider removing the `{}`", remove.trim()),
Expand Down Expand Up @@ -1438,6 +1438,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
} else {
(prefix_span, format!("{}{}", prefix, "*".repeat(steps)))
};
if suggestion.trim().is_empty() {
return None;
}

return Some((
span,
Expand Down
1 change: 0 additions & 1 deletion compiler/rustc_infer/src/infer/error_reporting/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
// ignore-tidy-filelength
//! Error Reporting Code for the inference engine
//!
//! Because of the way inference, and in particular region inference,
Expand Down
37 changes: 0 additions & 37 deletions compiler/rustc_infer/src/infer/error_reporting/note.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,16 +25,6 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
infer::Reborrow(span) => {
RegionOriginNote::Plain { span, msg: fluent::infer_reborrow }.add_to_diagnostic(err)
}
infer::ReborrowUpvar(span, ref upvar_id) => {
let var_name = self.tcx.hir().name(upvar_id.var_path.hir_id);
RegionOriginNote::WithName {
span,
msg: fluent::infer_reborrow,
name: &var_name.to_string(),
continues: false,
}
.add_to_diagnostic(err);
}
infer::RelateObjectBound(span) => {
RegionOriginNote::Plain { span, msg: fluent::infer_relate_object_bound }
.add_to_diagnostic(err);
Expand Down Expand Up @@ -162,33 +152,6 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
);
err
}
infer::ReborrowUpvar(span, ref upvar_id) => {
let var_name = self.tcx.hir().name(upvar_id.var_path.hir_id);
let mut err = struct_span_err!(
self.tcx.sess,
span,
E0313,
"lifetime of borrowed pointer outlives lifetime of captured variable `{}`...",
var_name
);
note_and_explain_region(
self.tcx,
&mut err,
"...the borrowed pointer is valid for ",
sub,
"...",
None,
);
note_and_explain_region(
self.tcx,
&mut err,
&format!("...but `{}` is only valid for ", var_name),
sup,
"",
None,
);
err
}
infer::RelateObjectBound(span) => {
let mut err = struct_span_err!(
self.tcx.sess,
Expand Down
4 changes: 0 additions & 4 deletions compiler/rustc_infer/src/infer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -409,9 +409,6 @@ pub enum SubregionOrigin<'tcx> {
/// Creating a pointer `b` to contents of another reference
Reborrow(Span),

/// Creating a pointer `b` to contents of an upvar
ReborrowUpvar(Span, ty::UpvarId),

/// Data with type `Ty<'tcx>` was borrowed
DataBorrowed(Ty<'tcx>, Span),

Expand Down Expand Up @@ -1954,7 +1951,6 @@ impl<'tcx> SubregionOrigin<'tcx> {
RelateParamBound(a, ..) => a,
RelateRegionParamBound(a) => a,
Reborrow(a) => a,
ReborrowUpvar(a, _) => a,
DataBorrowed(_, a) => a,
ReferenceOutlivesReferent(_, a) => a,
CompareImplItemObligation { span, .. } => span,
Expand Down
4 changes: 3 additions & 1 deletion library/alloc/src/collections/vec_deque/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -636,6 +636,7 @@ impl<T, A: Allocator> VecDeque<T, A> {
/// buf.push_back(3);
/// buf.push_back(4);
/// buf.push_back(5);
/// buf.push_back(6);
/// assert_eq!(buf.get(1), Some(&4));
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
Expand All @@ -661,10 +662,11 @@ impl<T, A: Allocator> VecDeque<T, A> {
/// buf.push_back(3);
/// buf.push_back(4);
/// buf.push_back(5);
/// buf.push_back(6);
/// assert_eq!(buf[1], 4);
/// if let Some(elem) = buf.get_mut(1) {
/// *elem = 7;
/// }
///
/// assert_eq!(buf[1], 7);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
Expand Down
2 changes: 1 addition & 1 deletion library/std/src/path.rs
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,7 @@ pub const MAIN_SEPARATOR: char = crate::sys::path::MAIN_SEP;
/// The primary separator of path components for the current platform.
///
/// For example, `/` on Unix and `\` on Windows.
#[unstable(feature = "main_separator_str", issue = "94071")]
#[stable(feature = "main_separator_str", since = "CURRENT_RUSTC_VERSION")]
pub const MAIN_SEPARATOR_STR: &str = crate::sys::path::MAIN_SEP_STR;

////////////////////////////////////////////////////////////////////////////////
Expand Down
4 changes: 2 additions & 2 deletions src/bootstrap/setup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -351,7 +351,7 @@ pub fn interactive_path() -> io::Result<Profile> {
Ok(template)
}

// install a git hook to automatically run tidy --bless, if they want
// install a git hook to automatically run tidy, if they want
fn install_git_hook_maybe(config: &Config) -> io::Result<()> {
let git = t!(config.git().args(&["rev-parse", "--git-common-dir"]).output().map(|output| {
assert!(output.status.success(), "failed to run `git`");
Expand All @@ -367,7 +367,7 @@ fn install_git_hook_maybe(config: &Config) -> io::Result<()> {
println!();
println!(
"Rust's CI will automatically fail if it doesn't pass `tidy`, the internal tool for ensuring code quality.
If you'd like, x.py can install a git hook for you that will automatically run `tidy --bless` before
If you'd like, x.py can install a git hook for you that will automatically run `test tidy` before
pushing your code to ensure your code is up to par. If you decide later that this behavior is
undesirable, simply delete the `pre-push` file from .git/hooks."
);
Expand Down
2 changes: 1 addition & 1 deletion src/etc/pre-push.sh
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#!/usr/bin/env bash
#
# Call `tidy --bless` before git push
# Call `tidy` before git push
# Copy this script to .git/hooks to activate,
# and remove it from .git/hooks to deactivate.
#
Expand Down
15 changes: 15 additions & 0 deletions src/test/ui/borrowck/issue-93078.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
trait Modify {
fn modify(&mut self) ;
}

impl<T> Modify for T {
fn modify(&mut self) {}
}

trait Foo {
fn mute(&mut self) {
self.modify(); //~ ERROR cannot borrow `self` as mutable
}
}

fn main() {}
12 changes: 12 additions & 0 deletions src/test/ui/borrowck/issue-93078.stderr
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
error[E0596]: cannot borrow `self` as mutable, as it is not declared as mutable
--> $DIR/issue-93078.rs:11:9
|
LL | self.modify();
| ^^^^^^^^^^^^^ cannot borrow as mutable
|
= note: as `Self` may be unsized, this call attempts to take `&mut &mut self`
= note: however, `&mut self` expands to `self: &mut Self`, therefore `self` cannot be borrowed mutably

error: aborting due to previous error

For more information about this error, try `rustc --explain E0596`.
4 changes: 4 additions & 0 deletions src/test/ui/error-codes/E0013.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
static X: i32 = 42;
const Y: i32 = X; //~ ERROR constants cannot refer to statics [E0013]

fn main() {}
11 changes: 11 additions & 0 deletions src/test/ui/error-codes/E0013.stderr
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
error[E0013]: constants cannot refer to statics
--> $DIR/E0013.rs:2:16
|
LL | const Y: i32 = X;
| ^
|
= help: consider extracting the value of the `static` to a `const`, and referring to that

error: aborting due to previous error

For more information about this error, try `rustc --explain E0013`.
8 changes: 8 additions & 0 deletions src/test/ui/error-codes/E0015.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
fn create_some() -> Option<u8> {
Some(1)
}

const FOO: Option<u8> = create_some();
//~^ ERROR cannot call non-const fn `create_some` in constants [E0015]

fn main() {}
11 changes: 11 additions & 0 deletions src/test/ui/error-codes/E0015.stderr
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
error[E0015]: cannot call non-const fn `create_some` in constants
--> $DIR/E0015.rs:5:25
|
LL | const FOO: Option<u8> = create_some();
| ^^^^^^^^^^^^^
|
= note: calls in constants are limited to constant functions, tuple structs and tuple variants

error: aborting due to previous error

For more information about this error, try `rustc --explain E0015`.
10 changes: 10 additions & 0 deletions src/test/ui/type/closure-with-wrong-borrows.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
struct S<'a>(&'a str);

fn f(inner: fn(&str, &S)) {
}

#[allow(unreachable_code)]
fn main() {
let inner: fn(_, _) = unimplemented!();
f(inner); //~ ERROR mismatched types
}
19 changes: 19 additions & 0 deletions src/test/ui/type/closure-with-wrong-borrows.stderr
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
error[E0308]: mismatched types
--> $DIR/closure-with-wrong-borrows.rs:9:7
|
LL | f(inner);
| - ^^^^^ one type is more general than the other
| |
| arguments to this function are incorrect
|
= note: expected fn pointer `for<'a, 'b, 'c> fn(&'a str, &'b S<'c>)`
found fn pointer `fn(_, _)`
note: function defined here
--> $DIR/closure-with-wrong-borrows.rs:3:4
|
LL | fn f(inner: fn(&str, &S)) {
| ^ -------------------

error: aborting due to previous error

For more information about this error, try `rustc --explain E0308`.
29 changes: 26 additions & 3 deletions src/tools/jsondoclint/src/validator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,17 @@ use std::hash::Hash;

use rustdoc_json_types::{
Constant, Crate, DynTrait, Enum, FnDecl, Function, FunctionPointer, GenericArg, GenericArgs,
GenericBound, GenericParamDef, Generics, Id, Impl, Import, ItemEnum, Module, OpaqueTy, Path,
Primitive, ProcMacro, Static, Struct, StructKind, Term, Trait, TraitAlias, Type, TypeBinding,
TypeBindingKind, Typedef, Union, Variant, VariantKind, WherePredicate,
GenericBound, GenericParamDef, Generics, Id, Impl, Import, ItemEnum, ItemSummary, Module,
OpaqueTy, Path, Primitive, ProcMacro, Static, Struct, StructKind, Term, Trait, TraitAlias,
Type, TypeBinding, TypeBindingKind, Typedef, Union, Variant, VariantKind, WherePredicate,
};
use serde_json::Value;

use crate::{item_kind::Kind, json_find, Error, ErrorKind};

// This is a rustc implementation detail that we rely on here
const LOCAL_CRATE_ID: u32 = 0;

/// The Validator walks over the JSON tree, and ensures it is well formed.
/// It is made of several parts.
///
Expand Down Expand Up @@ -53,12 +56,19 @@ impl<'a> Validator<'a> {
}

pub fn check_crate(&mut self) {
// Graph traverse the index
let root = &self.krate.root;
self.add_mod_id(root);
while let Some(id) = set_remove(&mut self.todo) {
self.seen_ids.insert(id);
self.check_item(id);
}

let root_crate_id = self.krate.index[root].crate_id;
assert_eq!(root_crate_id, LOCAL_CRATE_ID, "LOCAL_CRATE_ID is wrong");
for (id, item_info) in &self.krate.paths {
self.check_item_info(id, item_info);
}
}

fn check_item(&mut self, id: &'a Id) {
Expand Down Expand Up @@ -364,6 +374,19 @@ impl<'a> Validator<'a> {
fp.generic_params.iter().for_each(|gpd| self.check_generic_param_def(gpd));
}

fn check_item_info(&mut self, id: &Id, item_info: &ItemSummary) {
// FIXME: Their should be a better way to determine if an item is local, rather than relying on `LOCAL_CRATE_ID`,
// which encodes rustc implementation details.
if item_info.crate_id == LOCAL_CRATE_ID && !self.krate.index.contains_key(id) {
self.errs.push(Error {
id: id.clone(),
kind: ErrorKind::Custom(
"Id for local item in `paths` but not in `index`".to_owned(),
),
})
}
}

fn add_id_checked(&mut self, id: &'a Id, valid: fn(Kind) -> bool, expected: &str) {
if let Some(kind) = self.kind_of(id) {
if valid(kind) {
Expand Down
Loading