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

implement the ? operator #31954

Merged
merged 2 commits into from
Mar 8, 2016
Merged
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
4 changes: 4 additions & 0 deletions src/librustc/middle/check_match.rs
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,10 @@ fn check_arms(cx: &MatchCheckCtxt,
hir::MatchSource::Normal => {
span_err!(cx.tcx.sess, pat.span, E0001, "unreachable pattern")
},

hir::MatchSource::TryDesugar => {
cx.tcx.sess.span_bug(pat.span, "unreachable try pattern")
},
}
}
Useful => (),
Expand Down
1 change: 1 addition & 0 deletions src/librustc_front/hir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -835,6 +835,7 @@ pub enum MatchSource {
},
WhileLetDesugar,
ForLoopDesugar,
TryDesugar,
}

#[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug, Copy)]
Expand Down
69 changes: 69 additions & 0 deletions src/librustc_front/lowering.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1605,6 +1605,63 @@ pub fn lower_expr(lctx: &LoweringContext, e: &Expr) -> P<hir::Expr> {
});
}

// Desugar ExprKind::Try
// From: `<expr>?`
ExprKind::Try(ref sub_expr) => {
// to:
//
// {
// match <expr> {
// Ok(val) => val,
// Err(err) => {
// return Err(From::from(err))
// }
// }
// }

return cache_ids(lctx, e.id, |lctx| {
// expand <expr>
let sub_expr = lower_expr(lctx, sub_expr);

// Ok(val) => val
let ok_arm = {
let val_ident = lctx.str_to_ident("val");
let val_pat = pat_ident(lctx, e.span, val_ident);
let val_expr = expr_ident(lctx, e.span, val_ident, None);
let ok_pat = pat_ok(lctx, e.span, val_pat);

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

// Err(err) => return Err(From::from(err))
let err_arm = {
let err_ident = lctx.str_to_ident("err");
let from_expr = {
let path = std_path(lctx, &["convert", "From", "from"]);
let path = path_global(e.span, path);
let from = expr_path(lctx, path, None);
let err_expr = expr_ident(lctx, e.span, err_ident, None);

expr_call(lctx, e.span, from, hir_vec![err_expr], None)
};
let err_expr = {
let path = std_path(lctx, &["result", "Result", "Err"]);
let path = path_global(e.span, path);
let err_ctor = expr_path(lctx, path, None);
expr_call(lctx, e.span, err_ctor, hir_vec![from_expr], None)
};
let err_pat = pat_err(lctx, e.span, pat_ident(lctx, e.span, err_ident));
let ret_expr = expr(lctx, e.span,
hir::Expr_::ExprRet(Some(err_expr)), None);

arm(hir_vec![err_pat], ret_expr)
};

expr_match(lctx, e.span, sub_expr, hir_vec![err_arm, ok_arm],
hir::MatchSource::TryDesugar, None)
})
}

ExprKind::Mac(_) => panic!("Shouldn't exist here"),
},
span: e.span,
Expand Down Expand Up @@ -1819,6 +1876,18 @@ fn block_all(lctx: &LoweringContext,
})
}

fn pat_ok(lctx: &LoweringContext, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
let ok = std_path(lctx, &["result", "Result", "Ok"]);
let path = path_global(span, ok);
pat_enum(lctx, span, path, hir_vec![pat])
}

fn pat_err(lctx: &LoweringContext, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
let err = std_path(lctx, &["result", "Result", "Err"]);
let path = path_global(span, err);
pat_enum(lctx, span, path, hir_vec![pat])
}

fn pat_some(lctx: &LoweringContext, span: Span, pat: P<hir::Pat>) -> P<hir::Pat> {
let some = std_path(lctx, &["option", "Option", "Some"]);
let path = path_global(span, some);
Expand Down
3 changes: 3 additions & 0 deletions src/libsyntax/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1022,6 +1022,9 @@ pub enum ExprKind {

/// No-op: used solely so we can pretty-print faithfully
Paren(P<Expr>),

/// `expr?`
Try(P<Expr>),
}

/// The explicit Self type in a "qualified path". The actual
Expand Down
9 changes: 9 additions & 0 deletions src/libsyntax/feature_gate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,9 @@ const KNOWN_FEATURES: &'static [(&'static str, &'static str, Option<u32>, Status

// a...b and ...b
("inclusive_range_syntax", "1.7.0", Some(28237), Active),

// `expr?`
("question_mark", "1.9.0", Some(31436), Active)
];
// (changing above list without updating src/doc/reference.md makes @cmr sad)

Expand Down Expand Up @@ -570,6 +573,7 @@ pub struct Features {
pub staged_api: bool,
pub stmt_expr_attributes: bool,
pub deprecated: bool,
pub question_mark: bool,
}

