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