Skip to content

Commit

Permalink
Auto merge of #112805 - matthiaskrgr:rollup-r5yrefu, r=matthiaskrgr
Browse files Browse the repository at this point in the history
Rollup of 7 pull requests

Successful merges:

 - #109970 ([doc] `poll_fn`: explain how to `pin` captured state safely)
 - #112705 (Simplify `Span::source_callee` impl)
 - #112757 (Use BorrowFlag instead of explicit isize)
 - #112768 (Rewrite various resolve/diagnostics errors as translatable diagnostics)
 - #112777 (Continue folding in query normalizer on weak aliases)
 - #112780 (Treat TAIT equation as always ambiguous in coherence)
 - #112783 (Don't ICE on bound var in `reject_fn_ptr_impls`)

r? `@ghost`
`@rustbot` modify labels: rollup
  • Loading branch information
bors committed Jun 19, 2023
2 parents 4051305 + 68d3e0e commit fe7454b
Show file tree
Hide file tree
Showing 20 changed files with 339 additions and 62 deletions.
11 changes: 4 additions & 7 deletions compiler/rustc_infer/src/infer/combine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,13 +124,10 @@ impl<'tcx> InferCtxt<'tcx> {
}

// During coherence, opaque types should be treated as *possibly*
// equal to each other, even if their generic params differ, as
// they could resolve to the same hidden type, even for different
// generic params.
(
&ty::Alias(ty::Opaque, ty::AliasTy { def_id: a_def_id, .. }),
&ty::Alias(ty::Opaque, ty::AliasTy { def_id: b_def_id, .. }),
) if self.intercrate && a_def_id == b_def_id => {
// equal to any other type (except for possibly itself). This is an
// extremely heavy hammer, but can be relaxed in a fowards-compatible
// way later.
(&ty::Alias(ty::Opaque, _), _) | (_, &ty::Alias(ty::Opaque, _)) if self.intercrate => {
relation.register_predicates([ty::Binder::dummy(ty::PredicateKind::Ambiguous)]);
Ok(a)
}
Expand Down
18 changes: 18 additions & 0 deletions compiler/rustc_resolve/messages.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ resolve_add_as_non_derive =
add as non-Derive macro
`#[{$macro_path}]`
resolve_added_macro_use =
have you added the `#[macro_use]` on the module/import?
resolve_ampersand_used_without_explicit_lifetime_name =
`&` without an explicit lifetime name cannot be used here
.note = explicit lifetime name needed here
Expand Down Expand Up @@ -45,9 +48,18 @@ resolve_cannot_capture_dynamic_environment_in_fn_item =
can't capture dynamic environment in a fn item
.help = use the `|| {"{"} ... {"}"}` closure form instead
resolve_cannot_find_ident_in_this_scope =
cannot find {$expected} `{$ident}` in this scope
resolve_cannot_use_self_type_here =
can't use `Self` here
resolve_change_import_binding =
you can use `as` to change the binding name of the import
resolve_consider_adding_a_derive =
consider adding a derive
resolve_const_not_member_of_trait =
const `{$const_}` is not a member of trait `{$trait_}`
.label = not a member of trait `{$trait_}`
Expand All @@ -74,6 +86,9 @@ resolve_expected_found =
expected module, found {$res} `{$path_str}`
.label = not a module
resolve_explicit_unsafe_traits =
unsafe traits like `{$ident}` should be implemented explicitly
resolve_forward_declared_generic_param =
generic parameters with a default cannot use forward declared identifiers
.label = defaulted generic parameters cannot be forward declared
Expand All @@ -96,6 +111,9 @@ resolve_ident_bound_more_than_once_in_same_pattern =
resolve_imported_crate = `$crate` may not be imported
resolve_imports_cannot_refer_to =
imports cannot refer to {$what}
resolve_indeterminate =
cannot determine resolution for the visibility
Expand Down
31 changes: 12 additions & 19 deletions compiler/rustc_resolve/src/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ use rustc_span::symbol::{kw, sym, Ident, Symbol};
use rustc_span::{BytePos, Span, SyntaxContext};
use thin_vec::ThinVec;

use crate::errors::{
AddedMacroUse, ChangeImportBinding, ChangeImportBindingSuggestion, ConsiderAddingADerive,
ExplicitUnsafeTraits,
};
use crate::imports::{Import, ImportKind};
use crate::late::{PatternSource, Rib};
use crate::path_names_to_string;
Expand Down Expand Up @@ -376,16 +380,10 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
_ => unreachable!(),
}

let rename_msg = "you can use `as` to change the binding name of the import";
if let Some(suggestion) = suggestion {
err.span_suggestion(
binding_span,
rename_msg,
suggestion,
Applicability::MaybeIncorrect,
);
err.subdiagnostic(ChangeImportBindingSuggestion { span: binding_span, suggestion });
} else {
err.span_label(binding_span, rename_msg);
err.subdiagnostic(ChangeImportBinding { span: binding_span });
}
}

Expand Down Expand Up @@ -1382,12 +1380,11 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
);

