Skip to content

Commit

Permalink
Nicer diagnostic for missing { } around a multi-statement functio…
Browse files Browse the repository at this point in the history
…n body

Closes #946

If this is a non-local named function with a single-statement body, followed by a non-declaration statement, they probably forgot `{` `}`

Note that this will not fire if it's a global function, because then what follows will not be another valid Cpp2 declaration and so it will be treated as Cpp1 code
  • Loading branch information
hsutter committed Jan 18, 2024
1 parent 9ce1677 commit 087af3c
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 2 deletions.
2 changes: 1 addition & 1 deletion regression-tests/test-results/version
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@

cppfront compiler v0.3.0 Build 9116:1317
cppfront compiler v0.3.0 Build 9117:2039
Copyright(c) Herb Sutter All rights reserved

SPDX-License-Identifier: CC-BY-NC-ND-4.0
Expand Down
2 changes: 1 addition & 1 deletion source/build.info
Original file line number Diff line number Diff line change
@@ -1 +1 @@
"9116:1317"
"9117:2039"
23 changes: 23 additions & 0 deletions source/parse.h
Original file line number Diff line number Diff line change
Expand Up @@ -8490,6 +8490,29 @@ class parser

}

// If this is a non-local named function with a single-statement body,
// followed by a non-declaration statement, they probably forgot { }
// so give a nicer diagnostic
if (
!done()
&& n->is_function()
&& n->has_name()
&& !n->parent_is_function()
&& n->initializer
&& !n->initializer->is_compound()
)
{
auto start_pos = pos;
auto stmt = statement();
auto at_a_statement = stmt != nullptr && !stmt->is_declaration();
pos = start_pos; // backtrack no matter what, we're just peeking here

if (at_a_statement) {
error("in this scope, a single-statement function body cannot be immediately followed by a statement - did you forget to put { } braces around a multi-statement function body?", false);
return n;
}
}

if (
n->is_type()
&& n->initializer
Expand Down

0 comments on commit 087af3c

Please sign in to comment.