Skip to content

Commit

Permalink
Rollup merge of rust-lang#39921 - cramertj:add-catch-to-ast, r=nikoma…
Browse files Browse the repository at this point in the history
…tsakis

Add catch {} to AST

Part of rust-lang#39849. Builds on rust-lang#39864.
  • Loading branch information
alexcrichton authored Mar 10, 2017
2 parents 5c71f91 + b549f14 commit e2d3770
Show file tree
Hide file tree
Showing 13 changed files with 159 additions and 5 deletions.
37 changes: 33 additions & 4 deletions src/librustc/hir/lowering.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ pub struct LoweringContext<'a> {
trait_impls: BTreeMap<DefId, Vec<NodeId>>,
trait_default_impl: BTreeMap<DefId, NodeId>,

catch_scopes: Vec<NodeId>,
loop_scopes: Vec<NodeId>,
is_in_loop_condition: bool,

Expand Down Expand Up @@ -121,6 +122,7 @@ pub fn lower_crate(sess: &Session,
bodies: BTreeMap::new(),
trait_impls: BTreeMap::new(),
trait_default_impl: BTreeMap::new(),
catch_scopes: Vec::new(),
loop_scopes: Vec::new(),
is_in_loop_condition: false,
type_def_lifetime_params: DefIdMap(),
Expand Down Expand Up @@ -259,6 +261,21 @@ impl<'a> LoweringContext<'a> {
span
}

fn with_catch_scope<T, F>(&mut self, catch_id: NodeId, f: F) -> T
where F: FnOnce(&mut LoweringContext) -> T
{
let len = self.catch_scopes.len();
self.catch_scopes.push(catch_id);

let result = f(self);
assert_eq!(len + 1, self.catch_scopes.len(),
"catch scopes should be added and removed in stack order");

self.catch_scopes.pop().unwrap();

result
}

fn with_loop_scope<T, F>(&mut self, loop_id: NodeId, f: F) -> T
where F: FnOnce(&mut LoweringContext) -> T
{
Expand Down Expand Up @@ -293,15 +310,17 @@ impl<'a> LoweringContext<'a> {
result
}

fn with_new_loop_scopes<T, F>(&mut self, f: F) -> T
fn with_new_scopes<T, F>(&mut self, f: F) -> T
where F: FnOnce(&mut LoweringContext) -> T
{
let was_in_loop_condition = self.is_in_loop_condition;
self.is_in_loop_condition = false;

let catch_scopes = mem::replace(&mut self.catch_scopes, Vec::new());
let loop_scopes = mem::replace(&mut self.loop_scopes, Vec::new());
let result = f(self);
mem::replace(&mut self.loop_scopes, loop_scopes);
self.catch_scopes = catch_scopes;
self.loop_scopes = loop_scopes;

self.is_in_loop_condition = was_in_loop_condition;

Expand Down Expand Up @@ -1063,7 +1082,7 @@ impl<'a> LoweringContext<'a> {
self.record_body(value, None))
}
ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
self.with_new_loop_scopes(|this| {
self.with_new_scopes(|this| {
let body = this.lower_block(body);
let body = this.expr_block(body, ThinVec::new());
let body_id = this.record_body(body, Some(decl));
Expand Down Expand Up @@ -1660,13 +1679,17 @@ impl<'a> LoweringContext<'a> {
this.lower_opt_sp_ident(opt_ident),
hir::LoopSource::Loop))
}
ExprKind::Catch(ref body) => {
// FIXME(cramertj): Add catch to HIR
self.with_catch_scope(e.id, |this| hir::ExprBlock(this.lower_block(body)))
}
ExprKind::Match(ref expr, ref arms) => {
hir::ExprMatch(P(self.lower_expr(expr)),
arms.iter().map(|x| self.lower_arm(x)).collect(),
hir::MatchSource::Normal)
}
ExprKind::Closure(capture_clause, ref decl, ref body, fn_decl_span) => {
self.with_new_loop_scopes(|this| {
self.with_new_scopes(|this| {
this.with_parent_def(e.id, |this| {
let expr = this.lower_expr(body);
hir::ExprClosure(this.lower_capture_clause(capture_clause),
Expand Down Expand Up @@ -2064,6 +2087,12 @@ impl<'a> LoweringContext<'a> {
// Err(err) => #[allow(unreachable_code)]
// return Carrier::from_error(From::from(err)),
// }

// FIXME(cramertj): implement breaking to catch
if !self.catch_scopes.is_empty() {
bug!("`?` in catch scopes is unimplemented")
}

let unstable_span = self.allow_internal_unstable("?", e.span);

// Carrier::translate(<expr>)
Expand Down
2 changes: 2 additions & 0 deletions src/libsyntax/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -936,6 +936,8 @@ pub enum ExprKind {
Closure(CaptureBy, P<FnDecl>, P<Expr>, Span),
/// A block (`{ ... }`)
Block(P<Block>),
/// A catch block (`catch { ... }`)
Catch(P<Block>),

/// An assignment (`a = foo()`)
Assign(P<Expr>, P<Expr>),
Expand Down
6 changes: 6 additions & 0 deletions src/libsyntax/feature_gate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -339,6 +339,9 @@ declare_features! (

// `extern "x86-interrupt" fn()`
(active, abi_x86_interrupt, "1.17.0", Some(40180)),

// Allows the `catch {...}` expression
(active, catch_expr, "1.17.0", Some(31436)),
);

declare_features! (
Expand Down Expand Up @@ -1287,6 +1290,9 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> {
}
}
}
ast::ExprKind::Catch(_) => {
gate_feature_post!(&self, catch_expr, e.span, "`catch` expression is experimental");
}
_ => {}
}
visit::walk_expr(self, e);
Expand Down
1 change: 1 addition & 0 deletions src/libsyntax/fold.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1272,6 +1272,7 @@ pub fn noop_fold_expr<T: Folder>(Expr {id, node, span, attrs}: Expr, folder: &mu
};
}
ExprKind::Try(ex) => ExprKind::Try(folder.fold_expr(ex)),
ExprKind::Catch(body) => ExprKind::Catch(folder.fold_block(body)),
},
id: folder.new_id(id),
span: folder.new_span(span),
Expand Down
27 changes: 27 additions & 0 deletions src/libsyntax/parse/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2273,6 +2273,12 @@ impl<'a> Parser<'a> {
BlockCheckMode::Unsafe(ast::UserProvided),
attrs);
}
if self.is_catch_expr() {
assert!(self.eat_keyword(keywords::Do));
assert!(self.eat_keyword(keywords::Catch));
let lo = self.prev_span.lo;
return self.parse_catch_expr(lo, attrs);
}
if self.eat_keyword(keywords::Return) {
if self.token.can_begin_expr() {
let e = self.parse_expr()?;
Expand Down Expand Up @@ -3092,6 +3098,16 @@ impl<'a> Parser<'a> {
Ok(self.mk_expr(span_lo, hi, ExprKind::Loop(body, opt_ident), attrs))
}

/// Parse a `do catch {...}` expression (`do catch` token already eaten)
pub fn parse_catch_expr(&mut self, span_lo: BytePos, mut attrs: ThinVec<Attribute>)
-> PResult<'a, P<Expr>>
{
let (iattrs, body) = self.parse_inner_attrs_and_block()?;
attrs.extend(iattrs);
let hi = body.span.hi;
Ok(self.mk_expr(span_lo, hi, ExprKind::Catch(body), attrs))
}

// `match` token already eaten
fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
let match_span = self.prev_span;
Expand Down Expand Up @@ -3699,6 +3715,15 @@ impl<'a> Parser<'a> {
})
}

fn is_catch_expr(&mut self) -> bool {
self.token.is_keyword(keywords::Do) &&
self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&

// prevent `while catch {} {}`, `if catch {} {} else {}`, etc.
!self.restrictions.contains(Restrictions::RESTRICTION_NO_STRUCT_LITERAL)
}

fn is_union_item(&mut self) -> bool {
self.token.is_keyword(keywords::Union) &&
self.look_ahead(1, |t| t.is_ident() && !t.is_any_keyword())
Expand Down Expand Up @@ -4839,6 +4864,7 @@ impl<'a> Parser<'a> {
/// Parse struct Foo { ... }
fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
let class_name = self.parse_ident()?;

let mut generics = self.parse_generics()?;

// There is a special case worth noting here, as reported in issue #17904.
Expand Down Expand Up @@ -4888,6 +4914,7 @@ impl<'a> Parser<'a> {
/// Parse union Foo { ... }
fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
let class_name = self.parse_ident()?;

let mut generics = self.parse_generics()?;

let vdata = if self.token.is_keyword(keywords::Where) {
Expand Down
1 change: 1 addition & 0 deletions src/libsyntax/parse/token.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ fn ident_can_begin_expr(ident: ast::Ident) -> bool {
!ident_token.is_any_keyword() ||
ident_token.is_path_segment_keyword() ||
[
keywords::Do.name(),
keywords::Box.name(),
keywords::Break.name(),
keywords::Continue.name(),
Expand Down
5 changes: 5 additions & 0 deletions src/libsyntax/print/pprust.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2270,6 +2270,11 @@ impl<'a> State<'a> {
self.print_expr(e)?;
word(&mut self.s, "?")?
}
ast::ExprKind::Catch(ref blk) => {
self.head("catch")?;
space(&mut self.s)?;
self.print_block_with_attrs(&blk, attrs)?
}
}
self.ann.post(self, NodeExpr(expr))?;
self.end()
Expand Down
3 changes: 2 additions & 1 deletion src/libsyntax/symbol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -221,9 +221,10 @@ declare_keywords! {
(53, Default, "default")
(54, StaticLifetime, "'static")
(55, Union, "union")
(56, Catch, "catch")

// A virtual keyword that resolves to the crate root when used in a lexical scope.
(56, CrateRoot, "{{root}}")
(57, CrateRoot, "{{root}}")
}

// If an interner exists in TLS, return it. Otherwise, prepare a fresh one.
Expand Down
3 changes: 3 additions & 0 deletions src/libsyntax/visit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -787,6 +787,9 @@ pub fn walk_expr<'a, V: Visitor<'a>>(visitor: &mut V, expression: &'a Expr) {
ExprKind::Try(ref subexpression) => {
visitor.visit_expr(subexpression)
}
ExprKind::Catch(ref body) => {
visitor.visit_block(body)
}
}

visitor.visit_expr_post(expression)
Expand Down
15 changes: 15 additions & 0 deletions src/test/compile-fail/catch-in-match.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// Copyright 2017 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.

#![feature(catch_expr)]

fn main() {
match do catch { false } { _ => {} } //~ ERROR expected expression, found reserved keyword `do`
}
15 changes: 15 additions & 0 deletions src/test/compile-fail/catch-in-while.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// Copyright 2017 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.

#![feature(catch_expr)]

fn main() {
while do catch { false } {} //~ ERROR expected expression, found reserved keyword `do`
}
17 changes: 17 additions & 0 deletions src/test/compile-fail/feature-gate-catch_expr.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// Copyright 2017 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.

pub fn main() {
let catch_result = do catch { //~ ERROR `catch` expression is experimental
let x = 5;
x
};
assert_eq!(catch_result, 5);
}
32 changes: 32 additions & 0 deletions src/test/run-pass/catch-expr.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Copyright 2017 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.

#![feature(catch_expr)]

struct catch {}

pub fn main() {
let catch_result = do catch {
let x = 5;
x
};
assert_eq!(catch_result, 5);

let mut catch = true;
while catch { catch = false; }
assert_eq!(catch, false);

catch = if catch { false } else { true };
assert_eq!(catch, true);

match catch {
_ => {}
};
}

0 comments on commit e2d3770

Please sign in to comment.