if macro_kind == MacroKind::Derive && (ident.name == sym::Send || ident.name == sym::Sync) {
let msg = format!("unsafe traits like `{}` should be implemented explicitly", ident);
err.span_note(ident.span, msg);
err.subdiagnostic(ExplicitUnsafeTraits { span: ident.span, ident });
return;
}
if self.macro_names.contains(&ident.normalize_to_macros_2_0()) {
err.help("have you added the `#[macro_use]` on the module/import?");
err.subdiagnostic(AddedMacroUse);
return;
}
if ident.name == kw::Default
Expand All @@ -1396,14 +1393,10 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
let span = self.def_span(def_id);
let source_map = self.tcx.sess.source_map();
let head_span = source_map.guess_head_span(span);
if let Ok(head) = source_map.span_to_snippet(head_span) {
err.span_suggestion(head_span, "consider adding a derive", format!("#[derive(Default)]\n{head}"), Applicability::MaybeIncorrect);
} else {
err.span_help(
head_span,
"consider adding `#[derive(Default)]` to this enum",
);
}
err.subdiagnostic(ConsiderAddingADerive {
span: head_span.shrink_to_lo(),
suggestion: format!("#[derive(Default)]\n")
});
}
for ns in [Namespace::MacroNS, Namespace::TypeNS, Namespace::ValueNS] {
if let Ok(binding) = self.early_resolve_ident_in_lexical_scope(
Expand Down
60 changes: 60 additions & 0 deletions compiler/rustc_resolve/src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -586,3 +586,63 @@ pub(crate) enum ParamKindInEnumDiscriminant {
#[note(resolve_lifetime_param_in_enum_discriminant)]
Lifetime,
}

#[derive(Subdiagnostic)]
#[label(resolve_change_import_binding)]
pub(crate) struct ChangeImportBinding {
#[primary_span]
pub(crate) span: Span,
}

#[derive(Subdiagnostic)]
#[suggestion(
resolve_change_import_binding,
code = "{suggestion}",
applicability = "maybe-incorrect"
)]
pub(crate) struct ChangeImportBindingSuggestion {
#[primary_span]
pub(crate) span: Span,
pub(crate) suggestion: String,
}

#[derive(Diagnostic)]
#[diag(resolve_imports_cannot_refer_to)]
pub(crate) struct ImportsCannotReferTo<'a> {
#[primary_span]
pub(crate) span: Span,
pub(crate) what: &'a str,
}

#[derive(Diagnostic)]
#[diag(resolve_cannot_find_ident_in_this_scope)]
pub(crate) struct CannotFindIdentInThisScope<'a> {
#[primary_span]
pub(crate) span: Span,
pub(crate) expected: &'a str,
pub(crate) ident: Ident,
}

#[derive(Subdiagnostic)]
#[note(resolve_explicit_unsafe_traits)]
pub(crate) struct ExplicitUnsafeTraits {
#[primary_span]
pub(crate) span: Span,
pub(crate) ident: Ident,
}

#[derive(Subdiagnostic)]
#[help(resolve_added_macro_use)]
pub(crate) struct AddedMacroUse;

#[derive(Subdiagnostic)]
#[suggestion(
resolve_consider_adding_a_derive,
code = "{suggestion}",
applicability = "maybe-incorrect"
)]
pub(crate) struct ConsiderAddingADerive {
#[primary_span]
pub(crate) span: Span,
pub(crate) suggestion: String,
}
6 changes: 4 additions & 2 deletions compiler/rustc_resolve/src/late.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
//! If you wonder why there's no `early.rs`, that's because it's split into three files -
//! `build_reduced_graph.rs`, `macros.rs` and `imports.rs`.

use crate::errors::ImportsCannotReferTo;
use crate::BindingKey;
use crate::{path_names_to_string, rustdoc, BindingError, Finalize, LexicalScopeBinding};
use crate::{Module, ModuleOrUniformRoot, NameBinding, ParentScope, PathResult};
Expand Down Expand Up @@ -2244,12 +2245,13 @@ impl<'a: 'ast, 'b, 'ast, 'tcx> LateResolutionVisitor<'a, 'b, 'ast, 'tcx> {
_ => &[TypeNS],
};
let report_error = |this: &Self, ns| {
let what = if ns == TypeNS { "type parameters" } else { "local variables" };
if this.should_report_errs() {
let what = if ns == TypeNS { "type parameters" } else { "local variables" };
this.r
.tcx
.sess
.span_err(ident.span, format!("imports cannot refer to {}", what));
.create_err(ImportsCannotReferTo { span: ident.span, what })
.emit();
}
};

Expand Down
13 changes: 10 additions & 3 deletions compiler/rustc_resolve/src/macros.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
//! A bunch of methods and structures more or less related to resolving macros and
//! interface provided by `Resolver` to macro expander.

