Skip to content

Commit 7656945

Browse files
committed
don't panic on #[derive] placed on statements/expressions
closes #49934
1 parent b91e6a2 commit 7656945

File tree

3 files changed

+46
-2
lines changed

3 files changed

+46
-2
lines changed

src/libsyntax/ext/base.rs

+14
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,20 @@ impl Annotatable {
118118
}
119119
}
120120

121+
pub fn expect_stmt(self) -> ast::Stmt {
122+
match self {
123+
Annotatable::Stmt(stmt) => stmt.into_inner(),
124+
_ => panic!("expected statement"),
125+
}
126+
}
127+
128+
pub fn expect_expr(self) -> P<ast::Expr> {
129+
match self {
130+
Annotatable::Expr(expr) => expr,
131+
_ => panic!("expected expression"),
132+
}
133+
}
134+
121135
pub fn derive_allowed(&self) -> bool {
122136
match *self {
123137
Annotatable::Item(ref item) => match item.node {

src/libsyntax/ext/expand.rs

+9-2
Original file line numberDiff line numberDiff line change
@@ -143,7 +143,7 @@ impl ExpansionKind {
143143
}
144144

145145
fn expect_from_annotatables<I: IntoIterator<Item = Annotatable>>(self, items: I) -> Expansion {
146-
let items = items.into_iter();
146+
let mut items = items.into_iter();
147147
match self {
148148
ExpansionKind::Items =>
149149
Expansion::Items(items.map(Annotatable::expect_item).collect()),
@@ -153,7 +153,14 @@ impl ExpansionKind {
153153
Expansion::TraitItems(items.map(Annotatable::expect_trait_item).collect()),
154154
ExpansionKind::ForeignItems =>
155155
Expansion::ForeignItems(items.map(Annotatable::expect_foreign_item).collect()),
156-
_ => unreachable!(),
156+
ExpansionKind::Stmts => Expansion::Stmts(items.map(Annotatable::expect_stmt).collect()),
157+
ExpansionKind::Expr => Expansion::Expr(
158+
items.next().expect("expected exactly one expression").expect_expr()
159+
),
160+
ExpansionKind::OptExpr =>
161+
Expansion::OptExpr(items.next().map(Annotatable::expect_expr)),
162+
ExpansionKind::Pat | ExpansionKind::Ty =>
163+
panic!("patterns and types aren't annotatable"),
157164
}
158165
}
159166
}

src/test/compile-fail/issue-49934.rs

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
// Copyright 2018 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+
#![feature(stmt_expr_attributes)]
11+
12+
fn main() {
13+
#[derive(Debug)] //~ ERROR `derive`
14+
println!("Hello, world!");
15+
16+
let _ = #[derive(Debug)] "Hello, world!";
17+
//~^ ERROR `derive`
18+
19+
let _ = [
20+
#[derive(Debug)] //~ ERROR `derive`
21+
"Hello, world!"
22+
];
23+
}

0 commit comments

Comments
 (0)