Skip to content

Commit

Permalink
Auto merge of rust-lang#130237 - matthiaskrgr:rollup-qmgr8i7, r=matth…
Browse files Browse the repository at this point in the history
…iaskrgr

Rollup of 9 pull requests

Successful merges:

 - rust-lang#129260 (Don't suggest adding return type for closures with default return type)
 - rust-lang#129520 (Suggest the correct pattern syntax on usage of unit variant pattern for a struct variant)
 - rust-lang#129866 (Clarify documentation labelling and definitions for std::collections)
 - rust-lang#130123 (Report the `note` when specified in `diagnostic::on_unimplemented`)
 - rust-lang#130161 (refactor merge base logic and fix `x fmt`)
 - rust-lang#130206 (Map `WSAEDQUOT` to `ErrorKind::FilesystemQuotaExceeded`)
 - rust-lang#130207 (Map `ERROR_CANT_RESOLVE_FILENAME` to `ErrorKind::FilesystemLoop`)
 - rust-lang#130219 (Fix false positive with `missing_docs` and `#[test]`)
 - rust-lang#130221 (Make SearchPath::new public)

r? `@ghost`
`@rustbot` modify labels: rollup
  • Loading branch information
bors committed Sep 11, 2024
2 parents 5bce6d4 + 678c249 commit 8d6b88b
Show file tree
Hide file tree
Showing 43 changed files with 354 additions and 171 deletions.
2 changes: 2 additions & 0 deletions compiler/rustc_builtin_macros/src/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,8 @@ pub(crate) fn expand_test_or_bench(
cx.attr_nested_word(sym::cfg, sym::test, attr_sp),
// #[rustc_test_marker = "test_case_sort_key"]
cx.attr_name_value_str(sym::rustc_test_marker, test_path_symbol, attr_sp),
// #[doc(hidden)]
cx.attr_nested_word(sym::doc, sym::hidden, attr_sp),
],
// const $ident: test::TestDescAndFn =
ast::ItemKind::Const(
Expand Down
6 changes: 3 additions & 3 deletions compiler/rustc_builtin_macros/src/test_harness.rs
Original file line number Diff line number Diff line change
Expand Up @@ -326,8 +326,8 @@ fn mk_main(cx: &mut TestCtxt<'_>) -> P<ast::Item> {
let main_attr = ecx.attr_word(sym::rustc_main, sp);
// #[coverage(off)]
let coverage_attr = ecx.attr_nested_word(sym::coverage, sym::off, sp);
// #[allow(missing_docs)]
let missing_docs_attr = ecx.attr_nested_word(sym::allow, sym::missing_docs, sp);
// #[doc(hidden)]
let doc_hidden_attr = ecx.attr_nested_word(sym::doc, sym::hidden, sp);

// pub fn main() { ... }
let main_ret_ty = ecx.ty(sp, ast::TyKind::Tup(ThinVec::new()));
Expand Down Expand Up @@ -357,7 +357,7 @@ fn mk_main(cx: &mut TestCtxt<'_>) -> P<ast::Item> {

let main = P(ast::Item {
ident: main_id,
attrs: thin_vec![main_attr, coverage_attr, missing_docs_attr],
attrs: thin_vec![main_attr, coverage_attr, doc_hidden_attr],
id: ast::DUMMY_NODE_ID,
kind: main,
vis: ast::Visibility { span: sp, kind: ast::VisibilityKind::Public, tokens: None },
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_hir_typeck/src/_match.rs
Original file line number Diff line number Diff line change
Expand Up @@ -389,7 +389,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
{
// check that the `if` expr without `else` is the fn body's expr
if expr.span == sp {
return self.get_fn_decl(hir_id).map(|(_, fn_decl, _)| {
return self.get_fn_decl(hir_id).map(|(_, fn_decl)| {
let (ty, span) = match fn_decl.output {
hir::FnRetTy::DefaultReturn(span) => ("()".to_string(), span),
hir::FnRetTy::Return(ty) => (ty_to_string(&self.tcx, ty), ty.span),
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_hir_typeck/src/coercion.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1860,10 +1860,10 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> {
};

// If this is due to an explicit `return`, suggest adding a return type.
if let Some((fn_id, fn_decl, can_suggest)) = fcx.get_fn_decl(block_or_return_id)
if let Some((fn_id, fn_decl)) = fcx.get_fn_decl(block_or_return_id)
&& !due_to_block
{
fcx.suggest_missing_return_type(&mut err, fn_decl, expected, found, can_suggest, fn_id);
fcx.suggest_missing_return_type(&mut err, fn_decl, expected, found, fn_id);
}

// If this is due to a block, then maybe we forgot a `return`/`break`.
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_hir_typeck/src/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -774,7 +774,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
self.ret_coercion_span.set(Some(expr.span));
}
let cause = self.cause(expr.span, ObligationCauseCode::ReturnNoExpression);
if let Some((_, fn_decl, _)) = self.get_fn_decl(expr.hir_id) {
if let Some((_, fn_decl)) = self.get_fn_decl(expr.hir_id) {
coercion.coerce_forced_unit(
self,
&cause,
Expand Down
39 changes: 13 additions & 26 deletions compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ use rustc_middle::{bug, span_bug};
use rustc_session::lint;
use rustc_span::def_id::LocalDefId;
use rustc_span::hygiene::DesugaringKind;
use rustc_span::symbol::{kw, sym};
use rustc_span::symbol::kw;
use rustc_span::Span;
use rustc_target::abi::FieldIdx;
use rustc_trait_selection::error_reporting::infer::need_type_info::TypeAnnotationNeeded;
Expand Down Expand Up @@ -859,38 +859,28 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
)
}

/// Given a `HirId`, return the `HirId` of the enclosing function, its `FnDecl`, and whether a
/// suggestion can be made, `None` otherwise.
/// Given a `HirId`, return the `HirId` of the enclosing function and its `FnDecl`.
pub(crate) fn get_fn_decl(
&self,
blk_id: HirId,
) -> Option<(LocalDefId, &'tcx hir::FnDecl<'tcx>, bool)> {
) -> Option<(LocalDefId, &'tcx hir::FnDecl<'tcx>)> {
// Get enclosing Fn, if it is a function or a trait method, unless there's a `loop` or
// `while` before reaching it, as block tail returns are not available in them.
self.tcx.hir().get_fn_id_for_return_block(blk_id).and_then(|item_id| {
match self.tcx.hir_node(item_id) {
Node::Item(&hir::Item {
ident,
kind: hir::ItemKind::Fn(ref sig, ..),
owner_id,
..
}) => {
// This is less than ideal, it will not suggest a return type span on any
// method called `main`, regardless of whether it is actually the entry point,
// but it will still present it as the reason for the expected type.
Some((owner_id.def_id, sig.decl, ident.name != sym::main))
}
kind: hir::ItemKind::Fn(ref sig, ..), owner_id, ..
}) => Some((owner_id.def_id, sig.decl)),
Node::TraitItem(&hir::TraitItem {
kind: hir::TraitItemKind::Fn(ref sig, ..),
owner_id,
..
}) => Some((owner_id.def_id, sig.decl, true)),
// FIXME: Suggestable if this is not a trait implementation
}) => Some((owner_id.def_id, sig.decl)),
Node::ImplItem(&hir::ImplItem {
kind: hir::ImplItemKind::Fn(ref sig, ..),
owner_id,
..
}) => Some((owner_id.def_id, sig.decl, false)),
}) => Some((owner_id.def_id, sig.decl)),
Node::Expr(&hir::Expr {
hir_id,
kind: hir::ExprKind::Closure(&hir::Closure { def_id, kind, fn_decl, .. }),
Expand All @@ -901,33 +891,30 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
// FIXME(async_closures): Implement this.
return None;
}
hir::ClosureKind::Closure => Some((def_id, fn_decl, true)),
hir::ClosureKind::Closure => Some((def_id, fn_decl)),
hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
_,
hir::CoroutineSource::Fn,
)) => {
let (ident, sig, owner_id) = match self.tcx.parent_hir_node(hir_id) {
let (sig, owner_id) = match self.tcx.parent_hir_node(hir_id) {
Node::Item(&hir::Item {
ident,
kind: hir::ItemKind::Fn(ref sig, ..),
owner_id,
..
}) => (ident, sig, owner_id),
}) => (sig, owner_id),
Node::TraitItem(&hir::TraitItem {
ident,
kind: hir::TraitItemKind::Fn(ref sig, ..),
owner_id,
..
}) => (ident, sig, owner_id),
}) => (sig, owner_id),
Node::ImplItem(&hir::ImplItem {
ident,
kind: hir::ImplItemKind::Fn(ref sig, ..),
owner_id,
..
}) => (ident, sig, owner_id),
}) => (sig, owner_id),
_ => return None,
};
Some((owner_id.def_id, sig.decl, ident.name != sym::main))
Some((owner_id.def_id, sig.decl))
}
_ => None,
}
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1873,7 +1873,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
// that highlight errors inline.
let mut sp = blk.span;
let mut fn_span = None;
if let Some((fn_def_id, decl, _)) = self.get_fn_decl(blk.hir_id) {
if let Some((fn_def_id, decl)) = self.get_fn_decl(blk.hir_id) {
let ret_sp = decl.output.span();
if let Some(block_sp) = self.parent_item_span(blk.hir_id) {
// HACK: on some cases (`ui/liveness/liveness-issue-2163.rs`) the
Expand Down
49 changes: 36 additions & 13 deletions compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,9 +79,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
// `break` type mismatches provide better context for tail `loop` expressions.
return false;
}
if let Some((fn_id, fn_decl, can_suggest)) = self.get_fn_decl(blk_id) {
if let Some((fn_id, fn_decl)) = self.get_fn_decl(blk_id) {
pointing_at_return_type =
self.suggest_missing_return_type(err, fn_decl, expected, found, can_suggest, fn_id);
self.suggest_missing_return_type(err, fn_decl, expected, found, fn_id);
self.suggest_missing_break_or_return_expr(
err, expr, fn_decl, expected, found, blk_id, fn_id,
);
Expand Down Expand Up @@ -813,7 +813,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
fn_decl: &hir::FnDecl<'tcx>,
expected: Ty<'tcx>,
found: Ty<'tcx>,
can_suggest: bool,
fn_id: LocalDefId,
) -> bool {
// Can't suggest `->` on a block-like coroutine
Expand All @@ -826,28 +825,26 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let found =
self.resolve_numeric_literals_with_default(self.resolve_vars_if_possible(found));
// Only suggest changing the return type for methods that
// haven't set a return type at all (and aren't `fn main()` or an impl).
// haven't set a return type at all (and aren't `fn main()`, impl or closure).
match &fn_decl.output {
&hir::FnRetTy::DefaultReturn(span) if expected.is_unit() && !can_suggest => {
// `fn main()` must return `()`, do not suggest changing return type
err.subdiagnostic(errors::ExpectedReturnTypeLabel::Unit { span });
return true;
}
// For closure with default returns, don't suggest adding return type
&hir::FnRetTy::DefaultReturn(_) if self.tcx.is_closure_like(fn_id.to_def_id()) => {}
&hir::FnRetTy::DefaultReturn(span) if expected.is_unit() => {
if let Some(found) = found.make_suggestable(self.tcx, false, None) {
if !self.can_add_return_type(fn_id) {
err.subdiagnostic(errors::ExpectedReturnTypeLabel::Unit { span });
} else if let Some(found) = found.make_suggestable(self.tcx, false, None) {
err.subdiagnostic(errors::AddReturnTypeSuggestion::Add {
span,
found: found.to_string(),
});
return true;
} else if let Some(sugg) = suggest_impl_trait(self, self.param_env, found) {
err.subdiagnostic(errors::AddReturnTypeSuggestion::Add { span, found: sugg });
return true;
} else {
// FIXME: if `found` could be `impl Iterator` we should suggest that.
err.subdiagnostic(errors::AddReturnTypeSuggestion::MissingHere { span });
return true;
}

return true;
}
hir::FnRetTy::Return(hir_ty) => {
if let hir::TyKind::OpaqueDef(item_id, ..) = hir_ty.kind
Expand Down Expand Up @@ -905,6 +902,32 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
false
}

/// Checks whether we can add a return type to a function.
/// Assumes given function doesn't have a explicit return type.
fn can_add_return_type(&self, fn_id: LocalDefId) -> bool {
match self.tcx.hir_node_by_def_id(fn_id) {
Node::Item(&hir::Item { ident, .. }) => {
// This is less than ideal, it will not suggest a return type span on any
// method called `main`, regardless of whether it is actually the entry point,
// but it will still present it as the reason for the expected type.
ident.name != sym::main
}
Node::ImplItem(item) => {
// If it doesn't impl a trait, we can add a return type
let Node::Item(&hir::Item {
kind: hir::ItemKind::Impl(&hir::Impl { of_trait, .. }),
..
}) = self.tcx.parent_hir_node(item.hir_id())
else {
unreachable!();
};

of_trait.is_none()
}
_ => true,
}
}

fn try_note_caller_chooses_ty_for_ty_param(
&self,
diag: &mut Diag<'_>,
Expand Down
32 changes: 31 additions & 1 deletion compiler/rustc_hir_typeck/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ pub use coercion::can_coerce;
use fn_ctxt::FnCtxt;
use rustc_data_structures::unord::UnordSet;
use rustc_errors::codes::*;
use rustc_errors::{struct_span_code_err, Applicability, ErrorGuaranteed};
use rustc_errors::{pluralize, struct_span_code_err, Applicability, ErrorGuaranteed};
use rustc_hir as hir;
use rustc_hir::def::{DefKind, Res};
use rustc_hir::intravisit::Visitor;
Expand Down Expand Up @@ -423,6 +423,36 @@ fn report_unexpected_variant_res(
err.multipart_suggestion_verbose(descr, suggestion, Applicability::MaybeIncorrect);
err
}
Res::Def(DefKind::Variant, _) if expr.is_none() => {
err.span_label(span, format!("not a {expected}"));

let fields = &tcx.expect_variant_res(res).fields.raw;
let span = qpath.span().shrink_to_hi().to(span.shrink_to_hi());
let (msg, sugg) = if fields.is_empty() {
("use the struct variant pattern syntax".to_string(), " {}".to_string())
} else {
let msg = format!(
"the struct variant's field{s} {are} being ignored",
s = pluralize!(fields.len()),
are = pluralize!("is", fields.len())
);
let fields = fields
.iter()
.map(|field| format!("{}: _", field.name.to_ident_string()))
.collect::<Vec<_>>()
.join(", ");
let sugg = format!(" {{ {} }}", fields);
(msg, sugg)
};

err.span_suggestion_verbose(
qpath.span().shrink_to_hi().to(span.shrink_to_hi()),
msg,
sugg,
Applicability::HasPlaceholders,
);
err
}
_ => err.with_span_label(span, format!("not a {expected}")),
}
.emit()
Expand Down
14 changes: 9 additions & 5 deletions compiler/rustc_hir_typeck/src/method/suggest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1317,7 +1317,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let actual_prefix = rcvr_ty.prefix_string(self.tcx);
info!("unimplemented_traits.len() == {}", unimplemented_traits.len());
let mut long_ty_file = None;
let (primary_message, label) = if unimplemented_traits.len() == 1
let (primary_message, label, notes) = if unimplemented_traits.len() == 1
&& unimplemented_traits_only
{
unimplemented_traits
Expand All @@ -1327,16 +1327,16 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
if trait_ref.self_ty().references_error() || rcvr_ty.references_error()
{
// Avoid crashing.
return (None, None);
return (None, None, Vec::new());
}
let OnUnimplementedNote { message, label, .. } = self
let OnUnimplementedNote { message, label, notes, .. } = self
.err_ctxt()
.on_unimplemented_note(trait_ref, &obligation, &mut long_ty_file);
(message, label)
(message, label, notes)
})
.unwrap()
} else {
(None, None)
(None, None, Vec::new())
};
let primary_message = primary_message.unwrap_or_else(|| {
format!(
Expand All @@ -1363,6 +1363,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
"the following trait bounds were not satisfied:\n{bound_list}"
));
}
for note in notes {
err.note(note);
}

suggested_derive = self.suggest_derive(&mut err, unsatisfied_predicates);

unsatisfied_bounds = true;
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_session/src/search_paths.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ impl SearchPath {
Self::new(PathKind::All, make_target_lib_path(sysroot, triple))
}

fn new(kind: PathKind, dir: PathBuf) -> Self {
pub fn new(kind: PathKind, dir: PathBuf) -> Self {
// Get the files within the directory.
let files = match std::fs::read_dir(&dir) {
Ok(files) => files
Expand Down
1 change: 0 additions & 1 deletion compiler/rustc_span/src/symbol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1236,7 +1236,6 @@ symbols! {
mir_unwind_unreachable,
mir_variant,
miri,
missing_docs,
mmx_reg,
modifiers,
module,
Expand Down
Loading

0 comments on commit 8d6b88b

Please sign in to comment.