Skip to content

Commit e2d3770

Browse files
authored
Rollup merge of rust-lang#39921 - cramertj:add-catch-to-ast, r=nikomatsakis
Add catch {} to AST Part of rust-lang#39849. Builds on rust-lang#39864.
2 parents 5c71f91 + b549f14 commit e2d3770

File tree

13 files changed

+159
-5
lines changed

13 files changed

+159
-5
lines changed

src/librustc/hir/lowering.rs

+33-4
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,7 @@ pub struct LoweringContext<'a> {
8383
trait_impls: BTreeMap<DefId, Vec<NodeId>>,
8484
trait_default_impl: BTreeMap<DefId, NodeId>,
8585

86+
catch_scopes: Vec<NodeId>,
8687
loop_scopes: Vec<NodeId>,
8788
is_in_loop_condition: bool,
8889

@@ -121,6 +122,7 @@ pub fn lower_crate(sess: &Session,
121122
bodies: BTreeMap::new(),
122123
trait_impls: BTreeMap::new(),
123124
trait_default_impl: BTreeMap::new(),
125+
catch_scopes: Vec::new(),
124126
loop_scopes: Vec::new(),
125127
is_in_loop_condition: false,
126128
type_def_lifetime_params: DefIdMap(),
@@ -259,6 +261,21 @@ impl<'a> LoweringContext<'a> {
259261
span
260262
}
261263

264+
fn with_catch_scope<T, F>(&mut self, catch_id: NodeId, f: F) -> T
265+
where F: FnOnce(&mut LoweringContext) -> T
266+
{
267+
let len = self.catch_scopes.len();
268+
self.catch_scopes.push(catch_id);
269+
270+
let result = f(self);
271+
assert_eq!(len + 1, self.catch_scopes.len(),
272+
"catch scopes should be added and removed in stack order");
273+
274+
self.catch_scopes.pop().unwrap();
275+
276+
result
277+
}
278+
262279
fn with_loop_scope<T, F>(&mut self, loop_id: NodeId, f: F) -> T
263280
where F: FnOnce(&mut LoweringContext) -> T
264281
{
@@ -293,15 +310,17 @@ impl<'a> LoweringContext<'a> {
293310
result
294311
}
295312

296-
fn with_new_loop_scopes<T, F>(&mut self, f: F) -> T
313+
fn with_new_scopes<T, F>(&mut self, f: F) -> T
297314
where F: FnOnce(&mut LoweringContext) -> T
298315
{
299316
let was_in_loop_condition = self.is_in_loop_condition;
300317
self.is_in_loop_condition = false;
301318

319+
let catch_scopes = mem::replace(&mut self.catch_scopes, Vec::new());
302320
let loop_scopes = mem::replace(&mut self.loop_scopes, Vec::new());
303321
let result = f(self);
304-
mem::replace(&mut self.loop_scopes, loop_scopes);
322+
self.catch_scopes = catch_scopes;
323+
self.loop_scopes = loop_scopes;
305324

306325
self.is_in_loop_condition = was_in_loop_condition;
307326

@@ -1063,7 +1082,7 @@ impl<'a> LoweringContext<'a> {
10631082
self.record_body(value, None))
10641083
}
10651084
ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
1066-
self.with_new_loop_scopes(|this| {
1085+
self.with_new_scopes(|this| {
10671086
let body = this.lower_block(body);
10681087
let body = this.expr_block(body, ThinVec::new());
10691088
let body_id = this.record_body(body, Some(decl));
@@ -1660,13 +1679,17 @@ impl<'a> LoweringContext<'a> {
16601679
this.lower_opt_sp_ident(opt_ident),
16611680
hir::LoopSource::Loop))
16621681
}
1682+
ExprKind::Catch(ref body) => {
1683+
// FIXME(cramertj): Add catch to HIR
1684+
self.with_catch_scope(e.id, |this| hir::ExprBlock(this.lower_block(body)))
1685+
}
16631686
ExprKind::Match(ref expr, ref arms) => {
16641687
hir::ExprMatch(P(self.lower_expr(expr)),
16651688
arms.iter().map(|x| self.lower_arm(x)).collect(),
16661689
hir::MatchSource::Normal)
16671690
}
16681691
ExprKind::Closure(capture_clause, ref decl, ref body, fn_decl_span) => {
1669-
self.with_new_loop_scopes(|this| {
1692+
self.with_new_scopes(|this| {
16701693
this.with_parent_def(e.id, |this| {
16711694
let expr = this.lower_expr(body);
16721695
hir::ExprClosure(this.lower_capture_clause(capture_clause),
@@ -2064,6 +2087,12 @@ impl<'a> LoweringContext<'a> {
20642087
// Err(err) => #[allow(unreachable_code)]
20652088
// return Carrier::from_error(From::from(err)),
20662089
// }
2090+
2091+
// FIXME(cramertj): implement breaking to catch
2092+
if !self.catch_scopes.is_empty() {
2093+
bug!("`?` in catch scopes is unimplemented")
2094+
}
2095+
20672096
let unstable_span = self.allow_internal_unstable("?", e.span);
20682097

20692098
// Carrier::translate(<expr>)

src/libsyntax/ast.rs

+2
Original file line numberDiff line numberDiff line change
@@ -936,6 +936,8 @@ pub enum ExprKind {
936936
Closure(CaptureBy, P<FnDecl>, P<Expr>, Span),
937937
/// A block (`{ ... }`)
938938
Block(P<Block>),
939+
/// A catch block (`catch { ... }`)
940+
Catch(P<Block>),
939941

940942
/// An assignment (`a = foo()`)
941943
Assign(P<Expr>, P<Expr>),

src/libsyntax/feature_gate.rs

+6
Original file line numberDiff line numberDiff line change
@@ -339,6 +339,9 @@ declare_features! (
339339

340340
// `extern "x86-interrupt" fn()`
341341
(active, abi_x86_interrupt, "1.17.0", Some(40180)),
342+
343+
// Allows the `catch {...}` expression
344+
(active, catch_expr, "1.17.0", Some(31436)),
342345
);
343346

344347
declare_features! (
@@ -1287,6 +1290,9 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> {
12871290
}
12881291
}
12891292
}
1293+
ast::ExprKind::Catch(_) => {
1294+
gate_feature_post!(&self, catch_expr, e.span, "`catch` expression is experimental");
1295+
}
12901296
_ => {}
12911297
}
12921298
visit::walk_expr(self, e);

src/libsyntax/fold.rs

+1
Original file line numberDiff line numberDiff line change
@@ -1272,6 +1272,7 @@ pub fn noop_fold_expr<T: Folder>(Expr {id, node, span, attrs}: Expr, folder: &mu
12721272
};
12731273
}
12741274
ExprKind::Try(ex) => ExprKind::Try(folder.fold_expr(ex)),
1275+
ExprKind::Catch(body) => ExprKind::Catch(folder.fold_block(body)),
12751276
},
12761277
id: folder.new_id(id),
12771278
span: folder.new_span(span),

src/libsyntax/parse/parser.rs

+27
Original file line numberDiff line numberDiff line change
@@ -2273,6 +2273,12 @@ impl<'a> Parser<'a> {
22732273
BlockCheckMode::Unsafe(ast::UserProvided),
22742274
attrs);
22752275
}
2276+
if self.is_catch_expr() {
2277+
assert!(self.eat_keyword(keywords::Do));
2278+
assert!(self.eat_keyword(keywords::Catch));
2279+
let lo = self.prev_span.lo;
2280+
return self.parse_catch_expr(lo, attrs);
2281+
}
22762282
if self.eat_keyword(keywords::Return) {
22772283
if self.token.can_begin_expr() {
22782284
let e = self.parse_expr()?;
@@ -3092,6 +3098,16 @@ impl<'a> Parser<'a> {
30923098
Ok(self.mk_expr(span_lo, hi, ExprKind::Loop(body, opt_ident), attrs))
30933099
}
30943100

3101+
/// Parse a `do catch {...}` expression (`do catch` token already eaten)
3102+
pub fn parse_catch_expr(&mut self, span_lo: BytePos, mut attrs: ThinVec<Attribute>)
3103+
-> PResult<'a, P<Expr>>
3104+
{
3105+
let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3106+
attrs.extend(iattrs);
3107+
let hi = body.span.hi;
3108+
Ok(self.mk_expr(span_lo, hi, ExprKind::Catch(body), attrs))
3109+
}
3110+
30953111
// `match` token already eaten
30963112
fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
30973113
let match_span = self.prev_span;
@@ -3699,6 +3715,15 @@ impl<'a> Parser<'a> {
36993715
})
37003716
}
37013717

3718+
fn is_catch_expr(&mut self) -> bool {
3719+
self.token.is_keyword(keywords::Do) &&
3720+
self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
3721+
self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
3722+
3723+
// prevent `while catch {} {}`, `if catch {} {} else {}`, etc.
3724+
!self.restrictions.contains(Restrictions::RESTRICTION_NO_STRUCT_LITERAL)
3725+
}
3726+
37023727
fn is_union_item(&mut self) -> bool {
37033728
self.token.is_keyword(keywords::Union) &&
37043729
self.look_ahead(1, |t| t.is_ident() && !t.is_any_keyword())
@@ -4839,6 +4864,7 @@ impl<'a> Parser<'a> {
48394864
/// Parse struct Foo { ... }
48404865
fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
48414866
let class_name = self.parse_ident()?;
4867+
48424868
let mut generics = self.parse_generics()?;
48434869

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

48934920
let vdata = if self.token.is_keyword(keywords::Where) {

src/libsyntax/parse/token.rs

+1
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,7 @@ fn ident_can_begin_expr(ident: ast::Ident) -> bool {
8686
!ident_token.is_any_keyword() ||
8787
ident_token.is_path_segment_keyword() ||
8888
[
89+
keywords::Do.name(),
8990
keywords::Box.name(),
9091
keywords::Break.name(),
9192
keywords::Continue.name(),

src/libsyntax/print/pprust.rs

+5
Original file line numberDiff line numberDiff line change
@@ -2270,6 +2270,11 @@ impl<'a> State<'a> {
22702270
self.print_expr(e)?;
22712271
word(&mut self.s, "?")?
22722272
}
2273+
ast::ExprKind::Catch(ref blk) => {
2274+
self.head("catch")?;
2275+
space(&mut self.s)?;
2276+
self.print_block_with_attrs(&blk, attrs)?
2277+
}
22732278
}
22742279
self.ann.post(self, NodeExpr(expr))?;
22752280
self.end()

src/libsyntax/symbol.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -221,9 +221,10 @@ declare_keywords! {
221221
(53, Default, "default")
222222
(54, StaticLifetime, "'static")
223223
(55, Union, "union")
224+
(56, Catch, "catch")
224225

225226
// A virtual keyword that resolves to the crate root when used in a lexical scope.
226-
(56, CrateRoot, "{{root}}")
227+
(57, CrateRoot, "{{root}}")
227228
}
228229

229230
// If an interner exists in TLS, return it. Otherwise, prepare a fresh one.

src/libsyntax/visit.rs

+3
Original file line numberDiff line numberDiff line change
@@ -787,6 +787,9 @@ pub fn walk_expr<'a, V: Visitor<'a>>(visitor: &mut V, expression: &'a Expr) {
787787
ExprKind::Try(ref subexpression) => {
788788
visitor.visit_expr(subexpression)
789789
}
790+
ExprKind::Catch(ref body) => {
791+
visitor.visit_block(body)
792+
}
790793
}
791794

792795
visitor.visit_expr_post(expression)
+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
2+
// file at the top-level directory of this distribution and at
3+
// http://rust-lang.org/COPYRIGHT.
4+
//
5+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6+
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8+
// option. This file may not be copied, modified, or distributed
9+
// except according to those terms.
10+
11+
#![feature(catch_expr)]
12+
13+
fn main() {
14+
match do catch { false } { _ => {} } //~ ERROR expected expression, found reserved keyword `do`
15+
}
+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
2+
// file at the top-level directory of this distribution and at
3+
// http://rust-lang.org/COPYRIGHT.
4+
//
5+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6+
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8+
// option. This file may not be copied, modified, or distributed
9+
// except according to those terms.
10+
11+
#![feature(catch_expr)]
12+
13+
fn main() {
14+
while do catch { false } {} //~ ERROR expected expression, found reserved keyword `do`
15+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
2+
// file at the top-level directory of this distribution and at
3+
// http://rust-lang.org/COPYRIGHT.
4+
//
5+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6+
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8+
// option. This file may not be copied, modified, or distributed
9+
// except according to those terms.
10+
11+
pub fn main() {
12+
let catch_result = do catch { //~ ERROR `catch` expression is experimental
13+
let x = 5;
14+
x
15+
};
16+
assert_eq!(catch_result, 5);
17+
}

src/test/run-pass/catch-expr.rs

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
2+
// file at the top-level directory of this distribution and at
3+
// http://rust-lang.org/COPYRIGHT.
4+
//
5+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6+
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8+
// option. This file may not be copied, modified, or distributed
9+
// except according to those terms.
10+
11+
#![feature(catch_expr)]
12+
13+
struct catch {}
14+
15+
pub fn main() {
16+
let catch_result = do catch {
17+
let x = 5;
18+
x
19+
};
20+
assert_eq!(catch_result, 5);
21+
22+
let mut catch = true;
23+
while catch { catch = false; }
24+
assert_eq!(catch, false);
25+
26+
catch = if catch { false } else { true };
27+
assert_eq!(catch, true);
28+
29+
match catch {
30+
_ => {}
31+
};
32+
}

0 commit comments

Comments
 (0)