authorbors <bors@rust-lang.org> 2026-04-20 16:15:13 UTC
committerbors <bors@rust-lang.org> 2026-04-20 16:15:13 UTC
logc28e3037785af39226f5751294ed1c6cf4698e10
treefdc2387b3731e94bb04928e73d92cdd6a6374da7
parent91367b0f73196f0d133066e0e9363da339ed87b5
parent02dda7315ab10a63771b0e17d21cad823e61eed4

Auto merge of #155552 - JonathanBrouwer:rollup-JKIpTuW, r=JonathanBrouwer

Rollup of 11 pull requests Successful merges: - rust-lang/rust#154654 (Move `std::io::ErrorKind` to `core::io`) - rust-lang/rust#145270 (Fix an ICE observed with an explicit tail-call in a default trait method) - rust-lang/rust#154895 (borrowck: Apply `user_arg_index` nomenclature more broadly) - rust-lang/rust#155213 (resolve: Make sure visibilities of import declarations make sense) - rust-lang/rust#155346 (`single_use_lifetimes`: respect `anonymous_lifetime_in_impl_trait`) - rust-lang/rust#155517 (Add a test for Mach-O `#[link_section]` API inherited from LLVM) - rust-lang/rust#155549 (Remove some unnecessary lifetimes.) - rust-lang/rust#154248 (resolve : mark repr_simd as internal) - rust-lang/rust#154772 (slightly optimize the `non-camel-case-types` lint) - rust-lang/rust#155541 (Add `#[rust_analyzer::prefer_underscore_import]` to the traits in `rustc_type_ir::inherent`) - rust-lang/rust#155544 (bootstrap: Make "detected modifications" for download-rustc less verbose)

55 files changed, 1142 insertions(+), 605 deletions(-)

