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 11 pull requests #91382

Closed
wants to merge 29 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
577e985
Only shown relevant type params in E0283 label
estebank Nov 8, 2021
d0d51ea
Refer to uninferred `const` params by their name, instead of `{ _: _ }`
estebank Nov 8, 2021
8a08bef
Refer to const params as "const params" and not "type params"
estebank Nov 8, 2021
e462819
Add test with multiple type params failing inference
estebank Nov 19, 2021
d6e34ad
When recovering from a `:` in a pattern, use adequate AST pattern
estebank Jul 15, 2021
eeaa215
Don't treat unnormalized function arguments as well-formed
jackh726 Nov 26, 2021
df3e7a2
Refactor EmitterWriter::emit_suggestion_default
rukai Nov 26, 2021
b6f9416
tests: Ignore `test/debuginfo/rc_arc.rs` on windows-gnu
petrochenkov Nov 28, 2021
e500eb6
Bump compiler_builtins to 0.1.55 to bring in fixes for targets lackin…
cr1901 Nov 28, 2021
3c42a11
Fix small typo
kijimaD Nov 29, 2021
6c3c3e0
CTFE: support assert_zero_valid and assert_uninit_valid
RalfJung Nov 28, 2021
dec0d83
:arrow_up: rust-analyzer
lnicola Nov 29, 2021
c027105
review comments: clean up
estebank Nov 21, 2021
f67e73a
Factor out build reduced graph for extern crate
mjptree Nov 26, 2021
29b4b6c
Stop treating extern crate loading failures as fatal errors
mjptree Nov 26, 2021
2c9d9b4
Improve suggestion for extern crate self error message
mjptree Nov 26, 2021
692e96c
Bless nll
jackh726 Nov 29, 2021
188d670
Don't re-export `MirPass`
ecstatic-morse Nov 29, 2021
aec1574
Rollup merge of #87160 - estebank:colon-recovery, r=nagisa
matthiaskrgr Nov 30, 2021
ec9cd2a
Rollup merge of #90709 - estebank:erase-known-type-params, r=nagisa
matthiaskrgr Nov 30, 2021
5cf4b13
Rollup merge of #91045 - mjptree:issue-90702-fix, r=petrochenkov
matthiaskrgr Nov 30, 2021
0629ad2
Rollup merge of #91243 - jackh726:issue-91068, r=nikomatsakis
matthiaskrgr Nov 30, 2021
e6c17fd
Rollup merge of #91250 - rukai:remove_trailing_whitespace, r=wesleywiser
matthiaskrgr Nov 30, 2021
da7612c
Rollup merge of #91317 - petrochenkov:debugnu, r=Mark-Simulacrum
matthiaskrgr Nov 30, 2021
ad898ec
Rollup merge of #91323 - RalfJung:assert-type, r=oli-obk
matthiaskrgr Nov 30, 2021
86bd6a0
Rollup merge of #91340 - cr1901:no-atomic, r=Mark-Simulacrum
matthiaskrgr Nov 30, 2021
06afe44
Rollup merge of #91358 - kd-collective:fix_typo, r=cjgillot
matthiaskrgr Nov 30, 2021
5d4d3f2
Rollup merge of #91360 - lnicola:rust-analyzer-2021-11-29, r=lnicola
matthiaskrgr Nov 30, 2021
1a46a42
Rollup merge of #91368 - ecstatic-morse:mir-pass-reexport, r=cjgillot
matthiaskrgr Nov 30, 2021
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
4 changes: 2 additions & 2 deletions Cargo.lock
Original file line number Diff line number Diff line change
Expand Up @@ -678,9 +678,9 @@ dependencies = [

[[package]]
name = "compiler_builtins"
version = "0.1.53"
version = "0.1.55"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2467ff455350a4df7d02f1ed1449d0279605a763de5d586dcf6aa7d732508bcb"
checksum = "c9ac60765140c97aaf531dae151a287646b0805ec725805da9e2a3ee31cd501c"
dependencies = [
"cc",
"rustc-std-workspace-core",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,6 @@ impl UniversalRegionRelationsBuilder<'cx, 'tcx> {
debug!("build: input_or_output={:?}", ty);
// We add implied bounds from both the unnormalized and normalized ty
// See issue #87748
let constraints_implied_1 = self.add_implied_bounds(ty);
let TypeOpOutput { output: norm_ty, constraints: constraints1, .. } = self
.param_env
.and(type_op::normalize::Normalize::new(ty))
Expand Down Expand Up @@ -284,10 +283,9 @@ impl UniversalRegionRelationsBuilder<'cx, 'tcx> {
// }
// ```
// Both &Self::Bar and &() are WF
let constraints_implied_2 =
if ty != norm_ty { self.add_implied_bounds(norm_ty) } else { None };
let constraints_implied = self.add_implied_bounds(norm_ty);
normalized_inputs_and_output.push(norm_ty);
constraints1.into_iter().chain(constraints_implied_1).chain(constraints_implied_2)
constraints1.into_iter().chain(constraints_implied)
})
.collect();

Expand Down
26 changes: 25 additions & 1 deletion compiler/rustc_const_eval/src/interpret/intrinsics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -394,10 +394,12 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
sym::transmute => {
self.copy_op_transmute(&args[0], dest)?;
}
sym::assert_inhabited => {
sym::assert_inhabited | sym::assert_zero_valid | sym::assert_uninit_valid => {
let ty = instance.substs.type_at(0);
let layout = self.layout_of(ty)?;

// For *all* intrinsics we first check `is_uninhabited` to give a more specific
// error message.
if layout.abi.is_uninhabited() {
// The run-time intrinsic panics just to get a good backtrace; here we abort
// since there is no problem showing a backtrace even for aborts.
Expand All @@ -409,6 +411,28 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
),
)?;
}
if intrinsic_name == sym::assert_zero_valid
&& !layout.might_permit_raw_init(self, /*zero:*/ true)
{
M::abort(
self,
format!(
"aborted execution: attempted to zero-initialize type `{}`, which is invalid",
ty
),
)?;
}
if intrinsic_name == sym::assert_uninit_valid
&& !layout.might_permit_raw_init(self, /*zero:*/ false)
{
M::abort(
self,
format!(
"aborted execution: attempted to leave type `{}` uninitialized, which is invalid",
ty
),
)?;
}
}
sym::simd_insert => {
let index = u64::from(self.read_scalar(&args[1])?.to_u32()?);
Expand Down
2 changes: 0 additions & 2 deletions compiler/rustc_const_eval/src/transform/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
pub mod check_consts;
pub mod promote_consts;
pub mod validate;

pub use rustc_middle::mir::MirPass;
1 change: 0 additions & 1 deletion compiler/rustc_const_eval/src/transform/promote_consts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ use std::cell::Cell;
use std::{cmp, iter, mem};

use crate::transform::check_consts::{qualifs, ConstCx};
use crate::transform::MirPass;

/// A `MirPass` for promotion.
///
Expand Down
5 changes: 2 additions & 3 deletions compiler/rustc_const_eval/src/transform/validate.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
//! Validates the MIR to ensure that invariants are upheld.

use super::MirPass;
use rustc_index::bit_set::BitSet;
use rustc_infer::infer::TyCtxtInferExt;
use rustc_middle::mir::interpret::Scalar;
use rustc_middle::mir::traversal;
use rustc_middle::mir::visit::{PlaceContext, Visitor};
use rustc_middle::mir::{
AggregateKind, BasicBlock, Body, BorrowKind, Local, Location, MirPhase, Operand, PlaceElem,
PlaceRef, ProjectionElem, Rvalue, SourceScope, Statement, StatementKind, Terminator,
AggregateKind, BasicBlock, Body, BorrowKind, Local, Location, MirPass, MirPhase, Operand,
PlaceElem, PlaceRef, ProjectionElem, Rvalue, SourceScope, Statement, StatementKind, Terminator,
TerminatorKind, START_BLOCK,
};
use rustc_middle::ty::fold::BottomUpFolder;
Expand Down
41 changes: 26 additions & 15 deletions compiler/rustc_errors/src/emitter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,7 @@ pub trait Emitter {

/// Formats the substitutions of the primary_span
///
/// The are a lot of conditions to this method, but in short:
/// There are a lot of conditions to this method, but in short:
///
/// * If the current `Diagnostic` has only one visible `CodeSuggestion`,
/// we format the `help` suggestion depending on the content of the
Expand Down Expand Up @@ -736,7 +736,9 @@ impl EmitterWriter {

let line_offset = buffer.num_lines();

let left = margin.left(source_string.len()); // Left trim
// Left trim
let left = margin.left(source_string.len());

// Account for unicode characters of width !=0 that were removed.
let left = source_string
.chars()
Expand Down Expand Up @@ -1623,18 +1625,27 @@ impl EmitterWriter {
suggestions.iter().take(MAX_SUGGESTIONS)
{
notice_capitalization |= only_capitalization;
// Only show underline if the suggestion spans a single line and doesn't cover the
// entirety of the code output. If you have multiple replacements in the same line
// of code, show the underline.
let show_underline = !(parts.len() == 1 && parts[0].snippet.trim() == complete.trim())
&& complete.lines().count() == 1;

let has_deletion = parts.iter().any(|p| p.is_deletion());
let is_multiline = complete.lines().count() > 1;

let show_diff = has_deletion && !is_multiline;
enum DisplaySuggestion {
Underline,
Diff,
None,
}

let show_code_change = if has_deletion && !is_multiline {
DisplaySuggestion::Diff
} else if (parts.len() != 1 || parts[0].snippet.trim() != complete.trim())
&& !is_multiline
{
DisplaySuggestion::Underline
} else {
DisplaySuggestion::None
};

if show_diff {
if let DisplaySuggestion::Diff = show_code_change {
row_num += 1;
}

Expand All @@ -1657,7 +1668,7 @@ impl EmitterWriter {
&self.maybe_anonymized(line_start + line_pos),
Style::LineNumber,
);
if show_diff {
if let DisplaySuggestion::Diff = show_code_change {
// Add the line number for both addition and removal to drive the point home.
//
// N - fn foo<A: T>(bar: A) {
Expand Down Expand Up @@ -1727,7 +1738,7 @@ impl EmitterWriter {
let mut offsets: Vec<(usize, isize)> = Vec::new();
// Only show an underline in the suggestions if the suggestion is not the
// entirety of the code being shown and the displayed code is not multiline.
if show_underline {
if let DisplaySuggestion::Diff | DisplaySuggestion::Underline = show_code_change {
draw_col_separator(&mut buffer, row_num, max_line_num_len + 1);
for part in parts {
let span_start_pos = sm.lookup_char_pos(part.span.lo()).col_display;
Expand Down Expand Up @@ -1755,7 +1766,7 @@ impl EmitterWriter {
assert!(underline_start >= 0 && underline_end >= 0);
let padding: usize = max_line_num_len + 3;
for p in underline_start..underline_end {
if !show_diff {
if let DisplaySuggestion::Underline = show_code_change {
// If this is a replacement, underline with `^`, if this is an addition
// underline with `+`.
buffer.putc(
Expand All @@ -1766,7 +1777,7 @@ impl EmitterWriter {
);
}
}
if show_diff {
if let DisplaySuggestion::Diff = show_code_change {
// Colorize removal with red in diff format.
buffer.set_style_range(
row_num - 2,
Expand Down Expand Up @@ -1797,7 +1808,7 @@ impl EmitterWriter {
// if we elided some lines, add an ellipsis
if lines.next().is_some() {
buffer.puts(row_num, max_line_num_len - 1, "...", Style::LineNumber);
} else if !show_underline {
} else if let DisplaySuggestion::None = show_code_change {
draw_col_separator_no_space(&mut buffer, row_num, max_line_num_len + 1);
row_num += 1;
}
Expand Down Expand Up @@ -2083,7 +2094,7 @@ const OUTPUT_REPLACEMENTS: &[(char, &str)] = &[
('\t', " "), // We do our own tab replacement
('\u{200D}', ""), // Replace ZWJ with nothing for consistent terminal output of grapheme clusters.
('\u{202A}', ""), // The following unicode text flow control characters are inconsistently
('\u{202B}', ""), // supported accross CLIs and can cause confusion due to the bytes on disk
('\u{202B}', ""), // supported across CLIs and can cause confusion due to the bytes on disk
('\u{202D}', ""), // not corresponding to the visible source code, so we replace them always.
('\u{202E}', ""),
('\u{2066}', ""),
Expand Down
136 changes: 131 additions & 5 deletions compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::infer::type_variable::TypeVariableOriginKind;
use crate::infer::InferCtxt;
use crate::infer::{InferCtxt, Symbol};
use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticBuilder};
use rustc_hir as hir;
use rustc_hir::def::{DefKind, Namespace};
Expand All @@ -10,7 +10,7 @@ use rustc_middle::hir::map::Map;
use rustc_middle::infer::unify_key::ConstVariableOriginKind;
use rustc_middle::ty::print::Print;
use rustc_middle::ty::subst::{GenericArg, GenericArgKind};
use rustc_middle::ty::{self, DefIdTree, InferConst, Ty, TyCtxt};
use rustc_middle::ty::{self, Const, DefIdTree, InferConst, Ty, TyCtxt, TypeFoldable, TypeFolder};
use rustc_span::symbol::kw;
use rustc_span::Span;
use std::borrow::Cow;
Expand Down Expand Up @@ -305,6 +305,15 @@ pub enum UnderspecifiedArgKind {
Const { is_parameter: bool },
}

impl UnderspecifiedArgKind {
fn descr(&self) -> &'static str {
match self {
Self::Type { .. } => "type",
Self::Const { .. } => "const",
}
}
}

impl InferenceDiagnosticsData {
/// Generate a label for a generic argument which can't be inferred. When not
/// much is known about the argument, `use_diag` may be used to describe the
Expand Down Expand Up @@ -548,6 +557,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
}
}

let param_type = arg_data.kind.descr();
let suffix = match local_visitor.found_node_ty {
Some(ty) if ty.is_closure() => {
let substs =
Expand Down Expand Up @@ -586,13 +596,15 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
}
Some(ty) if is_named_and_not_impl_trait(ty) && arg_data.name == "_" => {
let ty = ty_to_string(ty);
format!("the explicit type `{}`, with the type parameters specified", ty)
format!("the explicit type `{}`, with the {} parameters specified", ty, param_type)
}
Some(ty) if is_named_and_not_impl_trait(ty) && ty.to_string() != arg_data.name => {
let ty = ResolvedTypeParamEraser::new(self.tcx).fold_ty(ty);
let ty = ErrTypeParamEraser(self.tcx).fold_ty(ty);
let ty = ty_to_string(ty);
format!(
"the explicit type `{}`, where the type parameter `{}` is specified",
ty, arg_data.name,
"the explicit type `{}`, where the {} parameter `{}` is specified",
ty, param_type, arg_data.name,
)
}
_ => "a type".to_string(),
Expand Down Expand Up @@ -868,3 +880,117 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
err
}
}

/// Turn *resolved* type params into `[type error]` to signal we don't want to display them. After
/// performing that replacement, we'll turn all remaining infer type params to use their name from
/// their definition, and replace all the `[type error]`s back to being infer so they display in
/// the output as `_`. If we didn't go through `[type error]`, we would either show all type params
/// by their name *or* `_`, neither of which is desireable: we want to show all types that we could
/// infer as `_` to reduce verbosity and avoid telling the user about unnecessary type annotations.
struct ResolvedTypeParamEraser<'tcx> {
tcx: TyCtxt<'tcx>,
level: usize,
}

impl<'tcx> ResolvedTypeParamEraser<'tcx> {
fn new(tcx: TyCtxt<'tcx>) -> Self {
ResolvedTypeParamEraser { tcx, level: 0 }
}

/// Replace not yet inferred const params with their def name.
fn replace_infers(&self, c: &'tcx Const<'tcx>, index: u32, name: Symbol) -> &'tcx Const<'tcx> {
match c.val {
ty::ConstKind::Infer(..) => self.tcx().mk_const_param(index, name, c.ty),
_ => c,
}
}
}

impl<'tcx> TypeFolder<'tcx> for ResolvedTypeParamEraser<'tcx> {
fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
self.tcx
}
fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
self.level += 1;
let t = match t.kind() {
// We'll hide this type only if all its type params are hidden as well.
ty::Adt(def, substs) => {
let generics = self.tcx().generics_of(def.did);
// Account for params with default values, like `Vec`, where we
// want to show `Vec<T>`, not `Vec<T, _>`. If we replaced that
// subst, then we'd get the incorrect output, so we passthrough.
let substs: Vec<_> = substs
.iter()
.zip(generics.params.iter())
.map(|(subst, param)| match &(subst.unpack(), &param.kind) {
(_, ty::GenericParamDefKind::Type { has_default: true, .. }) => subst,
(crate::infer::GenericArgKind::Const(c), _) => {
self.replace_infers(c, param.index, param.name).into()
}
_ => subst.super_fold_with(self),
})
.collect();
let should_keep = |subst: &GenericArg<'_>| match subst.unpack() {
ty::subst::GenericArgKind::Type(t) => match t.kind() {
ty::Error(_) => false,
_ => true,
},
// Account for `const` params here, otherwise `doesnt_infer.rs`
// shows `_` instead of `Foo<{ _: u32 }>`
ty::subst::GenericArgKind::Const(_) => true,
_ => false,
};
if self.level == 1 || substs.iter().any(should_keep) {
let substs = self.tcx().intern_substs(&substs[..]);
self.tcx().mk_ty(ty::Adt(def, substs))
} else {
self.tcx().ty_error()
}
}
ty::Ref(_, ty, _) => {
let ty = self.fold_ty(ty);
match ty.kind() {
// Avoid `&_`, these can be safely presented as `_`.
ty::Error(_) => self.tcx().ty_error(),
_ => t.super_fold_with(self),
}
}
// We could account for `()` if we wanted to replace it, but it's assured to be short.
ty::Tuple(_)
| ty::Slice(_)
| ty::RawPtr(_)
| ty::FnDef(..)
| ty::FnPtr(_)
| ty::Opaque(..)
| ty::Projection(_)
| ty::Never => t.super_fold_with(self),
ty::Array(ty, c) => self
.tcx()
.mk_ty(ty::Array(self.fold_ty(ty), self.replace_infers(c, 0, Symbol::intern("N")))),
// We don't want to hide type params that haven't been resolved yet.
// This would be the type that will be written out with the type param
// name in the output.
ty::Infer(_) => t,
// We don't want to hide the outermost type, only its type params.
_ if self.level == 1 => t.super_fold_with(self),
// Hide this type
_ => self.tcx().ty_error(),
};
self.level -= 1;
t
}
}

/// Replace `[type error]` with `ty::Infer(ty::Var)` to display `_`.
struct ErrTypeParamEraser<'tcx>(TyCtxt<'tcx>);
impl<'tcx> TypeFolder<'tcx> for ErrTypeParamEraser<'tcx> {
fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
self.0
}
fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
match t.kind() {
ty::Error(_) => self.tcx().mk_ty_var(ty::TyVid::from_u32(0)),
_ => t.super_fold_with(self),
}
}
}
Loading