Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP Switch x? desugaring to use QuestionMark trait and Try enum #38301

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions src/libcore/ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2813,24 +2813,29 @@ pub trait BoxPlace<Data: ?Sized> : Place<Data> {
/// should not rely on any implementations of `Carrier` other than `Result`,
/// i.e., you should not expect `?` to continue to work with `Option`, etc.
#[unstable(feature = "question_mark_carrier", issue = "31436")]
#[cfg_attr(not(stage0), rustc_deprecated(since = "", reason = "replaced by `QuestionMark`"))]
pub trait Carrier {
/// The type of the value when computation succeeds.
type Success;
/// The type of the value when computation errors out.
type Error;

/// Create a `Carrier` from a success value.
#[allow(deprecated)]
fn from_success(Self::Success) -> Self;

/// Create a `Carrier` from an error value.
#[allow(deprecated)]
fn from_error(Self::Error) -> Self;

/// Translate this `Carrier` to another implementation of `Carrier` with the
/// same associated types.
#[allow(deprecated)]
fn translate<T>(self) -> T where T: Carrier<Success=Self::Success, Error=Self::Error>;
}

#[unstable(feature = "question_mark_carrier", issue = "31436")]
#[allow(deprecated)]
impl<U, V> Carrier for Result<U, V> {
type Success = U;
type Error = V;
Expand All @@ -2843,6 +2848,7 @@ impl<U, V> Carrier for Result<U, V> {
Err(e)
}

#[allow(deprecated)]
fn translate<T>(self) -> T
where T: Carrier<Success=U, Error=V>
{
Expand All @@ -2855,6 +2861,7 @@ impl<U, V> Carrier for Result<U, V> {

struct _DummyErrorType;

#[allow(deprecated)]
impl Carrier for _DummyErrorType {
type Success = ();
type Error = ();
Expand All @@ -2867,9 +2874,55 @@ impl Carrier for _DummyErrorType {
_DummyErrorType
}

#[allow(deprecated)]
fn translate<T>(self) -> T
where T: Carrier<Success=(), Error=()>
{
T::from_success(())
}
}

/// The `QuestionMark` trait is used to specify the functionality of `?`.
///
#[cfg(not(stage0))]
#[unstable(feature = "question_mark_qm", issue = "31436")]
pub trait QuestionMark<Done> {
///
type Continue;
///
fn question_mark(self) -> Try<Self::Continue, Done>;
}

/// The `Try` enum.
#[cfg(not(stage0))]
#[unstable(feature = "question_mark_try", issue = "31436")]
#[derive(Debug, Copy, Clone)]
pub enum Try<T, E> {
///
Continue(T),
///
Done(E),
}

#[cfg(not(stage0))]
#[unstable(feature = "question_mark_impl", issue = "31436")]
impl<T, U, E, F> QuestionMark<Result<U, F>> for Result<T, E>
where F: From<E>
{
type Continue = T;
fn question_mark(self) -> Try<T, Result<U, F>> {
match self {
Ok(x) => Try::Continue(x),
Err(e) => Try::Done(Err(From::from(e))),
}
}
}

#[cfg(not(stage0))]
impl QuestionMark<_DummyErrorType> for _DummyErrorType
{
type Continue = Self;
fn question_mark(self) -> Try<Self, Self> {
Try::Continue(self)
}
}
58 changes: 25 additions & 33 deletions src/librustc/hir/lowering.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1762,56 +1762,48 @@ impl<'a> LoweringContext<'a> {
ExprKind::Try(ref sub_expr) => {
// to:
//
// match QuestionMark::question_mark(<expr>) {
// Try::Continue(val) => val,
// Try::Done(r) => return r,
// }
// match Carrier::translate(<expr>) {
// Ok(val) => val,
// Err(err) => return Carrier::from_error(From::from(err))
// }
let unstable_span = self.allow_internal_unstable("?", e.span);

// Carrier::translate(<expr>)
// QuestionMark::question_mark(<expr>)
let discr = {
// expand <expr>
let sub_expr = self.lower_expr(sub_expr);

let path = &["ops", "Carrier", "translate"];
let path = &["ops", "QuestionMark", "question_mark"];
let path = P(self.expr_std_path(unstable_span, path, ThinVec::new()));
P(self.expr_call(e.span, path, hir_vec![sub_expr]))
};

// Ok(val) => val
// Continue(val) => val
let ok_arm = {
let val_ident = self.str_to_ident("val");
let val_pat = self.pat_ident(e.span, val_ident);
let val_expr = P(self.expr_ident(e.span, val_ident, val_pat.id));
let ok_pat = self.pat_ok(e.span, val_pat);
let val_pat = self.pat_ident(unstable_span, val_ident);
let val_expr = P(self.expr_ident(unstable_span, val_ident, val_pat.id));
let ok_pat = self.pat_continue(unstable_span, val_pat);

self.arm(hir_vec![ok_pat], val_expr)
};

// Err(err) => return Carrier::from_error(From::from(err))
// Done(r) => return r
let err_arm = {
let err_ident = self.str_to_ident("err");
let err_local = self.pat_ident(e.span, err_ident);
let from_expr = {
let path = &["convert", "From", "from"];
let from = P(self.expr_std_path(e.span, path, ThinVec::new()));
let err_expr = self.expr_ident(e.span, err_ident, err_local.id);

self.expr_call(e.span, from, hir_vec![err_expr])
};
let from_err_expr = {
let path = &["ops", "Carrier", "from_error"];
let from_err = P(self.expr_std_path(unstable_span, path,
ThinVec::new()));
P(self.expr_call(e.span, from_err, hir_vec![from_expr]))
};
let err_local = self.pat_ident(unstable_span, err_ident);

let ret_expr = P(self.expr(e.span,
hir::Expr_::ExprRet(Some(from_err_expr)),
let err_expr = self.expr_ident(unstable_span, err_ident, err_local.id);
let ret_expr = P(self.expr(unstable_span,
hir::Expr_::ExprRet(Some(P(err_expr))),
ThinVec::new()));

let err_pat = self.pat_err(e.span, err_local);
self.arm(hir_vec![err_pat], ret_expr)
let done_pat = self.pat_done(unstable_span, err_local);
self.arm(hir_vec![done_pat], ret_expr)
};

return self.expr_match(e.span, discr, hir_vec![err_arm, ok_arm],
Expand Down Expand Up @@ -2060,14 +2052,6 @@ impl<'a> LoweringContext<'a> {
}
}

fn pat_ok(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
self.pat_std_enum(span, &["result", "Result", "Ok"], hir_vec![pat])
}

fn pat_err(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
self.pat_std_enum(span, &["result", "Result", "Err"], hir_vec![pat])
}

fn pat_some(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
self.pat_std_enum(span, &["option", "Option", "Some"], hir_vec![pat])
}
Expand All @@ -2076,6 +2060,14 @@ impl<'a> LoweringContext<'a> {
self.pat_std_enum(span, &["option", "Option", "None"], hir_vec![])
}

fn pat_continue(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
self.pat_std_enum(span, &["ops", "Try", "Continue"], hir_vec![pat])
}

fn pat_done(&mut self, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
self.pat_std_enum(span, &["ops", "Try", "Done"], hir_vec![pat])
}

fn pat_std_enum(&mut self,
span: Span,
components: &[&str],
Expand Down
61 changes: 25 additions & 36 deletions src/test/run-pass/try-operator-custom.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,33 +8,25 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#![feature(question_mark, question_mark_carrier)]
#![feature(question_mark, question_mark_qm, question_mark_try)]

use std::ops::Carrier;
use std::ops::QuestionMark;
use std::ops::Try;

enum MyResult<T, U> {
Awesome(T),
Terrible(U)
#[derive(PartialEq)]
enum MyResult<U, V> {
Awesome(U),
Terrible(V)
}

impl<U, V> Carrier for MyResult<U, V> {
type Success = U;
type Error = V;

fn from_success(u: U) -> MyResult<U, V> {
MyResult::Awesome(u)
}

fn from_error(e: V) -> MyResult<U, V> {
MyResult::Terrible(e)
}

fn translate<T>(self) -> T
where T: Carrier<Success=U, Error=V>
{
impl<U, V, X, Y> QuestionMark<MyResult<X, Y>> for MyResult<U, V>
where Y: From<V>,
{
type Continue = U;
fn question_mark(self) -> Try<Self::Continue, MyResult<X, Y>> {
match self {
MyResult::Awesome(u) => T::from_success(u),
MyResult::Terrible(e) => T::from_error(e),
MyResult::Awesome(u) => Try::Continue(u),
MyResult::Terrible(e) => Try::Done(MyResult::Terrible(Y::from(e))),
}
}
}
Expand All @@ -43,31 +35,28 @@ fn f(x: i32) -> Result<i32, String> {
if x == 0 {
Ok(42)
} else {
let y = g(x)?;
let y = Err(String::new())?;
Ok(y)
}
}

fn g(x: i32) -> MyResult<i32, String> {
let _y = f(x - 1)?;
MyResult::Terrible("Hello".to_owned())
}

fn h() -> MyResult<i32, String> {
let a: Result<i32, &'static str> = Err("Hello");
let b = a?;
MyResult::Awesome(b)
if x == 0 {
return MyResult::Awesome(42);
} else {
let _y = i()?;
MyResult::Awesome(1)
}
}

fn i() -> MyResult<i32, String> {
let a: MyResult<i32, &'static str> = MyResult::Terrible("Hello");
fn i() -> MyResult<u32, String> {
let a: MyResult<u32, &'static str> = MyResult::Terrible("Hello");
let b = a?;
MyResult::Awesome(b)
}

fn main() {
assert!(f(0) == Ok(42));
assert!(f(10) == Err("Hello".to_owned()));
let _ = h();
assert!(g(0) == MyResult::Awesome(42));
assert!(g(10) == MyResult::Terrible("Hello".to_owned()));
let _ = i();
}