Skip to content

Commit 6c08064

Browse files
authored
Merge pull request #25008 from owenv/improved_#else_if_diagnostic
[Parse] Improve diagnostic and add fixit to correct '#else if' to '#elseif'
2 parents d1a1ed1 + 901d947 commit 6c08064

File tree

3 files changed

+21
-0
lines changed

3 files changed

+21
-0
lines changed

include/swift/AST/DiagnosticsParse.def

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,10 @@ ERROR(extra_tokens_conditional_compilation_directive,none,
6868
"extra tokens following conditional compilation directive", ())
6969
ERROR(unexpected_rbrace_in_conditional_compilation_block,none,
7070
"unexpected '}' in conditional compilation block", ())
71+
ERROR(unexpected_if_following_else_compilation_directive,none,
72+
"unexpected 'if' keyword following '#else' conditional compilation "
73+
"directive; did you mean '#elseif'?",
74+
())
7175

7276
ERROR(pound_diagnostic_expected_string,none,
7377
"expected string literal in %select{#warning|#error}0 directive",(bool))

lib/Parse/ParseIfConfig.cpp

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -595,6 +595,12 @@ ParserResult<IfConfigDecl> Parser::parseIfConfig(
595595
Expr *Condition = nullptr;
596596
bool isActive = false;
597597

598+
if (!Tok.isAtStartOfLine() && isElse && Tok.is(tok::kw_if)) {
599+
diagnose(Tok, diag::unexpected_if_following_else_compilation_directive)
600+
.fixItReplace(SourceRange(ClauseLoc, consumeToken()), "#elseif");
601+
isElse = false;
602+
}
603+
598604
// Parse the condition. Evaluate it to determine the active
599605
// clause unless we're doing a parse-only pass.
600606
if (isElse) {

test/Parse/ConditionalCompilation/basicParseErrors.swift

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,3 +138,14 @@ fn_k()
138138
func undefinedFunc() // ignored.
139139
#endif
140140
undefinedFunc() // expected-error {{use of unresolved identifier 'undefinedFunc'}}
141+
142+
#if FOO
143+
#else if BAR
144+
// expected-error@-1 {{unexpected 'if' keyword following '#else' conditional compilation directive; did you mean '#elseif'?}} {{1-9=#elseif}}
145+
#else
146+
#endif
147+
148+
#if FOO
149+
#else
150+
if true {}
151+
#endif // OK

0 commit comments

Comments
 (0)