[LibClang - C - AST] Switch-Case Statement Children

Hello Clang Community,

Why is the first statement after a “case” label the child of the case label, but every other statement (including the break) after that its sibling? It seems like either all should be children or all should be siblings.

Suppose you have the following code snippet (full source files for any snippets below are included with this mail).

switch(expr) {
case 1:
func1();
func2();
break;
case 2:
func1();
break;
}

Which when fed to clang with

$ clang -Xclang -ast-dump -fsyntax-only test.c

produces the following AST (edited for clarity):

SwitchStmt <line:7:3, line:15:3>
`-CompoundStmt <col:15, line:15:3>

-CaseStmt <line:8:3, line:9:11>
-CallExpr <line:9:5, col:11> —————————— func1() here is child to case 1 -CallExpr <line:10:5, col:11> —————————— func2() here is sibling to case 1 -BreakStmt <line:11:5> -CaseStmt <line:12:3, line:13:11> -CallExpr <line:13:5, col:11> ————————— func1() here again is child to case 2
`-BreakStmt line:14:5

My clang version and install info:

Apple clang version 12.0.5 (clang-1205.0.22.9)
Target: x86_64-apple-darwin20.4.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin

Best regards,

Jacob Faibussowitsch
(Jacob Fai - booss - oh - vitch)

test.c (194 Bytes)

astDump.out (5.97 KB)

astDumpNoColor.txt (2.96 KB)

Hello Jacob,

This is an excellent question.

This falls out of the grammar of a labeled statement: https://cigix.me/c17#6.8.1

case constant-expression : statement

The statement following the case label is part of the case label.

This differs from the compound statement: https://cigix.me/c17#6.8.2 which contains an optional block-item-list which can consistent of multiple statements or declarations:

block-item-list:
block-item
block-item-list block-item

block-item:
declaration
statement

I hope this explanation clears it up for you.

Regards
Shafik