home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 11 Util / 11-Util.zip / txtut122.zip / textutil / src / ansi2knr.c < prev    next >
C/C++ Source or Header  |  1998-04-05  |  14KB  |  486 lines

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