home *** CD-ROM | disk | FTP | other *** search
/ Columbia Kermit / kermit.zip / archives / ckc095.zip / ckwart.c < prev    next >
C/C++ Source or Header  |  1989-08-31  |  14KB  |  649 lines

  1. char *wartv = "Wart Version 1A(006) Jan 1989";
  2.  
  3. /* W A R T */
  4.  
  5. /*
  6.  pre-process a lex-like file into a C program.
  7.  
  8.  Author:Jeff Damens, Columbia University Center for Computing Activites, 11/84.
  9.  Copyright (C) 1985, Trustees of Columbia University in the City of New York.
  10.  Permission is granted to any individual or institution to use, copy, or
  11.  redistribute this software so long as it is not sold for profit, provided this
  12.  copyright notice is retained. 
  13.  
  14.  * input format is:
  15.  *  lines to be copied | %state <state names...>
  16.  *  %%
  17.  * <state> | <state,state,...> CHAR  { actions }
  18.  * ...
  19.  *  %%
  20.  */
  21.  
  22. #include "ckcdeb.h"            /* Includes */
  23. #include <stdio.h>
  24. #include <ctype.h>
  25.  
  26. /*
  27.  The following "CHAR" should be changed to "short", "int", or "long" if your
  28.  wart program will generate more than 127 states.  Since wart is used mainly
  29.  with C-Kermit, which has less than 50 states, "short" is adequate.  This 
  30.  keeps the program about 3K-4K smaller.
  31. */
  32.  
  33. #define TBL_TYPE "CHAR"            /* C data type of state table */
  34.  
  35. #define C_L 014                /* Formfeed */
  36.  
  37. #define SEP 1                            /* Token types */
  38. #define LBRACK 2
  39. #define RBRACK 3
  40. #define WORD 4
  41. #define COMMA 5
  42.  
  43. /* Storage sizes */
  44.  
  45. #define MAXSTATES 50            /* max number of states */
  46. #define MAXWORD 50            /* max # of chars/word */
  47. #define SBYTES ((MAXSTATES+7)/8)    /* # of bytes for state bitmask */
  48.  
  49. /* Name of wart function in generated program */
  50.  
  51. #ifndef FNAME
  52. #define FNAME "wart"
  53. #endif
  54.  
  55. /* Structure for state information */
  56.  
  57. struct trans { CHAR states[SBYTES];    /* included states */
  58.                int anyst;        /* true if this good from any state */
  59.                CHAR inchr;        /* input character */
  60.            int actno;        /* associated action */
  61.            struct trans *nxt; };    /* next transition */
  62.  
  63. typedef struct trans *Trans;
  64.  
  65. char *malloc();                /* Returns pointer (not int) */
  66.  
  67.  
  68. /* Variables and tables */
  69.  
  70. int lines,nstates,nacts;
  71.  
  72. char tokval[MAXWORD];
  73.  
  74. int tbl[MAXSTATES*128];
  75.  
  76. char *tbl_type = TBL_TYPE;
  77.  
  78. char *txt1 = "\n#define BEGIN state =\n\nint state = 0;\n\n";
  79.  
  80. char *fname = FNAME;        /* function name goes here */
  81.  
  82. /* rest of program... */
  83.  
  84. char *txt2 = "()\n\
  85. {\n\
  86.     int c,actno;\n\
  87.     extern ";
  88.  
  89. /* Data type of state table is inserted here (short or int) */
  90.  
  91. char *txt2a = " tbl[];\n\
  92.     while (1) {\n\
  93.     c = input();\n\
  94.     if ((actno = tbl[c + state*128]) != -1)\n\
  95.         switch(actno) {\n";
  96.  
  97. /* this program's output goes here, followed by final text... */
  98.  
  99. char *txt3 = "\n        }\n    }\n}\n\n";
  100.  
  101.  
  102. /*
  103.  * turn on the bit associated with the given state
  104.  *
  105.  */
  106. setstate(state,t)
  107. int state;
  108. Trans t;
  109. {
  110.   int idx,msk;
  111.   idx = state/8;            /* byte associated with state */
  112.   msk = 0x80 >> (state % 8);        /* bit mask for state */
  113.   t->states[idx] |= msk;
  114. }
  115.  
  116. /*
  117.  * see if the state is involved in the transition
  118.  *
  119.  */
  120.  
  121. teststate(state,t)
  122. int state;
  123. Trans t;
  124. {
  125.   int idx,msk;
  126.   idx = state/8;
  127.   msk = 0x80 >> (state % 8);
  128.   return(t->states[idx] & msk);
  129. }
  130.  
  131.  
  132. /*
  133.  * read input from here...
  134.  *
  135.  */
  136.  
  137. Trans
  138. rdinput(infp,outfp)
  139. FILE *infp,*outfp;
  140. {
  141.   Trans x,rdrules();
  142.   lines = 1;                /* line counter */
  143.   nstates = 0;                /* no states */
  144.   nacts = 0;                /* no actions yet */
  145.   fprintf(outfp,"\n%c* WARNING -- This C source program generated by ",'/');
  146.   fprintf(outfp,"Wart preprocessor. */\n");
  147.   fprintf(outfp,"%c* Do not edit this file; edit the Wart-format ",'/');
  148.   fprintf(outfp,"source file instead, */\n");
  149.   fprintf(outfp,"%c* and then run it through Wart to produce a new ",'/');
  150.   fprintf(outfp,"C source file.     */\n\n");
  151.   fprintf(outfp,"%c* Wart Version Info: */\n",'/');
  152.   fprintf(outfp,"char *wartv = \"%s\";\n\n",wartv);
  153.  
  154.   initial(infp,outfp);            /* read state names, initial defs */
  155.   prolog(outfp);            /* write out our initial code */
  156.   x = rdrules(infp,outfp);        /* read rules */
  157.   epilogue(outfp);            /* write out epilogue code */
  158.   return(x);
  159. }
  160.  
  161.  
  162. /*
  163.  * initial - read initial definitions and state names.  Returns
  164.  * on EOF or %%.
  165.  *
  166.  */
  167.  
  168. initial(infp,outfp)
  169. FILE *infp,*outfp;
  170. {
  171.   int c;
  172.   char wordbuf[MAXWORD];
  173.   while ((c = getc(infp)) != EOF) {
  174.     if (c == '%') {
  175.             rdword(infp,wordbuf);
  176.             if (strcmp(wordbuf,"states") == 0)
  177.                 rdstates(infp,outfp);
  178.             else if (strcmp(wordbuf,"%") == 0) return;
  179.             else fprintf(outfp,"%%%s",wordbuf);
  180.               }
  181.     else putc(c,outfp);
  182.     if (c == '\n') lines++;
  183.      }
  184. }
  185.  
  186. /*
  187.  * boolean function to tell if the given character can be part of
  188.  * a word.
  189.  *
  190.  */
  191. isin(s,c) char *s; int c; {
  192.    for (; *s != '\0'; s++)
  193.       if (*s == c) return(1);
  194.    return(0);
  195. }
  196. isword(c)
  197. int c;
  198. {
  199.   static char special[] = ".%_-$@";    /* these are allowable */
  200.   return(isalnum(c) || isin(special,c));
  201. }
  202.  
  203. /*
  204.  * read the next word into the given buffer.
  205.  *
  206.  */
  207. rdword(fp,buf)
  208. FILE *fp;
  209. char *buf;
  210. {
  211.   int len = 0,c;
  212.   while (isword(c = getc(fp)) && ++len < MAXWORD) *buf++ = c;
  213.   *buf++ = '\0';            /* tie off word */
  214.   ungetc(c,fp);                /* put break char back */
  215. }
  216.  
  217.  
  218. /*
  219.  * read state names, up to a newline.
  220.  *
  221.  */
  222.  
  223. rdstates(fp,ofp)
  224. FILE *fp,*ofp;
  225. {
  226.   int c;
  227.   char wordbuf[MAXWORD];
  228.   while ((c = getc(fp)) != EOF && c != '\n')
  229.   {
  230.     if (isspace(c) || c == C_L) continue;    /* skip whitespace */
  231.     ungetc(c,fp);            /* put char back */
  232.     rdword(fp,wordbuf);        /* read the whole word */
  233.     enter(wordbuf,++nstates);    /* put into symbol tbl */
  234.     fprintf(ofp,"#define %s %d\n",wordbuf,nstates);
  235.   }
  236.   lines++;
  237. }
  238.         
  239. /*
  240.  * allocate a new, empty transition node
  241.  *
  242.  */
  243.  
  244. Trans
  245. newtrans()
  246. {
  247.   Trans new;
  248.   int i;
  249.   new = (Trans) malloc(sizeof (struct trans));
  250.   for (i=0; i<SBYTES; i++) new->states[i] = 0;
  251.   new->anyst = 0;
  252.   new->nxt = NULL;
  253.   return(new);
  254. }
  255.  
  256.  
  257. /*
  258.  * read all the rules.
  259.  *
  260.  */
  261.  
  262. Trans
  263. rdrules(fp,out)
  264. FILE *fp,*out;
  265. {
  266.   Trans head,cur,prev;
  267.   int curtok;
  268.   head = cur = NULL;
  269.   while ((curtok = gettoken(fp)) != SEP) 
  270.  
  271.     switch(curtok) {
  272.         case LBRACK: if (cur == NULL) cur = newtrans();
  273.                      else fatal("duplicate state list");
  274.                  statelist(fp,cur);/* set states */
  275.                  continue;    /* prepare to read char */
  276.  
  277.         case WORD:   if (strlen(tokval) != 1)
  278.                     fatal("multiple chars in state");
  279.                  if (cur == NULL) {
  280.                 cur = newtrans();
  281.                 cur->anyst = 1;
  282.                 }
  283.                  cur->actno = ++nacts;
  284.                  cur->inchr = tokval[0];
  285.                  if (head == NULL) head = cur;
  286.                  else prev->nxt = cur;
  287.                  prev = cur;
  288.                  cur = NULL;
  289.                  copyact(fp,out,nacts);
  290.                  break; 
  291.          default: fatal("bad input format");
  292.          }
  293.     
  294.    return(head);
  295. }
  296.  
  297.  
  298. /*
  299.  * read a list of (comma-separated) states, set them in the
  300.  * given transition.
  301.  *
  302.  */
  303. statelist(fp,t)
  304. FILE *fp;
  305. Trans t;
  306. {
  307.   int curtok,sval;
  308.   curtok = COMMA;
  309.   while (curtok != RBRACK) {
  310.     if (curtok != COMMA) fatal("missing comma");
  311.     if ((curtok = gettoken(fp)) != WORD) fatal("missing state name");
  312.         if ((sval = lkup(tokval)) == -1) {
  313.         fprintf(stderr,"state %s undefined\n",tokval);
  314.         fatal("undefined state");
  315.        }
  316.         setstate(sval,t);    
  317.  curtok = gettoken(fp);
  318.    }
  319. }
  320.  
  321. /*
  322.  * copy an action from the input to the output file
  323.  *
  324.  */
  325. copyact(inp,outp,actno)
  326. FILE *inp,*outp;
  327. int actno;
  328. {
  329.   int c,bcnt;
  330.   fprintf(outp,"case %d:\n",actno);
  331.   while (c = getc(inp), (isspace(c) || c == C_L))
  332.      if (c == '\n') lines++;
  333.   if (c == '{') {
  334.      bcnt = 1;
  335.      fputs("    {",outp);
  336.      while (bcnt > 0 && (c = getc(inp)) != EOF) {
  337.     if (c == '{') bcnt++;
  338.     else if (c == '}') bcnt--;
  339.     else if (c == '\n') lines++;
  340.     putc(c,outp);
  341.       }
  342.      if (bcnt > 0) fatal("action doesn't end");
  343.     }
  344.    else {
  345.       while (c != '\n' && c != EOF) {
  346.         putc(c,outp);
  347.         c = getc(inp);
  348.         }
  349.       lines++;
  350.     }
  351.    fprintf(outp,"\n    break;\n");
  352. }
  353.  
  354.  
  355. /*
  356.  * find the action associated with a given character and state.
  357.  * returns -1 if one can't be found.
  358.  *
  359.  */
  360. faction(hd,state,chr)
  361. Trans hd;
  362. int state,chr;
  363. {
  364.   while (hd != NULL) {
  365.     if (hd->anyst || teststate(state,hd))
  366.       if (hd->inchr == '.' || hd->inchr == chr) return(hd->actno);
  367.     hd = hd->nxt;
  368.     }
  369.   return(-1);
  370. }
  371.  
  372.  
  373. /*
  374.  * empty the table...
  375.  *
  376.  */
  377. emptytbl()
  378. {
  379.   int i;
  380.   for (i=0; i<nstates*128; i++) tbl[i] = -1;
  381. }
  382.  
  383. /*
  384.  * add the specified action to the output for the given state and chr.
  385.  *
  386.  */
  387.  
  388. addaction(act,state,chr)
  389. int act,state,chr;
  390. {
  391.  tbl[state*128 + chr] = act;
  392. }
  393.  
  394. writetbl(fp)
  395. FILE *fp;
  396. {
  397.   warray(fp,"tbl",tbl,128*(nstates+1),TBL_TYPE);
  398. }
  399.  
  400.  
  401. /*
  402.  * write an array to the output file, given its name and size.
  403.  *
  404.  */
  405. warray(fp,nam,cont,siz,typ)
  406. FILE *fp;
  407. char *nam;
  408. int cont[],siz;
  409. char *typ;
  410. {
  411.   int i;
  412.   fprintf(fp,"%s %s[] = {\n",typ,nam);
  413.   for (i = 0; i < siz; ) {
  414.     fprintf(fp,"%2d, ",cont[i]);
  415.     if ((++i % 16) == 0) putc('\n',fp);
  416.     }
  417.   fprintf(fp,"};\n");
  418. }
  419.  
  420. main(argc,argv)
  421. int argc;
  422. char *argv[];
  423. {
  424.   Trans head;
  425.   int state,c;
  426.   FILE *infile,*outfile;
  427.  
  428.   if (argc > 1) {
  429.     if ((infile = fopen(argv[1],"r")) == NULL) {
  430.         fprintf(stderr,"Can't open %s\n",argv[1]);
  431.     fatal("unreadable input file"); } }
  432.   else infile = stdin;
  433.  
  434.   if (argc > 2) {
  435.     if ((outfile = fopen(argv[2],"w")) == NULL) {
  436.         fprintf(stderr,"Can't write to %s\n",argv[2]);
  437.     fatal("bad output file"); } }
  438.   else outfile = stdout;
  439.  
  440.   clrhash();                /* empty hash table */
  441.   head = rdinput(infile,outfile);    /* read input file */
  442.   emptytbl();                /* empty our tables */
  443.   for (state = 0; state <= nstates; state++)
  444.     for (c = 1; c < 128; c++)
  445.      addaction(faction(head,state,c),state,c);    /* find actions, add to tbl */
  446.   writetbl(outfile);
  447.   copyrest(infile,outfile);
  448.   printf("%d states, %d actions\n",nstates,nacts);
  449. #ifdef undef
  450.   for (state = 1; state <= nstates; state ++)
  451.     for (c = 1; c < 128; c++)
  452.        if (tbl[state*128 + c] != -1) printf("state %d, chr %d, act %d\n",
  453.            state,c,tbl[state*128 + c]);
  454. #endif
  455.   exit(GOOD_EXIT);
  456. }
  457.  
  458.  
  459. /*
  460.  * fatal error handler
  461.  *
  462.  */
  463.  
  464. fatal(msg)
  465. char *msg;
  466. {
  467.   fprintf(stderr,"error in line %d: %s\n",lines,msg);
  468.   exit(BAD_EXIT);
  469. }
  470.  
  471. prolog(outfp)
  472. FILE *outfp;
  473. {
  474.   int c;
  475.   while ((c = *txt1++)     != '\0') putc(c,outfp);
  476.   while ((c = *fname++)    != '\0') putc(c,outfp);
  477.   while ((c = *txt2++)     != '\0') putc(c,outfp);
  478.   while ((c = *tbl_type++) != '\0') putc(c,outfp);
  479.   while ((c = *txt2a++)    != '\0') putc(c,outfp);
  480. }
  481.  
  482. epilogue(outfp)
  483. FILE *outfp;
  484. {
  485.   int c;
  486.   while ((c = *txt3++) != '\0') putc(c,outfp);
  487. }
  488.  
  489. copyrest(in,out)
  490. FILE *in,*out;
  491. {
  492.   int c;
  493.   while ((c = getc(in)) != EOF) putc(c,out);
  494. }
  495.  
  496.  
  497. /*
  498.  * gettoken - returns token type of next token, sets tokval
  499.  * to the string value of the token if appropriate.
  500.  *
  501.  */
  502.  
  503. gettoken(fp)
  504. FILE *fp;
  505. {
  506.   int c;
  507.   while (1) {                /* loop if reading comments... */
  508.     do {
  509.       c = getc(fp);
  510.       if (c == '\n') lines++;
  511.        } while ((isspace(c) || c == C_L)); /* skip whitespace */
  512.     switch(c) {
  513.       case EOF: return(SEP);
  514.       case '%': if ((c = getc(fp)) == '%') return(SEP);
  515.             tokval[0] = '%';
  516.             tokval[1] = c;
  517.             rdword(fp,tokval+2);
  518.             return(WORD);
  519.       case '<': return(LBRACK);
  520.       case '>': return(RBRACK);
  521.       case ',': return(COMMA);
  522.       case '/': if ((c = getc(fp)) == '*') {
  523.                   rdcmnt(fp);    /* skip over the comment */
  524.               continue; }    /* and keep looping */
  525.             else {
  526.             ungetc(c,fp);    /* put this back into input */
  527.             c = '/'; }    /* put character back, fall thru */
  528.  
  529.       default: if (isword(c)) {
  530.               ungetc(c,fp);
  531.               rdword(fp,tokval);
  532.               return(WORD);
  533.                   }
  534.            else fatal("Invalid character in input");
  535.          }
  536.   }
  537. }
  538.  
  539. /*
  540.  * skip over a comment
  541.  *
  542.  */
  543.  
  544. rdcmnt(fp)
  545. FILE *fp;
  546. {
  547.   int c,star,prcnt;
  548.   prcnt = star = 0;            /* no star seen yet */
  549.   while (!((c = getc(fp)) == '/' && star)) {
  550.     if (c == EOF || (prcnt && c == '%')) fatal("Unterminated comment");
  551.     prcnt = (c == '%');
  552.     star = (c == '*');
  553.     if (c == '\n') lines++; }
  554. }
  555.  
  556.  
  557.  
  558. /*
  559.  * symbol table management for wart
  560.  *
  561.  * entry points:
  562.  *   clrhash - empty hash table.
  563.  *   enter - enter a name into the symbol table
  564.  *   lkup - find a name's value in the symbol table.
  565.  *
  566.  */
  567.  
  568. #define HASHSIZE 101            /* # of entries in hash table */
  569.  
  570. struct sym { char *name;        /* symbol name */
  571.          int val;            /* value */
  572.          struct sym *hnxt; }    /* next on collision chain */
  573.     *htab[HASHSIZE];            /* the hash table */
  574.  
  575.  
  576. /*
  577.  * empty the hash table before using it...
  578.  *
  579.  */
  580. clrhash()
  581. {
  582.   int i;
  583.   for (i=0; i<HASHSIZE; i++) htab[i] = NULL;
  584. }
  585.  
  586. /*
  587.  * compute the value of the hash for a symbol
  588.  *
  589.  */
  590. hash(name)
  591. char *name;
  592. {
  593.   int sum;
  594.   for (sum = 0; *name != '\0'; name++) sum += (sum + *name);
  595.   sum %= HASHSIZE;            /* take sum mod hashsize */
  596.   if (sum < 0) sum += HASHSIZE;        /* disallow negative hash value */
  597.   return(sum);
  598. }
  599.  
  600. /*
  601.  * make a private copy of a string...
  602.  *
  603.  */
  604. char *
  605. copy(s)
  606. char *s;
  607. {
  608.   char *new;
  609.   new = (char *) malloc(strlen(s) + 1);
  610.   strcpy(new,s);
  611.   return(new);
  612. }
  613.  
  614.  
  615. /*
  616.  * enter state name into the hash table
  617.  *
  618.  */
  619. enter(name,svalue)
  620. char *name;
  621. int svalue;
  622. {
  623.   int h;
  624.   struct sym *cur;
  625.   if (lkup(name) != -1) {
  626.     fprintf(stderr,"state %s appears twice...\n");
  627.     exit(BAD_EXIT); }
  628.   h = hash(name);
  629.   cur = (struct sym *)malloc(sizeof (struct sym));
  630.   cur->name = copy(name);
  631.   cur->val = svalue;
  632.   cur->hnxt = htab[h];
  633.   htab[h] = cur;
  634. }
  635.  
  636. /*
  637.  * find name in the symbol table, return its value.  Returns -1
  638.  * if not found.
  639.  *
  640.  */
  641. lkup(name)
  642. char *name;
  643. {
  644.   struct sym *cur;
  645.   for (cur = htab[hash(name)]; cur != NULL; cur = cur->hnxt)
  646.     if (strcmp(cur->name,name) == 0) return(cur->val);
  647.   return(-1);
  648. }
  649.