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