impl Features {
Expand Down Expand Up @@ -603,6 +607,7 @@ impl Features {
staged_api: false,
stmt_expr_attributes: false,
deprecated: false,
question_mark: false,
}
}
}
Expand Down Expand Up @@ -1001,6 +1006,9 @@ impl<'a, 'v> Visitor<'v> for PostExpansionVisitor<'a> {
e.span,
"inclusive range syntax is experimental");
}
ast::ExprKind::Try(..) => {
self.gate_feature("question_mark", e.span, "the `?` operator is not stable");
}
_ => {}
}
visit::walk_expr(self, e);
Expand Down Expand Up @@ -1203,6 +1211,7 @@ fn check_crate_inner<F>(cm: &CodeMap, span_handler: &Handler,
staged_api: cx.has_feature("staged_api"),
stmt_expr_attributes: cx.has_feature("stmt_expr_attributes"),
deprecated: cx.has_feature("deprecated"),
question_mark: cx.has_feature("question_mark"),
}
}

Expand Down
3 changes: 2 additions & 1 deletion src/libsyntax/fold.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1332,7 +1332,8 @@ pub fn noop_fold_expr<T: Folder>(Expr {id, node, span, attrs}: Expr, folder: &mu
fields.move_map(|x| folder.fold_field(x)),
maybe_expr.map(|x| folder.fold_expr(x)))
},
ExprKind::Paren(ex) => ExprKind::Paren(folder.fold_expr(ex))
ExprKind::Paren(ex) => ExprKind::Paren(folder.fold_expr(ex)),
ExprKind::Try(ex) => ExprKind::Try(folder.fold_expr(ex)),
},
span: folder.new_span(span),
attrs: attrs.map_thin_attrs(|v| fold_attrs(v, folder)),
Expand Down
7 changes: 6 additions & 1 deletion src/libsyntax/parse/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2534,6 +2534,12 @@ impl<'a> Parser<'a> {
let mut e = e0;
let mut hi;
loop {
// expr?
while self.eat(&token::Question) {
let hi = self.span.hi;
e = self.mk_expr(lo, hi, ExprKind::Try(e), None);
}

// expr.f
if self.eat(&token::Dot) {
match self.token {
Expand Down Expand Up @@ -2907,7 +2913,6 @@ impl<'a> Parser<'a> {
}
};


if self.expr_is_complete(&lhs) {
// Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
return Ok(lhs);
Expand Down
4 changes: 4 additions & 0 deletions src/libsyntax/print/pprust.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2277,6 +2277,10 @@ impl<'a> State<'a> {
try!(self.print_inner_attributes_inline(attrs));
try!(self.print_expr(&e));
try!(self.pclose());
},
ast::ExprKind::Try(ref e) => {
try!(self.print_expr(e));
try!(word(&mut self.s, "?"))
}
}
try!(self.ann.post(self, NodeExpr(expr)));
Expand Down
3 changes: 3 additions & 0 deletions src/libsyntax/visit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -793,6 +793,9 @@ pub fn walk_expr<'v, V: Visitor<'v>>(visitor: &mut V, expression: &'v Expr) {
visitor.visit_expr(&output.expr)
}
}
ExprKind::Try(ref subexpression) => {
visitor.visit_expr(subexpression)
}
}

visitor.visit_expr_post(expression)
Expand Down
20 changes: 20 additions & 0 deletions src/test/compile-fail/feature-gate-try-operator.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

macro_rules! id {
($e:expr) => { $e }
}

fn main() {
id!(x?); //~ error: the `?` operator is not stable (see issue #31436)
//~^ help: add #![feature(question_mark)] to the crate attributes to enable
y?; //~ error: the `?` operator is not stable (see issue #31436)
//~^ help: add #![feature(question_mark)] to the crate attributes to enable
}
2 changes: 1 addition & 1 deletion src/test/parse-fail/issue-19096.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,5 @@

fn main() {
let t = (42, 42);
t.0::<isize>; //~ ERROR expected one of `.`, `;`, `}`, or an operator, found `::`
t.0::<isize>; //~ ERROR expected one of `.`, `;`, `?`, `}`, or an operator, found `::`
}
2 changes: 1 addition & 1 deletion src/test/parse-fail/issue-3036.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,4 @@
fn main()
{
let x = 3
} //~ ERROR: expected one of `.`, `;`, or an operator, found `}`
} //~ ERROR: expected one of `.`, `;`, `?`, or an operator, found `}`
2 changes: 1 addition & 1 deletion src/test/parse-fail/macros-no-semicolon.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,6 @@

