Skip to content

suggest .. for erroneous ... in struct pattern; don't discard successfully-parsed fields on error #46721

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/libsyntax/parse/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,11 @@ use std::str;

pub type PResult<'a, T> = Result<T, DiagnosticBuilder<'a>>;

/// Like `PResult`, but the `Err` value is a tuple whose first value is a
/// "partial result" (of some useful work we did before hitting the error), and
/// whose second value is the error.
pub type PartialPResult<'a, T> = Result<T, (T, DiagnosticBuilder<'a>)>;

#[macro_use]
pub mod parser;

Expand Down
42 changes: 28 additions & 14 deletions src/libsyntax/parse/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ use parse::{new_sub_parser_from_file, ParseSess, Directory, DirectoryOwnership};
use util::parser::{AssocOp, Fixity};
use print::pprust;
use ptr::P;
use parse::PResult;
use parse::{PResult, PartialPResult};
use tokenstream::{self, Delimited, ThinTokenStream, TokenTree, TokenStream};
use symbol::{Symbol, keywords};
use util::ThinVec;
Expand Down Expand Up @@ -3426,40 +3426,52 @@ impl<'a> Parser<'a> {
}

/// Parse the fields of a struct-like pattern
fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<codemap::Spanned<ast::FieldPat>>, bool)> {
fn parse_pat_fields(&mut self)
-> PartialPResult<'a, (Vec<codemap::Spanned<ast::FieldPat>>, bool)> {
let mut fields = Vec::new();
let mut etc = false;
let mut first = true;

while self.token != token::CloseDelim(token::Brace) {
if first {
first = false;
} else {
self.expect(&token::Comma)?;
self.expect(&token::Comma).map_err(|err| ((fields.clone(), etc), err))?;
// accept trailing commas
if self.check(&token::CloseDelim(token::Brace)) { break }
}

let attrs = self.parse_outer_attributes()?;
let attrs = self.parse_outer_attributes()
.map_err(|err| ((fields.clone(), etc), err))?;
let lo = self.span;
let hi;

if self.check(&token::DotDot) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The only thing this PR needs to do is to replace this self.check(&token::DotDot) with self.check(&token::DotDot) || self.token == token::DotDotDot, and report a non-fatal error (self.span_err(...)) if it's actually a DotDotDot.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see ...

(I might claim that the extra machinery in this PR is still potentially useful for taking successfully-parsed field patterns into account when there's some other kind of syntax error ... but maybe that can be a separate, future PR if I find this PartialPResult device being useful elsewhere.)

self.bump();
if self.token != token::CloseDelim(token::Brace) {
let token_str = self.this_token_to_string();
return Err(self.fatal(&format!("expected `{}`, found `{}`", "}",
token_str)))
let err = self.fatal(&format!("expected `{}`, found `{}`", "}",
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

format!("expected {}...", "}", ...) is a bit silly, could you change it? :)

token_str));
return Err(((fields, etc), err));
}
etc = true;
break;
} else if self.token == token::DotDotDot {
let mut err = self.fatal("expected field pattern, found `...`");
err.span_suggestion(self.span,
"to omit remaining fields, use one fewer `.`",
"..".to_owned());
return Err(((fields, false), err));
}

// Check if a colon exists one ahead. This means we're parsing a fieldname.
let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
// Parsing a pattern of the form "fieldname: pat"
let fieldname = self.parse_field_name()?;
let fieldname = self.parse_field_name()
.map_err(|err| ((fields.clone(), etc), err))?;
self.bump();
let pat = self.parse_pat()?;
let pat = self.parse_pat()
.map_err(|err| ((fields.clone(), etc), err))?;
hi = pat.span;
(pat, fieldname, false)
} else {
Expand All @@ -3468,7 +3480,8 @@ impl<'a> Parser<'a> {
let boxed_span = self.span;
let is_ref = self.eat_keyword(keywords::Ref);
let is_mut = self.eat_keyword(keywords::Mut);
let fieldname = self.parse_ident()?;
let fieldname = self.parse_ident()
.map_err(|err| ((fields.clone(), etc), err))?;
hi = self.prev_span;

let bind_type = match (is_ref, is_mut) {
Expand Down Expand Up @@ -3646,11 +3659,12 @@ impl<'a> Parser<'a> {
}
// Parse struct pattern
self.bump();
let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
e.emit();
self.recover_stmt();
(vec![], false)
});
let (fields, etc) = self.parse_pat_fields()
.unwrap_or_else(|((fields, etc), mut err)| {
err.emit();
self.recover_stmt();
(fields, etc)
});
self.bump();
pat = PatKind::Struct(path, fields, etc);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#![allow(unused)]

struct PersonalityInventory {
expressivity: f32,
instrumentality: f32
}

impl PersonalityInventory {
fn expressivity(&self) -> f32 {
match *self {
PersonalityInventory { expressivity: exp, ... } => exp
//~^ ERROR expected field pattern, found `...`
//~| ERROR pattern does not mention field `instrumentality` [E0027]
}
}
}

fn main() {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
error: expected field pattern, found `...`
--> $DIR/issue-46718-expected-dotdot-found-dotdotdot.rs:21:55
|
21 | PersonalityInventory { expressivity: exp, ... } => exp
| ^^^ help: to omit remaining fields, use one fewer `.`: `..`

error[E0027]: pattern does not mention field `instrumentality`
--> $DIR/issue-46718-expected-dotdot-found-dotdotdot.rs:21:13
|
21 | PersonalityInventory { expressivity: exp, ... } => exp
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ missing field `instrumentality`
Copy link
Contributor

@estebank estebank Dec 14, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree with @xfix's comment, it'd be nice if this error wasn't shown. IIRC, this error happens during type check, so you'd have to modify the ast::StructPatKind and its equivalent in the hir to include a boolean recovered and only emit this error if it's true (I'm doing the same for type errors involving tail expressions and recovered if blocks in #46732). I'm sure that there're are other errors that could benefit from this signal too, but I wouldn't go looking to fix them on this PR. This change would probably cause many more files to be modified, so we could land this first and have a follow up PR if you prefer.


error: aborting due to 2 previous errors