lundi 29 juin 2020

Coccinelle rule to match foo() call inside an if

So, the problem I stumble upon is that code inside if can be pretty complex, it can be stuff like if (NOT(ret = foo())) and also if (foo() == NULL), and other variations are possible.

To me the obvious answer is the rule line if (...foo()...), but Coccinelle says it fails to parse this.

I tried everything I managed to find or to guess, so far to no avail.


As a demo example, here's a test.c

#include <stddef.h>
#include <stdbool.h>

#define NOT(expr) (!(expr))

void remove_this_call_if_foo_is_called() {}
const char* foo() { return "hello"; }
const char* bar() { return "hello"; }

int main() {
    const char* ret;
    if (NOT(ret = foo())) {
        remove_this_call_if_foo_is_called();
    }

    if (foo() == NULL) {
        remove_this_call_if_foo_is_called();
    }

    if (foo()) {
        remove_this_call_if_foo_is_called();
    }

    if (bar()) {
        // Do not remove if something different from foo() is called.
        remove_this_call_if_foo_is_called();
    }
}

And I want to remove remove_this_call_if_foo_is_called() calls whenever they're in an if () body and the if condition has foo() call.

A Coccinelle example that unfortunately always removes these lines is:

@ rule1 @
@@
if (...) {
    ...
-   remove_this_call_if_foo_is_called();
    ...
}

Aucun commentaire:

Enregistrer un commentaire