Skip to content
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

Emit specific error for struct literal in conditions #59981

Merged
merged 4 commits into from
Apr 19, 2019
Merged
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
4 changes: 1 addition & 3 deletions src/librustc_borrowck/borrowck/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -897,8 +897,7 @@ impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> {
self.cannot_borrow_path_as_mutable(error_span, &descr, Origin::Ast)
}
BorrowViolation(euv::ClosureInvocation) => {
span_bug!(err.span,
"err_mutbl with a closure invocation");
span_bug!(err.span, "err_mutbl with a closure invocation");
}
};

Expand Down Expand Up @@ -1096,7 +1095,6 @@ impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> {
BorrowViolation(euv::MatchDiscriminant) => {
"cannot borrow data mutably"
}

BorrowViolation(euv::ClosureInvocation) => {
is_closure = true;
"closure invocation"
Expand Down
161 changes: 85 additions & 76 deletions src/librustc_resolve/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,56 @@ impl<'a> Resolver<'a> {
(err, candidates)
}

fn followed_by_brace(&self, span: Span) -> (bool, Option<(Span, String)>) {
// HACK(estebank): find a better way to figure out that this was a
// parser issue where a struct literal is being used on an expression
// where a brace being opened means a block is being started. Look
// ahead for the next text to see if `span` is followed by a `{`.
let sm = self.session.source_map();
let mut sp = span;
loop {
sp = sm.next_point(sp);
match sm.span_to_snippet(sp) {
Ok(ref snippet) => {
if snippet.chars().any(|c| { !c.is_whitespace() }) {
break;
}
}
_ => break,
}
}
let followed_by_brace = match sm.span_to_snippet(sp) {
Ok(ref snippet) if snippet == "{" => true,
_ => false,
};
// In case this could be a struct literal that needs to be surrounded
// by parenthesis, find the appropriate span.
let mut i = 0;
let mut closing_brace = None;
loop {
sp = sm.next_point(sp);
match sm.span_to_snippet(sp) {
Ok(ref snippet) => {
if snippet == "}" {
let sp = span.to(sp);
if let Ok(snippet) = sm.span_to_snippet(sp) {
closing_brace = Some((sp, snippet));
}
break;
}
}
_ => break,
}
i += 1;
// The bigger the span, the more likely we're incorrect --
// bound it to 100 chars long.
if i > 100 {
break;
}
}
return (followed_by_brace, closing_brace)
}

/// Provides context-dependent help for errors reported by the `smart_resolve_path_fragment`
/// function.
/// Returns `true` if able to provide context-dependent help.
Expand Down Expand Up @@ -278,6 +328,39 @@ impl<'a> Resolver<'a> {
_ => false,
};

let mut bad_struct_syntax_suggestion = || {
let (followed_by_brace, closing_brace) = self.followed_by_brace(span);
let mut suggested = false;
match source {
PathSource::Expr(Some(parent)) => {
suggested = path_sep(err, &parent);
}
PathSource::Expr(None) if followed_by_brace == true => {
if let Some((sp, snippet)) = closing_brace {
err.span_suggestion(
sp,
"surround the struct literal with parenthesis",
format!("({})", snippet),
Applicability::MaybeIncorrect,
);
} else {
err.span_label(
span, // Note the parenthesis surrounding the suggestion below
format!("did you mean `({} {{ /* fields */ }})`?", path_str),
);
}
suggested = true;
},
_ => {}
}
if !suggested {
err.span_label(
span,
format!("did you mean `{} {{ /* fields */ }}`?", path_str),
);
}
};

match (def, source) {
(Def::Macro(..), _) => {
err.span_suggestion(
Expand Down Expand Up @@ -331,87 +414,13 @@ impl<'a> Resolver<'a> {
);
}
} else {
// HACK(estebank): find a better way to figure out that this was a
// parser issue where a struct literal is being used on an expression
// where a brace being opened means a block is being started. Look
// ahead for the next text to see if `span` is followed by a `{`.
let sm = self.session.source_map();
let mut sp = span;
loop {
sp = sm.next_point(sp);
match sm.span_to_snippet(sp) {
Ok(ref snippet) => {
if snippet.chars().any(|c| { !c.is_whitespace() }) {
break;
}
}
_ => break,
}
}
let followed_by_brace = match sm.span_to_snippet(sp) {
Ok(ref snippet) if snippet == "{" => true,
_ => false,
};
// In case this could be a struct literal that needs to be surrounded
// by parenthesis, find the appropriate span.
let mut i = 0;
let mut closing_brace = None;
loop {
sp = sm.next_point(sp);
match sm.span_to_snippet(sp) {
Ok(ref snippet) => {
if snippet == "}" {
let sp = span.to(sp);
if let Ok(snippet) = sm.span_to_snippet(sp) {
closing_brace = Some((sp, snippet));
}
break;
}
}
_ => break,
}
i += 1;
// The bigger the span, the more likely we're incorrect --
// bound it to 100 chars long.
if i > 100 {
break;
}
}
match source {
PathSource::Expr(Some(parent)) => if !path_sep(err, &parent) {
err.span_label(
span,
format!("did you mean `{} {{ /* fields */ }}`?", path_str),
);
}
PathSource::Expr(None) if followed_by_brace == true => {
if let Some((sp, snippet)) = closing_brace {
err.span_suggestion(
sp,
"surround the struct literal with parenthesis",
format!("({})", snippet),
Applicability::MaybeIncorrect,
);
} else {
err.span_label(
span,
format!("did you mean `({} {{ /* fields */ }})`?", path_str),
);
}
},
_ => {
err.span_label(
span,
format!("did you mean `{} {{ /* fields */ }}`?", path_str),
);
},
}
bad_struct_syntax_suggestion();
}
}
(Def::Union(..), _) |
(Def::Variant(..), _) |
(Def::Ctor(_, _, CtorKind::Fictive), _) if ns == ValueNS => {
err.span_label(span, format!("did you mean `{} {{ /* fields */ }}`?", path_str));
bad_struct_syntax_suggestion();
}
(Def::SelfTy(..), _) if ns == ValueNS => {
err.span_label(span, fallback_label);
Expand Down
53 changes: 48 additions & 5 deletions src/libsyntax/parse/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2855,11 +2855,13 @@ impl<'a> Parser<'a> {
let (delim, tts) = self.expect_delimited_token_tree()?;
hi = self.prev_span;
ex = ExprKind::Mac(respan(lo.to(hi), Mac_ { path, tts, delim }));
} else if self.check(&token::OpenDelim(token::Brace)) &&
!self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL) {
// This is a struct literal, unless we're prohibited
// from parsing struct literals here.
return self.parse_struct_expr(lo, path, attrs);
} else if self.check(&token::OpenDelim(token::Brace)) {
if let Some(expr) = self.maybe_parse_struct_expr(lo, &path, &attrs) {
return expr;
} else {
hi = path.span;
ex = ExprKind::Path(None, path);
}
} else {
hi = path.span;
ex = ExprKind::Path(None, path);
Expand Down Expand Up @@ -2902,6 +2904,47 @@ impl<'a> Parser<'a> {
self.maybe_recover_from_bad_qpath(expr, true)
}

fn maybe_parse_struct_expr(
&mut self,
lo: Span,
path: &ast::Path,
attrs: &ThinVec<Attribute>,
) -> Option<PResult<'a, P<Expr>>> {
petrochenkov marked this conversation as resolved.
Show resolved Hide resolved
let struct_allowed = !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
let certainly_not_a_block = || self.look_ahead(1, |t| t.is_ident()) && (
// `{ ident, ` cannot start a block
self.look_ahead(2, |t| t == &token::Comma) ||
self.look_ahead(2, |t| t == &token::Colon) && (
// `{ ident: token, ` cannot start a block
self.look_ahead(4, |t| t == &token::Comma) ||
// `{ ident: ` cannot start a block unless it's a type ascription `ident: Type`
self.look_ahead(3, |t| !t.can_begin_type())
)
);

if struct_allowed || certainly_not_a_block() {
// This is a struct literal, but we don't can't accept them here
let expr = self.parse_struct_expr(lo, path.clone(), attrs.clone());
if let (Ok(expr), false) = (&expr, struct_allowed) {
let mut err = self.diagnostic().struct_span_err(
expr.span,
"struct literals are not allowed here",
);
err.multipart_suggestion(
"surround the struct literal with parenthesis",
vec![
(lo.shrink_to_lo(), "(".to_string()),
(expr.span.shrink_to_hi(), ")".to_string()),
],
Applicability::MachineApplicable,
);
err.emit();
}
return Some(expr);
}
None
}

fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
-> PResult<'a, P<Expr>> {
let struct_sp = lo.to(self.prev_span);
Expand Down
6 changes: 2 additions & 4 deletions src/test/ui/error-codes/E0423.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,13 @@ fn bar() {
struct T {}

if let S { x: _x, y: 2 } = S { x: 1, y: 2 } { println!("Ok"); }
//~^ ERROR E0423
//~| expected type, found `1`
//~^ ERROR struct literals are not allowed here
if T {} == T {} { println!("Ok"); }
//~^ ERROR E0423
//~| ERROR expected expression, found `==`
}

fn foo() {
for _ in std::ops::Range { start: 0, end: 10 } {}
//~^ ERROR E0423
//~| ERROR expected type, found `0`
//~^ ERROR struct literals are not allowed here
}
54 changes: 15 additions & 39 deletions src/test/ui/error-codes/E0423.stderr
Original file line number Diff line number Diff line change
@@ -1,36 +1,28 @@
error: expected type, found `1`
--> $DIR/E0423.rs:12:39
error: struct literals are not allowed here
--> $DIR/E0423.rs:12:32
|
LL | if let S { x: _x, y: 2 } = S { x: 1, y: 2 } { println!("Ok"); }
| ^ expecting a type here because of type ascription
|
= note: type ascription is a nightly-only feature that lets you annotate an expression with a type: `<expr>: <type>`
note: this expression expects an ascribed type after the colon
--> $DIR/E0423.rs:12:36
| ^^^^^^^^^^^^^^^^
help: surround the struct literal with parenthesis
|
LL | if let S { x: _x, y: 2 } = S { x: 1, y: 2 } { println!("Ok"); }
| ^
= help: this might be indicative of a syntax error elsewhere
LL | if let S { x: _x, y: 2 } = (S { x: 1, y: 2 }) { println!("Ok"); }
| ^ ^

error: expected expression, found `==`
--> $DIR/E0423.rs:15:13
--> $DIR/E0423.rs:14:13
|
LL | if T {} == T {} { println!("Ok"); }
| ^^ expected expression

error: expected type, found `0`
--> $DIR/E0423.rs:21:39
error: struct literals are not allowed here
--> $DIR/E0423.rs:20:14
|
LL | for _ in std::ops::Range { start: 0, end: 10 } {}
| ^ expecting a type here because of type ascription
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
help: surround the struct literal with parenthesis
|
= note: type ascription is a nightly-only feature that lets you annotate an expression with a type: `<expr>: <type>`
note: this expression expects an ascribed type after the colon
--> $DIR/E0423.rs:21:32
|
LL | for _ in std::ops::Range { start: 0, end: 10 } {}
| ^^^^^
= help: this might be indicative of a syntax error elsewhere
LL | for _ in (std::ops::Range { start: 0, end: 10 }) {}
| ^ ^

error[E0423]: expected function, found struct `Foo`
--> $DIR/E0423.rs:4:13
Expand All @@ -41,30 +33,14 @@ LL | let f = Foo();
| did you mean `Foo { /* fields */ }`?
| help: a function with a similar name exists: `foo`

error[E0423]: expected value, found struct `S`
--> $DIR/E0423.rs:12:32
|
LL | if let S { x: _x, y: 2 } = S { x: 1, y: 2 } { println!("Ok"); }
| ^---------------
| |
| help: surround the struct literal with parenthesis: `(S { x: 1, y: 2 })`

error[E0423]: expected value, found struct `T`
--> $DIR/E0423.rs:15:8
--> $DIR/E0423.rs:14:8
|
LL | if T {} == T {} { println!("Ok"); }
| ^---
| |
| help: surround the struct literal with parenthesis: `(T {})`

error[E0423]: expected value, found struct `std::ops::Range`
--> $DIR/E0423.rs:21:14
|
LL | for _ in std::ops::Range { start: 0, end: 10 } {}
| ^^^^^^^^^^^^^^^----------------------
| |
| help: surround the struct literal with parenthesis: `(std::ops::Range { start: 0, end: 10 })`

error: aborting due to 7 previous errors
error: aborting due to 5 previous errors

For more information about this error, try `rustc --explain E0423`.
6 changes: 3 additions & 3 deletions src/test/ui/parser/struct-literal-in-for.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@ impl Foo {
}

fn main() {
for x in Foo { //~ ERROR expected value, found struct `Foo`
x: 3 //~ ERROR expected type, found `3`
}.hi() { //~ ERROR expected one of `.`, `;`, `?`, `}`, or an operator, found `{`
for x in Foo { //~ ERROR struct literals are not allowed here
x: 3 //~^ ERROR `bool` is not an iterator
}.hi() {
println!("yo");
}
}
Loading