The following example used a set of XTRAN rules ("meta-code") for re-engineering C by searching for situations in C code where expression statements can be combined by building more complex expressions. This kind of situation frequently arises from translation of assembly languages to C, but of course it can also arise in code originally written as C.
The meta-code uses XTRAN's powerful statement and expression pattern matching and replacement capabilities to perform the re-engineering. It uses two statement patterns, a "match" pattern and a "replace" pattern. The meta-code iterates through the code until no more replacements can be done. This has the effect that the result of a replacement is then examined for a possible subsequent replacement involving additional statements.
In the patterns below, this indicates C elements and
<this> indicates meta
elements.
The "match" pattern is a two-statement pattern:
<expr1> = <expr2>;
<expr1> <asnopr> <expr3>;
where <exprn> match any
legal C expressions and <asnopr> matches a C assignment operator
such as /= or +=. Note that <expr1> must be the same in both statements in
order for the pattern to match.
The "replace" pattern is a single statement:
<expr1> = <expr2> <opr> <expr3>;
where <exprn> are
whatever expressions matched the corresponding <exprn> in the "match" pattern,
and <opr> is the
non-assignment version of whatever operator matched <asnopr>: *
for *=, etc.
The effect of this pattern match and replacement is to combine consecutive C expression statements where it is possible to do so by creating more complex expressions. For example, the meta-code would combine
str.arr[2] = a + b;
str.arr[2] *= c / d;
str.arr[2] -= e % f;
to
str.arr[2] = (a + b) * (c / d);
str.arr[2] -= e % f;
and then to
str.arr[2] = (a + b) * (c / d) - e % f;
Note, in the actual example below, that the meta-code also preserves all comments on all involved statements.
void prc(void)
{
short s1, s2, s3, s4;
s1 = s2; /*s1 = s2;*/
s1 += s3; /*s1 += s3;*/
s1 *= s4; /*s1 *= s4;*/
/*
* This is a comment preceding a series of s2 assignments.
*/
s2 = s1; /*s2 = s1;*/
s2 |= s4; /*s2 |= s4;*/
/*
* This is a comment in the middle of the s2 assignments.
*/
s2 &= s3; /*s2 &= s3;*/
s2 ^= s1; /*s2 ^= s1;*/
return;
}
void prc(void)
{
short s1, s2, s3, s4;
s1 = (s2 + s3) * s4; /*s1 = s2;*/
/*s1 += s3;*/
/*s1 *= s4;*/
/*
* This is a comment preceding a series of s2 assignments.
*/
/*
* This is a comment in the middle of the s2 assignments.
*/
s2 = (s1 | s4) & s3 ^ s1; /*s2 = s1;*/
/*s2 |= s4;*/
/*s2 &= s3;*/
/*s2 ^= s1;*/
return;
}
COPYRIGHT 2008; reproduction prohibited without permission. Revised 2006-11-27
XTRAN is a trademark of Pennington Systems Incorporated.
Pennington Systems Incorporated
8655 East
Via de Ventura, Suite G200
Scottsdale, Arizona 85258-3321
Phone: +1(480)626-5503
Fax: +1(480)626-7618
Email: Info@Pennington.com
Web: http://WWW.Pennington.com