Skip to content

Commit 4605628

Browse files
committed
Auto merge of #60796 - cuviper:try-desugar-into, r=<try>
[WIP] Use `Into::into` in operator `?` #38751 proposes using `into` for `?`, and while commenters suggested problems with inference, I couldn't find any evidence where this was actually attempted -- so here we go!
2 parents 823a75d + a96f3b2 commit 4605628

File tree

19 files changed

+44
-34
lines changed

19 files changed

+44
-34
lines changed

src/libcore/ops/try.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ pub trait Try {
3434
///
3535
/// If an `Err(e)` result is returned, the value `e` will be "wrapped"
3636
/// in the return type of the enclosing scope (which must itself implement
37-
/// `Try`). Specifically, the value `X::from_error(From::from(e))`
37+
/// `Try`). Specifically, the value `X::from_error(Into::into(e))`
3838
/// is returned, where `X` is the return type of the enclosing function.
3939
#[unstable(feature = "try_trait", issue = "42327")]
4040
fn into_result(self) -> Result<Self::Ok, Self::Error>;

src/libcore/tests/result.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -198,7 +198,7 @@ pub fn test_unwrap_or_default() {
198198
#[test]
199199
fn test_try() {
200200
fn try_result_some() -> Option<u8> {
201-
let val = Ok(1)?;
201+
let val = Ok::<_, NoneError>(1)?;
202202
Some(val)
203203
}
204204
assert_eq!(try_result_some(), Some(1));

src/librustc/dep_graph/dep_node.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -370,7 +370,7 @@ impl fmt::Debug for DepNode {
370370

371371
write!(f, "(")?;
372372

373-
crate::ty::tls::with_opt(|opt_tcx| {
373+
crate::ty::tls::with_opt(|opt_tcx| -> fmt::Result {
374374
if let Some(tcx) = opt_tcx {
375375
if let Some(def_id) = self.extract_def_id(tcx) {
376376
write!(f, "{}", tcx.def_path_debug_str(def_id))?;

src/librustc/hir/def_id.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,7 @@ impl fmt::Debug for DefId {
171171
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
172172
write!(f, "DefId({}:{}", self.krate, self.index.as_array_index())?;
173173

174-
ty::tls::with_opt(|opt_tcx| {
174+
ty::tls::with_opt(|opt_tcx| -> fmt::Result {
175175
if let Some(tcx) = opt_tcx {
176176
write!(f, " ~ {}", tcx.def_path_debug_str(*self))?;
177177
}

src/librustc/hir/lowering.rs

+7-7
Original file line numberDiff line numberDiff line change
@@ -4763,9 +4763,9 @@ impl<'a> LoweringContext<'a> {
47634763
// Ok(val) => #[allow(unreachable_code)] val,
47644764
// Err(err) => #[allow(unreachable_code)]
47654765
// // If there is an enclosing `catch {...}`
4766-
// break 'catch_target Try::from_error(From::from(err)),
4766+
// break 'catch_target Try::from_error(Into::into(err)),
47674767
// // Otherwise
4768-
// return Try::from_error(From::from(err)),
4768+
// return Try::from_error(Into::into(err)),
47694769
// }
47704770

47714771
let unstable_span = self.sess.source_map().mark_span_with_reason(
@@ -4826,17 +4826,17 @@ impl<'a> LoweringContext<'a> {
48264826
};
48274827

48284828
// `Err(err) => #[allow(unreachable_code)]
4829-
// return Try::from_error(From::from(err)),`
4829+
// return Try::from_error(Into::into(err)),`
48304830
let err_arm = {
48314831
let err_ident = self.str_to_ident("err");
48324832
let (err_local, err_local_nid) = self.pat_ident(try_span, err_ident);
4833-
let from_expr = {
4834-
let from_path = &[sym::convert, sym::From, sym::from];
4833+
let into_expr = {
4834+
let into_path = &[sym::convert, sym::Into, sym::into];
48354835
let err_expr = self.expr_ident(try_span, err_ident, err_local_nid);
4836-
self.expr_call_std_path(try_span, from_path, hir_vec![err_expr])
4836+
self.expr_call_std_path(try_span, into_path, hir_vec![err_expr])
48374837
};
48384838
let from_err_expr =
4839-
self.wrap_in_try_constructor(sym::from_error, from_expr, unstable_span);
4839+
self.wrap_in_try_constructor(sym::from_error, into_expr, unstable_span);
48404840
let thin_attrs = ThinVec::from(attrs);
48414841
let catch_scope = self.catch_scopes.last().map(|x| *x);
48424842
let ret_expr = if let Some(catch_node) = catch_scope {

src/librustc/infer/unify_key.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -139,10 +139,10 @@ impl<'tcx> UnifyValue for ConstVarValue<'tcx> {
139139

140140
// If one side is known, prefer that one.
141141
(ConstVariableValue::Known { .. }, ConstVariableValue::Unknown { .. }) => {
142-
Ok(value1.val)
142+
value1.val
143143
}
144144
(ConstVariableValue::Unknown { .. }, ConstVariableValue::Known { .. }) => {
145-
Ok(value2.val)
145+
value2.val
146146
}
147147

148148
// If both sides are *unknown*, it hardly matters, does it?
@@ -154,9 +154,9 @@ impl<'tcx> UnifyValue for ConstVarValue<'tcx> {
154154
// universe is the minimum of the two universes, because that is
155155
// the one which contains the fewest names in scope.
156156
let universe = cmp::min(universe1, universe2);
157-
Ok(ConstVariableValue::Unknown { universe })
157+
ConstVariableValue::Unknown { universe }
158158
}
159-
}?;
159+
};
160160

161161
Ok(ConstVarValue {
162162
origin: ConstVariableOrigin::ConstInference(DUMMY_SP),

src/librustc/mir/interpret/mod.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -159,7 +159,7 @@ impl<'s> AllocDecodingSession<'s> {
159159

160160
// Decode the AllocDiscriminant now so that we know if we have to reserve an
161161
// AllocId.
162-
let (alloc_kind, pos) = decoder.with_position(pos, |decoder| {
162+
let (alloc_kind, pos) = decoder.with_position(pos, |decoder| -> Result<_, D::Error> {
163163
let alloc_kind = AllocDiscriminant::decode(decoder)?;
164164
Ok((alloc_kind, decoder.position()))
165165
})?;
@@ -217,7 +217,7 @@ impl<'s> AllocDecodingSession<'s> {
217217
};
218218

219219
// Now decode the actual data
220-
let alloc_id = decoder.with_position(pos, |decoder| {
220+
let alloc_id = decoder.with_position(pos, |decoder| -> Result<_, D::Error> {
221221
match alloc_kind {
222222
AllocDiscriminant::Alloc => {
223223
let allocation = <&'tcx Allocation as Decodable>::decode(decoder)?;

src/librustc/mir/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -2543,7 +2543,7 @@ impl<'tcx> Debug for Rvalue<'tcx> {
25432543
let variant_def = &adt_def.variants[variant];
25442544

25452545
let f = &mut *fmt;
2546-
ty::tls::with(|tcx| {
2546+
ty::tls::with(|tcx| -> fmt::Result {
25472547
let substs = tcx.lift(&substs).expect("could not lift for printing");
25482548
FmtPrinter::new(tcx, f, Namespace::ValueNS)
25492549
.print_def_path(variant_def.def_id, substs)?;

src/librustc/ty/codec.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -201,7 +201,7 @@ pub fn decode_predicates<'a, 'tcx, D>(decoder: &mut D)
201201
}?;
202202
Ok((predicate, Decodable::decode(decoder)?))
203203
})
204-
.collect::<Result<Vec<_>, _>>()?,
204+
.collect::<Result<Vec<_>, D::Error>>()?,
205205
})
206206
}
207207

src/librustc/ty/instance.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -174,7 +174,7 @@ impl<'tcx> InstanceDef<'tcx> {
174174

175175
impl<'tcx> fmt::Display for Instance<'tcx> {
176176
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
177-
ty::tls::with(|tcx| {
177+
ty::tls::with(|tcx| -> fmt::Result {
178178
let substs = tcx.lift(&self.substs).expect("could not lift for printing");
179179
FmtPrinter::new(tcx, &mut *f, Namespace::ValueNS)
180180
.print_def_path(self.def_id(), substs)?;

src/librustc/ty/layout.rs

+11-7
Original file line numberDiff line numberDiff line change
@@ -255,7 +255,10 @@ impl<'a, 'tcx> LayoutCx<'tcx, TyCtxt<'a, 'tcx, 'tcx>> {
255255
Prefixed(Size, Align),
256256
}
257257

258-
let univariant_uninterned = |fields: &[TyLayout<'_>], repr: &ReprOptions, kind| {
258+
let univariant_uninterned = |fields: &[TyLayout<'_>],
259+
repr: &ReprOptions,
260+
kind|
261+
-> Result<_, LayoutError<'tcx>> {
259262
let packed = repr.packed();
260263
if packed && repr.align > 0 {
261264
bug!("struct cannot be packed and aligned");
@@ -464,9 +467,10 @@ impl<'a, 'tcx> LayoutCx<'tcx, TyCtxt<'a, 'tcx, 'tcx>> {
464467
size
465468
})
466469
};
467-
let univariant = |fields: &[TyLayout<'_>], repr: &ReprOptions, kind| {
468-
Ok(tcx.intern_layout(univariant_uninterned(fields, repr, kind)?))
469-
};
470+
let univariant =
471+
|fields: &[TyLayout<'_>], repr: &ReprOptions, kind| -> Result<_, LayoutError<'tcx>> {
472+
Ok(tcx.intern_layout(univariant_uninterned(fields, repr, kind)?))
473+
};
470474
debug_assert!(!ty.has_infer_types());
471475

472476
Ok(match ty.sty {
@@ -641,7 +645,7 @@ impl<'a, 'tcx> LayoutCx<'tcx, TyCtxt<'a, 'tcx, 'tcx>> {
641645
align = align.max(variant.align);
642646

643647
Ok(variant)
644-
}).collect::<Result<IndexVec<VariantIdx, _>, _>>()?;
648+
}).collect::<Result<IndexVec<VariantIdx, _>, LayoutError<'tcx>>>()?;
645649

646650
let abi = if prefix.abi.is_uninhabited() ||
647651
variants.iter().all(|v| v.abi.is_uninhabited()) {
@@ -939,7 +943,7 @@ impl<'a, 'tcx> LayoutCx<'tcx, TyCtxt<'a, 'tcx, 'tcx>> {
939943
align = align.max(st.align);
940944

941945
Ok(st)
942-
}).collect::<Result<IndexVec<VariantIdx, _>, _>>()?;
946+
}).collect::<Result<IndexVec<VariantIdx, _>, LayoutError<'tcx>>>()?;
943947

944948
let offset = st[i].fields.offset(field_index) + niche.offset;
945949
let size = st[i].size;
@@ -1054,7 +1058,7 @@ impl<'a, 'tcx> LayoutCx<'tcx, TyCtxt<'a, 'tcx, 'tcx>> {
10541058
size = cmp::max(size, st.size);
10551059
align = align.max(st.align);
10561060
Ok(st)
1057-
}).collect::<Result<IndexVec<VariantIdx, _>, _>>()?;
1061+
}).collect::<Result<IndexVec<VariantIdx, _>, LayoutError<'tcx>>>()?;
10581062

10591063
// Align the maximum variant size to the largest alignment.
10601064
size = size.align_to(align.abi);

src/librustc/ty/query/on_disk_cache.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -202,7 +202,7 @@ impl<'sess> OnDiskCache<'sess> {
202202
// Encode query results
203203
let mut query_result_index = EncodedQueryResultIndex::new();
204204

205-
time(tcx.sess, "encode query results", || {
205+
time(tcx.sess, "encode query results", || -> Result<_, E::Error> {
206206
use crate::ty::query::queries::*;
207207
let enc = &mut encoder;
208208
let qri = &mut query_result_index;
@@ -260,7 +260,7 @@ impl<'sess> OnDiskCache<'sess> {
260260

261261
Ok((dep_node_index, pos))
262262
})
263-
.collect::<Result<_, _>>()?;
263+
.collect::<Result<_, E::Error>>()?;
264264

265265
let interpret_alloc_index = {
266266
let mut interpret_alloc_index = Vec::new();

src/librustc_driver/lib.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -253,7 +253,7 @@ pub fn run_compiler(
253253
if let Some((ppm, opt_uii)) = pretty_info {
254254
if ppm.needs_ast_map(&opt_uii) {
255255
pretty::visit_crate(sess, &mut compiler.parse()?.peek_mut(), ppm);
256-
compiler.global_ctxt()?.peek_mut().enter(|tcx| {
256+
compiler.global_ctxt()?.peek_mut().enter(|tcx| -> interface::Result<_> {
257257
let expanded_crate = compiler.expansion()?.take().0;
258258
pretty::print_after_hir_lowering(
259259
tcx,

src/librustc_metadata/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
#![feature(box_patterns)]
44
#![feature(drain_filter)]
55
#![feature(libc)]
6+
#![feature(never_type)]
67
#![feature(nll)]
78
#![feature(proc_macro_internals)]
89
#![feature(proc_macro_quote)]

src/librustc_mir/hair/constant.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ crate fn lit_to_const<'a, 'gcx, 'tcx>(
1717
) -> Result<ty::Const<'tcx>, LitToConstError> {
1818
use syntax::ast::*;
1919

20-
let trunc = |n| {
20+
let trunc = |n| -> Result<_, LitToConstError> {
2121
let param_ty = ParamEnv::reveal_all().and(tcx.lift_to_global(&ty).unwrap());
2222
let width = tcx.layout_of(param_ty).map_err(|_| LitToConstError::Reported)?.size;
2323
trace!("trunc {} with size {} and shift {}", n, width.bits(), 128 - width.bits());

src/libsyntax_pos/symbol.rs

+2
Original file line numberDiff line numberDiff line change
@@ -287,6 +287,8 @@ symbols! {
287287
infer_static_outlives_requirements,
288288
inline,
289289
intel,
290+
into,
291+
Into,
290292
into_iter,
291293
IntoIterator,
292294
into_result,

src/test/ui/issues/issue-32709.stderr

+2-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,8 @@ error[E0277]: `?` couldn't convert the error to `()`
44
LL | Err(5)?;
55
| ^ the trait `std::convert::From<{integer}>` is not implemented for `()`
66
|
7-
= note: required by `std::convert::From::from`
7+
= note: required because of the requirements on the impl of `std::convert::Into<()>` for `{integer}`
8+
= note: required by `std::convert::Into::into`
89

910
error: aborting due to previous error
1011

src/test/ui/try-block/try-block-bad-type.stderr

+2-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,8 @@ LL | Err("")?;
1010
<i32 as std::convert::From<i8>>
1111
<i32 as std::convert::From<std::num::NonZeroI32>>
1212
and 2 others
13-
= note: required by `std::convert::From::from`
13+
= note: required because of the requirements on the impl of `std::convert::Into<i32>` for `&str`
14+
= note: required by `std::convert::Into::into`
1415

1516
error[E0271]: type mismatch resolving `<std::result::Result<i32, i32> as std::ops::Try>::Ok == &str`
1617
--> $DIR/try-block-bad-type.rs:12:9

src/test/ui/try-on-option.stderr

+2-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,8 @@ error[E0277]: `?` couldn't convert the error to `()`
44
LL | x?;
55
| ^ the trait `std::convert::From<std::option::NoneError>` is not implemented for `()`
66
|
7-
= note: required by `std::convert::From::from`
7+
= note: required because of the requirements on the impl of `std::convert::Into<()>` for `std::option::NoneError`
8+
= note: required by `std::convert::Into::into`
89

910
error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `std::ops::Try`)
1011
--> $DIR/try-on-option.rs:13:5

0 commit comments

Comments
 (0)