Code completion with clang gives wrong results

Consider the file foo.c:

#include <stdbool.h>

int six, bo;
int main(void) {
    return six + b + sizeof(int);
}

Then clang can be used to suggest possible code completions in line 15 column 19 (portion after the b in the return statement) as follows:

cat foo.c | clang -fsyntax-only -Xclang -code-completion-macros -Xclang  -code-completion-at=-:5:19 -xc -

This gives

PREFERRED-TYPE: int
COMPLETION: bo : [#int#]bo
COMPLETION: bool : bool

Obviously the only right match would be bo as an expression is expected.

Does clang provide options so that completions that do not lead to an expression are automatically filtered out? Or needs this done manually?

Also, I could not really find any sources that document options for clang like -code-completion-macros or -code-completion-at. The command above which uses these option is used in the vim-clang plugin. Are these documented somewhere (in hope there are further options).

bool isn’t invalid in that context - not sufficient, but isn’t a lexical dead-end either

You could end up with return six + bool() ... for instance (bool() is the same as false, which converts to/is a zero value integer literal)

Though I guess when we put int blarg(void) in the test, at least the completion suggestion is [#int#]blarg() (it includes the parens), so I’m not sure if My line of reasoning here is valid for the autocomplete situation.

I don’t think it’s valid in C, or? I used the -xc flag

yeah, fair point - not sure what the bool might be for

1 Like

There are probably not that many people using the clang code completions facilities. For vim, you will find a LSP plugin and then you can use clangd for code completion and more.

Thanks for pointing me to the LSP plugin. I just gave it a few quick tests and it seems to work perfect!