%x PRNT %x EVAL #include #include #include #include void apnd(); void eval(); void text(); void prnt(); char *buf; int len; int sz; %% (.|\n) apnd(); \<%= text(); BEGIN(PRNT); \<%[^=] text(); BEGIN(EVAL); (.|\n) apnd(); %\> prnt(); BEGIN(0); (.|\n) apnd(); %\> eval(); BEGIN(0); <> prnt(); yyterminate(); <> eval(); yyterminate(); <> text(); yyterminate(); %% int main(int argc, char *argv[]) { len = 0; sz = 512; if(!(buf = malloc(sz))) err(1, "malloc"); yylex(); return 0; } void apnd() { if(len+1 > sz){ sz += 512; if(!(buf = realloc(buf, sz))) err(1, "realloc"); } buf[len++] = *yytext; } void eval() { printf("%.*s\n", len, buf); len = 0; } void text() { int i, ofs; if(!len) return; printf("printf(\""); for(i = ofs = 0; i < len; i++){ /* * C89 compilers need only support 509-length * string literals. */ if(i-ofs >= 509){ printf("\");\nprintf(\""); ofs = i; } if(buf[i] == '\\') printf("\\\\"); else if(buf[i] == '"') printf("\\\""); else if(buf[i] == '\n') printf("\\n"); else printf("%c", buf[i]); } printf("\");\n"); len = 0; } void prnt() { printf("printf(\"%%s\", %.*s);\n", len, buf); len = 0; }