/* * Program to generate a test file for print statments in a parser. * This version: addition, subtraction, unary minus, and parentheses only. * * Modify this program to test the other operators. * * Optionally generates a compile-ready C program that shows the value * of the given expressions, if the Boolean makecprog is TRUE. * * I set makecprog using a count of (ignored) command line arguments: * * thisprog.exe xxx xxx >foo.c * * Compile foo.c and run foo.exe to see the expression results. * * To make the test file for the parser, use no arguments: * * thisprog.exe >bar.txt * * Use bar.txt as input to your parser. * If the above doesn't work for you, set makecprog using scanf(). * * Beware of integer overflow! * * -IAN! idallen@freenet.carleton.ca */ #include #include typedef enum { FALSE, TRUE } Boolean; static void nest1(long start, long nestlevel, long max); static void nest2(long start, long nestlevel, long max); static void nest3(long start, long nestlevel, long max); int main(int argc){ long nestlevel = 0; Boolean makecprog; char *func; /* If argc > 1, generate a C program than will compile * and print the value of the expressions. * Otherwise, output "print" statements with the expressions. */ makecprog = ( argc > 1 ); if( makecprog ){ printf("#include \n"); printf("int main(void){\n"); func = "printf(\"%d\\n\",\n"; } else { func = "print\n"; } #define NEST1 100 printf("%s", func); nest1(0,0,NEST1); printf("%s;\n", (makecprog)?")":""); printf("\n"); #define NEST2 100 printf("%s", func); nest2(0,0,NEST2); printf("%s;\n", (makecprog)?")":""); printf("\n"); #define NEST3 100 printf("%s", func); nest3(0,0,NEST3); printf("%s;\n", (makecprog)?")":""); printf("\n"); if( makecprog ) printf("}\n"); } /* * Simple addition and subtraction. */ static void nest1(long start, long nestlevel, long max){ printf(" %s %d + \n", (start%2) == 0 ? "" : "-", start); if( nestlevel < max ) nest1(start+1, nestlevel+1, max); printf(" %s %d -\n", (start%2) == 0 ? "" : "-", start); if( nestlevel == 0 ) printf(" %d\n", 0); } /* * Addition and subtraction and parentheses. */ static void nest2(long start, long nestlevel, long max){ printf(" %d + (\n", start); if( nestlevel < max ) nest2(start+1, nestlevel+1, max); printf(" %d ) -\n", start); if( nestlevel == 0 ) printf(" %d\n", 0); } /* * Nested addition and subtraction and parentheses. */ static void nest3(long start, long nestlevel, long max){ nest1(nestlevel,0,max); printf(" + (\n", start); if( nestlevel < max ) nest3(start+1, nestlevel+1, max); printf(" %d ) -\n", start); if( nestlevel == 0 ) printf(" %d\n", 0); }