home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 1996 February / PCWK0296.iso / sharewar / dos / program / gs300sr1 / gs300sr1.exe / ANSI2KNR.C < prev    next >
C/C++ Source or Header  |  1994-07-29  |  12KB  |  448 lines

  1. /* Copyright (C) 1989, 1991, 1993, 1994 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.  * Usage:
  24.     ansi2knr [-Ovarargs=convert] input_file [output_file]
  25.  * If no output_file is supplied, output goes to stdout.
  26.  * There are no error messages.
  27.  *
  28.  * ansi2knr recognizes function definitions by seeing a non-keyword
  29.  * identifier at the left margin, followed by a left parenthesis,
  30.  * with a right parenthesis as the last character on the line.
  31.  * It will recognize a multi-line header provided that the last character
  32.  * of the last line of the header is a right parenthesis,
  33.  * and no intervening line ends with a left brace or a semicolon.
  34.  * These algorithms ignore whitespace and comments, except that
  35.  * the function name must be the first thing on the line.
  36.  * The following constructs will confuse it:
  37.  *    - Any other construct that starts at the left margin and
  38.  *        follows the above syntax (such as a macro or function call).
  39.  *    - Macros that tinker with the syntax of the function header.
  40.  *
  41.  * If the -Ovarargs=convert switch is supplied, ansi2knr will attempt to
  42.  * convert a ... argument to va_alist and va_dcl.  If this switch is not
  43.  * supplied, ansi2knr will simply drop any such arguments.
  44.  */
  45.  
  46. /*
  47.  * The original and principal author of ansi2knr is L. Peter Deutsch
  48.  * <ghost@aladdin.com>.  Other authors are noted in the change history
  49.  * that follows (in reverse chronological order):
  50.     lpd 94-07-16 added some conditionals to help GNU `configure',
  51.         suggested by Francois Pinard <pinard@iro.umontreal.ca>;
  52.         properly erase prototype args in function parameters,
  53.         contributed by Jim Avera <jima@netcom.com>;
  54.         correct error in writeblanks (it shouldn't erase EOLs)
  55.     lpd 89-xx-xx original version
  56.  */
  57.  
  58. /* Most of the conditionals here are to make ansi2knr work with */
  59. /* the GNU configure machinery. */
  60.  
  61. #ifdef HAVE_CONFIG_H
  62. # ifdef CONFIG_BROKETS
  63. /*
  64.    We use <config.h> instead of "config.h" so that a compilation
  65.    using -I. -I$srcdir will use ./config.h rather than $srcdir/config.h
  66.    (which it would do because it found this file in $srcdir).
  67.  */
  68. #  include <config.h>
  69. # else
  70. #  include "config.h"
  71. # endif
  72. #endif
  73.  
  74. #include <stdio.h>
  75. #include <ctype.h>
  76.  
  77. #ifdef HAVE_CONFIG_H
  78.  
  79. /*
  80.    For properly autoconfiguring ansi2knr, use AC_CONFIG_HEADER(config.h).
  81.    This will define HAVE_CONFIG_H and so, activate the following lines.
  82.  */
  83.  
  84. # if STDC_HEADERS || HAVE_STRING_H
  85. #  include <string.h>
  86. # else
  87. #  include <strings.h>
  88. # endif
  89.  
  90. #else /* not HAVE_CONFIG_H */
  91.  
  92. /*
  93.    Without AC_CONFIG_HEADER, merely use <string.h> as in the original
  94.    Ghostscript distribution.  This loses on older BSD systems.
  95.  */
  96.  
  97. # include <string.h>
  98.  
  99. #endif /* not HAVE_CONFIG_H */
  100.  
  101. #ifdef STDC_HEADERS
  102. # include <stdlib.h>
  103. #else
  104. /*
  105.    malloc and free should be declared in stdlib.h,
  106.    but if you've got a K&R compiler, they probably aren't.
  107.  */
  108. char *malloc();
  109. void free();
  110. #endif
  111.  
  112. /* Scanning macros */
  113. #define isidchar(ch) (isalnum(ch) || (ch) == '_')
  114. #define isidfirstchar(ch) (isalpha(ch) || (ch) == '_')
  115.  
  116. /* Forward references */
  117. char *skipspace();
  118. void writeblanks();
  119. int test1();
  120. int convert1();
  121.  
  122. /* The main program */
  123. int
  124. main(argc, argv)
  125.     int argc;
  126.     char *argv[];
  127. {    FILE *in, *out;
  128. #define bufsize 5000            /* arbitrary size */
  129.     char *buf;
  130.     char *line;
  131.     int convert_varargs = 0;
  132.     if ( argc > 1 && argv[1][0] == '-' )
  133.       {    if ( !strcmp(argv[1], "-Ovarargs=convert") )
  134.           {    convert_varargs = 1;
  135.             argc--;
  136.             argv++;
  137.           }
  138.         else
  139.           {    fprintf(stderr, "Unrecognized switch: %s\n", argv[1]);
  140.             exit(1);
  141.           }
  142.       }
  143.     switch ( argc )
  144.        {
  145.     default:
  146.         printf("Usage: ansi2knr [-Ovarargs=convert] input_file [output_file]\n");
  147.         exit(0);
  148.     case 2:
  149.         out = stdout;
  150.         break;
  151.     case 3:
  152.         out = fopen(argv[2], "w");
  153.         if ( out == NULL )
  154.            {    fprintf(stderr, "Cannot open output file %s\n", argv[2]);
  155.             exit(1);
  156.            }
  157.        }
  158.     in = fopen(argv[1], "r");
  159.     if ( in == NULL )
  160.        {    fprintf(stderr, "Cannot open input file %s\n", argv[1]);
  161.         exit(1);
  162.        }
  163.     fprintf(out, "#line 1 \"%s\"\n", argv[1]);
  164.     buf = malloc(bufsize);
  165.     line = buf;
  166.     while ( fgets(line, (unsigned)(buf + bufsize - line), in) != NULL )
  167.        {    switch ( test1(buf) )
  168.            {
  169.         case 2:            /* a function header */
  170.             convert1(buf, out, 1, convert_varargs);
  171.             break;
  172.         case 1:            /* a function */
  173.             convert1(buf, out, 0, convert_varargs);
  174.             break;
  175.         case -1:        /* maybe the start of a function */
  176.             line = buf + strlen(buf);
  177.             if ( line != buf + (bufsize - 1) ) /* overflow check */
  178.                 continue;
  179.             /* falls through */
  180.         default:        /* not a function */
  181.             fputs(buf, out);
  182.             break;
  183.            }
  184.         line = buf;
  185.        }
  186.     if ( line != buf ) fputs(buf, out);
  187.     free(buf);
  188.     fclose(out);
  189.     fclose(in);
  190.     return 0;
  191. }
  192.  
  193. /* Skip over space and comments, in either direction. */
  194. char *
  195. skipspace(p, dir)
  196.     register char *p;
  197.     register int dir;            /* 1 for forward, -1 for backward */
  198. {    for ( ; ; )
  199.        {    while ( isspace(*p) ) p += dir;
  200.         if ( !(*p == '/' && p[dir] == '*') ) break;
  201.         p += dir;  p += dir;
  202.         while ( !(*p == '*' && p[dir] == '/') )
  203.            {    if ( *p == 0 ) return p;    /* multi-line comment?? */
  204.             p += dir;
  205.            }
  206.         p += dir;  p += dir;
  207.        }
  208.     return p;
  209. }
  210.  
  211. /*
  212.  * Write blanks over part of a string.
  213.  * Don't overwrite end-of-line characters.
  214.  */
  215. void
  216. writeblanks(start, end)
  217.     char *start;
  218.     char *end;
  219. {    char *p;
  220.     for ( p = start; p < end; p++ )
  221.       if ( *p != '\r' && *p != '\n' ) *p = ' ';
  222. }
  223.  
  224. /*
  225.  * Test whether the string in buf is a function definition.
  226.  * The string may contain and/or end with a newline.
  227.  * Return as follows:
  228.  *    0 - definitely not a function definition;
  229.  *    1 - definitely a function definition;
  230.  *    2 - definitely a function prototype (NOT USED);
  231.  *    -1 - may be the beginning of a function definition,
  232.  *        append another line and look again.
  233.  * The reason we don't attempt to convert function prototypes is that
  234.  * Ghostscript's declaration-generating macros look too much like
  235.  * prototypes, and confuse the algorithms.
  236.  */
  237. int
  238. test1(buf)
  239.     char *buf;
  240. {    register char *p = buf;
  241.     char *bend;
  242.     char *endfn;
  243.     int contin;
  244.     if ( !isidfirstchar(*p) )
  245.         return 0;        /* no name at left margin */
  246.     bend = skipspace(buf + strlen(buf) - 1, -1);
  247.     switch ( *bend )
  248.        {
  249.     case ';': contin = 0 /*2*/; break;
  250.     case ')': contin = 1; break;
  251.     case '{': return 0;        /* not a function */
  252.     default: contin = -1;
  253.        }
  254.     while ( isidchar(*p) ) p++;
  255.     endfn = p;
  256.     p = skipspace(p, 1);
  257.     if ( *p++ != '(' )
  258.         return 0;        /* not a function */
  259.     p = skipspace(p, 1);
  260.     if ( *p == ')' )
  261.         return 0;        /* no parameters */
  262.     /* Check that the apparent function name isn't a keyword. */
  263.     /* We only need to check for keywords that could be followed */
  264.     /* by a left parenthesis (which, unfortunately, is most of them). */
  265.        {    static char *words[] =
  266.            {    "asm", "auto", "case", "char", "const", "double",
  267.             "extern", "float", "for", "if", "int", "long",
  268.             "register", "return", "short", "signed", "sizeof",
  269.             "static", "switch", "typedef", "unsigned",
  270.             "void", "volatile", "while", 0
  271.            };
  272.         char **key = words;
  273.         char *kp;
  274.         int len = endfn - buf;
  275.         while ( (kp = *key) != 0 )
  276.            {    if ( strlen(kp) == len && !strncmp(kp, buf, len) )
  277.                 return 0;    /* name is a keyword */
  278.             key++;
  279.            }
  280.        }
  281.     return contin;
  282. }
  283.  
  284. /* Convert a recognized function definition or header to K&R syntax. */
  285. int
  286. convert1(buf, out, header, convert_varargs)
  287.     char *buf;
  288.     FILE *out;
  289.     int header;            /* Boolean */
  290.     int convert_varargs;    /* Boolean */
  291. {    char *endfn;
  292.     register char *p;
  293.     char **breaks;
  294.     unsigned num_breaks = 2;    /* for testing */
  295.     char **btop;
  296.     char **bp;
  297.     char **ap;
  298.     char *vararg = 0;
  299.     /* Pre-ANSI implementations don't agree on whether strchr */
  300.     /* is called strchr or index, so we open-code it here. */
  301.     for ( endfn = buf; *(endfn++) != '('; ) ;
  302. top:    p = endfn;
  303.     breaks = (char **)malloc(sizeof(char *) * num_breaks * 2);
  304.     if ( breaks == 0 )
  305.        {    /* Couldn't allocate break table, give up */
  306.         fprintf(stderr, "Unable to allocate break table!\n");
  307.         fputs(buf, out);
  308.         return -1;
  309.        }
  310.     btop = breaks + num_breaks * 2 - 2;
  311.     bp = breaks;
  312.     /* Parse the argument list */
  313.     do
  314.        {    int level = 0;
  315.         char *lp = NULL;
  316.         char *rp;
  317.         char *end = NULL;
  318.         if ( bp >= btop )
  319.            {    /* Filled up break table. */
  320.             /* Allocate a bigger one and start over. */
  321.             free((char *)breaks);
  322.             num_breaks <<= 1;
  323.             goto top;
  324.            }
  325.         *bp++ = p;
  326.         /* Find the end of the argument */
  327.         for ( ; end == NULL; p++ )
  328.            {    switch(*p)
  329.                {
  330.             case ',':
  331.                 if ( !level ) end = p;
  332.                 break;
  333.             case '(':
  334.                 if ( !level ) lp = p;
  335.                 level++;
  336.                 break;
  337.             case ')':
  338.                 if ( --level < 0 ) end = p;
  339.                 else rp = p;
  340.                 break;
  341.             case '/':
  342.                 p = skipspace(p, 1) - 1;
  343.                 break;
  344.             default:
  345.                 ;
  346.                }
  347.            }
  348.         /* Erase any embedded prototype parameters. */
  349.         if ( lp )
  350.           writeblanks(lp + 1, rp);
  351.         p--;            /* back up over terminator */
  352.         /* Find the name being declared. */
  353.         /* This is complicated because of procedure and */
  354.         /* array modifiers. */
  355.         for ( ; ; )
  356.            {    p = skipspace(p - 1, -1);
  357.             switch ( *p )
  358.                {
  359.             case ']':    /* skip array dimension(s) */
  360.             case ')':    /* skip procedure args OR name */
  361.                {    int level = 1;
  362.                 while ( level )
  363.                  switch ( *--p )
  364.                    {
  365.                 case ']': case ')': level++; break;
  366.                 case '[': case '(': level--; break;
  367.                 case '/': p = skipspace(p, -1) + 1; break;
  368.                 default: ;
  369.                    }
  370.                }
  371.                 if ( *p == '(' && *skipspace(p + 1, 1) == '*' )
  372.                    {    /* We found the name being declared */
  373.                     while ( !isidfirstchar(*p) )
  374.                         p = skipspace(p, 1) + 1;
  375.                     goto found;
  376.                    }
  377.                 break;
  378.             default: goto found;
  379.                }
  380.            }
  381. found:        if ( *p == '.' && p[-1] == '.' && p[-2] == '.' )
  382.           {    if ( convert_varargs )
  383.               {    *bp++ = "va_alist";
  384.                 vararg = p-2;
  385.               }
  386.             else
  387.               {    p++;
  388.                 if ( bp == breaks + 1 )    /* sole argument */
  389.                   writeblanks(breaks[0], p);
  390.                 else
  391.                   writeblanks(bp[-1] - 1, p);
  392.                 bp--;
  393.               }
  394.            }
  395.         else
  396.            {    while ( isidchar(*p) ) p--;
  397.             *bp++ = p+1;
  398.            }
  399.         p = end;
  400.        }
  401.     while ( *p++ == ',' );
  402.     *bp = p;
  403.     /* Make a special check for 'void' arglist */
  404.     if ( bp == breaks+2 )
  405.        {    p = skipspace(breaks[0], 1);
  406.         if ( !strncmp(p, "void", 4) )
  407.            {    p = skipspace(p+4, 1);
  408.             if ( p == breaks[2] - 1 )
  409.                {    bp = breaks;    /* yup, pretend arglist is empty */
  410.                 writeblanks(breaks[0], p + 1);
  411.                }
  412.            }
  413.        }
  414.     /* Put out the function name and left parenthesis. */
  415.     p = buf;
  416.     while ( p != endfn ) putc(*p, out), p++;
  417.     /* Put out the declaration. */
  418.     if ( header )
  419.       {    fputs(");", out);
  420.         for ( p = breaks[0]; *p; p++ )
  421.           if ( *p == '\r' || *p == '\n' )
  422.             putc(*p, out);
  423.       }
  424.     else
  425.       {    for ( ap = breaks+1; ap < bp; ap += 2 )
  426.           {    p = *ap;
  427.             while ( isidchar(*p) )
  428.               putc(*p, out), p++;
  429.             if ( ap < bp - 1 )
  430.               fputs(", ", out);
  431.           }
  432.         fputs(")  ", out);
  433.         /* Put out the argument declarations */
  434.         for ( ap = breaks+2; ap <= bp; ap += 2 )
  435.           (*ap)[-1] = ';';
  436.         if ( vararg != 0 )
  437.           {    *vararg = 0;
  438.             fputs(breaks[0], out);        /* any prior args */
  439.             fputs("va_dcl", out);        /* the final arg */
  440.             fputs(bp[0], out);
  441.           }
  442.         else
  443.           fputs(breaks[0], out);
  444.       }
  445.     free((char *)breaks);
  446.     return 0;
  447. }
  448.