https://gcc.gnu.org/bugzilla/show_bug.cgi?id=70436
--- Comment #4 from Patrick Palka <ppalka at gcc dot gnu.org> ---
Here's a prototype that seems to do the job. Whenever we see an unbraced if,
increment the counter. Whenever we see a compound statement, reset the
counter. Whenever we see an else, warn if counter > 1 and then decrement the
counter.
diff --git a/gcc/cp/parser.c b/gcc/cp/parser.c
index 2f80856..3ad7196 100644
--- a/gcc/cp/parser.c
+++ b/gcc/cp/parser.c
@@ -10738,6 +10738,8 @@ cp_parser_expression_statement (cp_parser* parser, tree
in_statement_expr)
Returns a tree representing the statement. */
+static int num_unbraced_if_statements;
+
static tree
cp_parser_compound_statement (cp_parser *parser, tree in_statement_expr,
int bcs_flags, bool function_body)
@@ -10747,6 +10749,7 @@ cp_parser_compound_statement (cp_parser *parser, tree
in_statement_expr,
/* Consume the `{'. */
if (!cp_parser_require (parser, CPP_OPEN_BRACE, RT_OPEN_BRACE))
return error_mark_node;
+ num_unbraced_if_statements = 0;
if (DECL_DECLARED_CONSTEXPR_P (current_function_decl)
&& !function_body && cxx_dialect < cxx14)
pedwarn (input_location, OPT_Wpedantic,
@@ -10874,6 +10877,7 @@ cp_parser_selection_statement (cp_parser* parser, bool
*if_p,
bool nested_if;
unsigned char in_statement;
+ num_unbraced_if_statements++;
/* Add the condition. */
finish_if_stmt_cond (condition, statement);
@@ -10898,6 +10902,9 @@ cp_parser_selection_statement (cp_parser* parser, bool
*if_p,
= get_token_indent_info (cp_lexer_peek_token
(parser->lexer));
/* Consume the `else' keyword. */
cp_lexer_consume_token (parser->lexer);
+ if (num_unbraced_if_statements > 1)
+ warning_at (input_location, 0, "dangling else");
+ num_unbraced_if_statements--;
if (warn_duplicated_cond)
{
if (cp_lexer_next_token_is_keyword (parser->lexer,
@@ -11953,6 +11960,7 @@ cp_parser_already_scoped_statement (cp_parser* parser,
}
else
{
+ num_unbraced_if_statements = 0;
/* Avoid calling cp_parser_compound_statement, so that we
don't create a new scope. Do everything else by hand. */
cp_parser_require (parser, CPP_OPEN_BRACE, RT_OPEN_BRACE);