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 7 pull requests #91001

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
5f6cfd2
mention `remove` in `swap_remove`
wooster0 Nov 1, 2021
084b232
add const generics test
lcnr Nov 4, 2021
1642fdf
Add `-Zassert-incr-state` to assert state of incremental cache
pierwill Oct 31, 2021
ddc1d58
windows: Return the "Not Found" error when a path is empty
JohnTitor Nov 16, 2021
483cff7
Add SourceMap::indentation_before.
m-ou-se Nov 4, 2021
453e242
Improve suggestion for unit Option/Result at the end of a block.
m-ou-se Nov 4, 2021
b331b66
Improve compatible enum variant suggestions.
m-ou-se Nov 4, 2021
4877756
Update tests.
m-ou-se Nov 4, 2021
5a25751
Add new tests for compatible variant diagnostics.
m-ou-se Nov 4, 2021
09e4a75
Use span_suggestions instead of multipart_suggestions.
m-ou-se Nov 4, 2021
b66fb64
Update test output.
m-ou-se Nov 16, 2021
f5dc388
Point at source of trait bound obligations in more places
estebank Oct 5, 2021
3fe48b2
Change `trait_defs.rs` incremental hash test
estebank Oct 6, 2021
412793f
Point at bounds when comparing impl items to trait
estebank Oct 6, 2021
abf70a9
Do not mention associated items when they introduce an obligation
estebank Oct 12, 2021
a7261c3
Avoid suggesting literal formatting that turns into member access
notriddle Nov 17, 2021
a6b31eb
Align multiline messages to their label (add left margin)
estebank Oct 13, 2021
70e8240
Point at `impl` blocks when they introduce unmet obligations
estebank Oct 13, 2021
8d443ea
Suggest constraining `fn` type params when appropriate
estebank Oct 13, 2021
1cadfe6
Move tests for missing trait bounds to their own directory
estebank Oct 14, 2021
2c173af
review comments
estebank Nov 18, 2021
a8dcc87
Move tests from ui directory
estebank Nov 18, 2021
c5438c3
Rollup merge of #89580 - estebank:trait-bounds-are-tricky, r=nagisa
matthiaskrgr Nov 18, 2021
a4739f2
Rollup merge of #90386 - pierwill:assert-incr-state-85864, r=Aaron1011
matthiaskrgr Nov 18, 2021
38f2cfa
Rollup merge of #90480 - r00ster91:remove, r=kennytm
matthiaskrgr Nov 18, 2021
aa17eeb
Rollup merge of #90575 - m-ou-se:compatible-variant-improvements, r=e…
matthiaskrgr Nov 18, 2021
63ee3b2
Rollup merge of #90578 - lcnr:add-test, r=Mark-Simulacrum
matthiaskrgr Nov 18, 2021
005be61
Rollup merge of #90942 - JohnTitor:should-os-error-3, r=m-ou-se
matthiaskrgr Nov 18, 2021
177058c
Rollup merge of #90989 - notriddle:notriddle/rustc-suggest-float-endi…
matthiaskrgr Nov 18, 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
17 changes: 16 additions & 1 deletion compiler/rustc_errors/src/emitter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1266,22 +1266,37 @@ impl EmitterWriter {
}
self.msg_to_buffer(&mut buffer, msg, max_line_num_len, "note", None);
} else {
let mut label_width = 0;
// The failure note level itself does not provide any useful diagnostic information
if *level != Level::FailureNote {
buffer.append(0, level.to_str(), Style::Level(*level));
label_width += level.to_str().len();
}
// only render error codes, not lint codes
if let Some(DiagnosticId::Error(ref code)) = *code {
buffer.append(0, "[", Style::Level(*level));
buffer.append(0, &code, Style::Level(*level));
buffer.append(0, "]", Style::Level(*level));
label_width += 2 + code.len();
}
let header_style = if is_secondary { Style::HeaderMsg } else { Style::MainHeaderMsg };
if *level != Level::FailureNote {
buffer.append(0, ": ", header_style);
label_width += 2;
}
for &(ref text, _) in msg.iter() {
buffer.append(0, &replace_tabs(text), header_style);
// Account for newlines to align output to its label.
for (line, text) in replace_tabs(text).lines().enumerate() {
buffer.append(
0 + line,
&format!(
"{}{}",
if line == 0 { String::new() } else { " ".repeat(label_width) },
text
),
header_style,
);
}
}
}

