Skip to content

Commit 6f10e2f

Browse files
committed
Auto merge of #39921 - cramertj:add-catch-to-ast, r=nikomatsakis
Add catch {} to AST Part of #39849. Builds on #39864.
2 parents fa53235 + b1aa993 commit 6f10e2f

File tree

13 files changed

+159
-5
lines changed

13 files changed

+159
-5
lines changed

Diff for: src/librustc/hir/lowering.rs

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

87+
catch_scopes: Vec<NodeId>,
8788
loop_scopes: Vec<NodeId>,
8889
is_in_loop_condition: bool,
8990

@@ -123,6 +124,7 @@ pub fn lower_crate(sess: &Session,
123124
trait_impls: BTreeMap::new(),
124125
trait_default_impl: BTreeMap::new(),
125126
exported_macros: Vec::new(),
127+
catch_scopes: Vec::new(),
126128
loop_scopes: Vec::new(),
127129
is_in_loop_condition: false,
128130
type_def_lifetime_params: DefIdMap(),
@@ -261,6 +263,21 @@ impl<'a> LoweringContext<'a> {
261263
span
262264
}
263265

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

298-
fn with_new_loop_scopes<T, F>(&mut self, f: F) -> T
315+
fn with_new_scopes<T, F>(&mut self, f: F) -> T
299316
where F: FnOnce(&mut LoweringContext) -> T
300317
{
301318
let was_in_loop_condition = self.is_in_loop_condition;
302319
self.is_in_loop_condition = false;
303320

321+
let catch_scopes = mem::replace(&mut self.catch_scopes, Vec::new());
304322
let loop_scopes = mem::replace(&mut self.loop_scopes, Vec::new());
305323
let result = f(self);
306-
mem::replace(&mut self.loop_scopes, loop_scopes);
324+
self.catch_scopes = catch_scopes;
325+
self.loop_scopes = loop_scopes;
307326

308327
self.is_in_loop_condition = was_in_loop_condition;
309328

@@ -1065,7 +1084,7 @@ impl<'a> LoweringContext<'a> {
10651084
self.record_body(value, None))
10661085
}
10671086
ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => {
1068-
self.with_new_loop_scopes(|this| {
1087+
self.with_new_scopes(|this| {
10691088
let body = this.lower_block(body);
10701089
let body = this.expr_block(body, ThinVec::new());
10711090
let body_id = this.record_body(body, Some(decl));
@@ -1665,13 +1684,17 @@ impl<'a> LoweringContext<'a> {
16651684
this.lower_opt_sp_ident(opt_ident),
16661685
hir::LoopSource::Loop))
16671686
}
1687+
ExprKind::Catch(ref body) => {
1688+
// FIXME(cramertj): Add catch to HIR
1689+
self.with_catch_scope(e.id, |this| hir::ExprBlock(this.lower_block(body)))
1690+
}
16681691
ExprKind::Match(ref expr, ref arms) => {
16691692
hir::ExprMatch(P(self.lower_expr(expr)),
16701693
arms.iter().map(|x| self.lower_arm(x)).collect(),
16711694
hir::MatchSource::Normal)
16721695
}
16731696
ExprKind::Closure(capture_clause, ref decl, ref body, fn_decl_span) => {
1674-
self.with_new_loop_scopes(|this| {
1697+
self.with_new_scopes(|this| {
16751698
this.with_parent_def(e.id, |this| {
16761699
let expr = this.lower_expr(body);
16771700
hir::ExprClosure(this.lower_capture_clause(capture_clause),
@@ -2069,6 +2092,12 @@ impl<'a> LoweringContext<'a> {
20692092
// Err(err) => #[allow(unreachable_code)]
20702093
// return Carrier::from_error(From::from(err)),
20712094
// }
2095+
2096+
// FIXME(cramertj): implement breaking to catch
2097+
if !self.catch_scopes.is_empty() {
2098+
bug!("`?` in catch scopes is unimplemented")
2099+
}
2100+
20722101
let unstable_span = self.allow_internal_unstable("?", e.span);
20732102

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

Diff for: src/libsyntax/ast.rs

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

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

Diff for: 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);

Diff for: src/libsyntax/fold.rs

+1
Original file line numberDiff line numberDiff line change
@@ -1269,6 +1269,7 @@ pub fn noop_fold_expr<T: Folder>(Expr {id, node, span, attrs}: Expr, folder: &mu
12691269
};
12701270
}
12711271
ExprKind::Try(ex) => ExprKind::Try(folder.fold_expr(ex)),
1272+
ExprKind::Catch(body) => ExprKind::Catch(folder.fold_block(body)),
12721273
},
12731274
id: folder.new_id(id),
12741275
span: folder.new_span(span),

Diff for: src/libsyntax/parse/parser.rs

+27
Original file line numberDiff line numberDiff line change
@@ -2280,6 +2280,12 @@ impl<'a> Parser<'a> {
22802280
BlockCheckMode::Unsafe(ast::UserProvided),
22812281
attrs);
22822282
}
2283+
if self.is_catch_expr() {
2284+
assert!(self.eat_keyword(keywords::Do));
2285+
assert!(self.eat_keyword(keywords::Catch));
2286+
let lo = self.prev_span.lo;
2287+
return self.parse_catch_expr(lo, attrs);
2288+
}
22832289
if self.eat_keyword(keywords::Return) {
22842290
if self.token.can_begin_expr() {
22852291
let e = self.parse_expr()?;
@@ -3099,6 +3105,16 @@ impl<'a> Parser<'a> {
30993105
Ok(self.mk_expr(span_lo, hi, ExprKind::Loop(body, opt_ident), attrs))
31003106
}
31013107

3108+
/// Parse a `do catch {...}` expression (`do catch` token already eaten)
3109+
pub fn parse_catch_expr(&mut self, span_lo: BytePos, mut attrs: ThinVec<Attribute>)
3110+
-> PResult<'a, P<Expr>>
3111+
{
3112+
let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3113+
attrs.extend(iattrs);
3114+
let hi = body.span.hi;
3115+
Ok(self.mk_expr(span_lo, hi, ExprKind::Catch(body), attrs))
3116+
}
3117+
31023118
// `match` token already eaten
31033119
fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
31043120
let match_span = self.prev_span;
@@ -3706,6 +3722,15 @@ impl<'a> Parser<'a> {
37063722
})
37073723
}
37083724

3725+
fn is_catch_expr(&mut self) -> bool {
3726+
self.token.is_keyword(keywords::Do) &&
3727+
self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
3728+
self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
3729+
3730+
// prevent `while catch {} {}`, `if catch {} {} else {}`, etc.
3731+
!self.restrictions.contains(Restrictions::RESTRICTION_NO_STRUCT_LITERAL)
3732+
}
3733+
37093734
fn is_union_item(&self) -> bool {
37103735
self.token.is_keyword(keywords::Union) &&
37113736
self.look_ahead(1, |t| t.is_ident() && !t.is_any_keyword())
@@ -4882,6 +4907,7 @@ impl<'a> Parser<'a> {
48824907
/// Parse struct Foo { ... }
48834908
fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
48844909
let class_name = self.parse_ident()?;
4910+
48854911
let mut generics = self.parse_generics()?;
48864912

48874913
// There is a special case worth noting here, as reported in issue #17904.
@@ -4931,6 +4957,7 @@ impl<'a> Parser<'a> {
49314957
/// Parse union Foo { ... }
49324958
fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
49334959
let class_name = self.parse_ident()?;
4960+
49344961
let mut generics = self.parse_generics()?;
49354962

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

Diff for: 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(),

Diff for: src/libsyntax/print/pprust.rs

+5
Original file line numberDiff line numberDiff line change
@@ -2279,6 +2279,11 @@ impl<'a> State<'a> {
22792279
self.print_expr(e)?;
22802280
word(&mut self.s, "?")?
22812281
}
2282+
ast::ExprKind::Catch(ref blk) => {
2283+
self.head("do catch")?;
2284+
space(&mut self.s)?;
2285+
self.print_block_with_attrs(&blk, attrs)?
2286+
}
22822287
}
22832288
self.ann.post(self, NodeExpr(expr))?;
22842289
self.end()

Diff for: 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.

Diff for: src/libsyntax/visit.rs

+3
Original file line numberDiff line numberDiff line change
@@ -779,6 +779,9 @@ pub fn walk_expr<'a, V: Visitor<'a>>(visitor: &mut V, expression: &'a Expr) {
779779
ExprKind::Try(ref subexpression) => {
780780
visitor.visit_expr(subexpression)
781781
}
782+
ExprKind::Catch(ref body) => {
783+
visitor.visit_block(body)
784+
}
782785
}
783786

784787
visitor.visit_expr_post(expression)

Diff for: src/test/compile-fail/catch-in-match.rs

+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+
}

Diff for: src/test/compile-fail/catch-in-while.rs

+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+
}

Diff for: src/test/compile-fail/feature-gate-catch_expr.rs

+17
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+
}

Diff for: 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)