Skip to content

Commit

Permalink
Warn on if-catch with just a default case #1904.
Browse files Browse the repository at this point in the history
  • Loading branch information
lerno committed Jan 29, 2025
1 parent 13771cc commit 6848753
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 1 deletion.
1 change: 1 addition & 0 deletions releasenotes.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
- Allow `+++` to work on all types of arrays.
- Allow `(int[*]) { 1, 2 }` cast style initialization.
- Experimental change from `[*]` to `[?]`
- Warn on if-catch with just a `default` case.

### Fixes
- Fix issue requiring prefix on a generic interface declaration.
Expand Down
10 changes: 9 additions & 1 deletion src/compiler/sema_stmts.c
Original file line number Diff line number Diff line change
Expand Up @@ -1860,6 +1860,15 @@ static inline bool sema_analyse_if_stmt(SemaContext *context, Ast *statement)

if (then->ast_kind == AST_IF_CATCH_SWITCH_STMT)
{
Ast **cases = then->switch_stmt.cases;
if (vec_size(cases) == 1 && cases[0]->ast_kind == AST_DEFAULT_STMT)
{
if (!SEMA_WARN(cases[0], "An 'if-catch' with only a 'default' clause is unclear. "
"Removing the 'default:' will have exactly the same behaviour but will be less confusing."))
{
return false;
}
}
DeclId label_id = statement->if_stmt.flow.label;
then->switch_stmt.flow.label = label_id;
statement->if_stmt.flow.label = 0;
Expand Down Expand Up @@ -2397,7 +2406,6 @@ DONE:;
}
static bool sema_analyse_switch_body(SemaContext *context, Ast *statement, SourceSpan expr_span, Type *switch_type, Ast **cases, ExprAnySwitch *any_switch, Decl *var_holder)
{
bool use_type_id = false;
if (!type_is_comparable(switch_type))
{
sema_error_at(context, expr_span, "You cannot test '%s' for equality, and only values that supports '==' for comparison can be used in a switch.", type_to_error_string(switch_type));
Expand Down
10 changes: 10 additions & 0 deletions test/test_suite/errors/switch_default_catch.c3
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
fn void main()
{
int! x;
if (catch err = x)
{
default: // #warning: 'if-catch'
return;
}
return;
}

0 comments on commit 6848753

Please sign in to comment.