fn main() {
assert_eq!(1, 2)
assert_eq!(3, 4) //~ ERROR expected one of `.`, `;`, `}`, or an operator, found `assert_eq`
assert_eq!(3, 4) //~ ERROR expected one of `.`, `;`, `?`, `}`, or an operator, found `assert_eq`
println!("hello");
}
2 changes: 1 addition & 1 deletion src/test/parse-fail/match-refactor-to-expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ fn main() {
let foo =
match //~ NOTE did you mean to remove this `match` keyword?
Some(4).unwrap_or_else(5)
; //~ ERROR expected one of `.`, `{`, or an operator, found `;`
; //~ ERROR expected one of `.`, `?`, `{`, or an operator, found `;`

println!("{}", foo)
}
2 changes: 1 addition & 1 deletion src/test/parse-fail/range-3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,5 @@

pub fn main() {
let r = 1..2..3;
//~^ ERROR expected one of `.`, `;`, or an operator, found `..`
//~^ ERROR expected one of `.`, `;`, `?`, or an operator, found `..`
}
2 changes: 1 addition & 1 deletion src/test/parse-fail/range-4.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,5 @@

pub fn main() {
let r = ..1..2;
//~^ ERROR expected one of `.`, `;`, or an operator, found `..`
//~^ ERROR expected one of `.`, `;`, `?`, or an operator, found `..`
}
2 changes: 1 addition & 1 deletion src/test/parse-fail/raw-str-unbalanced.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,5 @@

static s: &'static str =
r#"
"## //~ ERROR expected one of `.`, `;`, or an operator, found `#`
"## //~ ERROR expected one of `.`, `;`, `?`, or an operator, found `#`
;
2 changes: 1 addition & 1 deletion src/test/parse-fail/removed-syntax-mut-vec-expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,5 @@
fn f() {
let v = [mut 1, 2, 3, 4];
//~^ ERROR expected identifier, found keyword `mut`
//~^^ ERROR expected one of `!`, `,`, `.`, `::`, `;`, `]`, `{`, or an operator, found `1`
//~^^ ERROR expected one of `!`, `,`, `.`, `::`, `;`, `?`, `]`, `{`, or an operator, found `1`
}
2 changes: 1 addition & 1 deletion src/test/parse-fail/removed-syntax-uniq-mut-expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,5 @@
fn f() {
let a_box = box mut 42;
//~^ ERROR expected identifier, found keyword `mut`
//~^^ ERROR expected one of `!`, `.`, `::`, `;`, `{`, or an operator, found `42`
//~^^ ERROR expected one of `!`, `.`, `::`, `;`, `?`, `{`, or an operator, found `42`
}
2 changes: 1 addition & 1 deletion src/test/parse-fail/removed-syntax-with-1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,5 @@ fn removed_with() {

let a = S { foo: (), bar: () };
let b = S { foo: () with a };
//~^ ERROR expected one of `,`, `.`, `}`, or an operator, found `with`
//~^ ERROR expected one of `,`, `.`, `?`, `}`, or an operator, found `with`
}
2 changes: 1 addition & 1 deletion src/test/parse-fail/struct-literal-in-for.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ impl Foo {
fn main() {
for x in Foo {
x: 3 //~ ERROR expected type, found `3`
}.hi() { //~ ERROR expected one of `.`, `;`, `}`, or an operator, found `{`
}.hi() { //~ ERROR expected one of `.`, `;`, `?`, `}`, or an operator, found `{`
println!("yo");
}
}
2 changes: 1 addition & 1 deletion src/test/parse-fail/struct-literal-in-if.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ impl Foo {
fn main() {
if Foo {
x: 3 //~ ERROR expected type, found `3`
}.hi() { //~ ERROR expected one of `.`, `;`, `}`, or an operator, found `{`
}.hi() { //~ ERROR expected one of `.`, `;`, `?`, `}`, or an operator, found `{`
println!("yo");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,6 @@ fn main() {
} {
Foo {
x: x
} => {} //~ ERROR expected one of `.`, `;`, `}`, or an operator, found `=>`
} => {} //~ ERROR expected one of `.`, `;`, `?`, `}`, or an operator, found `=>`
}
}
2 changes: 1 addition & 1 deletion src/test/parse-fail/struct-literal-in-while.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ impl Foo {
fn main() {
while Foo {
x: 3 //~ ERROR expected type, found `3`
}.hi() { //~ ERROR expected one of `.`, `;`, `}`, or an operator, found `{`
}.hi() { //~ ERROR expected one of `.`, `;`, `?`, `}`, or an operator, found `{`
println!("yo");
}
}
34 changes: 34 additions & 0 deletions src/test/run-pass/try-operator-hygiene.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// `expr?` expands to:
//
// match expr {
// Ok(val) => val,
// Err(err) => return From::from(err),
// }
//
// This test verifies that the expansion is hygienic, i.e. it's not affected by other `val` and
// `err` bindings that may be in scope.

#![feature(question_mark)]

use std::num::ParseIntError;

fn main() {
assert_eq!(parse(), Ok(1));
}

fn parse() -> Result<i32, ParseIntError> {
const val: char = 'a';
const err: char = 'b';

Ok("1".parse::<i32>()?)
}
Loading