Skip to content

Commit

Permalink
Properly recover from trailing attr in body
Browse files Browse the repository at this point in the history
When encountering an attribute in a body, we try to recover from an
attribute on an expression (as opposed to a statement). We need to
properly clean up when the attribute is at the end of the body where a
tail expression would be.

Fix rust-lang#118164.
  • Loading branch information
estebank committed Nov 22, 2023
1 parent 73bc121 commit 3707461
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 2 deletions.
20 changes: 18 additions & 2 deletions compiler/rustc_parse/src/parser/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -772,12 +772,27 @@ impl<'a> Parser<'a> {
&& let ast::AttrKind::Normal(attr_kind) = &attr.kind
&& let [segment] = &attr_kind.item.path.segments[..]
&& segment.ident.name == sym::cfg
&& let Ok(next_attr) = snapshot.parse_attribute(InnerAttrPolicy::Forbidden(None))
&& let next_attr = match snapshot.parse_attribute(InnerAttrPolicy::Forbidden(None))
{
Ok(next_attr) => next_attr,
Err(inner_err) => {
err.cancel();
inner_err.cancel();
return;
}
}
&& let ast::AttrKind::Normal(next_attr_kind) = next_attr.kind
&& let [next_segment] = &next_attr_kind.item.path.segments[..]
&& segment.ident.name == sym::cfg
&& let Ok(next_expr) = snapshot.parse_expr()
{
let next_expr = match snapshot.parse_expr() {
Ok(next_expr) => next_expr,
Err(inner_err) => {
err.cancel();
inner_err.cancel();
return;
}
};
// We have for sure
// #[cfg(..)]
// expr
Expand Down Expand Up @@ -819,6 +834,7 @@ impl<'a> Parser<'a> {
}
err.emit();
}

fn check_too_many_raw_str_terminators(&mut self, err: &mut Diagnostic) -> bool {
let sm = self.sess.source_map();
match (&self.prev_token.kind, &self.token.kind) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// Issue #118164: recovery path leaving unemitted error behind
fn bar() -> String {
#[cfg(feature = )]
[1, 2, 3].iter().map().collect::<String>()
#[attr] //~ ERROR expected statement after outer attribute
}
fn main() {
let _ = bar();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
error: expected statement after outer attribute
--> $DIR/properly-recover-from-trailing-outer-attribute-in-body.rs:5:5
|
LL | #[attr]
| ^^^^^^^

error: aborting due to previous error

0 comments on commit 3707461

Please sign in to comment.