Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
like image 327
tur1ng Avatar asked Mar 11 '10 18:03

tur1ng


1 Answers

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.

like image 97
LB40 Avatar answered Sep 27 '22 23:09

LB40