I'm using clang's RecursiveASTVisitor to parse some C code. I override visitStmt() and want to make a distinction between 'If' statement and 'Else If' statement.
Example:
if(a > 0){
XXX
}
else if(a == 0){
YYY
}
else{
ZZZ
}
In visitStmt(), I use:
if(isa<IfStmt>(S))
to judge whether a statement is IfStmt.
But how can I know the statement is 'Else If' rather than 'If'?
I want to insert different stubs(XXX under 'If' and YYY under 'Else If').
ps: I'm not a native English speaker. Please forgive me for my poor express.
In C there is not specific else if
statement, because
if (a) {
...
}
else if (b) {
...
}
else {
...
}
is conceputally (and in terms of an AST) something like the following
if (a) {
...
}
else {
if (b) {
...
}
else {
...
}
}
So the first snippet is sort of a "hidden nesting", because the body of the first else
just consists of a single if ... else
statement, so you can omit the {}
around it. And the last else
does not belong to the first if
but to the second.
So what you probably can do to determine whether you have an else if
or not, is step up in the tree, and check if the parent node of the current node is an else
statement and the if
is the first (or only) statement in that parent-else's body.
There are other languages (for instance VB) which have a If .. ElseIf .. Else
construct. But C doesn't.