toolset: simplifier

The idea of the simplifier is to replace 'complex' expressions by 'simpler' ones. We do this using rewrite rules that replace expressions 'a+b' and 'a*b' by their resp. value. As our language only contains operators '+' and '*', and constants, as the result of simplifying an expression we get a constant with the value of the expression.

Intended usage on the shell command line:


$ echo '(1+1)*(1+1)' | parser | simplifier | unparser
Example:
input:
(1+1)*(1+1)
output:
4

Rewrite rules:


Plus( Const( i ), Const( j )) -> Const( cplus( i, j )); Times( Const( i ), Const( j )) -> Const( ctimes( i, j ));

Main routine:


#include "k.h" /* data type defs */ #include "csgiok.h" /* structure file io defs */ #include "rk.h" /* rewrite defs */ int main() { char *io; /* error message, or == 0 */ expr the_expr; /* root of the parse tree */ io = CSGIOread_expr(stdin, &the_expr); if (io != 0) /* error! */ fatal("Read error: %s\n", io); the_expr = rewrite_expr(the_expr, base_rview); io = CSGIOwrite_expr(stdout, the_expr); if (io != 0) /* error! */ fatal("Write error: %s\n", io); exit(0); /* success! */ }
Utility routines, defned as file compute.k:

%{ KC_REWRITE /* export fn defs to rewrite code */ #include "compute.h" %} int cplus( int i, int j) { return i + j; } int ctimes( int i, int j) { return i * j; }

next overview up


Last updated at 23 February '01 by kimwitu@cs.utwente.nl