use crate::errors::{self, AddAsNonDerive, MacroExpectedFound, RemoveSurroundingDerive};
use crate::errors::{
self, AddAsNonDerive, CannotFindIdentInThisScope, MacroExpectedFound, RemoveSurroundingDerive,
};
use crate::Namespace::*;
use crate::{BuiltinMacroState, Determinacy};
use crate::{DeriveData, Finalize, ParentScope, ResolutionError, Resolver, ScopeSet};
Expand Down Expand Up @@ -793,8 +795,13 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
}
Err(..) => {
let expected = kind.descr_expected();
let msg = format!("cannot find {} `{}` in this scope", expected, ident);
let mut err = self.tcx.sess.struct_span_err(ident.span, msg);

let mut err = self.tcx.sess.create_err(CannotFindIdentInThisScope {
span: ident.span,
expected,
ident,
});

self.unresolved_macro_suggestions(&mut err, kind, &parent_scope, ident, krate);
err.emit();
}
Expand Down
17 changes: 10 additions & 7 deletions compiler/rustc_span/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,11 +65,11 @@ use rustc_data_structures::sync::{Lock, Lrc};

use std::borrow::Cow;
use std::cmp::{self, Ordering};
use std::fmt;
use std::hash::Hash;
use std::ops::{Add, Range, Sub};
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::{fmt, iter};

use md5::Digest;
use md5::Md5;
Expand Down Expand Up @@ -733,12 +733,15 @@ impl Span {
/// else returns the `ExpnData` for the macro definition
/// corresponding to the source callsite.
pub fn source_callee(self) -> Option<ExpnData> {
fn source_callee(expn_data: ExpnData) -> ExpnData {
let next_expn_data = expn_data.call_site.ctxt().outer_expn_data();
if !next_expn_data.is_root() { source_callee(next_expn_data) } else { expn_data }
}
let expn_data = self.ctxt().outer_expn_data();
if !expn_data.is_root() { Some(source_callee(expn_data)) } else { None }

// Create an iterator of call site expansions
iter::successors(Some(expn_data), |expn_data| {
Some(expn_data.call_site.ctxt().outer_expn_data())
})
// Find the last expansion which is not root
.take_while(|expn_data| !expn_data.is_root())
.last()
}

/// Checks if a span is "internal" to a macro in which `#[unstable]`
Expand Down Expand Up @@ -777,7 +780,7 @@ impl Span {

pub fn macro_backtrace(mut self) -> impl Iterator<Item = ExpnData> {
let mut prev_span = DUMMY_SP;
std::iter::from_fn(move || {
iter::from_fn(move || {
loop {
let expn_data = self.ctxt().outer_expn_data();
if expn_data.is_root() {
Expand Down
8 changes: 6 additions & 2 deletions compiler/rustc_trait_selection/src/traits/query/normalize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -322,8 +322,12 @@ impl<'cx, 'tcx> FallibleTypeFolder<TyCtxt<'tcx>> for QueryNormalizer<'cx, 'tcx>
};
// `tcx.normalize_projection_ty` may normalize to a type that still has
// unevaluated consts, so keep normalizing here if that's the case.
if res != ty && res.has_type_flags(ty::TypeFlags::HAS_CT_PROJECTION) {
res.try_super_fold_with(self)?
// Similarly, `tcx.normalize_weak_ty` will only unwrap one layer of type
// and we need to continue folding it to reveal the TAIT behind it.
if res != ty
&& (res.has_type_flags(ty::TypeFlags::HAS_CT_PROJECTION) || kind == ty::Weak)
{
res.try_fold_with(self)?
} else {
res
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -417,17 +417,15 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
// Fast path to avoid evaluating an obligation that trivially holds.
// There may be more bounds, but these are checked by the regular path.
ty::FnPtr(..) => return false,

// These may potentially implement `FnPtr`
ty::Placeholder(..)
| ty::Dynamic(_, _, _)
| ty::Alias(_, _)
| ty::Infer(_)
| ty::Param(..) => {}
| ty::Param(..)
| ty::Bound(_, _) => {}

ty::Bound(_, _) => span_bug!(
obligation.cause.span(),
"cannot have escaping bound var in self type of {obligation:#?}"
),
// These can't possibly implement `FnPtr` as they are concrete types
// and not `FnPtr`
ty::Bool
Expand Down
4 changes: 2 additions & 2 deletions library/core/src/cell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1374,7 +1374,7 @@ impl Clone for BorrowRef<'_> {
debug_assert!(is_reading(borrow));
// Prevent the borrow counter from overflowing into
// a writing borrow.
assert!(borrow != isize::MAX);
assert!(borrow != BorrowFlag::MAX);
self.borrow.set(borrow + 1);
BorrowRef { borrow: self.borrow }
}
Expand Down Expand Up @@ -1756,7 +1756,7 @@ impl<'b> BorrowRefMut<'b> {
let borrow = self.borrow.get();
debug_assert!(is_writing(borrow));
// Prevent the borrow counter from underflowing.
assert!(borrow != isize::MIN);
assert!(borrow != BorrowFlag::MIN);
self.borrow.set(borrow - 1);
BorrowRefMut { borrow: self.borrow }
}
Expand Down
Loading

0 comments on commit fe7454b

Please sign in to comment.