compiler/rustc_borrowck/src/diagnostics/region_name.rs+7-6
......@@ -499,18 +499,18 @@ impl<'tcx> MirBorrowckCtxt<'_, '_, 'tcx> {
499499 fr: RegionVid,
500500 ) -> Option<RegionName> {
501501 let implicit_inputs = self.regioncx.universal_regions().defining_ty.implicit_inputs();
502 let argument_index = self.regioncx.get_argument_index_for_region(self.infcx.tcx, fr)?;
502 let user_arg_index = self.regioncx.get_user_arg_index_for_region(self.infcx.tcx, fr)?;
503503
504504 let arg_ty = self.regioncx.universal_regions().unnormalized_input_tys
505 [implicit_inputs + argument_index];
505 [implicit_inputs + user_arg_index];
506506 let (_, span) = self.regioncx.get_argument_name_and_span_for_region(
507507 self.body,
508508 self.local_names(),
509 argument_index,
509 user_arg_index,
510510 );
511511
512512 let highlight = self
513 .get_argument_hir_ty_for_highlighting(argument_index)
513 .get_argument_hir_ty_for_highlighting(user_arg_index)
514514 .and_then(|arg_hir_ty| self.highlight_if_we_can_match_hir_ty(fr, arg_ty, arg_hir_ty))
515515 .unwrap_or_else(|| {
516516 // `highlight_if_we_cannot_match_hir_ty` needs to know the number we will give to
......@@ -528,10 +528,11 @@ impl<'tcx> MirBorrowckCtxt<'_, '_, 'tcx> {
528528
529529 fn get_argument_hir_ty_for_highlighting(
530530 &self,
531 argument_index: usize,
531 user_arg_index: usize,
532532 ) -> Option<&hir::Ty<'tcx>> {
533533 let fn_decl = self.infcx.tcx.hir_fn_decl_by_hir_id(self.mir_hir_id())?;
534 let argument_hir_ty: &hir::Ty<'_> = fn_decl.inputs.get(argument_index)?;
534 // Closures don't have implicit self arguments in HIR, so use `user_arg_index` directly.
535 let argument_hir_ty: &hir::Ty<'_> = fn_decl.inputs.get(user_arg_index)?;
535536 match argument_hir_ty.kind {
536537 // This indicates a variable with no type annotation, like
537538 // `|x|`... in that case, we can't highlight the type but
compiler/rustc_borrowck/src/diagnostics/var_name.rs+9-9
......@@ -31,7 +31,7 @@ impl<'tcx> RegionInferenceContext<'tcx> {
3131 })
3232 .or_else(|| {
3333 debug!("get_var_name_and_span_for_region: attempting argument");
34 self.get_argument_index_for_region(tcx, fr).and_then(|index| {
34 self.get_user_arg_index_for_region(tcx, fr).and_then(|index| {
3535 let local = self.user_arg_index_to_local(body, index);
3636 if body_uses_local(body, local) {
3737 Some(self.get_argument_name_and_span_for_region(body, local_names, index))
......@@ -93,26 +93,26 @@ impl<'tcx> RegionInferenceContext<'tcx> {
9393 ///
9494 /// N.B., in the case of a closure, the index is indexing into the signature as seen by the
9595 /// user - in particular, index 0 is not the implicit self parameter.
96 pub(crate) fn get_argument_index_for_region(
96 pub(crate) fn get_user_arg_index_for_region(
9797 &self,
9898 tcx: TyCtxt<'tcx>,
9999 fr: RegionVid,
100100 ) -> Option<usize> {
101101 let implicit_inputs = self.universal_regions().defining_ty.implicit_inputs();
102 let argument_index =
102 let user_arg_index =
103103 self.universal_regions().unnormalized_input_tys.iter().skip(implicit_inputs).position(
104104 |arg_ty| {
105 debug!("get_argument_index_for_region: arg_ty = {arg_ty:?}");
105 debug!("get_user_arg_index_for_region: arg_ty = {arg_ty:?}");
106106 tcx.any_free_region_meets(arg_ty, |r| r.as_var() == fr)
107107 },
108108 )?;
109109
110110 debug!(
111 "get_argument_index_for_region: found {fr:?} in argument {argument_index} which has type {:?}",
112 self.universal_regions().unnormalized_input_tys[argument_index],
111 "get_user_arg_index_for_region: found {fr:?} in argument {user_arg_index} which has type {:?}",
112 self.universal_regions().unnormalized_input_tys[user_arg_index],
113113 );
114114
115 Some(argument_index)
115 Some(user_arg_index)
116116 }
117117
118118 /// Given the index of an argument as seen from the user (i.e. excluding
......@@ -128,9 +128,9 @@ impl<'tcx> RegionInferenceContext<'tcx> {
128128 &self,
129129 body: &Body<'tcx>,
130130 local_names: &IndexSlice<Local, Option<Symbol>>,
131 argument_index: usize,
131 user_arg_index: usize,
132132 ) -> (Option<Symbol>, Span) {
133 let argument_local = self.user_arg_index_to_local(body, argument_index);
133 let argument_local = self.user_arg_index_to_local(body, user_arg_index);
134134 debug!("get_argument_name_and_span_for_region: argument_local={argument_local:?}");
135135
136136 let argument_name = local_names[argument_local];
compiler/rustc_borrowck/src/polonius/dump.rs+2-2
......@@ -107,7 +107,7 @@ impl LocalizedConstraintGraphVisitor for LocalizedOutlivesConstraintCollector {
107107/// - a mermaid graph of the NLL regions and the constraints between them
108108/// - a mermaid graph of the NLL SCCs and the constraints between them
109109fn emit_polonius_dump<'tcx>(
110 dumper: &MirDumper<'_, '_, 'tcx>,
110 dumper: &MirDumper<'_, 'tcx>,
111111 body: &Body<'tcx>,
112112 regioncx: &RegionInferenceContext<'tcx>,
113113 borrow_set: &BorrowSet<'tcx>,
......@@ -186,7 +186,7 @@ fn emit_polonius_dump<'tcx>(
186186
187187/// Emits the polonius MIR, as escaped HTML.
188188fn emit_html_mir<'tcx>(
189 dumper: &MirDumper<'_, '_, 'tcx>,
189 dumper: &MirDumper<'_, 'tcx>,
190190 body: &Body<'tcx>,
191191 out: &mut dyn io::Write,
192192) -> io::Result<()> {
compiler/rustc_borrowck/src/universal_regions.rs+3
......@@ -79,6 +79,9 @@ pub(crate) struct UniversalRegions<'tcx> {
7979 ///
8080 /// N.B., associated types in these types have not been normalized,
8181 /// as the name suggests. =)
82 ///
83 /// N.B., in the case of a closure, index 0 is the implicit self parameter,
84 /// and not the first input as seen by the user.
8285 pub unnormalized_input_tys: &'tcx [Ty<'tcx>],
8386
8487 pub yield_ty: Option<Ty<'tcx>>,
compiler/rustc_feature/src/unstable.rs+2-2
......@@ -303,6 +303,8 @@ declare_features! (
303303 (internal, panic_runtime, "1.10.0", Some(32837)),
304304 /// Allows using pattern types.
305305 (internal, pattern_types, "1.79.0", Some(123646)),
306 /// Allows `repr(simd)` and importing the various simd intrinsics.
307 (internal, repr_simd, "1.4.0", Some(27731)),
306308 /// Allows using compiler's own crates.
307309 (unstable, rustc_private, "1.0.0", Some(27812)),
308310 /// Allows using internal rustdoc features like `doc(keyword)`.
......@@ -657,8 +659,6 @@ declare_features! (
657659 (incomplete, ref_pat_eat_one_layer_2024_structural, "1.81.0", Some(123076)),
658660 /// Allows using the `#[register_tool]` attribute.
659661 (unstable, register_tool, "1.41.0", Some(66079)),
660 /// Allows `repr(simd)` and importing the various simd intrinsics.
661 (unstable, repr_simd, "1.4.0", Some(27731)),
662662 /// Allows bounding the return type of AFIT/RPITIT.
663663 (unstable, return_type_notation, "1.70.0", Some(109417)),
664664 /// Target features on riscv.
compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs+27-27
......@@ -1901,14 +1901,14 @@ impl FnParam<'_> {
19011901 }
19021902}
19031903
1904struct FnCallDiagCtxt<'a, 'b, 'tcx> {
1905 arg_matching_ctxt: ArgMatchingCtxt<'a, 'b, 'tcx>,
1904struct FnCallDiagCtxt<'a, 'tcx> {
1905 arg_matching_ctxt: ArgMatchingCtxt<'a, 'tcx>,
19061906 errors: Vec<Error<'tcx>>,
19071907 matched_inputs: IndexVec<ExpectedIdx, Option<ProvidedIdx>>,
19081908}
19091909
1910impl<'a, 'b, 'tcx> Deref for FnCallDiagCtxt<'a, 'b, 'tcx> {
1911 type Target = ArgMatchingCtxt<'a, 'b, 'tcx>;
1910impl<'a, 'tcx> Deref for FnCallDiagCtxt<'a, 'tcx> {
1911 type Target = ArgMatchingCtxt<'a, 'tcx>;
19121912
19131913 fn deref(&self) -> &Self::Target {
19141914 &self.arg_matching_ctxt
......@@ -1921,9 +1921,9 @@ enum ArgumentsFormatting {
19211921 Multiline { fallback_indent: String, brace_indent: String },
19221922}
19231923
1924impl<'a, 'b, 'tcx> FnCallDiagCtxt<'a, 'b, 'tcx> {
1924impl<'a, 'tcx> FnCallDiagCtxt<'a, 'tcx> {
19251925 fn new(
1926 arg: &'a FnCtxt<'b, 'tcx>,
1926 arg: &'a FnCtxt<'a, 'tcx>,
19271927 compatibility_diagonal: IndexVec<ProvidedIdx, Compatibility<'tcx>>,
19281928 formal_and_expected_inputs: IndexVec<ExpectedIdx, (Ty<'tcx>, Ty<'tcx>)>,
19291929 provided_args: IndexVec<ProvidedIdx, &'tcx Expr<'tcx>>,
......@@ -2629,7 +2629,7 @@ impl<'a, 'b, 'tcx> FnCallDiagCtxt<'a, 'b, 'tcx> {
26292629 (suggestions, labels, suggestion_text)
26302630 }
26312631
2632 fn label_generic_mismatches(&self, err: &mut Diag<'b>) {
2632 fn label_generic_mismatches(&self, err: &mut Diag<'a>) {
26332633 self.fn_ctxt.label_generic_mismatches(
26342634 err,
26352635 self.fn_def_id,
......@@ -2805,22 +2805,22 @@ impl<'a, 'b, 'tcx> FnCallDiagCtxt<'a, 'b, 'tcx> {
28052805 }
28062806}
28072807
2808struct ArgMatchingCtxt<'a, 'b, 'tcx> {
2809 args_ctxt: ArgsCtxt<'a, 'b, 'tcx>,
2808struct ArgMatchingCtxt<'a, 'tcx> {
2809 args_ctxt: ArgsCtxt<'a, 'tcx>,
28102810 provided_arg_tys: IndexVec<ProvidedIdx, (Ty<'tcx>, Span)>,
28112811}
28122812
2813impl<'a, 'b, 'tcx> Deref for ArgMatchingCtxt<'a, 'b, 'tcx> {
2814 type Target = ArgsCtxt<'a, 'b, 'tcx>;
2813impl<'a, 'tcx> Deref for ArgMatchingCtxt<'a, 'tcx> {
2814 type Target = ArgsCtxt<'a, 'tcx>;
28152815
28162816 fn deref(&self) -> &Self::Target {
28172817 &self.args_ctxt
28182818 }
28192819}
28202820
2821impl<'a, 'b, 'tcx> ArgMatchingCtxt<'a, 'b, 'tcx> {
2821impl<'a, 'tcx> ArgMatchingCtxt<'a, 'tcx> {
28222822 fn new(
2823 arg: &'a FnCtxt<'b, 'tcx>,
2823 arg: &'a FnCtxt<'a, 'tcx>,
28242824 compatibility_diagonal: IndexVec<ProvidedIdx, Compatibility<'tcx>>,
28252825 formal_and_expected_inputs: IndexVec<ExpectedIdx, (Ty<'tcx>, Ty<'tcx>)>,
28262826 provided_args: IndexVec<ProvidedIdx, &'tcx Expr<'tcx>>,
......@@ -2951,23 +2951,23 @@ impl<'a, 'b, 'tcx> ArgMatchingCtxt<'a, 'b, 'tcx> {
29512951 }
29522952}
29532953
2954struct ArgsCtxt<'a, 'b, 'tcx> {
2955 call_ctxt: CallCtxt<'a, 'b, 'tcx>,
2954struct ArgsCtxt<'a, 'tcx> {
2955 call_ctxt: CallCtxt<'a, 'tcx>,
29562956 call_metadata: CallMetadata,
29572957 args_span: Span,
29582958}
29592959
2960impl<'a, 'b, 'tcx> Deref for ArgsCtxt<'a, 'b, 'tcx> {
2961 type Target = CallCtxt<'a, 'b, 'tcx>;
2960impl<'a, 'tcx> Deref for ArgsCtxt<'a, 'tcx> {
2961 type Target = CallCtxt<'a, 'tcx>;
29622962
29632963 fn deref(&self) -> &Self::Target {
29642964 &self.call_ctxt
29652965 }
29662966}
29672967
2968impl<'a, 'b, 'tcx> ArgsCtxt<'a, 'b, 'tcx> {
2968impl<'a, 'tcx> ArgsCtxt<'a, 'tcx> {
29692969 fn new(
2970 arg: &'a FnCtxt<'b, 'tcx>,
2970 arg: &'a FnCtxt<'a, 'tcx>,
29712971 compatibility_diagonal: IndexVec<ProvidedIdx, Compatibility<'tcx>>,
29722972 formal_and_expected_inputs: IndexVec<ExpectedIdx, (Ty<'tcx>, Ty<'tcx>)>,
29732973 provided_args: IndexVec<ProvidedIdx, &'tcx Expr<'tcx>>,
......@@ -2978,7 +2978,7 @@ impl<'a, 'b, 'tcx> ArgsCtxt<'a, 'b, 'tcx> {
29782978 call_expr: &'tcx Expr<'tcx>,
29792979 tuple_arguments: TupleArgumentsFlag,
29802980 ) -> Self {
2981 let call_ctxt: CallCtxt<'_, '_, '_> = CallCtxt::new(
2981 let call_ctxt: CallCtxt<'_, '_> = CallCtxt::new(
29822982 arg,
29832983 compatibility_diagonal,
29842984 formal_and_expected_inputs,
......@@ -3085,8 +3085,8 @@ struct CallMetadata {
30853085 is_method: bool,
30863086}
30873087
3088struct CallCtxt<'a, 'b, 'tcx> {
3089 fn_ctxt: &'a FnCtxt<'b, 'tcx>,
3088struct CallCtxt<'a, 'tcx> {
3089 fn_ctxt: &'a FnCtxt<'a, 'tcx>,
30903090 compatibility_diagonal: IndexVec<ProvidedIdx, Compatibility<'tcx>>,
30913091 formal_and_expected_inputs: IndexVec<ExpectedIdx, (Ty<'tcx>, Ty<'tcx>)>,
30923092 provided_args: IndexVec<ProvidedIdx, &'tcx hir::Expr<'tcx>>,
......@@ -3100,17 +3100,17 @@ struct CallCtxt<'a, 'b, 'tcx> {
31003100 callee_ty: Option<Ty<'tcx>>,
31013101}
31023102
3103impl<'a, 'b, 'tcx> Deref for CallCtxt<'a, 'b, 'tcx> {
3104 type Target = &'a FnCtxt<'b, 'tcx>;
3103impl<'a, 'tcx> Deref for CallCtxt<'a, 'tcx> {
3104 type Target = &'a FnCtxt<'a, 'tcx>;
31053105
31063106 fn deref(&self) -> &Self::Target {
31073107 &self.fn_ctxt
31083108 }
31093109}
31103110
3111impl<'a, 'b, 'tcx> CallCtxt<'a, 'b, 'tcx> {
3111impl<'a, 'tcx> CallCtxt<'a, 'tcx> {
31123112 fn new(
3113 fn_ctxt: &'a FnCtxt<'b, 'tcx>,
3113 fn_ctxt: &'a FnCtxt<'a, 'tcx>,
31143114 compatibility_diagonal: IndexVec<ProvidedIdx, Compatibility<'tcx>>,
31153115 formal_and_expected_inputs: IndexVec<ExpectedIdx, (Ty<'tcx>, Ty<'tcx>)>,
31163116 provided_args: IndexVec<ProvidedIdx, &'tcx hir::Expr<'tcx>>,
......@@ -3120,7 +3120,7 @@ impl<'a, 'b, 'tcx> CallCtxt<'a, 'b, 'tcx> {
31203120 call_span: Span,
31213121 call_expr: &'tcx hir::Expr<'tcx>,
31223122 tuple_arguments: TupleArgumentsFlag,
3123 ) -> CallCtxt<'a, 'b, 'tcx> {
3123 ) -> CallCtxt<'a, 'tcx> {
31243124 let callee_expr = match &call_expr.peel_blocks().kind {
31253125 hir::ExprKind::Call(callee, _) => Some(*callee),
31263126 hir::ExprKind::MethodCall(_, receiver, ..) => {
compiler/rustc_hir_typeck/src/method/prelude_edition_lints.rs+8-10
......@@ -16,15 +16,15 @@ use tracing::debug;
1616use crate::FnCtxt;
1717use crate::method::probe::{self, Pick};
1818
19struct AmbiguousTraitMethodCall<'a, 'b, 'tcx> {
19struct AmbiguousTraitMethodCall<'a, 'tcx> {
2020 segment_name: Symbol,
2121 self_expr_span: Span,
2222 pick: &'a Pick<'tcx>,
2323 tcx: TyCtxt<'tcx>,
24 edition: &'b str,
24 edition: &'static str,
2525}
2626
27impl<'a, 'b, 'c, 'tcx> Diagnostic<'a, ()> for AmbiguousTraitMethodCall<'b, 'c, 'tcx> {
27impl<'a, 'b, 'tcx> Diagnostic<'a, ()> for AmbiguousTraitMethodCall<'b, 'tcx> {
2828 fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, ()> {
2929 let Self { segment_name, self_expr_span, pick, tcx, edition } = self;
3030 let mut lint = Diag::new(
......@@ -80,20 +80,18 @@ impl<'a, 'b, 'c, 'tcx> Diagnostic<'a, ()> for AmbiguousTraitMethodCall<'b, 'c, '
8080 }
8181}
8282
83struct AmbiguousTraitMethod<'a, 'b, 'tcx, 'pcx, 'fnctx> {
84 segment: &'a hir::PathSegment<'pcx>,
83struct AmbiguousTraitMethod<'a, 'tcx, 'fnctx> {
84 segment: &'a hir::PathSegment<'tcx>,
8585 call_expr: &'tcx hir::Expr<'tcx>,
8686 self_expr: &'tcx hir::Expr<'tcx>,
8787 pick: &'a Pick<'tcx>,
8888 args: &'tcx [hir::Expr<'tcx>],
89 edition: &'b str,
89 edition: &'static str,
9090 span: Span,
9191 this: &'a FnCtxt<'fnctx, 'tcx>,
9292}
9393
94impl<'a, 'b, 'c, 'tcx, 'pcx, 'fnctx> Diagnostic<'a, ()>
95 for AmbiguousTraitMethod<'b, 'c, 'tcx, 'pcx, 'fnctx>
96{
94impl<'a, 'c, 'tcx, 'fnctx> Diagnostic<'a, ()> for AmbiguousTraitMethod<'c, 'tcx, 'fnctx> {
9795 fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, ()> {
9896 let Self { segment, call_expr, self_expr, pick, args, edition, span, this } = self;
9997 let mut lint = Diag::new(
......@@ -158,7 +156,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
158156 pub(super) fn lint_edition_dependent_dot_call(
159157 &self,
160158 self_ty: Ty<'tcx>,
161 segment: &hir::PathSegment<'_>,
159 segment: &hir::PathSegment<'tcx>,
162160 span: Span,
163161 call_expr: &'tcx hir::Expr<'tcx>,
164162 self_expr: &'tcx hir::Expr<'tcx>,
compiler/rustc_hir_typeck/src/upvar.rs+6-6
......@@ -958,15 +958,15 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
958958 capture_clause: hir::CaptureBy,
959959 span: Span,
960960 ) {
961 struct MigrationLint<'a, 'b, 'tcx> {
961 struct MigrationLint<'a, 'tcx> {
962962 closure_def_id: LocalDefId,
963 this: &'a FnCtxt<'b, 'tcx>,
963 this: &'a FnCtxt<'a, 'tcx>,
964964 body_id: hir::BodyId,
965965 need_migrations: Vec<NeededMigration>,
966966 migration_message: String,
967967 }
968968
969 impl<'a, 'b, 'c, 'tcx> Diagnostic<'a, ()> for MigrationLint<'b, 'c, 'tcx> {
969 impl<'a, 'b, 'tcx> Diagnostic<'a, ()> for MigrationLint<'b, 'tcx> {
970970 fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, ()> {
971971 let Self { closure_def_id, this, body_id, need_migrations, migration_message } =
972972 self;
......@@ -2084,8 +2084,8 @@ fn drop_location_span(tcx: TyCtxt<'_>, hir_id: HirId) -> Span {
20842084 tcx.sess.source_map().end_point(owner_span)
20852085}
20862086
2087struct InferBorrowKind<'fcx, 'a, 'tcx> {
2088 fcx: &'fcx FnCtxt<'a, 'tcx>,
2087struct InferBorrowKind<'a, 'tcx> {
2088 fcx: &'a FnCtxt<'a, 'tcx>,
20892089 // The def-id of the closure whose kind and upvar accesses are being inferred.
20902090 closure_def_id: LocalDefId,
20912091
......@@ -2119,7 +2119,7 @@ struct InferBorrowKind<'fcx, 'a, 'tcx> {
21192119 fake_reads: Vec<(Place<'tcx>, FakeReadCause, HirId)>,
21202120}
21212121
2122impl<'fcx, 'a, 'tcx> euv::Delegate<'tcx> for InferBorrowKind<'fcx, 'a, 'tcx> {
2122impl<'a, 'tcx> euv::Delegate<'tcx> for InferBorrowKind<'a, 'tcx> {
21232123 #[instrument(skip(self), level = "debug")]
21242124 fn fake_read(
21252125 &mut self,
compiler/rustc_lint/src/default_could_be_derived.rs+4-4
......@@ -156,15 +156,15 @@ impl<'tcx> LateLintPass<'tcx> for DefaultCouldBeDerived {
156156 }
157157}
158158
159struct WrongDefaultImpl<'a, 'hir, 'tcx> {
159struct WrongDefaultImpl<'a, 'tcx> {
160160 tcx: TyCtxt<'tcx>,
161161 type_def_id: DefId,
162 orig_fields: FxHashMap<Symbol, &'a hir::FieldDef<'hir>>,
163 fields: &'a [hir::ExprField<'hir>],
162 orig_fields: FxHashMap<Symbol, &'a hir::FieldDef<'tcx>>,
163 fields: &'a [hir::ExprField<'tcx>],
164164 impl_span: Span,
165165}
166166
167impl<'a, 'b, 'hir, 'tcx> Diagnostic<'a, ()> for WrongDefaultImpl<'b, 'hir, 'tcx> {
167impl<'a, 'b, 'tcx> Diagnostic<'a, ()> for WrongDefaultImpl<'b, 'tcx> {
168168 fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, ()> {
169169 let Self { tcx, type_def_id, orig_fields, fields, impl_span } = self;
170170 let mut diag =
compiler/rustc_lint/src/nonstandard_style.rs+14-18
......@@ -51,31 +51,27 @@ declare_lint_pass!(NonCamelCaseTypes => [NON_CAMEL_CASE_TYPES]);
5151/// be upper cased or lower cased. For the purposes of the lint suggestion, we care about being able
5252/// to change the char's case.
5353fn char_has_case(c: char) -> bool {
54 let mut l = c.to_lowercase();
55 let mut u = c.to_uppercase();
56 while let Some(l) = l.next() {
57 match u.next() {
58 Some(u) if l != u => return true,
59 _ => {}
60 }
61 }
62 u.next().is_some()
54 !c.to_lowercase().eq(c.to_uppercase())
55}
56
57// contains a capitalisable character followed by, or preceded by, an underscore
58fn has_underscore_case(s: &str) -> bool {
59 let mut last = '\0';
60 s.chars().any(|c| match (std::mem::replace(&mut last, c), c) {
61 ('_', cs) | (cs, '_') => char_has_case(cs),
62 _ => false,
63 })
6364}
6465
6566fn is_camel_case(name: &str) -> bool {
6667 let name = name.trim_matches('_');
67 if name.is_empty() {
68 let Some(first) = name.chars().next() else {
6869 return true;
69 }
70 };
7071
71 // start with a non-lowercase letter rather than non-uppercase
72 // start with a non-lowercase letter rather than uppercase
7273 // ones (some scripts don't have a concept of upper/lowercase)
73 !name.chars().next().unwrap().is_lowercase()
74 && !name.contains("__")
75 && !name.chars().collect::<Vec<_>>().array_windows().any(|&[fst, snd]| {
76 // contains a capitalisable character followed by, or preceded by, an underscore
77 char_has_case(fst) && snd == '_' || char_has_case(snd) && fst == '_'
78 })
74 !(first.is_lowercase() || name.contains("__") || has_underscore_case(name))
7975}
8076
8177fn to_camel_case(s: &str) -> String {
compiler/rustc_lint_defs/src/builtin.rs+1
......@@ -109,6 +109,7 @@ declare_lint_pass! {
109109 SHADOWING_SUPERTRAIT_ITEMS,
110110 SINGLE_USE_LIFETIMES,
111111 STABLE_FEATURES,
112 TAIL_CALL_TRACK_CALLER,
112113 TAIL_EXPR_DROP_ORDER,
113114 TEST_UNSTABLE_LINT,
114115 TEXT_DIRECTION_CODEPOINT_IN_COMMENT,
compiler/rustc_middle/src/mir/pretty.rs+10-10
......@@ -61,14 +61,14 @@ impl PrettyPrintMirOptions {
6161/// Manages MIR dumping, which is MIR writing done to a file with a specific name. In particular,
6262/// it makes it impossible to dump MIR to one of these files when it hasn't been requested from the
6363/// command line. Layered on top of `MirWriter`, which does the actual writing.
64pub struct MirDumper<'dis, 'de, 'tcx> {
64pub struct MirDumper<'a, 'tcx> {
6565 show_pass_num: bool,
6666 pass_name: &'static str,
67 disambiguator: &'dis dyn Display,
68 writer: MirWriter<'de, 'tcx>,
67 disambiguator: &'a dyn Display,
68 writer: MirWriter<'a, 'tcx>,
6969}
7070
71impl<'dis, 'de, 'tcx> MirDumper<'dis, 'de, 'tcx> {
71impl<'a, 'tcx> MirDumper<'a, 'tcx> {
7272 // If dumping should be performed (e.g. because it was requested on the
7373 // CLI), returns a `MirDumper` with default values for the following fields:
7474 // - `show_pass_num`: `false`
......@@ -112,7 +112,7 @@ impl<'dis, 'de, 'tcx> MirDumper<'dis, 'de, 'tcx> {
112112 }
113113
114114 #[must_use]
115 pub fn set_disambiguator(mut self, disambiguator: &'dis dyn Display) -> Self {
115 pub fn set_disambiguator(mut self, disambiguator: &'a dyn Display) -> Self {
116116 self.disambiguator = disambiguator;
117117 self
118118 }
......@@ -120,7 +120,7 @@ impl<'dis, 'de, 'tcx> MirDumper<'dis, 'de, 'tcx> {
120120 #[must_use]
121121 pub fn set_extra_data(
122122 mut self,
123 extra_data: &'de dyn Fn(PassWhere, &mut dyn io::Write) -> io::Result<()>,
123 extra_data: &'a dyn Fn(PassWhere, &mut dyn io::Write) -> io::Result<()>,
124124 ) -> Self {
125125 self.writer.extra_data = extra_data;
126126 self
......@@ -369,13 +369,13 @@ pub fn write_mir_pretty<'tcx>(
369369}
370370
371371/// Does the writing of MIR to output, e.g. a file.
372pub struct MirWriter<'de, 'tcx> {
372pub struct MirWriter<'a, 'tcx> {
373373 tcx: TyCtxt<'tcx>,
374 extra_data: &'de dyn Fn(PassWhere, &mut dyn io::Write) -> io::Result<()>,
374 extra_data: &'a dyn Fn(PassWhere, &mut dyn io::Write) -> io::Result<()>,
375375 options: PrettyPrintMirOptions,
376376}
377377
378impl<'de, 'tcx> MirWriter<'de, 'tcx> {
378impl<'a, 'tcx> MirWriter<'a, 'tcx> {
379379 pub fn new(tcx: TyCtxt<'tcx>) -> Self {
380380 MirWriter { tcx, extra_data: &|_, _| Ok(()), options: PrettyPrintMirOptions::from_cli(tcx) }
381381 }
......@@ -709,7 +709,7 @@ pub fn dump_mir_def_ids(tcx: TyCtxt<'_>, single: Option<DefId>) -> Vec<DefId> {
709709///////////////////////////////////////////////////////////////////////////
710710// Basic blocks and their parts (statements, terminators, ...)
711711
712impl<'de, 'tcx> MirWriter<'de, 'tcx> {
712impl<'a, 'tcx> MirWriter<'a, 'tcx> {
713713 /// Write out a human-readable textual representation for the given basic block.
714714 fn write_basic_block(
715715 &self,
compiler/rustc_mir_build/src/check_tail_calls.rs+14-20
......@@ -4,12 +4,13 @@ use rustc_errors::Applicability;
44use rustc_hir::LangItem;
55use rustc_hir::def::DefKind;
66use rustc_hir::def_id::CRATE_DEF_ID;
7use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
78use rustc_middle::span_bug;
89use rustc_middle::thir::visit::{self, Visitor};
910use rustc_middle::thir::{BodyTy, Expr, ExprId, ExprKind, Thir};
1011use rustc_middle::ty::{self, Ty, TyCtxt};
1112use rustc_span::def_id::{DefId, LocalDefId};
12use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span};
13use rustc_span::{ErrorGuaranteed, Span};
1314
1415pub(crate) fn check_tail_calls(tcx: TyCtxt<'_>, def: LocalDefId) -> Result<(), ErrorGuaranteed> {
1516 let (thir, expr) = tcx.thir_body(def)?;
......@@ -21,7 +22,6 @@ pub(crate) fn check_tail_calls(tcx: TyCtxt<'_>, def: LocalDefId) -> Result<(), E
2122 }
2223
2324 let is_closure = matches!(tcx.def_kind(def), DefKind::Closure);
24 let caller_ty = tcx.type_of(def).skip_binder();
2525
2626 let mut visitor = TailCallCkVisitor {
2727 tcx,
......@@ -30,7 +30,7 @@ pub(crate) fn check_tail_calls(tcx: TyCtxt<'_>, def: LocalDefId) -> Result<(), E
3030 // FIXME(#132279): we're clearly in a body here.
3131 typing_env: ty::TypingEnv::non_body_analysis(tcx, def),
3232 is_closure,
33 caller_ty,
33 caller_def_id: def,
3434 };
3535
3636 visitor.visit_expr(&thir[expr]);
......@@ -47,8 +47,8 @@ struct TailCallCkVisitor<'a, 'tcx> {
4747 /// The result of the checks, `Err(_)` if there was a problem with some
4848 /// tail call, `Ok(())` if all of them were fine.
4949 found_errors: Result<(), ErrorGuaranteed>,
50 /// Type of the caller function.
51 caller_ty: Ty<'tcx>,
50 /// `LocalDefId` of the caller function.
51 caller_def_id: LocalDefId,
5252}
5353
5454impl<'tcx> TailCallCkVisitor<'_, 'tcx> {
......@@ -148,11 +148,13 @@ impl<'tcx> TailCallCkVisitor<'_, 'tcx> {
148148 // we should think what is the expected behavior here.
149149 // (we should probably just accept this by revealing opaques?)
150150 if caller_sig.inputs_and_output != callee_sig.inputs_and_output {
151 let caller_ty = self.tcx.type_of(self.caller_def_id).skip_binder();
152
151153 self.report_signature_mismatch(
152154 expr.span,
153155 self.tcx.liberate_late_bound_regions(
154156 CRATE_DEF_ID.to_def_id(),
155 self.caller_ty.fn_sig(self.tcx),
157 caller_ty.fn_sig(self.tcx),
156158 ),
157159 self.tcx.liberate_late_bound_regions(CRATE_DEF_ID.to_def_id(), ty.fn_sig(self.tcx)),
158160 );
......@@ -173,7 +175,7 @@ impl<'tcx> TailCallCkVisitor<'_, 'tcx> {
173175 // coercing the function to an `fn()` pointer. (although in that case the tailcall is
174176 // basically useless -- the shim calls the actual function, so tailcalling the shim is
175177 // equivalent to calling the function)
176 let caller_needs_location = self.needs_location(self.caller_ty);
178 let caller_needs_location = self.caller_needs_location();
177179
178180 if caller_needs_location {
179181 self.report_track_caller_caller(expr.span);
......@@ -189,19 +191,11 @@ impl<'tcx> TailCallCkVisitor<'_, 'tcx> {
189191 }
190192 }
191193
192 /// Returns true if function of type `ty` needs location argument
193 /// (i.e. if a function is marked as `#[track_caller]`).
194 ///
195 /// Panics if the function's instance can't be immediately resolved.
196 fn needs_location(&self, ty: Ty<'tcx>) -> bool {
197 if let &ty::FnDef(did, substs) = ty.kind() {
198 let instance =
199 ty::Instance::expect_resolve(self.tcx, self.typing_env, did, substs, DUMMY_SP);
200
201 instance.def.requires_caller_location(self.tcx)
202 } else {
203 false
204 }
194 /// Returns true if the caller function needs a location argument
195 /// (i.e. if a function is marked as `#[track_caller]`)
196 fn caller_needs_location(&self) -> bool {
197 let flags = self.tcx.codegen_fn_attrs(self.caller_def_id).flags;
198 flags.contains(CodegenFnAttrFlags::TRACK_CALLER)
205199 }
206200
207201 fn report_in_closure(&mut self, expr: &Expr<'_>) {
compiler/rustc_mir_build/src/errors.rs+3-3
......@@ -649,14 +649,14 @@ pub(crate) enum UnusedUnsafeEnclosing {
649649 },
650650}
651651
652pub(crate) struct NonExhaustivePatternsTypeNotEmpty<'p, 'tcx, 'm> {
653 pub(crate) cx: &'m RustcPatCtxt<'p, 'tcx>,
652pub(crate) struct NonExhaustivePatternsTypeNotEmpty<'a, 'tcx> {
653 pub(crate) cx: &'a RustcPatCtxt<'a, 'tcx>,
654654 pub(crate) scrut_span: Span,
655655 pub(crate) braces_span: Option<Span>,
656656 pub(crate) ty: Ty<'tcx>,
657657}
658658
659impl<'a, G: EmissionGuarantee> Diagnostic<'a, G> for NonExhaustivePatternsTypeNotEmpty<'_, '_, '_> {
659impl<'a, G: EmissionGuarantee> Diagnostic<'a, G> for NonExhaustivePatternsTypeNotEmpty<'_, '_> {
660660 fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, G> {
661661 let mut diag =
662662 Diag::new(dcx, level, msg!("non-exhaustive patterns: type `{$ty}` is non-empty"));
compiler/rustc_monomorphize/src/graph_checks/statics.rs+4-4
......@@ -37,14 +37,14 @@ newtype_index! {
3737// Adjacency-list graph for statics using `StaticNodeIdx` as node type.
3838// We cannot use `DefId` as the node type directly because each node must be
3939// represented by an index in the range `0..num_nodes`.
40struct StaticRefGraph<'a, 'b, 'tcx> {
40struct StaticRefGraph<'a, 'tcx> {
4141 // maps from `StaticNodeIdx` to `DefId` and vice versa
4242 statics: &'a FxIndexSet<DefId>,
4343 // contains for each `MonoItem` the `MonoItem`s it uses
44 used_map: &'b UnordMap<MonoItem<'tcx>, Vec<MonoItem<'tcx>>>,
44 used_map: &'a UnordMap<MonoItem<'tcx>, Vec<MonoItem<'tcx>>>,
4545}
4646
47impl<'a, 'b, 'tcx> DirectedGraph for StaticRefGraph<'a, 'b, 'tcx> {
47impl<'a, 'tcx> DirectedGraph for StaticRefGraph<'a, 'tcx> {
4848 type Node = StaticNodeIdx;
4949
5050 fn num_nodes(&self) -> usize {
......@@ -52,7 +52,7 @@ impl<'a, 'b, 'tcx> DirectedGraph for StaticRefGraph<'a, 'b, 'tcx> {
5252 }
5353}
5454
55impl<'a, 'b, 'tcx> Successors for StaticRefGraph<'a, 'b, 'tcx> {
55impl<'a, 'tcx> Successors for StaticRefGraph<'a, 'tcx> {
5656 fn successors(&self, node_idx: StaticNodeIdx) -> impl Iterator<Item = StaticNodeIdx> {
5757 let def_id = self.statics[node_idx.index()];
5858 self.used_map[&MonoItem::Static(def_id)].iter().filter_map(|&mono_item| match mono_item {
compiler/rustc_resolve/src/build_reduced_graph.rs+4-6
......@@ -251,16 +251,15 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
251251 pub(crate) fn build_reduced_graph_external(&self, module: ExternModule<'ra>) {
252252 let def_id = module.def_id();
253253 let children = self.tcx.module_children(def_id);
254 let parent_scope = ParentScope::module(module.to_module(), self.arenas);
255254 for (i, child) in children.iter().enumerate() {
256 self.build_reduced_graph_for_external_crate_res(child, parent_scope, i, None)
255 self.build_reduced_graph_for_external_crate_res(child, module, i, None)
257256 }
258257 for (i, child) in
259258 self.cstore().ambig_module_children_untracked(self.tcx, def_id).enumerate()
260259 {
261260 self.build_reduced_graph_for_external_crate_res(
262261 &child.main,
263 parent_scope,
262 module,
264263 children.len() + i,
265264 Some(&child.second),
266265 )
......@@ -271,11 +270,10 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
271270 fn build_reduced_graph_for_external_crate_res(
272271 &self,
273272 child: &ModChild,
274 parent_scope: ParentScope<'ra>,
273 parent: ExternModule<'ra>,
275274 child_index: usize,
276275 ambig_child: Option<&ModChild>,
277276 ) {
278 let parent = parent_scope.module.expect_extern();
279277 let child_span = |this: &Self, reexport_chain: &[Reexport], res: def::Res<_>| {
280278 this.def_span(
281279 reexport_chain
......@@ -288,7 +286,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
288286 let ident = IdentKey::new(orig_ident);
289287 let span = child_span(self, reexport_chain, res);
290288 let res = res.expect_non_local();
291 let expansion = parent_scope.expansion;
289 let expansion = LocalExpnId::ROOT;
292290 let ambig = ambig_child.map(|ambig_child| {
293291 let ModChild { ident: _, res, vis, ref reexport_chain } = *ambig_child;
294292 let span = child_span(self, reexport_chain, res);
compiler/rustc_resolve/src/ident.rs+12-14
......@@ -5,7 +5,6 @@ use Namespace::*;
55use rustc_ast::{self as ast, NodeId};
66use rustc_errors::ErrorGuaranteed;
77use rustc_hir::def::{DefKind, MacroKinds, Namespace, NonMacroAttrKind, PartialRes, PerNS};
8use rustc_middle::ty::Visibility;
98use rustc_middle::{bug, span_bug};
109use rustc_session::lint::builtin::PROC_MACRO_DERIVE_RESOLUTION_FALLBACK;
1110use rustc_session::parse::feature_err;
......@@ -24,9 +23,9 @@ use crate::late::{
2423use crate::macros::{MacroRulesScope, sub_namespace_match};
2524use crate::{
2625 AmbiguityError, AmbiguityKind, AmbiguityWarning, BindingKey, CmResolver, Decl, DeclKind,
27 Determinacy, Finalize, IdentKey, ImportKind, LateDecl, LocalModule, Module, ModuleKind,
28 ModuleOrUniformRoot, ParentScope, PathResult, PrivacyError, Res, ResolutionError, Resolver,
29 Scope, ScopeSet, Segment, Stage, Symbol, Used, errors,
26 Determinacy, Finalize, IdentKey, ImportKind, ImportSummary, LateDecl, LocalModule, Module,
27 ModuleKind, ModuleOrUniformRoot, ParentScope, PathResult, PrivacyError, Res, ResolutionError,
28 Resolver, Scope, ScopeSet, Segment, Stage, Symbol, Used, errors,
3029};
3130
3231#[derive(Copy, Clone)]
......@@ -485,11 +484,11 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
485484 // We do not need to report them if we are either in speculative resolution,
486485 // or in late resolution when everything is already imported and expanded
487486 // and no ambiguities exist.
488 let import_vis = match finalize {
487 let import = match finalize {
489488 None | Some(Finalize { stage: Stage::Late, .. }) => {
490489 return ControlFlow::Break(Ok(decl));
491490 }
492 Some(Finalize { import_vis, .. }) => import_vis,
491 Some(Finalize { import, .. }) => import,
493492 };
494493
495494 if let Some(&(innermost_decl, _)) = innermost_results.first() {
......@@ -503,7 +502,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
503502 decl,
504503 scope,
505504 &innermost_results,
506 import_vis,
505 import,
507506 ) {
508507 // No need to search for more potential ambiguities, one is enough.
509508 return ControlFlow::Break(Ok(innermost_decl));
......@@ -790,19 +789,18 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
790789 decl: Decl<'ra>,
791790 scope: Scope<'ra>,
792791 innermost_results: &[(Decl<'ra>, Scope<'ra>)],
793 import_vis: Option<Visibility>,
792 import: Option<ImportSummary>,
794793 ) -> bool {
795794 let (innermost_decl, innermost_scope) = innermost_results[0];
796795 let (res, innermost_res) = (decl.res(), innermost_decl.res());
797796 let ambig_vis = if res != innermost_res {
798797 None
799 } else if let Some(import_vis) = import_vis
800 && let min =
801 (|d: Decl<'_>| d.vis().min(import_vis.to_def_id(), self.tcx).expect_local())
802 && let (min1, min2) = (min(decl), min(innermost_decl))
803 && min1 != min2
798 } else if let Some(import) = import
799 && let vis1 = self.import_decl_vis(decl, import)
800 && let vis2 = self.import_decl_vis(innermost_decl, import)
801 && vis1 != vis2
804802 {
805 Some((min1, min2))
803 Some((vis1, vis2))
806804 } else {
807805 return false;
808806 };
compiler/rustc_resolve/src/imports.rs+52-19
......@@ -37,8 +37,9 @@ use crate::errors::{
3737use crate::ref_mut::CmCell;
3838use crate::{
3939 AmbiguityError, BindingKey, CmResolver, Decl, DeclData, DeclKind, Determinacy, Finalize,
40 IdentKey, ImportSuggestion, LocalModule, ModuleOrUniformRoot, ParentScope, PathResult, PerNS,
41 Res, ResolutionError, Resolver, ScopeSet, Segment, Used, module_to_string, names_to_string,
40 IdentKey, ImportSuggestion, ImportSummary, LocalModule, ModuleOrUniformRoot, ParentScope,
41 PathResult, PerNS, Res, ResolutionError, Resolver, ScopeSet, Segment, Used, module_to_string,
42 names_to_string,
4243};
4344
4445/// A potential import declaration in the process of being planted into a module.
......@@ -267,6 +268,14 @@ impl<'ra> ImportData<'ra> {
267268 ImportKind::MacroExport => Reexport::MacroExport,
268269 }
269270 }
271
272 fn summary(&self) -> ImportSummary {
273 ImportSummary {
274 vis: self.vis,
275 nearest_parent_mod: self.parent_scope.module.nearest_parent_mod().expect_local(),
276 is_single: matches!(self.kind, ImportKind::Single { .. }),
277 }
278 }
270279}
271280
272281/// Records information about the resolution of a name in a namespace of a module.
......@@ -327,9 +336,9 @@ struct UnresolvedImportError {
327336
328337// Reexports of the form `pub use foo as bar;` where `foo` is `extern crate foo;`
329338// are permitted for backward-compatibility under a deprecation lint.
330fn pub_use_of_private_extern_crate_hack(import: Import<'_>, decl: Decl<'_>) -> Option<NodeId> {
331 match (&import.kind, &decl.kind) {
332 (ImportKind::Single { .. }, DeclKind::Import { import: decl_import, .. })
339fn pub_use_of_private_extern_crate_hack(import: ImportSummary, decl: Decl<'_>) -> Option<NodeId> {
340 match (import.is_single, decl.kind) {
341 (true, DeclKind::Import { import: decl_import, .. })
333342 if let ImportKind::ExternCrate { id, .. } = decl_import.kind
334343 && import.vis.is_public() =>
335344 {
......@@ -361,23 +370,42 @@ fn remove_same_import<'ra>(d1: Decl<'ra>, d2: Decl<'ra>) -> (Decl<'ra>, Decl<'ra
361370}
362371
363372impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
373 pub(crate) fn import_decl_vis(&self, decl: Decl<'ra>, import: ImportSummary) -> Visibility {
374 assert!(import.vis.is_accessible_from(import.nearest_parent_mod, self.tcx));
375 let decl_vis = decl.vis();
376 if decl_vis.is_at_least(import.vis, self.tcx) {
377 // Ordered, import is less visible than the imported declaration, or the same,
378 // use the import's visibility.
379 import.vis
380 } else if decl_vis.is_accessible_from(import.nearest_parent_mod, self.tcx) {
381 // Ordered, imported declaration is less visible than the import, but is still visible
382 // from the current module, use the declaration's visibility.
383 assert!(import.vis.is_at_least(decl_vis, self.tcx));
384 if pub_use_of_private_extern_crate_hack(import, decl).is_some() {
385 import.vis
386 } else {
387 decl_vis.expect_local()
388 }
389 } else {
390 // Ordered or not, the imported declaration is too private for the current module.
391 // It doesn't matter what visibility we choose here (except in the `PRIVATE_MACRO_USE`
392 // case), because either some error will be reported, or the import declaration
393 // will be thrown away (unfortunately cannot use delayed bug here for this reason).
394 // Use import visibility to keep the all declaration visibilities in a module ordered.
395 import.vis
396 }
397 }
398
364399 /// Given an import and the declaration that it points to,
365400 /// create the corresponding import declaration.
366401 pub(crate) fn new_import_decl(&self, decl: Decl<'ra>, import: Import<'ra>) -> Decl<'ra> {
367 let import_vis = import.vis.to_def_id();
368 let vis = if decl.vis().is_at_least(import_vis, self.tcx)
369 || pub_use_of_private_extern_crate_hack(import, decl).is_some()
370 {
371 import_vis
372 } else {
373 decl.vis()
374 };
402 let vis = self.import_decl_vis(decl, import.summary());
375403
376404 if let ImportKind::Glob { ref max_vis, .. } = import.kind
377 && (vis == import_vis
405 && (vis == import.vis
378406 || max_vis.get().is_none_or(|max_vis| vis.is_at_least(max_vis, self.tcx)))
379407 {
380 max_vis.set_unchecked(Some(vis.expect_local()))
408 max_vis.set_unchecked(Some(vis))
381409 }
382410
383411 self.arenas.alloc_decl(DeclData {
......@@ -385,7 +413,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
385413 ambiguity: CmCell::new(None),
386414 warn_ambiguity: CmCell::new(false),
387415 span: import.span,
388 vis: CmCell::new(vis),
416 vis: CmCell::new(vis.to_def_id()),
389417 expansion: import.parent_scope.expansion,
390418 parent_module: Some(import.parent_scope.module),
391419 })
......@@ -448,6 +476,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
448476 }
449477 } else if !old_glob_decl.vis().is_at_least(glob_decl.vis(), self.tcx) {
450478 // We are glob-importing the same item but with greater visibility.
479 // All visibilities here are ordered because all of them are ancestors of `module`.
451480 // FIXME: Update visibility in place, but without regressions
452481 // (#152004, #151124, #152347).
453482 glob_decl
......@@ -471,7 +500,10 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
471500 decl: Decl<'ra>,
472501 warn_ambiguity: bool,
473502 ) -> Result<(), Decl<'ra>> {
503 assert!(!decl.warn_ambiguity.get());
504 assert!(decl.ambiguity.get().is_none());
474505 let module = decl.parent_module.unwrap().expect_local();
506 assert!(self.is_accessible_from(decl.vis(), module.to_module()));
475507 let res = decl.res();
476508 self.check_reserved_macro_name(ident.name, orig_ident_span, res);
477509 // Even if underscore names cannot be looked up, we still need to add them to modules,
......@@ -487,7 +519,6 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
487519 orig_ident_span,
488520 warn_ambiguity,
489521 |this, resolution| {
490 assert!(!decl.warn_ambiguity.get());
491522 if decl.is_glob_import() {
492523 resolution.glob_decl = Some(match resolution.glob_decl {
493524 Some(old_decl) => this.select_glob_decl(
......@@ -1261,7 +1292,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
12611292 &import.parent_scope,
12621293 Some(Finalize {
12631294 report_private: false,
1264 import_vis: Some(import.vis),
1295 import: Some(import.summary()),
12651296 ..finalize
12661297 }),
12671298 bindings[ns].get().decl(),
......@@ -1461,7 +1492,9 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
14611492 // All namespaces must be re-exported with extra visibility for an error to occur.
14621493 if !any_successful_reexport {
14631494 let (ns, binding) = reexport_error.unwrap();
1464 if let Some(extern_crate_id) = pub_use_of_private_extern_crate_hack(import, binding) {
1495 if let Some(extern_crate_id) =
1496 pub_use_of_private_extern_crate_hack(import.summary(), binding)
1497 {
14651498 let extern_crate_sp = self.tcx.source_span(self.local_def_id(extern_crate_id));
14661499 self.lint_buffer.buffer_lint(
14671500 PUB_USE_OF_PRIVATE_EXTERN_CRATE,
compiler/rustc_resolve/src/late.rs+21-3
......@@ -365,6 +365,9 @@ enum LifetimeRibKind {
365365
366366 /// This rib acts as a barrier to forbid reference to lifetimes of a parent item.
367367 Item,
368
369 /// Lifetimes cannot be elided in `impl Trait` types without `#![feature(anonymous_lifetime_in_impl_trait)]`.
370 ImplTrait,
368371}
369372
370373#[derive(Copy, Clone, Debug)]
......@@ -941,7 +944,7 @@ impl<'ast, 'ra, 'tcx> Visitor<'ast> for LateResolutionVisitor<'_, 'ast, 'ra, 'tc
941944 }
942945 TyKind::ImplTrait(..) => {
943946 let candidates = self.lifetime_elision_candidates.take();
944 visit::walk_ty(self, ty);
947 self.with_lifetime_rib(LifetimeRibKind::ImplTrait, |this| visit::walk_ty(this, ty));
945948 self.lifetime_elision_candidates = candidates;
946949 }
947950 TyKind::TraitObject(bounds, ..) => {
......@@ -1353,6 +1356,7 @@ impl<'ast, 'ra, 'tcx> Visitor<'ast> for LateResolutionVisitor<'_, 'ast, 'ra, 'tc
13531356 LifetimeRibKind::AnonymousCreateParameter { .. }
13541357 | LifetimeRibKind::AnonymousReportError
13551358 | LifetimeRibKind::StaticIfNoLifetimeInScope { .. }
1359 | LifetimeRibKind::ImplTrait
13561360 | LifetimeRibKind::Elided(_)
13571361 | LifetimeRibKind::ElisionFailure
13581362 | LifetimeRibKind::ConcreteAnonConst(_)
......@@ -1780,6 +1784,15 @@ impl<'a, 'ast, 'ra, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
17801784 LifetimeRibKind::ConcreteAnonConst(_) => {
17811785 span_bug!(ident.span, "unexpected rib kind: {:?}", rib.kind)
17821786 }
1787
1788 LifetimeRibKind::ImplTrait => {
1789 if self.r.tcx.features().anonymous_lifetime_in_impl_trait()
1790 {
1791 None
1792 } else {
1793 Some(LifetimeUseSet::Many)
1794 }
1795 }
17831796 })
17841797 .unwrap_or(LifetimeUseSet::Many);
17851798 debug!(?use_ctxt, ?use_set);
......@@ -1819,6 +1832,7 @@ impl<'a, 'ast, 'ra, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
18191832 | LifetimeRibKind::Generics { .. }
18201833 | LifetimeRibKind::ElisionFailure
18211834 | LifetimeRibKind::AnonymousReportError
1835 | LifetimeRibKind::ImplTrait
18221836 | LifetimeRibKind::StaticIfNoLifetimeInScope { .. } => {}
18231837 }
18241838 }
......@@ -2000,7 +2014,9 @@ impl<'a, 'ast, 'ra, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
20002014 return;
20012015 }
20022016 LifetimeRibKind::Item => break,
2003 LifetimeRibKind::Generics { .. } | LifetimeRibKind::ConstParamTy => {}
2017 LifetimeRibKind::Generics { .. }
2018 | LifetimeRibKind::ConstParamTy
2019 | LifetimeRibKind::ImplTrait => {}
20042020 LifetimeRibKind::ConcreteAnonConst(_) => {
20052021 // There is always an `Elided(LifetimeRes::Infer)` inside an `AnonConst`.
20062022 span_bug!(lifetime.ident.span, "unexpected rib kind: {:?}", rib.kind)
......@@ -2323,7 +2339,9 @@ impl<'a, 'ast, 'ra, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
23232339 }
23242340 break;
23252341 }
2326 LifetimeRibKind::Generics { .. } | LifetimeRibKind::ConstParamTy => {}
2342 LifetimeRibKind::Generics { .. }
2343 | LifetimeRibKind::ConstParamTy
2344 | LifetimeRibKind::ImplTrait => {}
23272345 LifetimeRibKind::ConcreteAnonConst(_) => {
23282346 // There is always an `Elided(LifetimeRes::Infer)` inside an `AnonConst`.
23292347 span_bug!(elided_lifetime_span, "unexpected rib kind: {:?}", rib.kind)
compiler/rustc_resolve/src/lib.rs+11-2
......@@ -2722,6 +2722,15 @@ enum Stage {
27222722 Late,
27232723}
27242724
2725/// Parts of import data required for finalizing import resolution.
2726/// Does not carry a lifetime, so it can be stored in `Finalize`.
2727#[derive(Copy, Clone, Debug)]
2728struct ImportSummary {
2729 vis: Visibility,
2730 nearest_parent_mod: LocalDefId,
2731 is_single: bool,
2732}
2733
27252734/// Invariant: if `Finalize` is used, expansion and import resolution must be complete.
27262735#[derive(Copy, Clone, Debug)]
27272736struct Finalize {
......@@ -2740,8 +2749,8 @@ struct Finalize {
27402749 used: Used = Used::Other,
27412750 /// Finalizing early or late resolution.
27422751 stage: Stage = Stage::Early,
2743 /// Nominal visibility of the import item, in case we are resolving an import's final segment.
2744 import_vis: Option<Visibility> = None,
2752 /// Some import data, in case we are resolving an import's final segment.
2753 import: Option<ImportSummary> = None,
27452754}
27462755
27472756impl Finalize {
compiler/rustc_type_ir/src/inherent.rs+26
......@@ -17,6 +17,7 @@ use crate::{
1717 self as ty, ClauseKind, CollectAndApply, FieldInfo, Interner, PredicateKind, UpcastFrom,
1818};
1919
20#[rust_analyzer::prefer_underscore_import]
2021pub trait Ty<I: Interner<Ty = Self>>:
2122 Copy
2223 + Debug
......@@ -195,6 +196,7 @@ pub trait Ty<I: Interner<Ty = Self>>:
195196 }
196197}
197198
199#[rust_analyzer::prefer_underscore_import]
198200pub trait Tys<I: Interner<Tys = Self>>:
199201 Copy + Debug + Hash + Eq + SliceLike<Item = I::Ty> + TypeFoldable<I> + Default
200202{
......@@ -203,6 +205,7 @@ pub trait Tys<I: Interner<Tys = Self>>:
203205 fn output(self) -> I::Ty;
204206}
205207
208#[rust_analyzer::prefer_underscore_import]
206209pub trait FSigKind<I: Interner<FSigKind = Self>>: Copy + Debug + Hash + Eq {
207210 /// The identity function.
208211 fn fn_sig_kind(self) -> Self;
......@@ -220,6 +223,7 @@ pub trait FSigKind<I: Interner<FSigKind = Self>>: Copy + Debug + Hash + Eq {
220223 fn c_variadic(self) -> bool;
221224}
222225
226#[rust_analyzer::prefer_underscore_import]
223227pub trait Abi<I: Interner<Abi = Self>>: Copy + Debug + Hash + Eq {
224228 /// The identity function.
225229 fn abi(self) -> Self;
......@@ -237,6 +241,7 @@ pub trait Abi<I: Interner<Abi = Self>>: Copy + Debug + Hash + Eq {
237241 fn unpack_abi(abi_index: u8) -> Self;
238242}
239243
244#[rust_analyzer::prefer_underscore_import]
240245pub trait Safety<I: Interner<Safety = Self>>: Copy + Debug + Hash + Eq {
241246 /// The `safe` safety mode.
242247 fn safe() -> Self;
......@@ -251,6 +256,7 @@ pub trait Safety<I: Interner<Safety = Self>>: Copy + Debug + Hash + Eq {
251256 fn prefix_str(self) -> &'static str;
252257}
253258
259#[rust_analyzer::prefer_underscore_import]
254260pub trait Region<I: Interner<Region = Self>>:
255261 Copy
256262 + Debug
......@@ -276,6 +282,7 @@ pub trait Region<I: Interner<Region = Self>>:
276282 }
277283}
278284
285#[rust_analyzer::prefer_underscore_import]
279286pub trait Const<I: Interner<Const = Self>>:
280287 Copy
281288 + Debug
......@@ -320,19 +327,23 @@ pub trait Const<I: Interner<Const = Self>>:
320327 }
321328}
322329
330#[rust_analyzer::prefer_underscore_import]
323331pub trait ValueConst<I: Interner<ValueConst = Self>>: Copy + Debug + Hash + Eq {
324332 fn ty(self) -> I::Ty;
325333 fn valtree(self) -> I::ValTree;
326334}
327335
336#[rust_analyzer::prefer_underscore_import]
328337pub trait ExprConst<I: Interner<ExprConst = Self>>: Copy + Debug + Hash + Eq + Relate<I> {
329338 fn args(self) -> I::GenericArgs;
330339}
331340
341#[rust_analyzer::prefer_underscore_import]
332342pub trait GenericsOf<I: Interner<GenericsOf = Self>> {
333343 fn count(&self) -> usize;
334344}
335345
346#[rust_analyzer::prefer_underscore_import]
336347pub trait GenericArg<I: Interner<GenericArg = Self>>:
337348 Copy
338349 + Debug
......@@ -387,6 +398,7 @@ pub trait GenericArg<I: Interner<GenericArg = Self>>:
387398 }
388399}
389400
401#[rust_analyzer::prefer_underscore_import]
390402pub trait Term<I: Interner<Term = Self>>:
391403 Copy + Debug + Hash + Eq + IntoKind<Kind = ty::TermKind<I>> + TypeFoldable<I> + Relate<I>
392404{
......@@ -434,6 +446,7 @@ pub trait Term<I: Interner<Term = Self>>:
434446 }
435447}
436448
449#[rust_analyzer::prefer_underscore_import]
437450pub trait GenericArgs<I: Interner<GenericArgs = Self>>:
438451 Copy + Debug + Hash + Eq + SliceLike<Item = I::GenericArg> + Default + Relate<I>
439452{
......@@ -473,6 +486,7 @@ pub trait GenericArgs<I: Interner<GenericArgs = Self>>:
473486 }
474487}
475488
489#[rust_analyzer::prefer_underscore_import]
476490pub trait Predicate<I: Interner<Predicate = Self>>:
477491 Copy
478492 + Debug
......@@ -528,6 +542,7 @@ pub trait Predicate<I: Interner<Predicate = Self>>:
528542 }
529543}
530544
545#[rust_analyzer::prefer_underscore_import]
531546pub trait Clause<I: Interner<Clause = Self>>:
532547 Copy
533548 + Debug
......@@ -577,6 +592,7 @@ pub trait Clause<I: Interner<Clause = Self>>:
577592 fn instantiate_supertrait(self, cx: I, trait_ref: ty::Binder<I, ty::TraitRef<I>>) -> Self;
578593}
579594
595#[rust_analyzer::prefer_underscore_import]
580596pub trait Clauses<I: Interner<Clauses = Self>>:
581597 Copy
582598 + Debug
......@@ -589,16 +605,19 @@ pub trait Clauses<I: Interner<Clauses = Self>>:
589605{
590606}
591607
608#[rust_analyzer::prefer_underscore_import]
592609pub trait IntoKind {
593610 type Kind;
594611
595612 fn kind(self) -> Self::Kind;
596613}
597614
615#[rust_analyzer::prefer_underscore_import]
598616pub trait ParamLike: Copy + Debug + Hash + Eq {
599617 fn index(self) -> u32;
600618}
601619
620#[rust_analyzer::prefer_underscore_import]
602621pub trait AdtDef<I: Interner>: Copy + Debug + Hash + Eq {
603622 fn def_id(self) -> I::AdtId;
604623
......@@ -635,10 +654,12 @@ pub trait AdtDef<I: Interner>: Copy + Debug + Hash + Eq {
635654 fn destructor(self, interner: I) -> Option<AdtDestructorKind>;
636655}
637656
657#[rust_analyzer::prefer_underscore_import]
638658pub trait ParamEnv<I: Interner>: Copy + Debug + Hash + Eq + TypeFoldable<I> {
639659 fn caller_bounds(self) -> impl SliceLike<Item = I::Clause>;
640660}
641661
662#[rust_analyzer::prefer_underscore_import]
642663pub trait Features<I: Interner>: Copy {
643664 fn generic_const_exprs(self) -> bool;
644665
......@@ -647,6 +668,7 @@ pub trait Features<I: Interner>: Copy {
647668 fn feature_bound_holds_in_crate(self, symbol: I::Symbol) -> bool;
648669}
649670
671#[rust_analyzer::prefer_underscore_import]
650672pub trait DefId<I: Interner>: Copy + Debug + Hash + Eq + TypeFoldable<I> {
651673 fn is_local(self) -> bool;
652674
......@@ -663,6 +685,7 @@ impl<I: Interner, T: DefId<I> + Into<I::DefId> + TryFrom<I::DefId, Error: std::f
663685{
664686}
665687
688#[rust_analyzer::prefer_underscore_import]
666689pub trait BoundExistentialPredicates<I: Interner>:
667690 Copy + Debug + Hash + Eq + Relate<I> + SliceLike<Item = ty::Binder<I, ty::ExistentialPredicate<I>>>
668691{
......@@ -677,10 +700,12 @@ pub trait BoundExistentialPredicates<I: Interner>:
677700 ) -> impl IntoIterator<Item = ty::Binder<I, ty::ExistentialProjection<I>>>;
678701}
679702
703#[rust_analyzer::prefer_underscore_import]
680704pub trait Span<I: Interner>: Copy + Debug + Hash + Eq + TypeFoldable<I> {
681705 fn dummy() -> Self;
682706}
683707
708#[rust_analyzer::prefer_underscore_import]
684709pub trait OpaqueTypeStorageEntries: Debug + Copy + Default {
685710 /// Whether the number of opaques has changed in a way that necessitates
686711 /// reevaluating a goal. For now, this is only when the number of non-duplicated
......@@ -767,6 +792,7 @@ impl<'a, S: SliceLike> SliceLike for &'a S {
767792 }
768793}
769794
795#[rust_analyzer::prefer_underscore_import]
770796pub trait Symbol<I>: Copy + Hash + PartialEq + Eq + Debug {
771797 fn is_kw_underscore_lifetime(self) -> bool;
772798}
library/alloctests/benches/lib.rs+1
......@@ -1,5 +1,6 @@
11// This is marked as `test = true` and hence picked up by `./x miri`, but that would be too slow.
22#![cfg(not(miri))]
3#![allow(internal_features)]
34#![feature(iter_next_chunk)]
45#![feature(repr_simd)]
56#![feature(slice_partition_dedup)]
library/core/src/io/error.rs created+372
......@@ -0,0 +1,372 @@
1#![unstable(feature = "core_io", issue = "154046")]
2
3use crate::fmt;
4
5/// A list specifying general categories of I/O error.
6///
7/// This list is intended to grow over time and it is not recommended to
8/// exhaustively match against it.
9///
10/// # Handling errors and matching on `ErrorKind`
11///
12/// In application code, use `match` for the `ErrorKind` values you are
13/// expecting; use `_` to match "all other errors".
14///
15/// In comprehensive and thorough tests that want to verify that a test doesn't
16/// return any known incorrect error kind, you may want to cut-and-paste the
17/// current full list of errors from here into your test code, and then match
18/// `_` as the correct case. This seems counterintuitive, but it will make your
19/// tests more robust. In particular, if you want to verify that your code does
20/// produce an unrecognized error kind, the robust solution is to check for all
21/// the recognized error kinds and fail in those cases.
22#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
23#[stable(feature = "rust1", since = "1.0.0")]
24#[cfg_attr(not(test), rustc_diagnostic_item = "io_errorkind")]
25#[allow(deprecated)]
26#[non_exhaustive]
27pub enum ErrorKind {
28 /// An entity was not found, often a file.
29 #[stable(feature = "rust1", since = "1.0.0")]
30 NotFound,
31 /// The operation lacked the necessary privileges to complete.
32 #[stable(feature = "rust1", since = "1.0.0")]
33 PermissionDenied,
34 /// The connection was refused by the remote server.
35 #[stable(feature = "rust1", since = "1.0.0")]
36 ConnectionRefused,
37 /// The connection was reset by the remote server.
38 #[stable(feature = "rust1", since = "1.0.0")]
39 ConnectionReset,
40 /// The remote host is not reachable.
41 #[stable(feature = "io_error_a_bit_more", since = "1.83.0")]
42 HostUnreachable,
43 /// The network containing the remote host is not reachable.
44 #[stable(feature = "io_error_a_bit_more", since = "1.83.0")]
45 NetworkUnreachable,
46 /// The connection was aborted (terminated) by the remote server.
47 #[stable(feature = "rust1", since = "1.0.0")]
48 ConnectionAborted,
49 /// The network operation failed because it was not connected yet.
50 #[stable(feature = "rust1", since = "1.0.0")]
51 NotConnected,
52 /// A socket address could not be bound because the address is already in
53 /// use elsewhere.
54 #[stable(feature = "rust1", since = "1.0.0")]
55 AddrInUse,
56 /// A nonexistent interface was requested or the requested address was not
57 /// local.
58 #[stable(feature = "rust1", since = "1.0.0")]
59 AddrNotAvailable,
60 /// The system's networking is down.
61 #[stable(feature = "io_error_a_bit_more", since = "1.83.0")]
62 NetworkDown,
63 /// The operation failed because a pipe was closed.
64 #[stable(feature = "rust1", since = "1.0.0")]
65 BrokenPipe,
66 /// An entity already exists, often a file.
67 #[stable(feature = "rust1", since = "1.0.0")]
68 AlreadyExists,
69 /// The operation needs to block to complete, but the blocking operation was
70 /// requested to not occur.
71 #[stable(feature = "rust1", since = "1.0.0")]
72 WouldBlock,
73 /// A filesystem object is, unexpectedly, not a directory.
74 ///
75 /// For example, a filesystem path was specified where one of the intermediate directory
76 /// components was, in fact, a plain file.
77 #[stable(feature = "io_error_a_bit_more", since = "1.83.0")]
78 NotADirectory,
79 /// The filesystem object is, unexpectedly, a directory.
80 ///
81 /// A directory was specified when a non-directory was expected.
82 #[stable(feature = "io_error_a_bit_more", since = "1.83.0")]
83 IsADirectory,
84 /// A non-empty directory was specified where an empty directory was expected.
85 #[stable(feature = "io_error_a_bit_more", since = "1.83.0")]
86 DirectoryNotEmpty,
87 /// The filesystem or storage medium is read-only, but a write operation was attempted.
88 #[stable(feature = "io_error_a_bit_more", since = "1.83.0")]
89 ReadOnlyFilesystem,
90 /// Loop in the filesystem or IO subsystem; often, too many levels of symbolic links.
91 ///
92 /// There was a loop (or excessively long chain) resolving a filesystem object
93 /// or file IO object.
94 ///
95 /// On Unix this is usually the result of a symbolic link loop; or, of exceeding the
96 /// system-specific limit on the depth of symlink traversal.
97 #[unstable(feature = "io_error_more", issue = "86442")]
98 FilesystemLoop,
99 /// Stale network file handle.
100 ///
101 /// With some network filesystems, notably NFS, an open file (or directory) can be invalidated
102 /// by problems with the network or server.
103 #[stable(feature = "io_error_a_bit_more", since = "1.83.0")]
104 StaleNetworkFileHandle,
105 /// A parameter was incorrect.
106 #[stable(feature = "rust1", since = "1.0.0")]
107 InvalidInput,
108 /// Data not valid for the operation were encountered.
109 ///
110 /// Unlike [`InvalidInput`], this typically means that the operation
111 /// parameters were valid, however the error was caused by malformed
112 /// input data.
113 ///
114 /// For example, a function that reads a file into a string will error with
115 /// `InvalidData` if the file's contents are not valid UTF-8.
116 ///
117 /// [`InvalidInput`]: ErrorKind::InvalidInput
118 #[stable(feature = "io_invalid_data", since = "1.2.0")]
119 InvalidData,
120 /// The I/O operation's timeout expired, causing it to be canceled.
121 #[stable(feature = "rust1", since = "1.0.0")]
122 TimedOut,
123 /// An error returned when an operation could not be completed because a
124 /// call to an underlying writer returned [`Ok(0)`].
125 ///
126 /// This typically means that an operation could only succeed if it wrote a
127 /// particular number of bytes but only a smaller number of bytes could be
128 /// written.
129 ///
130 /// [`Ok(0)`]: Ok
131 #[stable(feature = "rust1", since = "1.0.0")]
132 WriteZero,
133 /// The underlying storage (typically, a filesystem) is full.
134 ///
135 /// This does not include out of quota errors.
136 #[stable(feature = "io_error_a_bit_more", since = "1.83.0")]
137 StorageFull,
138 /// Seek on unseekable file.
139 ///
140 /// Seeking was attempted on an open file handle which is not suitable for seeking - for
141 /// example, on Unix, a named pipe opened with `File::open`.
142 #[stable(feature = "io_error_a_bit_more", since = "1.83.0")]
143 NotSeekable,
144 /// Filesystem quota or some other kind of quota was exceeded.
145 #[stable(feature = "io_error_quota_exceeded", since = "1.85.0")]
146 QuotaExceeded,
147 /// File larger than allowed or supported.
148 ///
149 /// This might arise from a hard limit of the underlying filesystem or file access API, or from
150 /// an administratively imposed resource limitation. Simple disk full, and out of quota, have
151 /// their own errors.
152 #[stable(feature = "io_error_a_bit_more", since = "1.83.0")]
153 FileTooLarge,
154 /// Resource is busy.
155 #[stable(feature = "io_error_a_bit_more", since = "1.83.0")]
156 ResourceBusy,
157 /// Executable file is busy.
158 ///
159 /// An attempt was made to write to a file which is also in use as a running program. (Not all
160 /// operating systems detect this situation.)
161 #[stable(feature = "io_error_a_bit_more", since = "1.83.0")]
162 ExecutableFileBusy,
163 /// Deadlock (avoided).
164 ///
165 /// A file locking operation would result in deadlock. This situation is typically detected, if
166 /// at all, on a best-effort basis.
167 #[stable(feature = "io_error_a_bit_more", since = "1.83.0")]
168 Deadlock,
169 /// Cross-device or cross-filesystem (hard) link or rename.
170 #[stable(feature = "io_error_crosses_devices", since = "1.85.0")]
171 CrossesDevices,
172 /// Too many (hard) links to the same filesystem object.
173 ///
174 /// The filesystem does not support making so many hardlinks to the same file.
175 #[stable(feature = "io_error_a_bit_more", since = "1.83.0")]
176 TooManyLinks,
177 /// A filename was invalid.
178 ///
179 /// This error can also occur if a length limit for a name was exceeded.
180 #[stable(feature = "io_error_invalid_filename", since = "1.87.0")]
181 InvalidFilename,
182 /// Program argument list too long.
183 ///
184 /// When trying to run an external program, a system or process limit on the size of the
185 /// arguments would have been exceeded.
186 #[stable(feature = "io_error_a_bit_more", since = "1.83.0")]
187 ArgumentListTooLong,
188 /// This operation was interrupted.
189 ///
190 /// Interrupted operations can typically be retried.
191 #[stable(feature = "rust1", since = "1.0.0")]
192 Interrupted,
193
194 /// This operation is unsupported on this platform.
195 ///
196 /// This means that the operation can never succeed.
197 #[stable(feature = "unsupported_error", since = "1.53.0")]
198 Unsupported,
199
200 // ErrorKinds which are primarily categorisations for OS error
201 // codes should be added above.
202 //
203 /// An error returned when an operation could not be completed because an
204 /// "end of file" was reached prematurely.
205 ///
206 /// This typically means that an operation could only succeed if it read a
207 /// particular number of bytes but only a smaller number of bytes could be
208 /// read.
209 #[stable(feature = "read_exact", since = "1.6.0")]
210 UnexpectedEof,
211
212 /// An operation could not be completed, because it failed
213 /// to allocate enough memory.
214 #[stable(feature = "out_of_memory_error", since = "1.54.0")]
215 OutOfMemory,
216
217 /// The operation was partially successful and needs to be checked
218 /// later on due to not blocking.
219 #[unstable(feature = "io_error_inprogress", issue = "130840")]
220 InProgress,
221
222 // "Unusual" error kinds which do not correspond simply to (sets
223 // of) OS error codes, should be added just above this comment.
224 // `Other` and `Uncategorized` should remain at the end:
225 //
226 /// A custom error that does not fall under any other I/O error kind.
227 ///
228 /// This can be used to construct your own errors that do not match any
229 /// [`ErrorKind`].
230 ///
231 /// This [`ErrorKind`] is not used by the standard library.
232 ///
233 /// Errors from the standard library that do not fall under any of the I/O
234 /// error kinds cannot be `match`ed on, and will only match a wildcard (`_`) pattern.
235 /// New [`ErrorKind`]s might be added in the future for some of those.
236 #[stable(feature = "rust1", since = "1.0.0")]
237 Other,
238
239 /// Any I/O error from the standard library that's not part of this list.
240 ///
241 /// Errors that are `Uncategorized` now may move to a different or a new
242 /// [`ErrorKind`] variant in the future. It is not recommended to match
243 /// an error against `Uncategorized`; use a wildcard match (`_`) instead.
244 #[unstable(feature = "io_error_uncategorized", issue = "none")]
245 #[doc(hidden)]
246 Uncategorized,
247}
248
249impl ErrorKind {
250 pub(crate) const fn as_str(&self) -> &'static str {
251 use ErrorKind::*;
252 match *self {
253 // tidy-alphabetical-start
254 AddrInUse => "address in use",
255 AddrNotAvailable => "address not available",
256 AlreadyExists => "entity already exists",
257 ArgumentListTooLong => "argument list too long",
258 BrokenPipe => "broken pipe",
259 ConnectionAborted => "connection aborted",
260 ConnectionRefused => "connection refused",
261 ConnectionReset => "connection reset",
262 CrossesDevices => "cross-device link or rename",
263 Deadlock => "deadlock",
264 DirectoryNotEmpty => "directory not empty",
265 ExecutableFileBusy => "executable file busy",
266 FileTooLarge => "file too large",
267 FilesystemLoop => "filesystem loop or indirection limit (e.g. symlink loop)",
268 HostUnreachable => "host unreachable",
269 InProgress => "in progress",
270 Interrupted => "operation interrupted",
271 InvalidData => "invalid data",
272 InvalidFilename => "invalid filename",
273 InvalidInput => "invalid input parameter",
274 IsADirectory => "is a directory",
275 NetworkDown => "network down",
276 NetworkUnreachable => "network unreachable",
277 NotADirectory => "not a directory",
278 NotConnected => "not connected",
279 NotFound => "entity not found",
280 NotSeekable => "seek on unseekable file",
281 Other => "other error",
282 OutOfMemory => "out of memory",
283 PermissionDenied => "permission denied",
284 QuotaExceeded => "quota exceeded",
285 ReadOnlyFilesystem => "read-only filesystem or storage medium",
286 ResourceBusy => "resource busy",
287 StaleNetworkFileHandle => "stale network file handle",
288 StorageFull => "no storage space",
289 TimedOut => "timed out",
290 TooManyLinks => "too many links",
291 Uncategorized => "uncategorized error",
292 UnexpectedEof => "unexpected end of file",
293 Unsupported => "unsupported",
294 WouldBlock => "operation would block",
295 WriteZero => "write zero",
296 // tidy-alphabetical-end
297 }
298 }
299
300 // This compiles to the same code as the check+transmute, but doesn't require
301 // unsafe, or to hard-code max ErrorKind or its size in a way the compiler
302 // couldn't verify.
303 #[inline]
304 #[unstable(feature = "core_io_internals", reason = "exposed only for libstd", issue = "none")]
305 #[doc(hidden)]
306 pub const fn from_prim(ek: u32) -> Option<Self> {
307 macro_rules! from_prim {
308 ($prim:expr => $Enum:ident { $($Variant:ident),* $(,)? }) => {{
309 // Force a compile error if the list gets out of date.
310 const _: fn(e: $Enum) = |e: $Enum| match e {
311 $($Enum::$Variant => (),)*
312 };
313 match $prim {
314 $(v if v == ($Enum::$Variant as _) => Some($Enum::$Variant),)*
315 _ => None,
316 }
317 }}
318 }
319 from_prim!(ek => ErrorKind {
320 NotFound,
321 PermissionDenied,
322 ConnectionRefused,
323 ConnectionReset,
324 HostUnreachable,
325 NetworkUnreachable,
326 ConnectionAborted,
327 NotConnected,
328 AddrInUse,
329 AddrNotAvailable,
330 NetworkDown,
331 BrokenPipe,
332 AlreadyExists,
333 WouldBlock,
334 NotADirectory,
335 IsADirectory,
336 DirectoryNotEmpty,
337 ReadOnlyFilesystem,
338 FilesystemLoop,
339 StaleNetworkFileHandle,
340 InvalidInput,
341 InvalidData,
342 TimedOut,
343 WriteZero,
344 StorageFull,
345 NotSeekable,
346 QuotaExceeded,
347 FileTooLarge,
348 ResourceBusy,
349 ExecutableFileBusy,
350 Deadlock,
351 CrossesDevices,
352 TooManyLinks,
353 InvalidFilename,
354 ArgumentListTooLong,
355 Interrupted,
356 Other,
357 UnexpectedEof,
358 Unsupported,
359 OutOfMemory,
360 InProgress,
361 Uncategorized,
362 })
363 }
364}
365
366#[stable(feature = "io_errorkind_display", since = "1.60.0")]
367impl fmt::Display for ErrorKind {
368 /// Shows a human-readable description of the `ErrorKind`.
369 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
370 fmt.write_str(self.as_str())
371 }
372}
library/core/src/io/mod.rs+3
......@@ -1,6 +1,9 @@
11//! Traits, helpers, and type definitions for core I/O functionality.
22
33mod borrowed_buf;
4mod error;
45
56#[unstable(feature = "core_io_borrowed_buf", issue = "117693")]
67pub use self::borrowed_buf::{BorrowedBuf, BorrowedCursor};
8#[unstable(feature = "core_io", issue = "154046")]
9pub use self::error::ErrorKind;
library/core/src/lib.rs+1-1
......@@ -305,7 +305,7 @@ pub mod bstr;
305305pub mod cell;
306306pub mod char;
307307pub mod ffi;
308#[unstable(feature = "core_io_borrowed_buf", issue = "117693")]
308#[unstable(feature = "core_io", issue = "154046")]
309309pub mod io;
310310pub mod iter;
311311pub mod net;
library/coretests/tests/lib.rs+1
......@@ -36,6 +36,7 @@
3636#![feature(const_unsigned_bigint_helpers)]
3737#![feature(core_intrinsics)]
3838#![feature(core_intrinsics_fallbacks)]
39#![feature(core_io)]
3940#![feature(core_io_borrowed_buf)]
4041#![feature(core_private_bignum)]
4142#![feature(core_private_diy_float)]
library/std/src/io/error.rs+4-318
......@@ -1,6 +1,9 @@
11#[cfg(test)]
22mod tests;
33
4#[stable(feature = "rust1", since = "1.0.0")]
5pub use core::io::ErrorKind;
6
47// On 64-bit platforms, `io::Error` may use a bit-packed representation to
58// reduce size. However, this representation assumes that error codes are
69// always 32-bit wide.
......@@ -206,323 +209,6 @@ struct Custom {
206209 error: Box<dyn error::Error + Send + Sync>,
207210}
208211
209/// A list specifying general categories of I/O error.
210///
211/// This list is intended to grow over time and it is not recommended to
212/// exhaustively match against it.
213///
214/// It is used with the [`io::Error`] type.
215///
216/// [`io::Error`]: Error
217///
218/// # Handling errors and matching on `ErrorKind`
219///
220/// In application code, use `match` for the `ErrorKind` values you are
221/// expecting; use `_` to match "all other errors".
222///
223/// In comprehensive and thorough tests that want to verify that a test doesn't
224/// return any known incorrect error kind, you may want to cut-and-paste the
225/// current full list of errors from here into your test code, and then match
226/// `_` as the correct case. This seems counterintuitive, but it will make your
227/// tests more robust. In particular, if you want to verify that your code does
228/// produce an unrecognized error kind, the robust solution is to check for all
229/// the recognized error kinds and fail in those cases.
230#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
231#[stable(feature = "rust1", since = "1.0.0")]
232#[cfg_attr(not(test), rustc_diagnostic_item = "io_errorkind")]
233#[allow(deprecated)]
234#[non_exhaustive]
235pub enum ErrorKind {
236 /// An entity was not found, often a file.
237 #[stable(feature = "rust1", since = "1.0.0")]
238 NotFound,
239 /// The operation lacked the necessary privileges to complete.
240 #[stable(feature = "rust1", since = "1.0.0")]
241 PermissionDenied,
242 /// The connection was refused by the remote server.
243 #[stable(feature = "rust1", since = "1.0.0")]
244 ConnectionRefused,
245 /// The connection was reset by the remote server.
246 #[stable(feature = "rust1", since = "1.0.0")]
247 ConnectionReset,
248 /// The remote host is not reachable.
249 #[stable(feature = "io_error_a_bit_more", since = "1.83.0")]
250 HostUnreachable,
251 /// The network containing the remote host is not reachable.
252 #[stable(feature = "io_error_a_bit_more", since = "1.83.0")]
253 NetworkUnreachable,
254 /// The connection was aborted (terminated) by the remote server.
255 #[stable(feature = "rust1", since = "1.0.0")]
256 ConnectionAborted,
257 /// The network operation failed because it was not connected yet.
258 #[stable(feature = "rust1", since = "1.0.0")]
259 NotConnected,
260 /// A socket address could not be bound because the address is already in
261 /// use elsewhere.
262 #[stable(feature = "rust1", since = "1.0.0")]
263 AddrInUse,
264 /// A nonexistent interface was requested or the requested address was not
265 /// local.
266 #[stable(feature = "rust1", since = "1.0.0")]
267 AddrNotAvailable,
268 /// The system's networking is down.
269 #[stable(feature = "io_error_a_bit_more", since = "1.83.0")]
270 NetworkDown,
271 /// The operation failed because a pipe was closed.
272 #[stable(feature = "rust1", since = "1.0.0")]
273 BrokenPipe,
274 /// An entity already exists, often a file.
275 #[stable(feature = "rust1", since = "1.0.0")]
276 AlreadyExists,
277 /// The operation needs to block to complete, but the blocking operation was
278 /// requested to not occur.
279 #[stable(feature = "rust1", since = "1.0.0")]
280 WouldBlock,
281 /// A filesystem object is, unexpectedly, not a directory.
282 ///
283 /// For example, a filesystem path was specified where one of the intermediate directory
284 /// components was, in fact, a plain file.
285 #[stable(feature = "io_error_a_bit_more", since = "1.83.0")]
286 NotADirectory,
287 /// The filesystem object is, unexpectedly, a directory.
288 ///
289 /// A directory was specified when a non-directory was expected.
290 #[stable(feature = "io_error_a_bit_more", since = "1.83.0")]
291 IsADirectory,
292 /// A non-empty directory was specified where an empty directory was expected.
293 #[stable(feature = "io_error_a_bit_more", since = "1.83.0")]
294 DirectoryNotEmpty,
295 /// The filesystem or storage medium is read-only, but a write operation was attempted.
296 #[stable(feature = "io_error_a_bit_more", since = "1.83.0")]
297 ReadOnlyFilesystem,
298 /// Loop in the filesystem or IO subsystem; often, too many levels of symbolic links.
299 ///
300 /// There was a loop (or excessively long chain) resolving a filesystem object
301 /// or file IO object.
302 ///
303 /// On Unix this is usually the result of a symbolic link loop; or, of exceeding the
304 /// system-specific limit on the depth of symlink traversal.
305 #[unstable(feature = "io_error_more", issue = "86442")]
306 FilesystemLoop,
307 /// Stale network file handle.
308 ///
309 /// With some network filesystems, notably NFS, an open file (or directory) can be invalidated
310 /// by problems with the network or server.
311 #[stable(feature = "io_error_a_bit_more", since = "1.83.0")]
312 StaleNetworkFileHandle,
313 /// A parameter was incorrect.
314 #[stable(feature = "rust1", since = "1.0.0")]
315 InvalidInput,
316 /// Data not valid for the operation were encountered.
317 ///
318 /// Unlike [`InvalidInput`], this typically means that the operation
319 /// parameters were valid, however the error was caused by malformed
320 /// input data.
321 ///
322 /// For example, a function that reads a file into a string will error with
323 /// `InvalidData` if the file's contents are not valid UTF-8.
324 ///
325 /// [`InvalidInput`]: ErrorKind::InvalidInput
326 #[stable(feature = "io_invalid_data", since = "1.2.0")]
327 InvalidData,
328 /// The I/O operation's timeout expired, causing it to be canceled.
329 #[stable(feature = "rust1", since = "1.0.0")]
330 TimedOut,
331 /// An error returned when an operation could not be completed because a
332 /// call to [`write`] returned [`Ok(0)`].
333 ///
334 /// This typically means that an operation could only succeed if it wrote a
335 /// particular number of bytes but only a smaller number of bytes could be
336 /// written.
337 ///
338 /// [`write`]: crate::io::Write::write
339 /// [`Ok(0)`]: Ok
340 #[stable(feature = "rust1", since = "1.0.0")]
341 WriteZero,
342 /// The underlying storage (typically, a filesystem) is full.
343 ///
344 /// This does not include out of quota errors.
345 #[stable(feature = "io_error_a_bit_more", since = "1.83.0")]
346 StorageFull,
347 /// Seek on unseekable file.
348 ///
349 /// Seeking was attempted on an open file handle which is not suitable for seeking - for
350 /// example, on Unix, a named pipe opened with `File::open`.
351 #[stable(feature = "io_error_a_bit_more", since = "1.83.0")]
352 NotSeekable,
353 /// Filesystem quota or some other kind of quota was exceeded.
354 #[stable(feature = "io_error_quota_exceeded", since = "1.85.0")]
355 QuotaExceeded,
356 /// File larger than allowed or supported.
357 ///
358 /// This might arise from a hard limit of the underlying filesystem or file access API, or from
359 /// an administratively imposed resource limitation. Simple disk full, and out of quota, have
360 /// their own errors.
361 #[stable(feature = "io_error_a_bit_more", since = "1.83.0")]
362 FileTooLarge,
363 /// Resource is busy.
364 #[stable(feature = "io_error_a_bit_more", since = "1.83.0")]
365 ResourceBusy,
366 /// Executable file is busy.
367 ///
368 /// An attempt was made to write to a file which is also in use as a running program. (Not all
369 /// operating systems detect this situation.)
370 #[stable(feature = "io_error_a_bit_more", since = "1.83.0")]
371 ExecutableFileBusy,
372 /// Deadlock (avoided).
373 ///
374 /// A file locking operation would result in deadlock. This situation is typically detected, if
375 /// at all, on a best-effort basis.
376 #[stable(feature = "io_error_a_bit_more", since = "1.83.0")]
377 Deadlock,
378 /// Cross-device or cross-filesystem (hard) link or rename.
379 #[stable(feature = "io_error_crosses_devices", since = "1.85.0")]
380 CrossesDevices,
381 /// Too many (hard) links to the same filesystem object.
382 ///
383 /// The filesystem does not support making so many hardlinks to the same file.
384 #[stable(feature = "io_error_a_bit_more", since = "1.83.0")]
385 TooManyLinks,
386 /// A filename was invalid.
387 ///
388 /// This error can also occur if a length limit for a name was exceeded.
389 #[stable(feature = "io_error_invalid_filename", since = "1.87.0")]
390 InvalidFilename,
391 /// Program argument list too long.
392 ///
393 /// When trying to run an external program, a system or process limit on the size of the
394 /// arguments would have been exceeded.
395 #[stable(feature = "io_error_a_bit_more", since = "1.83.0")]
396 ArgumentListTooLong,
397 /// This operation was interrupted.
398 ///
399 /// Interrupted operations can typically be retried.
400 #[stable(feature = "rust1", since = "1.0.0")]
401 Interrupted,
402
403 /// This operation is unsupported on this platform.
404 ///
405 /// This means that the operation can never succeed.
406 #[stable(feature = "unsupported_error", since = "1.53.0")]
407 Unsupported,
408
409 // ErrorKinds which are primarily categorisations for OS error
410 // codes should be added above.
411 //
412 /// An error returned when an operation could not be completed because an
413 /// "end of file" was reached prematurely.
414 ///
415 /// This typically means that an operation could only succeed if it read a
416 /// particular number of bytes but only a smaller number of bytes could be
417 /// read.
418 #[stable(feature = "read_exact", since = "1.6.0")]
419 UnexpectedEof,
420
421 /// An operation could not be completed, because it failed
422 /// to allocate enough memory.
423 #[stable(feature = "out_of_memory_error", since = "1.54.0")]
424 OutOfMemory,
425
426 /// The operation was partially successful and needs to be checked
427 /// later on due to not blocking.
428 #[unstable(feature = "io_error_inprogress", issue = "130840")]
429 InProgress,
430
431 // "Unusual" error kinds which do not correspond simply to (sets
432 // of) OS error codes, should be added just above this comment.
433 // `Other` and `Uncategorized` should remain at the end:
434 //
435 /// A custom error that does not fall under any other I/O error kind.
436 ///
437 /// This can be used to construct your own [`Error`]s that do not match any
438 /// [`ErrorKind`].
439 ///
440 /// This [`ErrorKind`] is not used by the standard library.
441 ///
442 /// Errors from the standard library that do not fall under any of the I/O
443 /// error kinds cannot be `match`ed on, and will only match a wildcard (`_`) pattern.
444 /// New [`ErrorKind`]s might be added in the future for some of those.
445 #[stable(feature = "rust1", since = "1.0.0")]
446 Other,
447
448 /// Any I/O error from the standard library that's not part of this list.
449 ///
450 /// Errors that are `Uncategorized` now may move to a different or a new
451 /// [`ErrorKind`] variant in the future. It is not recommended to match
452 /// an error against `Uncategorized`; use a wildcard match (`_`) instead.
453 #[unstable(feature = "io_error_uncategorized", issue = "none")]
454 #[doc(hidden)]
455 Uncategorized,
456}
457
458impl ErrorKind {
459 pub(crate) fn as_str(&self) -> &'static str {
460 use ErrorKind::*;
461 match *self {
462 // tidy-alphabetical-start
463 AddrInUse => "address in use",
464 AddrNotAvailable => "address not available",
465 AlreadyExists => "entity already exists",
466 ArgumentListTooLong => "argument list too long",
467 BrokenPipe => "broken pipe",
468 ConnectionAborted => "connection aborted",
469 ConnectionRefused => "connection refused",
470 ConnectionReset => "connection reset",
471 CrossesDevices => "cross-device link or rename",
472 Deadlock => "deadlock",
473 DirectoryNotEmpty => "directory not empty",
474 ExecutableFileBusy => "executable file busy",
475 FileTooLarge => "file too large",
476 FilesystemLoop => "filesystem loop or indirection limit (e.g. symlink loop)",
477 HostUnreachable => "host unreachable",
478 InProgress => "in progress",
479 Interrupted => "operation interrupted",
480 InvalidData => "invalid data",
481 InvalidFilename => "invalid filename",
482 InvalidInput => "invalid input parameter",
483 IsADirectory => "is a directory",
484 NetworkDown => "network down",
485 NetworkUnreachable => "network unreachable",
486 NotADirectory => "not a directory",
487 NotConnected => "not connected",
488 NotFound => "entity not found",
489 NotSeekable => "seek on unseekable file",
490 Other => "other error",
491 OutOfMemory => "out of memory",
492 PermissionDenied => "permission denied",
493 QuotaExceeded => "quota exceeded",
494 ReadOnlyFilesystem => "read-only filesystem or storage medium",
495 ResourceBusy => "resource busy",
496 StaleNetworkFileHandle => "stale network file handle",
497 StorageFull => "no storage space",
498 TimedOut => "timed out",
499 TooManyLinks => "too many links",
500 Uncategorized => "uncategorized error",
501 UnexpectedEof => "unexpected end of file",
502 Unsupported => "unsupported",
503 WouldBlock => "operation would block",
504 WriteZero => "write zero",
505 // tidy-alphabetical-end
506 }
507 }
508}
509
510#[stable(feature = "io_errorkind_display", since = "1.60.0")]
511impl fmt::Display for ErrorKind {
512 /// Shows a human-readable description of the `ErrorKind`.
513 ///
514 /// This is similar to `impl Display for Error`, but doesn't require first converting to Error.
515 ///
516 /// # Examples
517 /// ```
518 /// use std::io::ErrorKind;
519 /// assert_eq!("entity not found", ErrorKind::NotFound.to_string());
520 /// ```
521 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
522 fmt.write_str(self.as_str())
523 }
524}
525
526212/// Intended for use for errors not exposed to the user, where allocating onto
527213/// the heap (for normal construction via Error::new) is too costly.
528214#[stable(feature = "io_error_from_errorkind", since = "1.14.0")]
......@@ -1051,7 +737,7 @@ impl fmt::Display for Error {
1051737 write!(fmt, "{detail} (os error {code})")
1052738 }
1053739 ErrorData::Custom(ref c) => c.error.fmt(fmt),
1054 ErrorData::Simple(kind) => write!(fmt, "{}", kind.as_str()),
740 ErrorData::Simple(kind) => kind.fmt(fmt),
1055741 ErrorData::SimpleMessage(msg) => msg.message.fmt(fmt),
1056742 }
1057743 }
library/std/src/io/error/repr_bitpacked.rs+1-64
......@@ -253,7 +253,7 @@ where
253253 }
254254 TAG_SIMPLE => {
255255 let kind_bits = (bits >> 32) as u32;
256 let kind = kind_from_prim(kind_bits).unwrap_or_else(|| {
256 let kind = ErrorKind::from_prim(kind_bits).unwrap_or_else(|| {
257257 debug_assert!(false, "Invalid io::error::Repr bits: `Repr({:#018x})`", bits);
258258 // This means the `ptr` passed in was not valid, which violates
259259 // the unsafe contract of `decode_repr`.
......@@ -283,69 +283,6 @@ where
283283 }
284284}
285285
286// This compiles to the same code as the check+transmute, but doesn't require
287// unsafe, or to hard-code max ErrorKind or its size in a way the compiler
288// couldn't verify.
289#[inline]
290fn kind_from_prim(ek: u32) -> Option<ErrorKind> {
291 macro_rules! from_prim {
292 ($prim:expr => $Enum:ident { $($Variant:ident),* $(,)? }) => {{
293 // Force a compile error if the list gets out of date.
294 const _: fn(e: $Enum) = |e: $Enum| match e {
295 $($Enum::$Variant => ()),*
296 };
297 match $prim {
298 $(v if v == ($Enum::$Variant as _) => Some($Enum::$Variant),)*
299 _ => None,
300 }
301 }}
302 }
303 from_prim!(ek => ErrorKind {
304 NotFound,
305 PermissionDenied,
306 ConnectionRefused,
307 ConnectionReset,
308 HostUnreachable,
309 NetworkUnreachable,
310 ConnectionAborted,
311 NotConnected,
312 AddrInUse,
313 AddrNotAvailable,
314 NetworkDown,
315 BrokenPipe,
316 AlreadyExists,
317 WouldBlock,
318 NotADirectory,
319 IsADirectory,
320 DirectoryNotEmpty,
321 ReadOnlyFilesystem,
322 FilesystemLoop,
323 StaleNetworkFileHandle,
324 InvalidInput,
325 InvalidData,
326 TimedOut,
327 WriteZero,
328 StorageFull,
329 NotSeekable,
330 QuotaExceeded,
331 FileTooLarge,
332 ResourceBusy,
333 ExecutableFileBusy,
334 Deadlock,
335 CrossesDevices,
336 TooManyLinks,
337 InvalidFilename,
338 ArgumentListTooLong,
339 Interrupted,
340 Other,
341 UnexpectedEof,
342 Unsupported,
343 OutOfMemory,
344 InProgress,
345 Uncategorized,
346 })
347}
348
349286// Some static checking to alert us if a change breaks any of the assumptions
350287// that our encoding relies on for correctness and soundness. (Some of these are
351288// a bit overly thorough/cautious, admittedly)
library/std/src/lib.rs+5
......@@ -321,7 +321,9 @@
321321#![feature(const_default)]
322322#![feature(core_float_math)]
323323#![feature(core_intrinsics)]
324#![feature(core_io)]
324325#![feature(core_io_borrowed_buf)]
326#![feature(core_io_internals)]
325327#![feature(cstr_display)]
326328#![feature(drop_guard)]
327329#![feature(duration_constants)]
......@@ -344,6 +346,9 @@
344346#![feature(hashmap_internals)]
345347#![feature(hint_must_use)]
346348#![feature(int_from_ascii)]
349#![feature(io_error_inprogress)]
350#![feature(io_error_more)]
351#![feature(io_error_uncategorized)]
347352#![feature(ip)]
348353#![feature(iter_advance_by)]
349354#![feature(iter_next_chunk)]
library/std/src/sys/io/error/sgx.rs+1-1
......@@ -60,6 +60,6 @@ pub fn error_string(errno: i32) -> String {
6060 } else if ((Error::UserRangeStart as _)..=(Error::UserRangeEnd as _)).contains(&errno) {
6161 format!("user-specified error {errno:08x}")
6262 } else {
63 decode_error_kind(errno).as_str().into()
63 format!("{}", decode_error_kind(errno))
6464 }
6565}
src/bootstrap/src/core/config/config.rs+37-18
......@@ -2196,6 +2196,42 @@ pub fn check_stage0_version(
21962196 }
21972197}
21982198
2199fn print_rustc_modifications(
2200 dwn_ctx: &DownloadContext<'_>,
2201 if_unchanged: bool,
2202 mut modifications: Vec<PathBuf>,
2203) -> Option<()> {
2204 if !dwn_ctx.exec_ctx.is_verbose() {
2205 modifications.retain(|path| !path.starts_with("compiler"));
2206 }
2207 if modifications.is_empty() {
2208 // only compiler changes; still force a rebuild but don't say why.
2209 eprintln!(
2210 "skipping rustc download with `download-rustc = 'if-unchanged'` due to local changes"
2211 );
2212 return None;
2213 }
2214
2215 eprintln!(
2216 "NOTE: detected {} modifications that could affect a build of rustc",
2217 modifications.len()
2218 );
2219 for file in modifications.iter().take(10) {
2220 eprintln!("- {}", file.display());
2221 }
2222 if modifications.len() > 10 {
2223 eprintln!("- ... and {} more", modifications.len() - 10);
2224 }
2225
2226 if if_unchanged {
2227 eprintln!("skipping rustc download due to `download-rustc = 'if-unchanged'`");
2228 None
2229 } else {
2230 eprintln!("downloading unconditionally due to `download-rustc = true`");
2231 Some(())
2232 }
2233}
2234
21992235pub fn download_ci_rustc_commit<'a>(
22002236 dwn_ctx: impl AsRef<DownloadContext<'a>>,
22012237 rust_info: &channel::GitInfo,
......@@ -2250,24 +2286,7 @@ pub fn download_ci_rustc_commit<'a>(
22502286 return None;
22512287 }
22522288
2253 eprintln!(
2254 "NOTE: detected {} modifications that could affect a build of rustc",
2255 modifications.len()
2256 );
2257 for file in modifications.iter().take(10) {
2258 eprintln!("- {}", file.display());
2259 }
2260 if modifications.len() > 10 {
2261 eprintln!("- ... and {} more", modifications.len() - 10);
2262 }
2263
2264 if if_unchanged {
2265 eprintln!("skipping rustc download due to `download-rustc = 'if-unchanged'`");
2266 return None;
2267 } else {
2268 eprintln!("downloading unconditionally due to `download-rustc = true`");
2269 }
2270
2289 print_rustc_modifications(dwn_ctx, if_unchanged, modifications)?;
22712290 upstream
22722291 }
22732292 PathFreshness::MissingUpstream => {
tests/run-make/macho-link-section/foo.rs created+14
......@@ -0,0 +1,14 @@
1#[unsafe(no_mangle)]
2#[unsafe(link_section = "__TEXT,custom_code,regular,pure_instructions")]
3static CODE: [u8; 10] = *b"0123456789";
4
5#[unsafe(no_mangle)]
6#[unsafe(link_section = "__DATA,all_attributes,regular,pure_instructions\
7 +no_toc+strip_static_syms+no_dead_strip+live_support\
8 +self_modifying_code+debug")]
9static ALL_THE_ATTRIBUTES: u32 = 42;
10
11#[unsafe(no_mangle)]
12#[unsafe(link_section = "__DATA,__mod_init_func,mod_init_funcs")]
13static CONSTRUCTOR: extern "C" fn() = constructor;
14extern "C" fn constructor() {}
tests/run-make/macho-link-section/rmake.rs created+47
......@@ -0,0 +1,47 @@
1//! Test that various Mach-O `#[link_section]` values are parsed and passed on correctly by codegen
2//! backends.
3//@ only-apple
4use run_make_support::{llvm_objdump, rustc};
5
6fn main() {
7 rustc().input("foo.rs").crate_type("lib").arg("--emit=obj").run();
8
9 let stdout =
10 llvm_objdump().arg("--macho").arg("--private-headers").input("foo.o").run().stdout_utf8();
11
12 let expected = [
13 ("__TEXT", "custom_code", "S_REGULAR", "PURE_INSTRUCTIONS"),
14 ("__DATA", "__mod_init_func", "S_MOD_INIT_FUNC_POINTERS", "(none)"),
15 (
16 "__DATA",
17 "all_attributes",
18 "S_REGULAR",
19 "PURE_INSTRUCTIONS NO_TOC STRIP_STATIC_SYMS \
20 NO_DEAD_STRIP LIVE_SUPPORT SELF_MODIFYING_CODE DEBUG",
21 ),
22 ];
23
24 for (segment, section, section_type, section_attributes) in expected {
25 let mut found = false;
26 // Skip header.
27 for section_info in stdout.split("Section").skip(1) {
28 if section_info.contains(&format!("segname {segment}"))
29 && section_info.contains(&format!("sectname {section}"))
30 {
31 assert!(
32 section_info.contains(&format!("type {section_type}")),
33 "should have type {section_type:?}"
34 );
35 assert!(
36 section_info.contains(&format!("attributes {section_attributes}\n")),
37 "should have attributes {section_attributes:?}"
38 );
39 found = true;
40 }
41 }
42
43 if !found {
44 panic!("could not find section {section} in binary");
45 }
46 }
47}
tests/rustdoc-html/intra-doc/deprecated.rs+2-2
......@@ -1,6 +1,6 @@
11//@ has deprecated/struct.A.html '//a[@href="{{channel}}/core/ops/range/struct.Range.html#structfield.start"]' 'start'
2//@ has deprecated/struct.B1.html '//a[@href="{{channel}}/std/io/error/enum.ErrorKind.html#variant.NotFound"]' 'not_found'
3//@ has deprecated/struct.B2.html '//a[@href="{{channel}}/std/io/error/enum.ErrorKind.html#variant.NotFound"]' 'not_found'
2//@ has deprecated/struct.B1.html '//a[@href="{{channel}}/core/io/error/enum.ErrorKind.html#variant.NotFound"]' 'not_found'
3//@ has deprecated/struct.B2.html '//a[@href="{{channel}}/core/io/error/enum.ErrorKind.html#variant.NotFound"]' 'not_found'
44
55#[deprecated = "[start][std::ops::Range::start]"]
66pub struct A;
tests/rustdoc-html/intra-doc/field.rs+2-2
......@@ -1,9 +1,9 @@
11//@ has field/index.html '//a[@href="{{channel}}/core/ops/range/struct.Range.html#structfield.start"]' 'start'
2//@ has field/index.html '//a[@href="{{channel}}/std/io/error/enum.ErrorKind.html#variant.NotFound"]' 'not_found'
2//@ has field/index.html '//a[@href="{{channel}}/core/io/error/enum.ErrorKind.html#variant.NotFound"]' 'not_found'
33//@ has field/index.html '//a[@href="struct.FieldAndMethod.html#structfield.x"]' 'x'
44//@ has field/index.html '//a[@href="enum.VariantAndMethod.html#variant.X"]' 'X'
55//! [start][std::ops::Range::start]
6//! [not_found][std::io::ErrorKind::NotFound]
6//! [not_found][core::io::ErrorKind::NotFound]
77//! [x][field@crate::FieldAndMethod::x]
88//! [X][variant@crate::VariantAndMethod::X]
99
tests/ui/explicit-tail-calls/caller_is_track_caller.rs+9
......@@ -13,4 +13,13 @@ fn c() {
1313 become a(); //~ error: a function marked with `#[track_caller]` cannot perform a tail-call
1414}
1515
16trait Trait {
17 fn d(&self);
18
19 #[track_caller]
20 fn e(&self) {
21 become self.d(); //~ error: a function marked with `#[track_caller]` cannot perform a tail-call
22 }
23}
24
1625fn main() {}
tests/ui/explicit-tail-calls/caller_is_track_caller.stderr+7-1
......@@ -10,5 +10,11 @@ error: a function marked with `#[track_caller]` cannot perform a tail-call
1010LL | become a();
1111 | ^^^^^^^^^^
1212
13error: aborting due to 2 previous errors
13error: a function marked with `#[track_caller]` cannot perform a tail-call
14 --> $DIR/caller_is_track_caller.rs:21:9
15 |
16LL | become self.d();
17 | ^^^^^^^^^^^^^^^
18
19error: aborting due to 3 previous errors
1420
tests/ui/explicit-tail-calls/default-trait-method.rs created+38
......@@ -0,0 +1,38 @@
1// A regression test for <https://github.com/rust-lang/rust/issues/144985>.
2// Previously, using `become` in a default trait method would lead to an ICE
3// in a path determining whether the method in question is marked as `#[track_caller]`.
4//
5//@ run-pass
6//@ ignore-backends: gcc
7
8#![feature(explicit_tail_calls)]
9#![expect(incomplete_features)]
10
11trait Trait {
12 fn bar(&self) -> usize {
13 123
14 }
15
16 fn foo(&self) -> usize {
17 #[allow(tail_call_track_caller)]
18 become self.bar();
19 }
20}
21
22struct Struct;
23
24impl Trait for Struct {}
25
26struct OtherStruct;
27
28impl Trait for OtherStruct {
29 #[track_caller]
30 fn bar(&self) -> usize {
31 456
32 }
33}
34
35fn main() {
36 assert_eq!(Struct.foo(), 123);
37 assert_eq!(OtherStruct.foo(), 456);
38}
tests/ui/feature-gates/feature-gate-io_error_kind_in_core.rs created+12
......@@ -0,0 +1,12 @@
1// Ensure `ErrorKind` from `core` is gated behind `core_io`
2//@ edition:2024
3
4use std::io::ErrorKind as ErrorKindFromStd;
5
6use core::io::ErrorKind as ErrorKindFromCore;
7//~^ ERROR use of unstable library feature `core_io`
8
9// Asserting both ErrorKinds are the same.
10const _: [ErrorKindFromCore; 1] = [ErrorKindFromStd::Other];
11
12fn main() {}
tests/ui/feature-gates/feature-gate-io_error_kind_in_core.stderr created+13
......@@ -0,0 +1,13 @@
1error[E0658]: use of unstable library feature `core_io`
2 --> $DIR/feature-gate-io_error_kind_in_core.rs:6:5
3 |
4LL | use core::io::ErrorKind as ErrorKindFromCore;
5 | ^^^^^^^^^^^^^^^^^^^
6 |
7 = note: see issue #154046 <https://github.com/rust-lang/rust/issues/154046> for more information
8 = help: add `#![feature(core_io)]` to the crate attributes to enable
9 = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date
10
11error: aborting due to 1 previous error
12
13For more information about this error, try `rustc --explain E0658`.
tests/ui/imports/ambiguous-import-visibility-globglob-priv-pass.rs created+23
......@@ -0,0 +1,23 @@
1//@ check-pass
2
3mod m {
4 pub struct S {}
5}
6
7mod one_private {
8 use crate::m::*;
9 pub use crate::m::*;
10}
11
12// One of the ambiguous imports is not visible from here,
13// and does not contribute to the ambiguity.
14use crate::one_private::S;
15
16// Separate module to make visibilities `in crate::inner` and `in crate::one_private` unordered.
17mod inner {
18 // One of the ambiguous imports is not visible from here,
19 // and does not contribute to the ambiguity.
20 use crate::one_private::S;
21}
22
23fn main() {}
tests/ui/imports/ambiguous-import-visibility-globglob-priv.rs created+21
......@@ -0,0 +1,21 @@
1mod m {
2 pub struct S {}
3}
4
5mod both {
6 pub mod private {
7 use crate::m::*;
8 pub(super) use crate::m::*;
9 }
10}
11
12use crate::both::private::S;
13//~^ ERROR struct import `S` is private
14
15// Separate module to make visibilities `in crate::inner` and `in crate::both(::private)` unordered.
16mod inner {
17 use crate::both::private::S;
18 //~^ ERROR struct import `S` is private
19}
20
21fn main() {}
tests/ui/imports/ambiguous-import-visibility-globglob-priv.stderr created+47
......@@ -0,0 +1,47 @@
1error[E0603]: struct import `S` is private
2 --> $DIR/ambiguous-import-visibility-globglob-priv.rs:12:27
3 |
4LL | use crate::both::private::S;
5 | ^ private struct import
6 |
7note: the struct import `S` is defined here...
8 --> $DIR/ambiguous-import-visibility-globglob-priv.rs:8:24
9 |
10LL | pub(super) use crate::m::*;
11 | ^^^^^^^^^^^
12note: ...and refers to the struct `S` which is defined here
13 --> $DIR/ambiguous-import-visibility-globglob-priv.rs:2:5
14 |
15LL | pub struct S {}
16 | ^^^^^^^^^^^^ you could import this directly
17help: import `S` through the re-export
18 |
19LL - use crate::both::private::S;
20LL + use m::S;
21 |
22
23error[E0603]: struct import `S` is private
24 --> $DIR/ambiguous-import-visibility-globglob-priv.rs:17:31
25 |
26LL | use crate::both::private::S;
27 | ^ private struct import
28 |
29note: the struct import `S` is defined here...
30 --> $DIR/ambiguous-import-visibility-globglob-priv.rs:8:24
31 |
32LL | pub(super) use crate::m::*;
33 | ^^^^^^^^^^^
34note: ...and refers to the struct `S` which is defined here
35 --> $DIR/ambiguous-import-visibility-globglob-priv.rs:2:5
36 |
37LL | pub struct S {}
38 | ^^^^^^^^^^^^ you could import this directly
39help: import `S` through the re-export
40 |
41LL - use crate::both::private::S;
42LL + use m::S;
43 |
44
45error: aborting due to 2 previous errors
46
47For more information about this error, try `rustc --explain E0603`.
tests/ui/imports/ambiguous-import-visibility-globglob.rs created+39
......@@ -0,0 +1,39 @@
1//@ check-pass
2
3// FIXME: should report "ambiguous import visibility" in all the cases below.
4
5mod m {
6 pub struct S {}
7}
8
9mod min_vis_first {
10 use crate::m::*;
11 pub(crate) use crate::m::*;
12 pub use crate::m::*;
13
14 pub use self::S as S1;
15 pub(crate) use self::S as S2;
16 use self::S as S3; // OK
17}
18
19mod mid_vis_first {
20 pub(crate) use crate::m::*;
21 use crate::m::*;
22 pub use crate::m::*;
23
24 pub use self::S as S1;
25 pub(crate) use self::S as S2;
26 use self::S as S3; // OK
27}
28
29mod max_vis_first {
30 pub use crate::m::*;
31 use crate::m::*;
32 pub(crate) use crate::m::*;
33
34 pub use self::S as S1;
35 pub(crate) use self::S as S2;
36 use self::S as S3; // OK
37}
38
39fn main() {}
tests/ui/imports/private-from-decl-macro.fail.stderr created+27
......@@ -0,0 +1,27 @@
1error[E0423]: expected value, found struct `S`
2 --> $DIR/private-from-decl-macro.rs:27:17
3 |
4LL | pub struct S {}
5 | --------------- `S` defined here
6...
7LL | let s = S;
8 | ^
9 |
10note: constant `m::S` exists but is inaccessible
11 --> $DIR/private-from-decl-macro.rs:10:5
12 |
13LL | const S: u8 = 0;
14 | ^^^^^^^^^^^^^^^^ not accessible
15help: use struct literal syntax instead
16 |
17LL | let s = S {};
18 | ++
19help: a local variable with a similar name exists (notice the capitalization)
20 |
21LL - let s = S;
22LL + let s = s;
23 |
24
25error: aborting due to 1 previous error
26
27For more information about this error, try `rustc --explain E0423`.
tests/ui/imports/private-from-decl-macro.rs created+35
......@@ -0,0 +1,35 @@
1//@ revisions: pass fail
2//@[pass] check-pass
3
4#![feature(decl_macro)]
5
6mod m {
7 // Name in two namespaces, one public, one private.
8 // The private name is filtered away when importing, even from a macro 2.0
9 pub struct S {}
10 const S: u8 = 0;
11
12 pub macro mac_single($S:ident) {
13 use crate::m::$S;
14 }
15
16 pub macro mac_glob() {
17 use crate::m::*;
18 }
19}
20
21mod single {
22 crate::m::mac_single!(S);
23
24 fn check() {
25 let s = S {};
26 #[cfg(fail)]
27 let s = S; //[fail]~ ERROR expected value, found struct `S`
28 }
29}
30
31mod glob {
32 crate::m::mac_glob!();
33}
34
35fn main() {}
tests/ui/privacy/restricted/decl-macros.rs created+15
......@@ -0,0 +1,15 @@
1#![feature(decl_macro)]
2
3mod m {
4 pub macro mac() {
5 struct A {}
6 pub(self) struct B {} //~ ERROR visibilities can only be restricted to ancestor modules
7 pub(in crate::m) struct C {} //~ ERROR visibilities can only be restricted to ancestor modules
8 }
9}
10
11mod n {
12 crate::m::mac!();
13}
14
15fn main() {}
tests/ui/privacy/restricted/decl-macros.stderr created+25
......@@ -0,0 +1,25 @@
1error[E0742]: visibilities can only be restricted to ancestor modules
2 --> $DIR/decl-macros.rs:6:13
3 |
4LL | pub(self) struct B {}
5 | ^^^^
6...
7LL | crate::m::mac!();
8 | ---------------- in this macro invocation
9 |
10 = note: this error originates in the macro `crate::m::mac` (in Nightly builds, run with -Z macro-backtrace for more info)
11
12error[E0742]: visibilities can only be restricted to ancestor modules
13 --> $DIR/decl-macros.rs:7:16
14 |
15LL | pub(in crate::m) struct C {}
16 | ^^^^^^^^
17...
18LL | crate::m::mac!();
19 | ---------------- in this macro invocation
20 |
21 = note: this error originates in the macro `crate::m::mac` (in Nightly builds, run with -Z macro-backtrace for more info)
22
23error: aborting due to 2 previous errors
24
25For more information about this error, try `rustc --explain E0742`.
tests/ui/pub/pub-reexport-priv-extern-crate.rs+6-1
......@@ -4,6 +4,8 @@ pub use core as reexported_core; //~ ERROR `core` is private and cannot be re-ex
44
55mod foo1 {
66 extern crate core;
7 pub use self::core as core2; //~ ERROR extern crate `core` is private and cannot be re-exported
8 //~^ WARN this was previously accepted
79}
810
911mod foo2 {
......@@ -17,4 +19,7 @@ mod baz {
1719 pub use crate::foo2::bar::core; //~ ERROR crate import `core` is private
1820}
1921
20fn main() {}
22fn main() {
23 // Check that `foo1::core2` has the reexport's visibility and is accessible.
24 foo1::core2::mem::drop(());
25}
tests/ui/pub/pub-reexport-priv-extern-crate.stderr+32-4
......@@ -1,5 +1,5 @@
11error[E0603]: crate import `core` is private
2 --> $DIR/pub-reexport-priv-extern-crate.rs:10:22
2 --> $DIR/pub-reexport-priv-extern-crate.rs:12:22
33 |
44LL | use crate::foo1::core;
55 | ^^^^ private crate import
......@@ -11,13 +11,13 @@ LL | extern crate core;
1111 | ^^^^^^^^^^^^^^^^^^
1212
1313error[E0603]: crate import `core` is private
14 --> $DIR/pub-reexport-priv-extern-crate.rs:17:31
14 --> $DIR/pub-reexport-priv-extern-crate.rs:19:31
1515 |
1616LL | pub use crate::foo2::bar::core;
1717 | ^^^^ private crate import
1818 |
1919note: the crate import `core` is defined here
20 --> $DIR/pub-reexport-priv-extern-crate.rs:12:9
20 --> $DIR/pub-reexport-priv-extern-crate.rs:14:9
2121 |
2222LL | extern crate core;
2323 | ^^^^^^^^^^^^^^^^^^
......@@ -36,7 +36,20 @@ help: consider making the `extern crate` item publicly accessible
3636LL | pub extern crate core;
3737 | +++
3838
39error: aborting due to 3 previous errors
39error[E0365]: extern crate `core` is private and cannot be re-exported
40 --> $DIR/pub-reexport-priv-extern-crate.rs:7:13
41 |
42LL | pub use self::core as core2;
43 | ^^^^^^^^^^^^^^^^^^^
44 |
45 = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
46 = note: for more information, see issue #127909 <https://github.com/rust-lang/rust/issues/127909>
47help: consider making the `extern crate` item publicly accessible
48 |
49LL | pub extern crate core;
50 | +++
51
52error: aborting due to 4 previous errors
4053
4154Some errors have detailed explanations: E0365, E0603.
4255For more information about an error, try `rustc --explain E0365`.
......@@ -55,3 +68,18 @@ help: consider making the `extern crate` item publicly accessible
5568LL | pub extern crate core;
5669 | +++
5770
71Future breakage diagnostic:
72error[E0365]: extern crate `core` is private and cannot be re-exported
73 --> $DIR/pub-reexport-priv-extern-crate.rs:7:13
74 |
75LL | pub use self::core as core2;
76 | ^^^^^^^^^^^^^^^^^^^
77 |
78 = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
79 = note: for more information, see issue #127909 <https://github.com/rust-lang/rust/issues/127909>
80 = note: `#[deny(pub_use_of_private_extern_crate)]` (part of `#[deny(future_incompatible)]`) on by default
81help: consider making the `extern crate` item publicly accessible
82 |
83LL | pub extern crate core;
84 | +++
85
tests/ui/resolve/decl-macro-use-no-ice.rs+1-1
......@@ -11,7 +11,7 @@ mod foo {
1111
1212 pub macro m() {
1313 use f; //~ ERROR `f` is private, and cannot be re-exported
14 f!(); //~ ERROR macro import `f` is private
14 f!();
1515 }
1616}
1717
tests/ui/resolve/decl-macro-use-no-ice.stderr+2-27
......@@ -17,31 +17,6 @@ LL | foo::m!();
1717 | --------- in this macro invocation
1818 = note: this error originates in the macro `foo::m` (in Nightly builds, run with -Z macro-backtrace for more info)
1919
20error[E0603]: macro import `f` is private
21 --> $DIR/decl-macro-use-no-ice.rs:14:9
22 |
23LL | f!();
24 | ^ private macro import
25...
26LL | foo::m!();
27 | --------- in this macro invocation
28 |
29note: the macro import `f` is defined here...
30 --> $DIR/decl-macro-use-no-ice.rs:13:13
31 |
32LL | use f;
33 | ^
34...
35LL | foo::m!();
36 | --------- in this macro invocation
37note: ...and refers to the macro `f` which is defined here
38 --> $DIR/decl-macro-use-no-ice.rs:10:5
39 |
40LL | macro f() {}
41 | ^^^^^^^^^
42 = note: this error originates in the macro `foo::m` (in Nightly builds, run with -Z macro-backtrace for more info)
43
44error: aborting due to 2 previous errors
20error: aborting due to 1 previous error
4521
46Some errors have detailed explanations: E0364, E0603.
47For more information about an error, try `rustc --explain E0364`.
22For more information about this error, try `rustc --explain E0364`.
tests/ui/single-use-lifetime/anonymous_lifetime_in_impl_trait.rs created+20
......@@ -0,0 +1,20 @@
1//@ revisions: with-gate without-gate
2//@ [with-gate] run-rustfix
3//@ [without-gate] check-pass
4
5#![cfg_attr(with_gate, feature(anonymous_lifetime_in_impl_trait))]
6
7#![deny(single_use_lifetimes)]
8
9// https://github.com/rust-lang/rust/issues/153836
10
11fn foo<'a>(x: impl IntoIterator<Item = &'a i32>) {
12//[with-gate]~^ ERROR: lifetime parameter `'a` only used once [single_use_lifetimes]
13 for i in x {
14 dbg!(i);
15 }
16}
17
18fn main() {
19 foo(&[1, 2, 3]);
20}
tests/ui/single-use-lifetime/anonymous_lifetime_in_impl_trait.with-gate.fixed created+20
......@@ -0,0 +1,20 @@
1//@ revisions: with-gate without-gate
2//@ [with-gate] run-rustfix
3//@ [without-gate] check-pass
4
5#![cfg_attr(with_gate, feature(anonymous_lifetime_in_impl_trait))]
6
7#![deny(single_use_lifetimes)]
8
9// https://github.com/rust-lang/rust/issues/153836
10
11fn foo(x: impl IntoIterator<Item = &i32>) {
12//[with-gate]~^ ERROR: lifetime parameter `'a` only used once [single_use_lifetimes]
13 for i in x {
14 dbg!(i);
15 }
16}
17
18fn main() {
19 foo(&[1, 2, 3]);
20}
tests/ui/single-use-lifetime/anonymous_lifetime_in_impl_trait.with-gate.stderr created+19
......@@ -0,0 +1,19 @@
1error: lifetime parameter `'a` only used once
2 --> $DIR/anonymous_lifetime_in_impl_trait.rs:11:8
3 |
4LL | fn foo<'a>(x: impl IntoIterator<Item = &'a i32>) {
5 | ^^ this lifetime... -- ...is used only here
6 |
7note: the lint level is defined here
8 --> $DIR/anonymous_lifetime_in_impl_trait.rs:7:9
9 |
10LL | #![deny(single_use_lifetimes)]
11 | ^^^^^^^^^^^^^^^^^^^^
12help: elide the single-use lifetime
13 |
14LL - fn foo<'a>(x: impl IntoIterator<Item = &'a i32>) {
15LL + fn foo(x: impl IntoIterator<Item = &i32>) {
16 |
17
18error: aborting due to 1 previous error
19