Skip to content

Commit d95c543

Browse files
committed
Add catch expr to AST and disallow catch as a struct name
1 parent 1b19284 commit d95c543

14 files changed

+196
-5
lines changed

src/librustc/hir/lowering.rs

Lines changed: 33 additions & 4 deletions
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>)

src/libsyntax/ast.rs

Lines changed: 2 additions & 0 deletions
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>),

src/libsyntax/feature_gate.rs

Lines changed: 6 additions & 0 deletions
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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1268,6 +1268,7 @@ pub fn noop_fold_expr<T: Folder>(Expr {id, node, span, attrs}: Expr, folder: &mu
12681268
};
12691269
}
12701270
ExprKind::Try(ex) => ExprKind::Try(folder.fold_expr(ex)),
1271+
ExprKind::Catch(body) => ExprKind::Catch(folder.fold_block(body)),
12711272
},
12721273
id: folder.new_id(id),
12731274
span: folder.new_span(span),

src/libsyntax/parse/parser.rs

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -602,6 +602,12 @@ impl<'a> Parser<'a> {
602602
}
603603
}
604604

605+
pub fn error_if_typename_is_catch(&mut self, ident: ast::Ident) {
606+
if ident.name == keywords::Catch.name() {
607+
self.span_err(self.span, "cannot use `catch` as the name of a type");
608+
}
609+
}
610+
605611
/// Check if the next token is `tok`, and return `true` if so.
606612
///
607613
/// This method will automatically add `tok` to `expected_tokens` if `tok` is not
@@ -2273,6 +2279,11 @@ impl<'a> Parser<'a> {
22732279
BlockCheckMode::Unsafe(ast::UserProvided),
22742280
attrs);
22752281
}
2282+
if self.is_catch_expr() {
2283+
assert!(self.eat_keyword(keywords::Catch));
2284+
let lo = self.prev_span.lo;
2285+
return self.parse_catch_expr(lo, attrs);
2286+
}
22762287
if self.eat_keyword(keywords::Return) {
22772288
if self.token.can_begin_expr() {
22782289
let e = self.parse_expr()?;
@@ -3092,6 +3103,16 @@ impl<'a> Parser<'a> {
30923103
Ok(self.mk_expr(span_lo, hi, ExprKind::Loop(body, opt_ident), attrs))
30933104
}
30943105

3106+
/// Parse a `catch {...}` expression (`catch` token already eaten)
3107+
pub fn parse_catch_expr(&mut self, span_lo: BytePos, mut attrs: ThinVec<Attribute>)
3108+
-> PResult<'a, P<Expr>>
3109+
{
3110+
let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3111+
attrs.extend(iattrs);
3112+
let hi = body.span.hi;
3113+
Ok(self.mk_expr(span_lo, hi, ExprKind::Catch(body), attrs))
3114+
}
3115+
30953116
// `match` token already eaten
30963117
fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
30973118
let match_span = self.prev_span;
@@ -3699,6 +3720,14 @@ impl<'a> Parser<'a> {
36993720
})
37003721
}
37013722

3723+
fn is_catch_expr(&mut self) -> bool {
3724+
self.token.is_keyword(keywords::Catch) &&
3725+
self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) &&
3726+
3727+
// prevent `while catch {} {}`, `if catch {} {} else {}`, etc.
3728+
!self.restrictions.contains(Restrictions::RESTRICTION_NO_STRUCT_LITERAL)
3729+
}
3730+
37023731
fn is_union_item(&self) -> bool {
37033732
self.token.is_keyword(keywords::Union) &&
37043733
self.look_ahead(1, |t| t.is_ident() && !t.is_any_keyword())
@@ -4875,6 +4904,8 @@ impl<'a> Parser<'a> {
48754904
/// Parse struct Foo { ... }
48764905
fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
48774906
let class_name = self.parse_ident()?;
4907+
self.error_if_typename_is_catch(class_name);
4908+
48784909
let mut generics = self.parse_generics()?;
48794910

48804911
// There is a special case worth noting here, as reported in issue #17904.
@@ -4924,6 +4955,8 @@ impl<'a> Parser<'a> {
49244955
/// Parse union Foo { ... }
49254956
fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
49264957
let class_name = self.parse_ident()?;
4958+
self.error_if_typename_is_catch(class_name);
4959+
49274960
let mut generics = self.parse_generics()?;
49284961

49294962
let vdata = if self.token.is_keyword(keywords::Where) {
@@ -5440,6 +5473,7 @@ impl<'a> Parser<'a> {
54405473
let struct_def;
54415474
let mut disr_expr = None;
54425475
let ident = self.parse_ident()?;
5476+
self.error_if_typename_is_catch(ident);
54435477
if self.check(&token::OpenDelim(token::Brace)) {
54445478
// Parse a struct variant.
54455479
all_nullary = false;
@@ -5481,6 +5515,7 @@ impl<'a> Parser<'a> {
54815515
/// Parse an "enum" declaration
54825516
fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
54835517
let id = self.parse_ident()?;
5518+
self.error_if_typename_is_catch(id);
54845519
let mut generics = self.parse_generics()?;
54855520
generics.where_clause = self.parse_where_clause()?;
54865521
self.expect(&token::OpenDelim(token::Brace))?;

src/libsyntax/print/pprust.rs

Lines changed: 5 additions & 0 deletions
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("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()

src/libsyntax/symbol.rs

Lines changed: 2 additions & 1 deletion
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

Lines changed: 3 additions & 0 deletions
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)
Lines changed: 15 additions & 0 deletions
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+
#![allow(non_camel_case_types)]
12+
#![allow(dead_code)]
13+
#![feature(catch_expr)]
14+
15+
struct catch; //~ ERROR cannot use `catch` as the name of a type
Lines changed: 17 additions & 0 deletions
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+
#![allow(non_camel_case_types)]
12+
#![allow(dead_code)]
13+
#![feature(catch_expr)]
14+
15+
enum Enum {
16+
catch {} //~ ERROR cannot use `catch` as the name of a type
17+
}
Lines changed: 15 additions & 0 deletions
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+
#![allow(non_camel_case_types)]
12+
#![allow(dead_code)]
13+
#![feature(catch_expr)]
14+
15+
struct catch {} //~ ERROR cannot use `catch` as the name of a type
Lines changed: 15 additions & 0 deletions
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+
#![allow(non_camel_case_types)]
12+
#![allow(dead_code)]
13+
#![feature(catch_expr)]
14+
15+
struct catch(); //~ ERROR cannot use `catch` as the name of a type
Lines changed: 17 additions & 0 deletions
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 = 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

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
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+
pub fn main() {
14+
let catch_result = catch {
15+
let x = 5;
16+
x
17+
};
18+
assert_eq!(catch_result, 5);
19+
20+
let mut catch = true;
21+
while catch { catch = false; }
22+
assert_eq!(catch, false);
23+
24+
catch = if catch { false } else { true };
25+
assert_eq!(catch, true);
26+
27+
match catch {
28+
_ => {}
29+
};
30+
}

0 commit comments

Comments
 (0)