[Cocci] Questions about if statements.

Julia Lawall julia.lawall at lip6.fr
Thu Mar 1 07:55:46 CET 2012


On Wed, 29 Feb 2012, Cyril Roelandt wrote:

> Hello,
>
> I have a few questions about matching if statements in Coccinelle. Let's say 
> I want to add a call to "foo()" at the end of the body of every if statement 
> (this is a really dummy exemple, but it should show my point). I wrote the 
> following semantic patch :
>
> $ cat if.cocci
> @@
> @@
> if (...)
> {
> ...
> + foo();
> }
>
> and applied it to the following C file :
>
> $ cat if.c
> extern int x;
> int
> main(void)
> {
>        if (x == 1)
>        {
>                bar();
>        }
>
>        if (x == 2)
>                bar();
> }
>
>
> $ spatch -sp_file if.cocci if.c
> init_defs_builtins: /usr/share/coccinelle/standard.h
> HANDLING: if.c
> diff =
> --- if.c
> +++ /tmp/cocci-output-22233-e7e7b8-if.c
> @@ -18,7 +18,8 @@ main(void)
>        if (x == 1)
>        {
>                bar();
> -       }
> +               foo();
> +}

It's not really deleted then added, it's just losing it's indentation. 
foo() is probably using it.  I'll look into it.

>
>        if (x == 2)
>                bar();
>
>
> This shows two issues :
>
> 1) The closing brace is deleted, and then added again, but is not properly 
> indented.  Note that :
>
> if (...)
> {
> + foo();
> ...
> }
>
> produces a beautiful patch. Am I doing something wrong ?
>
>
> 2) It does not match the second if statement. Should I look for both :
>
> if (...)
> {
> ...
> }
>
> and
>
> if (...)
>    S
>
> or is there a nice trick that matches both ?

No.  Do both patterns in an ( | ) with the S case second because S will 
also match { ... }

julia


More information about the Cocci mailing list