Expand Down
24 changes: 23 additions & 1 deletion compiler/rustc_incremental/src/persist/load.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use rustc_middle::dep_graph::{SerializedDepGraph, WorkProduct, WorkProductId};
use rustc_middle::ty::OnDiskCache;
use rustc_serialize::opaque::Decoder;
use rustc_serialize::Decodable;
use rustc_session::config::IncrementalStateAssertion;
use rustc_session::Session;
use std::path::Path;

Expand All @@ -16,6 +17,7 @@ use super::work_product;

type WorkProductMap = FxHashMap<WorkProductId, WorkProduct>;

#[derive(Debug)]
pub enum LoadResult<T> {
Ok { data: T },
DataOutOfDate,
Expand All @@ -24,6 +26,26 @@ pub enum LoadResult<T> {

impl<T: Default> LoadResult<T> {
pub fn open(self, sess: &Session) -> T {
// Check for errors when using `-Zassert-incremental-state`
match (sess.opts.assert_incr_state, &self) {
(Some(IncrementalStateAssertion::NotLoaded), LoadResult::Ok { .. }) => {
sess.fatal(
"We asserted that the incremental cache should not be loaded, \
but it was loaded.",
);
}
(
Some(IncrementalStateAssertion::Loaded),
LoadResult::Error { .. } | LoadResult::DataOutOfDate,
) => {
sess.fatal(
"We asserted that an existing incremental cache directory should \
be successfully loaded, but it was not.",
);
}
_ => {}
};

match self {
LoadResult::Error { message } => {
sess.warn(&message);
Expand All @@ -33,7 +55,7 @@ impl<T: Default> LoadResult<T> {
if let Err(err) = delete_all_session_dir_contents(sess) {
sess.err(&format!(
"Failed to delete invalidated or incompatible \
incremental compilation session directory contents `{}`: {}.",
incremental compilation session directory contents `{}`: {}.",
dep_graph_path(sess).display(),
err
));
Expand Down
15 changes: 12 additions & 3 deletions compiler/rustc_infer/src/infer/error_reporting/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2113,10 +2113,19 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
None
},
self.tcx.generics_of(owner.to_def_id()),
hir.span(hir_id),
)
});

let span = match generics {
// This is to get around the trait identity obligation, that has a `DUMMY_SP` as signal
// for other diagnostics, so we need to recover it here.
Some((_, _, node)) if span.is_dummy() => node,
_ => span,
};

let type_param_span = match (generics, bound_kind) {
(Some((_, ref generics)), GenericKind::Param(ref param)) => {
(Some((_, ref generics, _)), GenericKind::Param(ref param)) => {
// Account for the case where `param` corresponds to `Self`,
// which doesn't have the expected type argument.
if !(generics.has_self && param.index == 0) {
Expand Down Expand Up @@ -2153,7 +2162,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
};
let new_lt = generics
.as_ref()
.and_then(|(parent_g, g)| {
.and_then(|(parent_g, g, _)| {
let mut possible = (b'a'..=b'z').map(|c| format!("'{}", c as char));
let mut lts_names = g
.params
Expand All @@ -2175,7 +2184,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
.unwrap_or("'lt".to_string());
let add_lt_sugg = generics
.as_ref()
.and_then(|(_, g)| g.params.first())
.and_then(|(_, g, _)| g.params.first())
.and_then(|param| param.def_id.as_local())
.map(|def_id| {
(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -192,14 +192,16 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> {
ObligationCauseCode::MatchImpl(parent, ..) => &parent.code,
_ => &cause.code,
};
if let ObligationCauseCode::ItemObligation(item_def_id) = *code {
if let (ObligationCauseCode::ItemObligation(item_def_id), None) =
(code, override_error_code)
{
// Same case of `impl Foo for dyn Bar { fn qux(&self) {} }` introducing a `'static`
// lifetime as above, but called using a fully-qualified path to the method:
// `Foo::qux(bar)`.
let mut v = TraitObjectVisitor(FxHashSet::default());
v.visit_ty(param.param_ty);
if let Some((ident, self_ty)) =
self.get_impl_ident_and_self_ty_from_trait(item_def_id, &v.0)
self.get_impl_ident_and_self_ty_from_trait(*item_def_id, &v.0)
{
if self.suggest_constrain_dyn_trait_in_impl(&mut err, &v.0, ident, self_ty) {
override_error_code = Some(ident);
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_interface/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -636,6 +636,7 @@ fn test_debugging_options_tracking_hash() {

// Make sure that changing an [UNTRACKED] option leaves the hash unchanged.
// This list is in alphabetical order.
untracked!(assert_incr_state, Some(String::from("loaded")));
untracked!(ast_json, true);
untracked!(ast_json_noexpand, true);
untracked!(borrowck, String::from("other"));
Expand Down
32 changes: 32 additions & 0 deletions compiler/rustc_session/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,18 @@ pub enum LinkerPluginLto {
Disabled,
}

/// Used with `-Z assert-incr-state`.
#[derive(Clone, Copy, PartialEq, Hash, Debug)]
pub enum IncrementalStateAssertion {
/// Found and loaded an existing session directory.
///
/// Note that this says nothing about whether any particular query
/// will be found to be red or green.
Loaded,
/// Did not load an existing session directory.
NotLoaded,
}

impl LinkerPluginLto {
pub fn enabled(&self) -> bool {
match *self {
Expand Down Expand Up @@ -704,6 +716,7 @@ pub fn host_triple() -> &'static str {
impl Default for Options {
fn default() -> Options {
Options {
assert_incr_state: None,
crate_types: Vec::new(),
optimize: OptLevel::No,
debuginfo: DebugInfo::None,
Expand Down Expand Up @@ -1626,6 +1639,21 @@ fn select_debuginfo(
}
}

crate fn parse_assert_incr_state(
opt_assertion: &Option<String>,
error_format: ErrorOutputType,
) -> Option<IncrementalStateAssertion> {
match opt_assertion {
Some(s) if s.as_str() == "loaded" => Some(IncrementalStateAssertion::Loaded),
Some(s) if s.as_str() == "not-loaded" => Some(IncrementalStateAssertion::NotLoaded),
Some(s) => early_error(
error_format,
&format!("unexpected incremental state assertion value: {}", s),
),
None => None,
}
}

fn parse_native_lib_kind(
matches: &getopts::Matches,
kind: &str,
Expand Down Expand Up @@ -2015,6 +2043,9 @@ pub fn build_session_options(matches: &getopts::Matches) -> Options {

let incremental = cg.incremental.as_ref().map(PathBuf::from);

let assert_incr_state =
parse_assert_incr_state(&debugging_opts.assert_incr_state, error_format);

if debugging_opts.profile && incremental.is_some() {
early_error(
error_format,
Expand Down Expand Up @@ -2179,6 +2210,7 @@ pub fn build_session_options(matches: &getopts::Matches) -> Options {
};

Options {
assert_incr_state,
crate_types,
optimize: opt_level,
debuginfo,
Expand Down
5 changes: 4 additions & 1 deletion compiler/rustc_session/src/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ use crate::early_error;
use crate::lint;
use crate::search_paths::SearchPath;
use crate::utils::NativeLib;

use rustc_target::spec::{CodeModel, LinkerFlavor, MergeFunctions, PanicStrategy, SanitizerSet};
use rustc_target::spec::{RelocModel, RelroLevel, SplitDebuginfo, TargetTriple, TlsModel};

Expand Down Expand Up @@ -150,6 +149,7 @@ top_level_options!(
/// If `Some`, enable incremental compilation, using the given
/// directory to store intermediate results.
incremental: Option<PathBuf> [UNTRACKED],
assert_incr_state: Option<IncrementalStateAssertion> [UNTRACKED],

debugging_opts: DebuggingOptions [SUBSTRUCT],
prints: Vec<PrintRequest> [UNTRACKED],
Expand Down Expand Up @@ -1046,6 +1046,9 @@ options! {
"make cfg(version) treat the current version as incomplete (default: no)"),
asm_comments: bool = (false, parse_bool, [TRACKED],
"generate comments into the assembly (may change behavior) (default: no)"),
assert_incr_state: Option<String> = (None, parse_opt_string, [UNTRACKED],
"assert that the incremental cache is in given state: \
either `loaded` or `not-loaded`."),
ast_json: bool = (false, parse_bool, [UNTRACKED],
"print the AST as JSON and halt (default: no)"),
ast_json_noexpand: bool = (false, parse_bool, [UNTRACKED],
Expand Down
19 changes: 12 additions & 7 deletions compiler/rustc_span/src/source_map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -593,14 +593,19 @@ impl SourceMap {
}

pub fn span_to_margin(&self, sp: Span) -> Option<usize> {
match self.span_to_prev_source(sp) {
Err(_) => None,
Ok(source) => {
let last_line = source.rsplit_once('\n').unwrap_or(("", &source)).1;
Some(self.indentation_before(sp)?.len())
}

Some(last_line.len() - last_line.trim_start().len())
}
}
pub fn indentation_before(&self, sp: Span) -> Option<String> {
self.span_to_source(sp, |src, start_index, _| {
let before = &src[..start_index];
let last_line = before.rsplit_once('\n').map_or(before, |(_, last)| last);
Ok(last_line
.split_once(|c: char| !c.is_whitespace())
.map_or(last_line, |(indent, _)| indent)
.to_string())
})
.ok()
}

/// Returns the source snippet as `String` before the given `Span`.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1957,15 +1957,9 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
region, object_ty,
));
}
ObligationCauseCode::ItemObligation(item_def_id) => {
let item_name = tcx.def_path_str(item_def_id);
let msg = format!("required by `{}`", item_name);
let sp = tcx
.hir()
.span_if_local(item_def_id)
.unwrap_or_else(|| tcx.def_span(item_def_id));
let sp = tcx.sess.source_map().guess_head_span(sp);
err.span_note(sp, &msg);
ObligationCauseCode::ItemObligation(_item_def_id) => {
// We hold the `DefId` of the item introducing the obligation, but displaying it
// doesn't add user usable information. It always point at an associated item.
}
ObligationCauseCode::BindingObligation(item_def_id, span) => {
let item_name = tcx.def_path_str(item_def_id);
Expand Down
19 changes: 13 additions & 6 deletions compiler/rustc_trait_selection/src/traits/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@ use rustc_middle::ty::subst::{GenericArg, Subst, SubstsRef};
use rustc_middle::ty::{self, ToPredicate, Ty, TyCtxt, TypeFoldable, WithConstness};

use super::{Normalized, Obligation, ObligationCause, PredicateObligation, SelectionContext};
pub use rustc_infer::traits::util::*;
pub use rustc_infer::traits::{self, util::*};

use std::iter;

///////////////////////////////////////////////////////////////////////////
// `TraitAliasExpander` iterator
Expand Down Expand Up @@ -229,11 +231,16 @@ pub fn predicates_for_generics<'tcx>(
) -> impl Iterator<Item = PredicateObligation<'tcx>> {
debug!("predicates_for_generics(generic_bounds={:?})", generic_bounds);

generic_bounds.predicates.into_iter().map(move |predicate| Obligation {
cause: cause.clone(),
recursion_depth,
param_env,
predicate,
iter::zip(generic_bounds.predicates, generic_bounds.spans).map(move |(predicate, span)| {
let cause = match cause.code {
traits::ItemObligation(def_id) if !span.is_dummy() => traits::ObligationCause::new(
cause.span,
cause.body_id,
traits::BindingObligation(def_id, span),
),
_ => cause.clone(),
};
Obligation { cause, recursion_depth, param_env, predicate }
})
}

Expand Down
7 changes: 6 additions & 1 deletion compiler/rustc_trait_selection/src/traits/wf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -709,7 +709,12 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> {

iter::zip(iter::zip(predicates.predicates, predicates.spans), origins.into_iter().rev())
.map(|((pred, span), origin_def_id)| {
let cause = self.cause(traits::BindingObligation(origin_def_id, span));
let code = if span.is_dummy() {
traits::MiscObligation
} else {
traits::BindingObligation(origin_def_id, span)
};
let cause = self.cause(code);
traits::Obligation::with_depth(cause, self.recursion_depth, self.param_env, pred)
})
.filter(|pred| !pred.has_escaping_bound_vars())
Expand Down
Loading