Skip to content

[RFC] add the ? postfix operator #23040

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

Closed
wants to merge 1 commit 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
4 changes: 4 additions & 0 deletions src/librustc/middle/cfg/construct.rs
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,10 @@ impl<'a, 'tcx> CFGBuilder<'a, 'tcx> {
self.tcx.sess.span_bug(expr.span, "non-desugared ExprForLoop");
}

ast::ExprQuestion(..) => {
self.tcx.sess.span_bug(expr.span, "non-desugared ExprQuestion");
}

ast::ExprLoop(ref body, _) => {
//
// [pred]
Expand Down
1 change: 1 addition & 0 deletions src/librustc/middle/check_const.rs
Original file line number Diff line number Diff line change
Expand Up @@ -596,6 +596,7 @@ fn check_expr<'a, 'tcx>(v: &mut CheckCrateVisitor<'a, 'tcx>,
ast::ExprBreak(_) |
ast::ExprAgain(_) |
ast::ExprRet(_) |
ast::ExprQuestion(_) |

// Miscellaneous expressions that could be implemented.
ast::ExprRange(..) |
Expand Down
4 changes: 4 additions & 0 deletions src/librustc/middle/expr_use_visitor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -539,6 +539,10 @@ impl<'d,'t,'tcx,TYPER:mc::Typer<'tcx>> ExprUseVisitor<'d,'t,'tcx,TYPER> {
self.tcx().sess.span_bug(expr.span, "non-desugared ExprForLoop");
}

ast::ExprQuestion(..) => {
self.tcx().sess.span_bug(expr.span, "non-desugared ExprQuestion");
}

ast::ExprUnary(op, ref lhs) => {
let pass_args = if ast_util::is_by_value_unop(op) {
PassArgs::ByValue
Expand Down
10 changes: 10 additions & 0 deletions src/librustc/middle/liveness.rs
Original file line number Diff line number Diff line change
Expand Up @@ -491,6 +491,9 @@ fn visit_expr(ir: &mut IrMaps, expr: &Expr) {
ast::ExprForLoop(..) => {
ir.tcx.sess.span_bug(expr.span, "non-desugared ExprForLoop");
}
ast::ExprQuestion(..) => {
ir.tcx.sess.span_bug(expr.span, "non-desugared ExprQuestion");
}
ast::ExprBinary(op, _, _) if ast_util::lazy_binop(op.node) => {
ir.add_live_node_for_node(expr.id, ExprNode(expr.span));
visit::walk_expr(ir, expr);
Expand Down Expand Up @@ -1025,6 +1028,10 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> {
self.ir.tcx.sess.span_bug(expr.span, "non-desugared ExprForLoop");
}

ast::ExprQuestion(..) => {
self.ir.tcx.sess.span_bug(expr.span, "non-desugared ExprQuestion");
}

// Note that labels have been resolved, so we don't need to look
// at the label ident
ast::ExprLoop(ref blk, _) => {
Expand Down Expand Up @@ -1480,6 +1487,9 @@ fn check_expr(this: &mut Liveness, expr: &Expr) {
ast::ExprForLoop(..) => {
this.ir.tcx.sess.span_bug(expr.span, "non-desugared ExprForLoop");
}
ast::ExprQuestion(..) => {
this.ir.tcx.sess.span_bug(expr.span, "non-desugared ExprQuestion");
}
}
}

Expand Down
3 changes: 3 additions & 0 deletions src/librustc/middle/mem_categorization.rs
Original file line number Diff line number Diff line change
Expand Up @@ -561,6 +561,9 @@ impl<'t,'tcx,TYPER:Typer<'tcx>> MemCategorizationContext<'t,TYPER> {
ast::ExprForLoop(..) => {
self.tcx().sess.span_bug(expr.span, "non-desugared ExprForLoop");
}
ast::ExprQuestion(..) => {
self.tcx().sess.span_bug(expr.span, "non-desugared ExprQuestion");
}
}
}

Expand Down
4 changes: 4 additions & 0 deletions src/librustc/middle/ty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4646,6 +4646,10 @@ pub fn expr_kind(tcx: &ctxt, expr: &ast::Expr) -> ExprKind {
tcx.sess.span_bug(expr.span, "non-desugared ExprForLoop");
}

ast::ExprQuestion(..) => {
tcx.sess.span_bug(expr.span, "non-desugared ExprQuestion");
}

ast::ExprLit(ref lit) if lit_is_str(&**lit) => {
RvalueDpsExpr
}
Expand Down
1 change: 1 addition & 0 deletions src/librustc_back/svh.rs
Original file line number Diff line number Diff line change
Expand Up @@ -291,6 +291,7 @@ mod svh_visitor {
ExprIfLet(..) => unreachable!(),
ExprWhileLet(..) => unreachable!(),
ExprMac(..) => unreachable!(),
ExprQuestion(..) => unreachable!(),
}
}

Expand Down
5 changes: 5 additions & 0 deletions src/librustc_trans/trans/debuginfo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3586,6 +3586,11 @@ fn create_scope_map(cx: &CrateContext,
Found unexpanded macro.");
}

ast::ExprQuestion(..) => {
cx.sess().span_bug(exp.span, "debuginfo::create_scope_map() - \
Found unexpanded `expr?`.");
}

ast::ExprLoop(ref block, _) |
ast::ExprBlock(ref block) => {
with_new_scope(cx,
Expand Down
3 changes: 3 additions & 0 deletions src/librustc_typeck/check/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3775,6 +3775,9 @@ fn check_expr_with_unifier<'a, 'tcx, F>(fcx: &FnCtxt<'a, 'tcx>,
ast::ExprForLoop(..) => {
tcx.sess.span_bug(expr.span, "non-desugared ExprForLoop");
}
ast::ExprQuestion(..) => {
tcx.sess.span_bug(expr.span, "non-desugared ExprQuestion");
}
ast::ExprLoop(ref body, _) => {
check_block_no_value(fcx, &**body);
if !may_break(tcx, expr.id, &**body) {
Expand Down
5 changes: 4 additions & 1 deletion src/libsyntax/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -774,7 +774,10 @@ pub enum Expr_ {
ExprRepeat(P<Expr> /* element */, P<Expr> /* count */),

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

/// `expr?`
ExprQuestion(P<Expr>),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Arguably this could have a better name.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ExprTry?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For what's it's worth I think of ? as the exception propagation operator.

}

/// The explicit Self type in a "qualified path". The actual
Expand Down
56 changes: 56 additions & 0 deletions src/libsyntax/ext/expand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,62 @@ pub fn expand_expr(e: P<ast::Expr>, fld: &mut MacroExpander) -> P<ast::Expr> {
Some(fld.cx.expr_ident(span, result_ident))))
}

// Desugar `expr?`
// From: `<expr>?`
ast::ExprQuestion(expr) => {
// to:
//
// {
// match <expr> {
// Ok(val) => val,
// Err(err) => {
// return Err(FromError::from_error(err));
// }
// }
// }

// expand <expr>
let expr = fld.fold_expr(expr);

// Ok(val) => val,
let ok_arm = {
let val = fld.cx.ident_of("val");
let ok_pat = fld.cx.pat_ok(span, fld.cx.pat_ident(span, val));

fld.cx.arm(span, vec![ok_pat], fld.cx.expr_ident(span, val))
};

// Err(err) => return Err(FromError::from_error(err)),
let err_arm = {
let err = fld.cx.ident_of("err");
let from_error_expr = {
let path = {
let strs = vec![
fld.cx.ident_of_std("core"),
fld.cx.ident_of("error"),
fld.cx.ident_of("FromError"),
fld.cx.ident_of("from_error"),
];

fld.cx.expr_path(fld.cx.path_global(span, strs))
};
let args = vec![fld.cx.expr_ident(span, err)];

fld.cx.expr_call(span, path, args)
};
let err_expr = fld.cx.expr_err(span, from_error_expr);

let err_pat = fld.cx.pat_err(span, fld.cx.pat_ident(span, err));

let ret_expr = fld.cx.expr(span, ast::ExprRet(Some(err_expr)));

fld.cx.arm(span, vec![err_pat], ret_expr)
};

// match <expr> { .. }
fld.cx.expr_match(span, expr, vec![err_arm, ok_arm])
}

ast::ExprClosure(capture_clause, fn_decl, block) => {
let (rewritten_fn_decl, rewritten_block)
= expand_and_rename_fn_decl_and_block(fn_decl, block, fld);
Expand Down
3 changes: 3 additions & 0 deletions src/libsyntax/fold.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1311,6 +1311,9 @@ pub fn noop_fold_expr<T: Folder>(Expr {id, node, span}: Expr, folder: &mut T) ->
folder.fold_block(body),
opt_ident.map(|i| folder.fold_ident(i)))
}
ExprQuestion(e) => {
ExprQuestion(folder.fold_expr(e))
}
ExprLoop(body, opt_ident) => {
ExprLoop(folder.fold_block(body),
opt_ident.map(|i| folder.fold_ident(i)))
Expand Down
1 change: 1 addition & 0 deletions src/libsyntax/parse/classify.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ pub fn expr_requires_semi_to_be_stmt(e: &ast::Expr) -> bool {
| ast::ExprWhile(..)
| ast::ExprWhileLet(..)
| ast::ExprLoop(..)
| ast::ExprQuestion(..)
| ast::ExprForLoop(..) => false,
_ => true
}
Expand Down
30 changes: 27 additions & 3 deletions src/libsyntax/parse/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ use ast::{ExprBreak, ExprCall, ExprCast};
use ast::{ExprField, ExprTupField, ExprClosure, ExprIf, ExprIfLet, ExprIndex};
use ast::{ExprLit, ExprLoop, ExprMac, ExprRange};
use ast::{ExprMethodCall, ExprParen, ExprPath};
use ast::{ExprRepeat, ExprRet, ExprStruct, ExprTup, ExprUnary};
use ast::{ExprRepeat, ExprRet, ExprStruct, ExprTup, ExprUnary, ExprQuestion};
use ast::{ExprVec, ExprWhile, ExprWhileLet, ExprForLoop, Field, FnDecl};
use ast::{ForeignItem, ForeignItemStatic, ForeignItemFn, ForeignMod, FunctionRetTy};
use ast::{Ident, Inherited, ImplItem, Item, Item_, ItemStatic};
Expand Down Expand Up @@ -2059,6 +2059,10 @@ impl<'a> Parser<'a> {
})
}

pub fn mk_question(&mut self, expr: P<Expr>) -> ast::Expr_ {
ExprQuestion(expr)
}

pub fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::Expr_ {
ExprUnary(unop, expr)
}
Expand Down Expand Up @@ -2481,7 +2485,17 @@ impl<'a> Parser<'a> {
es.insert(0, e);
let id = spanned(dot, hi, i);
let nd = self.mk_method_call(id, tys, es);
e = self.mk_expr(lo, hi, nd);
let expr = self.mk_expr(lo, hi, nd);

// expr.f()?
if self.eat(&token::Question) {
hi = self.last_span.hi;

let nd = self.mk_question(expr);
e = self.mk_expr(lo, hi, nd);
} else {
e = expr;
}
}
_ => {
if !tys.is_empty() {
Expand Down Expand Up @@ -2556,7 +2570,17 @@ impl<'a> Parser<'a> {
hi = self.last_span.hi;

let nd = self.mk_call(e, es);
e = self.mk_expr(lo, hi, nd);
let expr = self.mk_expr(lo, hi, nd);

// expr(...)?
if self.eat(&token::Question) {
hi = self.last_span.hi;

let nd = self.mk_question(expr);
e = self.mk_expr(lo, hi, nd);
} else {
e = expr;
}
}

// expr[...]
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 @@ -1760,6 +1760,10 @@ impl<'a> State<'a> {
try!(space(&mut self.s));
try!(self.print_block(&**blk));
}
ast::ExprQuestion(ref expr) => {
try!(self.print_expr(&**expr));
try!(word(&mut self.s, "?"))
}
ast::ExprLoop(ref blk, opt_ident) => {
if let Some(ident) = opt_ident {
try!(self.print_ident(ident));
Expand Down
3 changes: 3 additions & 0 deletions src/libsyntax/visit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -821,6 +821,9 @@ pub fn walk_expr<'v, V: Visitor<'v>>(visitor: &mut V, expression: &'v Expr) {
visitor.visit_expr(&**subexpression);
visitor.visit_block(&**block)
}
ExprQuestion(ref expr) => {
visitor.visit_expr(&**expr);
}
ExprLoop(ref block, _) => visitor.visit_block(&**block),
ExprMatch(ref subexpression, ref arms, _) => {
visitor.visit_expr(&**subexpression);
Expand Down
71 changes: 71 additions & 0 deletions src/test/run-pass/question-operator.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
// Copyright 2015 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.

use std::error::FromError;
use std::fs::File;
use std::io::{Read, self};
use std::num::ParseIntError;
use std::str::FromStr;

fn parse<T: FromStr>(s: &str) -> Result<T, T::Err> {
s.parse()
}

fn on_method() -> Result<i32, ParseIntError> {
Ok("1".parse::<i32>()? + "2".parse()?)
}

fn in_chain() -> Result<String, ParseIntError> {
Ok("3".parse::<i32>()?.to_string())
}

fn on_call() -> Result<i32, ParseIntError> {
Ok(parse("4")?)
}

fn nested() -> Result<i32, ParseIntError> {
Ok("5".parse::<i32>()?.to_string().parse()?)
}

fn main() {
assert_eq!(Ok(3), on_method());

assert_eq!(Ok("3".to_string()), in_chain());

assert_eq!(Ok(4), on_call());

assert_eq!(Ok(5), nested());
}

enum Error {
Io(io::Error),
Parse(ParseIntError),
}

// just type check
fn merge_error() -> Result<i32, Error> {
let mut s = String::new();

File::open("foo.txt")?.read_to_string(&mut s)?;

Ok(s.parse::<i32>()? + 1)
}

impl FromError<io::Error> for Error {
fn from_error(e: io::Error) -> Error {
Error::Io(e)
}
}

impl FromError<ParseIntError> for Error {
fn from_error(e: ParseIntError) -> Error {
Error::Parse(e)
}
}