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

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

a = (A) ? B : C;

to the default syntax with if/ operators else:

if (A)
  a = B
else
  a = C

Does anyone know a tool capable of doing such a conversion?

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

Edit: The following code should also be converted:

a = ((A) ? B : C)->b;
+5
source share
5 answers

Coccinelle can do this quite easily.

Coccinelle - , SmPL ( ) C. Coccinelle Linux. API, , , - . , Coccinelle ( ) .

EDIT: :

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

:

! x & y. , . , y 0, 0. , y .

.

.

+12

Coccinelle .

@@
expression E1, E2, E3, E4;
@@

- E1 = E2 ? E3 : E4;
+ if (E2)
+   E1 = E3;
+ else
+   E1 = E4;

@@
type T;
identifier E5;
T *E3;
T *E4;
expression E1, E2;
@@

- E1 = ((E2) ? (E3) : (E4))->E5;
+ if (E2)
+   E1 = E3->E5;
+ else
+   E1 = E4->E5;


@@
type T;
identifier E5;
T E3;
T E4;
expression E1, E2;
@@

- E1 = ((E2) ? (E3) : (E4)).E5;
+ if (E2)
+   E1 = (E3).E5;
+ else
+   E1 = (E4).E5;
+3

DMS Software Reengineering Toolkit , .

DMS :

domain C.

rule ifthenelseize_conditional_expression(a:lvalue,A:condition,B:term,C:term):
stmt -> stmt
=  " \a = \A ? \B : \C; "
-> " if (\A) \a = \B;  else \a=\C ; ".

, .

, , . , , , , .

, . , DMS ; GCC4 GCC4 .

, , , . , , , ( ..), , (, ). , DMS, , ( , ) .

, , - . , , . , , .

, .

(DMS , C, ++, Java, # PHP).

+1

, if... , , - , if ... , :

expr_is_true ? exec_if_expr_is_TRUE : exec_if_expr_is_FALSE;

true, ? :, : ;. , false

expr_is_false ? exec_if_expr_is_FALSE : exec_if_expr_is_TRUE;
0

If the statements are very regular, why not run your files through a small Perl script? The basic logic for searching and converting is simple for your sample string. Here is an approximate approach:

use strict;
while(<>) {
    my $line = $_;
    chomp($line);
    if ( $line =~ m/(\S+)\s*=\s*\((\s*\S+\s*)\)\s*\?\s*(\S+)\s*:\s*(\S+)\s*;/ ) {
        print "if(" . $2 . ")\n\t" . $1 . " = " . $3 . "\nelse\n\t" . $1 . " = " . $4 . "\n";
    } else {
        print $line . "\n";
    }
}
exit(0);

You run it like this:

perl transformer.pl < foo.c > foo.c.new

Of course, it gets harder and harder if the text template is not as ordinary as the one you published. But free, fast and easy to try.

0
source