C: Convert A ? B : C into if (A) B else C

tur1ng picture tur1ng · Mar 11, 2010 · Viewed 11.8k times · Source

I was looking for a tool that can convert C code expressions for the form:

a = (A) ? B : C;

into the 'default' syntax with if/else statements:

if (A)
  a = B
else
  a = C

Does someone know a tool that's capable to do such a transformation?

I work with GCC 4.4.2 and create a preprocessed file with -E but do not want such structures in it.

Edit: Following code should be transformed, too:

a = ((A) ? B : C)->b;

Answer

LB40 picture LB40 · Mar 11, 2010

Coccinelle can do this quite easily.

Coccinelle is a program matching and transformation engine which provides the language SmPL (Semantic Patch Language) for specifying desired matches and transformations in C code. Coccinelle was initially targeted towards performing collateral evolutions in Linux. Such evolutions comprise the changes that are needed in client code in response to evolutions in library APIs, and may include modifications such as renaming a function, adding a function argument whose value is somehow context-dependent, and reorganizing a data structure. Beyond collateral evolutions, Coccinelle is successfully used (by us and others) for finding and fixing bugs in systems code.

EDIT: An example of semantic patch:

@@ expression E; constant C; @@
(
  !E & !C
|
- !E & C
+ !(E & C)
)

From the documentation:

The pattern !x&y. An expression of this form is almost always meaningless, because it combines a boolean operator with a bit operator. In particular, if the rightmost bit of y is 0, the result will always be 0. This semantic patch focuses on the case where y is a constant.

You have a good set of examples here.

The mailing list is really active and helpful.