home *** CD-ROM | disk | FTP | other *** search
/ C!T ROM 5 / ctrom5b.zip / ctrom5b / DOS / GRAFISCH / JPGSRC5A / ANSI2KNR.C < prev    next >
Text File  |  1994-01-19  |  17KB  |  489 lines

  1. /* Copyright (C) 1989, 1991, 1993 Aladdin Enterprises. All rights reserved. */
  2.  
  3. /* ansi2knr.c */
  4. /* Convert ANSI function declarations to K&R syntax */
  5.  
  6. /*
  7. ansi2knr is distributed in the hope that it will be useful, but
  8. WITHOUT ANY WARRANTY.  No author or distributor accepts responsibility
  9. to anyone for the consequences of using it or for whether it serves any
  10. particular purpose or works at all, unless he says so in writing.  Refer
  11. to the GNU General Public License for full details.
  12.  
  13. Everyone is granted permission to copy, modify and redistribute
  14. ansi2knr, but only under the conditions described in the GNU
  15. General Public License.  A copy of this license is supposed to have been
  16. given to you along with ansi2knr so you can know your rights and
  17. responsibilities.  It should be in a file named COPYING.  Among other
  18. things, the copyright notice and this notice must be preserved on all
  19. copies.
  20. */
  21.  
  22. /*
  23. ---------- Here is the GNU GPL file COPYING, referred to above ----------
  24. ----- These terms do NOT apply to the JPEG software itself; see README ------
  25.  
  26.             GHOSTSCRIPT GENERAL PUBLIC LICENSE
  27.             (Clarified 11 Feb 1988)
  28.  
  29.  Copyright (C) 1988 Richard M. Stallman
  30.  Everyone is permitted to copy and distribute verbatim copies of this
  31.  license, but changing it is not allowed.  You can also use this wording
  32.  to make the terms for other programs.
  33.  
  34.   The license agreements of most software companies keep you at the
  35. mercy of those companies.  By contrast, our general public license is
  36. intended to give everyone the right to share Ghostscript.  To make sure
  37. that you get the rights we want you to have, we need to make
  38. restrictions that forbid anyone to deny you these rights or to ask you
  39. to surrender the rights.  Hence this license agreement.
  40.  
  41.   Specifically, we want to make sure that you have the right to give
  42. away copies of Ghostscript, that you receive source code or else can get
  43. it if you want it, that you can change Ghostscript or use pieces of it
  44. in new free programs, and that you know you can do these things.
  45.  
  46.   To make sure that everyone has such rights, we have to forbid you to
  47. deprive anyone else of these rights.  For example, if you distribute
  48. copies of Ghostscript, you must give the recipients all the rights that
  49. you have.  You must make sure that they, too, receive or can get the
  50. source code.  And you must tell them their rights.
  51.  
  52.   Also, for our own protection, we must make certain that everyone finds
  53. out that there is no warranty for Ghostscript.  If Ghostscript is
  54. modified by someone else and passed on, we want its recipients to know
  55. that what they have is not what we distributed, so that any problems
  56. introduced by others will not reflect on our reputation.
  57.  
  58.   Therefore we (Richard M. Stallman and the Free Software Foundation,
  59. Inc.) make the following terms which say what you must do to be allowed
  60. to distribute or change Ghostscript.
  61.  
  62.  
  63.             COPYING POLICIES
  64.  
  65.   1. You may copy and distribute verbatim copies of Ghostscript source
  66. code as you receive it, in any medium, provided that you conspicuously
  67. and appropriately publish on each copy a valid copyright and license
  68. notice "Copyright (C) 1989 Aladdin Enterprises.  All rights reserved.
  69. Distributed by Free Software Foundation, Inc." (or with whatever year is
  70. appropriate); keep intact the notices on all files that refer to this
  71. License Agreement and to the absence of any warranty; and give any other
  72. recipients of the Ghostscript program a copy of this License Agreement
  73. along with the program.  You may charge a distribution fee for the
  74. physical act of transferring a copy.
  75.  
  76.   2. You may modify your copy or copies of Ghostscript or any portion of
  77. it, and copy and distribute such modifications under the terms of
  78. Paragraph 1 above, provided that you also do the following:
  79.  
  80.     a) cause the modified files to carry prominent notices stating
  81.     that you changed the files and the date of any change; and
  82.  
  83.     b) cause the whole of any work that you distribute or publish,
  84.     that in whole or in part contains or is a derivative of Ghostscript
  85.     or any part thereof, to be licensed at no charge to all third
  86.     parties on terms identical to those contained in this License
  87.     Agreement (except that you may choose to grant more extensive
  88.     warranty protection to some or all third parties, at your option).
  89.  
  90.     c) You may charge a distribution fee for the physical act of
  91.     transferring a copy, and you may at your option offer warranty
  92.     protection in exchange for a fee.
  93.  
  94. Mere aggregation of another unrelated program with this program (or its
  95. derivative) on a volume of a storage or distribution medium does not bring
  96. the other program under the scope of these terms.
  97.  
  98.   3. You may copy and distribute Ghostscript (or a portion or derivative
  99. of it, under Paragraph 2) in object code or executable form under the
  100. terms of Paragraphs 1 and 2 above provided that you also do one of the
  101. following:
  102.  
  103.     a) accompany it with the complete corresponding machine-readable
  104.     source code, which must be distributed under the terms of
  105.     Paragraphs 1 and 2 above; or,
  106.  
  107.     b) accompany it with a written offer, valid for at least three
  108.     years, to give any third party free (except for a nominal
  109.     shipping charge) a complete machine-readable copy of the
  110.     corresponding source code, to be distributed under the terms of
  111.     Paragraphs 1 and 2 above; or,
  112.  
  113.     c) accompany it with the information you received as to where the
  114.     corresponding source code may be obtained.  (This alternative is
  115.     allowed only for noncommercial distribution and only if you
  116.     received the program in object code or executable form alone.)
  117.  
  118. For an executable file, complete source code means all the source code for
  119. all modules it contains; but, as a special exception, it need not include
  120. source code for modules which are standard libraries that accompany the
  121. operating system on which the executable file runs.
  122.  
  123.   4. You may not copy, sublicense, distribute or transfer Ghostscript
  124. except as expressly provided under this License Agreement.  Any attempt
  125. otherwise to copy, sublicense, distribute or transfer Ghostscript is
  126. void and your rights to use the program under this License agreement
  127. shall be automatically terminated.  However, parties who have received
  128. computer software programs from you with this License Agreement will not
  129. have their licenses terminated so long as such parties remain in full
  130. compliance.
  131.  
  132.   5. If you wish to incorporate parts of Ghostscript into other free
  133. programs whose distribution conditions are different, write to the Free
  134. Software Foundation at 675 Mass Ave, Cambridge, MA 02139.  We have not
  135. yet worked out a simple rule that can be stated here, but we will often
  136. permit this.  We will be guided by the two goals of preserving the free
  137. status of all derivatives of our free software and of promoting the
  138. sharing and reuse of software.
  139.  
  140. Your comments and suggestions about our licensing policies and our
  141. software are welcome!  Please contact the Free Software Foundation,
  142. Inc., 675 Mass Ave, Cambridge, MA 02139, or call (617) 876-3296.
  143.  
  144.                NO WARRANTY
  145.  
  146.   BECAUSE GHOSTSCRIPT IS LICENSED FREE OF CHARGE, WE PROVIDE ABSOLUTELY
  147. NO WARRANTY, TO THE EXTENT PERMITTED BY APPLICABLE STATE LAW.  EXCEPT
  148. WHEN OTHERWISE STATED IN WRITING, FREE SOFTWARE FOUNDATION, INC, RICHARD
  149. M. STALLMAN, ALADDIN ENTERPRISES, L. PETER DEUTSCH, AND/OR OTHER PARTIES
  150. PROVIDE GHOSTSCRIPT "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
  151. EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  152. WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE
  153. ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF GHOSTSCRIPT IS WITH
  154. YOU.  SHOULD GHOSTSCRIPT PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
  155. NECESSARY SERVICING, REPAIR OR CORRECTION.
  156.  
  157.   IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW WILL RICHARD M.
  158. STALLMAN, THE FREE SOFTWARE FOUNDATION, INC., L. PETER DEUTSCH, ALADDIN
  159. ENTERPRISES, AND/OR ANY OTHER PARTY WHO MAY MODIFY AND REDISTRIBUTE
  160. GHOSTSCRIPT AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING
  161. ANY LOST PROFITS, LOST MONIES, OR OTHER SPECIAL, INCIDENTAL OR
  162. CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE
  163. (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED
  164. INACCURATE OR LOSSES SUSTAINED BY THIRD PARTIES OR A FAILURE OF THE
  165. PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS) GHOSTSCRIPT, EVEN IF YOU
  166. HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES, OR FOR ANY CLAIM
  167. BY ANY OTHER PARTY.
  168.  
  169. -------------------- End of file COPYING ------------------------------
  170. */
  171.  
  172.  
  173. #include <stdio.h>
  174. #include <ctype.h>
  175.  
  176. #ifdef BSD
  177. #include <strings.h>
  178. #else
  179. #ifdef VMS
  180.     extern int strlen(), strncmp();
  181. #else
  182. #include <string.h>
  183. #endif
  184. #endif
  185.  
  186. /* malloc and free should be declared in stdlib.h, */
  187. /* but if you've got a K&R compiler, they probably aren't. */
  188. #ifdef MSDOS
  189. #include <malloc.h>
  190. #else
  191. #ifdef VMS
  192.      extern char *malloc();
  193.      extern void free();
  194. #else
  195.      extern char *malloc();
  196.      extern int free();
  197. #endif
  198. #endif
  199.  
  200. /* Usage:
  201.     ansi2knr input_file [output_file]
  202.  * If no output_file is supplied, output goes to stdout.
  203.  * There are no error messages.
  204.  *
  205.  * ansi2knr recognizes functions by seeing a non-keyword identifier
  206.  * at the left margin, followed by a left parenthesis,
  207.  * with a right parenthesis as the last character on the line.
  208.  * It will recognize a multi-line header provided that the last character
  209.  * of the last line of the header is a right parenthesis,
  210.  * and no intervening line ends with a left brace or a semicolon.
  211.  * These algorithms ignore whitespace and comments, except that
  212.  * the function name must be the first thing on the line.
  213.  * The following constructs will confuse it:
  214.  *    - Any other construct that starts at the left margin and
  215.  *        follows the above syntax (such as a macro or function call).
  216.  *    - Macros that tinker with the syntax of the function header.
  217.  */
  218.  
  219. /* Scanning macros */
  220. #define isidchar(ch) (isalnum(ch) || (ch) == '_')
  221. #define isidfirstchar(ch) (isalpha(ch) || (ch) == '_')
  222.  
  223. /* Forward references */
  224. char *skipspace();
  225. int writeblanks();
  226. int test1();
  227. int convert1();
  228.  
  229. /* The main program */
  230. main(argc, argv)
  231.     int argc;
  232.     char *argv[];
  233. {    FILE *in, *out;
  234. #define bufsize 5000            /* arbitrary size */
  235.     char *buf;
  236.     char *line;
  237.     switch ( argc )
  238.        {
  239.     default:
  240.         printf("Usage: ansi2knr input_file [output_file]\n");
  241.         exit(0);
  242.     case 2:
  243.         out = stdout; break;
  244.     case 3:
  245.         out = fopen(argv[2], "w");
  246.         if ( out == NULL )
  247.            {    fprintf(stderr, "Cannot open %s\n", argv[2]);
  248.             exit(1);
  249.            }
  250.        }
  251.     in = fopen(argv[1], "r");
  252.     if ( in == NULL )
  253.        {    fprintf(stderr, "Cannot open %s\n", argv[1]);
  254.         exit(1);
  255.        }
  256.     fprintf(out, "#line 1 \"%s\"\n", argv[1]);
  257.     buf = malloc(bufsize);
  258.     line = buf;
  259.     while ( fgets(line, (unsigned)(buf + bufsize - line), in) != NULL )
  260.        {    switch ( test1(buf) )
  261.            {
  262.         case 1:            /* a function */
  263.             convert1(buf, out);
  264.             break;
  265.         case -1:        /* maybe the start of a function */
  266.             line = buf + strlen(buf);
  267.             if ( line != buf + (bufsize - 1) ) /* overflow check */
  268.                 continue;
  269.             /* falls through */
  270.         default:        /* not a function */
  271.             fputs(buf, out);
  272.             break;
  273.            }
  274.         line = buf;
  275.        }
  276.     if ( line != buf ) fputs(buf, out);
  277.     free(buf);
  278.     fclose(out);
  279.     fclose(in);
  280.     return 0;
  281. }
  282.  
  283. /* Skip over space and comments, in either direction. */
  284. char *
  285. skipspace(p, dir)
  286.     register char *p;
  287.     register int dir;            /* 1 for forward, -1 for backward */
  288. {    for ( ; ; )
  289.        {    while ( isspace(*p) ) p += dir;
  290.         if ( !(*p == '/' && p[dir] == '*') ) break;
  291.         p += dir;  p += dir;
  292.         while ( !(*p == '*' && p[dir] == '/') )
  293.            {    if ( *p == 0 ) return p;    /* multi-line comment?? */
  294.             p += dir;
  295.            }
  296.         p += dir;  p += dir;
  297.        }
  298.     return p;
  299. }
  300.  
  301. /*
  302.  * Write blanks over part of a string.
  303.  */
  304. int
  305. writeblanks(start, end)
  306.     char *start;
  307.     char *end;
  308. {    char *p;
  309.     for ( p = start; p < end; p++ ) *p = ' ';
  310.     return 0;
  311. }
  312.  
  313. /*
  314.  * Test whether the string in buf is a function definition.
  315.  * The string may contain and/or end with a newline.
  316.  * Return as follows:
  317.  *    0 - definitely not a function definition;
  318.  *    1 - definitely a function definition;
  319.  *    -1 - may be the beginning of a function definition,
  320.  *        append another line and look again.
  321.  */
  322. int
  323. test1(buf)
  324.     char *buf;
  325. {    register char *p = buf;
  326.     char *bend;
  327.     char *endfn;
  328.     int contin;
  329.     if ( !isidfirstchar(*p) )
  330.         return 0;        /* no name at left margin */
  331.     bend = skipspace(buf + strlen(buf) - 1, -1);
  332.     switch ( *bend )
  333.        {
  334.     case ')': contin = 1; break;
  335.     case '{':
  336.     case ';': return 0;        /* not a function */
  337.     default: contin = -1;
  338.        }
  339.     while ( isidchar(*p) ) p++;
  340.     endfn = p;
  341.     p = skipspace(p, 1);
  342.     if ( *p++ != '(' )
  343.         return 0;        /* not a function */
  344.     p = skipspace(p, 1);
  345.     if ( *p == ')' )
  346.         return 0;        /* no parameters */
  347.     /* Check that the apparent function name isn't a keyword. */
  348.     /* We only need to check for keywords that could be followed */
  349.     /* by a left parenthesis (which, unfortunately, is most of them). */
  350.        {    static char *words[] =
  351.            {    "asm", "auto", "case", "char", "const", "double",
  352.             "extern", "float", "for", "if", "int", "long",
  353.             "register", "return", "short", "signed", "sizeof",
  354.             "static", "switch", "typedef", "unsigned",
  355.             "void", "volatile", "while", 0
  356.            };
  357.         char **key = words;
  358.         char *kp;
  359.         int len = endfn - buf;
  360.         while ( (kp = *key) != 0 )
  361.            {    if ( strlen(kp) == len && !strncmp(kp, buf, len) )
  362.                 return 0;    /* name is a keyword */
  363.             key++;
  364.            }
  365.        }
  366.     return contin;
  367. }
  368.  
  369. int
  370. convert1(buf, out)
  371.     char *buf;
  372.     FILE *out;
  373. {    char *endfn;
  374.     register char *p;
  375.     char **breaks;
  376.     unsigned num_breaks = 2;    /* for testing */
  377.     char **btop;
  378.     char **bp;
  379.     char **ap;
  380.     /* Pre-ANSI implementations don't agree on whether strchr */
  381.     /* is called strchr or index, so we open-code it here. */
  382.     for ( endfn = buf; *(endfn++) != '('; ) ;
  383. top:    p = endfn;
  384.     breaks = (char **)malloc(sizeof(char *) * num_breaks * 2);
  385.     if ( breaks == 0 )
  386.        {    /* Couldn't allocate break table, give up */
  387.         fprintf(stderr, "Unable to allocate break table!\n");
  388.         fputs(buf, out);
  389.         return -1;
  390.        }
  391.     btop = breaks + num_breaks * 2 - 2;
  392.     bp = breaks;
  393.     /* Parse the argument list */
  394.     do
  395.        {    int level = 0;
  396.         char *end = NULL;
  397.         if ( bp >= btop )
  398.            {    /* Filled up break table. */
  399.             /* Allocate a bigger one and start over. */
  400.             free((char *)breaks);
  401.             num_breaks <<= 1;
  402.             goto top;
  403.            }
  404.         *bp++ = p;
  405.         /* Find the end of the argument */
  406.         for ( ; end == NULL; p++ )
  407.            {    switch(*p)
  408.                {
  409.             case ',': if ( !level ) end = p; break;
  410.             case '(': level++; break;
  411.             case ')': if ( --level < 0 ) end = p; break;
  412.             case '/': p = skipspace(p, 1) - 1; break;
  413.             default: ;
  414.                }
  415.            }
  416.         p--;            /* back up over terminator */
  417.         /* Find the name being declared. */
  418.         /* This is complicated because of procedure and */
  419.         /* array modifiers. */
  420.         for ( ; ; )
  421.            {    p = skipspace(p - 1, -1);
  422.             switch ( *p )
  423.                {
  424.             case ']':    /* skip array dimension(s) */
  425.             case ')':    /* skip procedure args OR name */
  426.                {    int level = 1;
  427.                 while ( level )
  428.                  switch ( *--p )
  429.                    {
  430.                 case ']': case ')': level++; break;
  431.                 case '[': case '(': level--; break;
  432.                 case '/': p = skipspace(p, -1) + 1; break;
  433.                 default: ;
  434.                    }
  435.                }
  436.                 if ( *p == '(' && *skipspace(p + 1, 1) == '*' )
  437.                    {    /* We found the name being declared */
  438.                     while ( !isidfirstchar(*p) )
  439.                         p = skipspace(p, 1) + 1;
  440.                     goto found;
  441.                    }
  442.                 break;
  443.             default: goto found;
  444.                }
  445.            }
  446. found:        if ( *p == '.' && p[-1] == '.' && p[-2] == '.' )
  447.            {    p++;
  448.             if ( bp == breaks + 1 )    /* sole argument */
  449.                 writeblanks(breaks[0], p);
  450.             else
  451.                 writeblanks(bp[-1] - 1, p);
  452.             bp--;
  453.            }
  454.         else
  455.            {    while ( isidchar(*p) ) p--;
  456.             *bp++ = p+1;
  457.            }
  458.         p = end;
  459.        }
  460.     while ( *p++ == ',' );
  461.     *bp = p;
  462.     /* Make a special check for 'void' arglist */
  463.     if ( bp == breaks+2 )
  464.        {    p = skipspace(breaks[0], 1);
  465.         if ( !strncmp(p, "void", 4) )
  466.            {    p = skipspace(p+4, 1);
  467.             if ( p == breaks[2] - 1 )
  468.                {    bp = breaks;    /* yup, pretend arglist is empty */
  469.                 writeblanks(breaks[0], p + 1);
  470.                }
  471.            }
  472.        }
  473.     /* Put out the function name */
  474.     p = buf;
  475.     while ( p != endfn ) putc(*p, out), p++;
  476.     /* Put out the declaration */
  477.     for ( ap = breaks+1; ap < bp; ap += 2 )
  478.        {    p = *ap;
  479.         while ( isidchar(*p) ) putc(*p, out), p++;
  480.         if ( ap < bp - 1 ) fputs(", ", out);
  481.        }
  482.     fputs(")  ", out);
  483.     /* Put out the argument declarations */
  484.     for ( ap = breaks+2; ap <= bp; ap += 2 ) (*ap)[-1] = ';';
  485.     fputs(breaks[0], out);
  486.     free((char *)breaks);
  487.     return 0;
  488. }
  489.